Search code examples
windowsportable-executable

reading PE32+ section's raw data


I'm trying to read the .pdata section of a x64 exe. I'm mapping the file to the memory, finding the .pdata section, and then I use it's PointerToRawData to get to the actual data of the section...
But then my "pdata" pointer points at a illegal address :(
This is what I do:

void* mappingHandle = CreateFileMapping(fileHandle,
                    NULL,
                    PAGE_READONLY,
                    0,
                    1,
                    NULL);
char* fileMemory  = (char*)MapViewOfFile(mappingHandle, FILE_MAP_READ, 0, 0, 1);
IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)fileMemory;
IMAGE_SECTION_HEADER* pdataSectionHeader = NULL;
if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) // "MZ" signature
{
    IMAGE_NT_HEADERS* ntHeaders = (IMAGE_NT_HEADERS*)(fileMemory + dosHeader->e_lfanew);
    if (ntHeaders->Signature == IMAGE_NT_SIGNATURE) // Supposed to be "PE"
    {
        unsigned int sectionCount = ntHeaders->FileHeader.NumberOfSections; 
        IMAGE_SECTION_HEADER* sectionHeaders = IMAGE_FIRST_SECTION(ntHeaders);
        pdataSectionHeader = sectionHeaders + 3; // Going to .pdata section.
    }
}
unsigned long pdataSize = pdataSectionHeader->SizeOfRawData;
char* pdata = fileMemory + pdataSectionHeader->PointerToRawData; 

can anybody tell me what I doing wrong?


Solution

  • The problem was in the way I mapped the file to the memory.
    I should have done it this way:

    void* mappingHandle = CreateFileMapping(fileHandle,
                        NULL,
                        PAGE_READONLY,
                        0,
                        0, //Here: 0 instead of 1
                        NULL);