c00000fd
c00000fd

Reputation: 22255

Can I find an offset of a resource in an EXE file with C++?

I'm writing a custom module that checks EXE files for consistency (which is not a part of this question.) For that I need to know an offset of a certain resource in the EXE file to calculate the size of the EXE file body that I need to check.

I came up with the following code to get an offset of the IDR_HTML_DLG resource in the strExeFilePath file:

int ncbOffsetInBytes = 0;
HMODULE hModule = LoadLibrary(strExeFilePath);
if(hModule)
{
    HRSRC hRes = ::FindResource(hModule, MAKEINTRESOURCE(IDR_HTML_DLG), RT_HTML);
    if(hRes)
    {
        long szLength = ::SizeofResource(hModule, hRes);
        HGLOBAL hGlobal = ::LoadResource(hModule, hRes);
        if(szLength && hGlobal)
        {
            BYTE* pData = (BYTE*)LockResource(hGlobal);
            DWORD dwLast = (DWORD)(pData + szLength);
            DWORD dwFirst = (DWORD)hModule;

            ncbOffsetInBytes = dwLast - dwFirst;
        }
    }

    ::FreeLibrary(hModule);
    hModule = NULL;
}

But the result in ncbOffsetInBytes turns out larger than the EXE file itself. Any idea how to correct it?

Upvotes: 0

Views: 1664

Answers (1)

Michael
Michael

Reputation: 1136

As @rodrigo points out, when a PE file is loaded into memory each of the relevant sections will be loaded into different memory sections, with padding between each section, and the offsets of sections, as well as the size of the module itself, will be different that the PE file on disk. There is some information on how this works here.

As I see it there are two ways you could do what you're trying to do.. You either need to take into account the size of the PE in memory and base your calculations on that - I believe the SizeOfImage member of IMAGE_OPTIONAL_HEADER gives the image size as loaded into memory. The other option would be to continue to use the size of the PE file on disk, in which case you could load the PE file into memory as a data file (rather than using LoadLibrary) and work in it from there. In this case, if you need to retrieve the offset of resources etc from the file you will probably need to manually parse and crawl the PE file structure - there is an excellent reference for this structure here.

Upvotes: 2

Related Questions