windowsassemblyportable-executable

Calculating the file offset of a entry point in a PE file


In

various webpages

there is information about how to find the file offset of the entry point in a exe-file.

You can read that

EP (File) = AddressOfEntryPoint – BaseOfCode + .text[PointerToRawData]

  • FileAlignment

However, when I have been calculating this myself (I used a couple of different exe files) I have came to the conclusion that

Offset of entry point in EXE file = AddressOfEntryPoint + .text[PointerToRawData] - .text[VirtualAddress]

Where AddressOfEntryPoint is fetched from IMAGE_OPTIONAL_HEADER and the other two values from the IMAGE_SECTION_HEADER.

What is wrong? Adding FileAlignment like they do just seems wrong, it does not make sense. Or does it? A file alignment suggests that I should use modulo or something to compute a value. If BaseOfCode and FileAlignment is the same value (mostly they are), it would not disturb adding them to the calculation, but how would it make sense?


Solution

  • Correct, you don't need to use the FileAlignment value at all.

    The algorithm should be something like as follow (very similar to yours):

    You simply don't need FileAlignment because the section in which the entry point lies is already aligned on that value.