Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In

http://en.redinskala.com/finding-the-ep/

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

Here I 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.

Is the information on that web page false? 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?

like image 547
Anders Lindén Avatar asked Nov 15 '15 19:11

Anders Lindén


People also ask

How do I find the entry point of a PE file?

The entry point is given by AddressOfEntryPoint in the PE header, which gives you the virtual address of the entry point.

What is the file signature of a PE file?

Signature (Image Only) After the MS-DOS stub, at the file offset specified at offset 0x3c, is a 4-byte signature that identifies the file as a PE format image file. This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes).

How many sections are possible in a PE file?

The PE file format has eleven predefined sections, as is common to applications for Windows NT, but each application can define its own unique sections for code and data.


1 Answers

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

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

  • Get AddressOfEntryPoint from IMAGE_OPTIONAL_HEADER.AddressOfEntryPoint (this is a VA)
  • Search in which section header this VA resides (usually the 1st one, but you should really search in all section headers).
  • Once you have the right section header, get its VirtualAddress and PointerToRawData fields.
  • Subtract VirtualAddress from AddressOfEntryPoint: you now have a "delta"
  • As the exactly same delta applies to offsets, then: add "delta" to PointerToRawData.

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

like image 69
Neitsa Avatar answered Sep 23 '22 02:09

Neitsa