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

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?

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.

Related

custom array printing in gdb

I know gdb has several means of exploring data, some of them quite convenient. However, I cannot combine them to get that I need/want. I would like to display some custom string based on the first n values of a big array starting at <PT_arr>, and the last m values of the same array at a distance (in this case) 4096. Looking something like this:
table beginning:
0x804cfe0 <PT_arr>: 0x00100300 0x00200300 0x00300300 0x00400300
table end:
0x804cfe0 <PT_arr+4064>: 0x00500300 0x00600300 0x00700300 0x00800300
printf let's me add custom text (like table beginning)
the examine x gives me that nice alignment, let's me read many elements and group them by byte, words, etc; and shows addresses at the left (which is ideal for my case).
x aligns the content of regions of memory in an easy to read manner with the size and unit parameters. (what I want)
display is constantly printing. (what I want).
The issue with display (manual), is that unlike examine x (manual) it doesn't have a size or unit parameter.
Is there a way to accomplish that?
Thanks.

How is SizeOfImage in the PE optional header computed?

How is SizeOfImage in the PE optional header computed?
Trying to learn the PE format, I've come across the SizeOfImage field in the optional header.
To quote the documentation:
The size (in bytes) of the image, including all headers, as the image
is loaded in memory. It must be a multiple of SectionAlignment.
However, I've experienced that if I set this field wrongly, then the executable won't run and an error 193 (badly formatted excutable) is displayed:
How do I compute the SizeOfImage field, and why won't an executable run if its set wrong (e.g. the executable runs if it's set to 0x00003000 but not 0x00004000 or 0x00002000)?
The safest way that I know of is to loop through each section and find the section to be loaded last in memory (i.e. the highest address). You can almost always assume this is the last section and just skip directly to that section if you trust your PE file (such as if you are using a standard linker, etc). You begin with calculating the end-of-data pointer of that section as follows:
pEndOfLastSection = pLastSection->VirtualAddress + pLastSection->Misc.VirtualSize + pOptionalHeader->ImageBase
pEndOfLastSection now represents the end of the actual section's data (as it exists in the file, padded to file alignment, but not padded to memory alignment) and doesn't include any padding the loader must add to ensure the section fits exactly within the granularity of the memory section alignment.
Despite the other fields that might seem to store the end of the section rounded up to the next nearest "memory" alignment, you must you must perform this calculation yourself on the pEndOfLastSection pointer. I wrote the following function which so far has worked for my purposes:
//
// peRoundUpToAlignment() - rounds dwValue up to nearest dwAlign
//
DWORD peRoundUpToAlignment(DWORD dwAlign, DWORD dwVal)
{
if (dwAlign)
{
//do the rounding with bitwise operations...
//create bit mask of bits to keep
// e.g. if section alignment is 0x1000 1000000000000
// we want the following bitmask 11111111111111111111000000000000
DWORD dwMask = ~(dwAlign-1);
//round up by adding full alignment (dwAlign-1 since if already aligned we don't want anything to change),
// then mask off any lower bits
dwVal = (dwVal + dwAlign-1) & dwMask;
}
return(dwVal);
} //peRoundUpToAlignment()
Now take your pEndOfLastSecion and pass it to the rounding function as follows:
//NOTE: we are rounding to memory section alignment, not file
pEndOfLastSectionMem = peRoundUpToAlignment(pOptionalHeader->SectionAlignment,pEndOfLastSection)
Now you have a "simulated" pointer to the end of the PE file as it would be loaded in memory. NOTE: the end pointers calculated above actually point 1 byte past the last byte of the last section; this allows you to subtract them from their base to get the size. Once you have the end pointer of the last section as it would be loaded in memory, you can subtract this from the loader base and get the size of the PE file as it should be loaded in memory, and this size is obviously the same regardless of where the loader might relocate the PE file:
uCalcSizeOfFile = pEndOfLastSectionMem - pOptionalHeader->ImageBase
Unless the image has been tampered with, the calculation of uCalcSizeOfFile above should be equal to the pOptionalHeader->SizeOfImage field.

Read PE and find SAFESEH status in C++ (make use of RVA)

I'm using imagehlp.h to parse my binary and get LOADED_IMAGE.
-LoadedImage.FileHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress
The above gets me the RVA for IMAGE_LOAD_CONFIG_DIRECTORY
As I unsderstand, RVA are offsets to my desired data structure.
So, (PIMAGE_LOAD_CONFIG_DIRECTORY)(RVA+LoadedImage.MappedAddress)
should return me my structure correctly (?).
Is this the right way to convert RVA to meaningful pointer.
I am not sure because the timestamp value in
PIMAGE_LOAD_CONFIG_DIRECTORY->TimeDateStamp does not show correctly.
On examination of the memory,
My LoadedImage.MappedAddress points me to "MZ" header. Which is the start of the binary file. Which means my baseaddress is correct. So I conclude that I'm not correctly using the RVA.
Anyone knows the correct way to use the RVA?
Before anyone points out, I've check that the value of virtualaddress for OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress` is not 0 before proceeding further.

Correct offset of specific section PE

I want to know if my calculations are correct.
I know the following:
AddressOfEntryPoint(of PE)
ImageBase(Of PE)
VirtualAddress of section i want
so the offset (in file) of this section is offset = ImageBase - VirtualAddress
Is this correct? If not ,please explain how I calculate offset of the section.
You can use pefile module.here
for section in pe.sections:
print section.PointerToRawData

ImageBase + SizeOfHeaders will jump at the section table

I was reading a tutorial on PE and it says
Go to the section table either by adding ImageBase to SizeOfHeaders
but SizeOfHeaders is
The size of all headers+section table
so if we add SizeOfHeaders to ImageBase won't we jump at the sections rather than the table?
SizeOfHeaders is not used to find out the position of the section table, even if they might match in some files (but I don't expect so).
Here's how it's done in the Windows headers (and thus the system loader):
#define IMAGE_FIRST_SECTION( ntheader ) ((PIMAGE_SECTION_HEADER) \
((ULONG_PTR)(ntheader) + \
FIELD_OFFSET( IMAGE_NT_HEADERS, OptionalHeader ) + \
((ntheader))->FileHeader.SizeOfOptionalHeader \
))
Note that the actual value of SizeOfOptionalHeader is not checked; it can be very big or even negative - some malware uses it trick to fool analyzing tools.
See here for more details and even nastier tricks.
SizeOfHeaders indeed is the size of the entire header, including the DOS stub.
To get the address of the section table, first get the address of the optional header, and add FileHeader.SizeOfOptionalHeader.

Resources