Objcopy remove section doesn't work with PEI files

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()) +

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.

The LLVM version I am using is the head of the main branch from: GitHub - llvm/llvm-project: The LLVM Project is a collection of modular and reusable compiler and toolchain technologies. Note: the repository does not accept github pull requests at this moment. Please submit your patches at http://reviews.llvm.org.