llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.25k stars 11.66k forks source link

Objcopy remove section doesn’t work with PEI files #63081

Open abbapatris opened 1 year ago

abbapatris commented 1 year ago

I was using the objcopy to remove a section from a PEI file and I kept getting the error: The specified executable is not a valid application for this OS platform.At line:1 char:1

I started breaking down the difference from the original generated executable and the one with the removed section and found that the first section is starting at location offset of 0x600 and the original one has the first start at the offset of 0x1000. Which made me realize the the section alignment is on a 4k boundary (or 0x1000) so the section should start at that location. I dug in to the code and found in file CoffWriter.cpp, method void COFFWriter::writeSections(), the placement of the section is based on the RawDataOffset.

I updated the line

uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
                   S.Header.PointerToRawData;

To be

uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
                     alignTo(S.Header.PointerToRawData, Obj.PeHeader.SectionAlignment);

I noticed the tests only verify that windows object files remove the sections, but they don’t check the PE or PEI files. I assume the linker fixes the problem automatically for the object files.

My executable I was doing this only had a dummy section that did nothing in order to verify that the section isn’t the problem itself.

llvmbot commented 1 year ago

@llvm/issue-subscribers-tools-llvm-objcopy-strip