cwinapiportable-executable

Loading PE Headers


Basically, what I am trying to do is to find last section of PE file. I have read PE specification very attentively, yet I can't discover where my code fails.

PIMAGE_DOS_HEADER pidh = (PIMAGE_DOS_HEADER)buffer;
PIMAGE_NT_HEADERS pinh = (PIMAGE_NT_HEADERS)(pidh + pidh->e_lfanew);
PIMAGE_FILE_HEADER pifh = (PIMAGE_FILE_HEADER)&pinh->FileHeader;
PIMAGE_OPTIONAL_HEADER pioh = (PIMAGE_OPTIONAL_HEADER)&pinh->OptionalHeader;
PIMAGE_SECTION_HEADER pish = (PIMAGE_SECTION_HEADER)(pinh + sizeof(IMAGE_NT_HEADERS) + (pifh->NumberOfSections - 1) * sizeof(IMAGE_SECTION_HEADER));

buffer is a byte array containing loaded executable, and pish is a pointer to the last section. For some reason, it appears that number of sections is over 20 000.

Any ideas ? Thanks in advance


Solution

  • There is one problem I see off hand: e_lfanew is the offset to the IMAGE_NT_HEADERS structure in bytes. You are adding this number of bytes to a IMAGE_DOS_HEADER pointer, so you are moving forward by sizeof(IMAGE_DOS_HEADER)*pidh->e_lfanew bytes.

    Fixed version:

    PIMAGE_DOS_HEADER pidh = (PIMAGE_DOS_HEADER)buffer;
    PIMAGE_NT_HEADERS pinh = (PIMAGE_NT_HEADERS)((BYTE*)pidh + pidh->e_lfanew);
    PIMAGE_FILE_HEADER pifh = (PIMAGE_FILE_HEADER)&pinh->FileHeader;
    PIMAGE_OPTIONAL_HEADER pioh = (PIMAGE_OPTIONAL_HEADER)&pinh->OptionalHeader;
    PIMAGE_SECTION_HEADER pish = (PIMAGE_SECTION_HEADER)((BYTE*)pinh + sizeof(IMAGE_NT_HEADERS) + (pifh->NumberOfSections - 1) * sizeof(IMAGE_SECTION_HEADER));
    

    The best way to debug problems like this is to drop into the code with your debugger and view the PE data yourself in memory. You can open up the Visual Studio hex editor for example and see all of the byte data, and which values you are actually reading out.

    Here's some information on viewing program memory in VS 2010: http://msdn.microsoft.com/en-us/library/s3aw423e.aspx