Search code examples
windowsexebinaryfilesportable-executable

Do I need to modify any headers if I change .text of PE?


I want to edit .text section of a PE file and insert machine code or change machine code.

In the end .text will end up being bigger or smaller than the original size.

For the .exe to still work, do I need to modify any headers?

What do I need to pay attention to in the PE file to make sure that it is still working as intended after .text surgery?


Solution

  • I'd suggest that if the .text section ends up smaller than the original, that you simply pad it out so that it's the same size as the original which will avoid you having to make too many other changes. If it ends up bigger than the original then things could get quite difficult.

    The .text section is usually the first section in the executable, and as sections are aligned in memory based on the "section alignment" entry in the PE header, the next section will usually be placed in memory at the next integer multiple of the section alignment after the end of the .text section. The usual section alignment seems to be 4KiB (0x1000 bytes), so depending on the original size of the .text section, you may have between 0 and 4095 bytes of free space to expand the .text section into before you collide with the next section in memory.

    If there is enough free space in memory to make your changes then you also have to deal with the alignment of the sections in the executable file itself, which is determined by the "file alignment" entry in the PE header. The amount of free space in the executable file for your changes will be the difference between the .text section's raw size and its virtual size, and since the usual file alignment seems to be 512 (0x200) bytes, will therefore be between 0 and 511 bytes. If there's not enough free space in the file (but is enough space in memory), you'll have to move the following sections by an integer multiple of the file alignment and adjust the file pointers of each section accordingly. You'll also need to update the "size of code" value in the PE header to account for the increased size of the .text section.

    If you need to expand it by more than the available free space in memory then things could get very difficult - the sections after .text often contain data referenced by the executable code, and so you can't just adjust the in-memory addresses of the following sections to make additional space as this is almost guaranteed to break the executable. You could attempt to update the executable code to account for the changes to the addresses of the following sections, but it's unlikely you'd be able to do this reliably in all cases.