Search code examples
filec++11dllioportable-executable

How to properly get contents of DLL file for PE parsing?


I'm trying to get the RVA of a function in kernel32.dll which means I need to use the offsets to find different structures in the file until I can get the IMAGE_EXPORT_DIRECTORY structure. However I know a lot of methods and ways of getting the contents of files interpret and leave certain characters and stuff out which would make this a nearly impossible task. So I want to know the best way to go about getting the contents of a dll file to copy into a character array.

Update: For anyone interested I created a function for mapping the dll into memory.

void* GetFileImage(char path[])
{
    HANDLE hFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
    if(hFile == INVALID_HANDLE_VALUE){return NULL;}

    HANDLE file_map = CreateFileMapping(hFile, NULL, PAGE_READONLY|SEC_IMAGE, 0, 0, "KernelMap");
    if(file_map == INVALID_HANDLE_VALUE){return NULL;}

    LPVOID file_image = MapViewOfFile(file_map, FILE_MAP_READ, 0, 0, 0);
    if(file_image == 0){return NULL;}

    return file_image;
}

Solution

  • There are multiple ways. Not that many multiple, though.

    1.If you are trying to parse a system loaded file such as kernel32.dll which are loaded into memory on system startup, you can directly use GetModuleHandle to grab the loaded base address and start parsing through PE (assuming you are familiar with the PE structure and static/delay loading of dlls and its exports).

    2.If the dll you are trying to parse is not one of the system loaded, you can load them using LoadLibrary, which will return you the loaded base address, thus enabling you to parse the PE.

    3.You can also do CreatFileMapping/MapViewOfFile to map the dll in your own virtual memory to parse.

    The msdn article suggested by @David Thomas will be of great help:: Peering Inside the PE