Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get pointer to IMAGE_DOS_HEADER with GetModuleHandle?

Tags:

c++

c

windows

I am trying to get the image base of my process once it is loaded in memory. From my understanding, you can call GetModuleHandle to get the image base. My question is, does the handle returned essentially point to the IMAGE_DOS_HEADER struct such that you could do the following:

PIMAGE_DOS_HEADER DosHeader;
DosHeader = (PIMAGE_DOS_HEADER)GetModuleHandle(NULL);

If this is not correct, what other method could you use?

like image 541
Chris Avatar asked Dec 08 '25 20:12

Chris


2 Answers

This is correct, though if you want the module handle of of a dll you need to specify its path. Otherwise you will get the handle to the process exe. You should also check the returned HMODULE first to see that its valid.

An example of how to get the virtual size of the module:

std::size_t GetModuleSize(const char* szModule)
{
    HMODULE hModule = GetModuleHandle(szModule);
    if(hModule == NULL) return 0;
    IMAGE_DOS_HEADER* pDOSHeader = (IMAGE_DOS_HEADER*)hModule;
    IMAGE_NT_HEADERS* pNTHeaders =(IMAGE_NT_HEADERS*)((BYTE*)pDOSHeader + pDOSHeader->e_lfanew);
    return pNTHeaders->OptionalHeader.SizeOfImage;
}

you'll notice I use IMAGE_DOS_HEADER* and not PIMAGE_DOS_HEADER as I find that more readable and clear.

like image 139
Necrolis Avatar answered Dec 11 '25 08:12

Necrolis


With Microsoft's compiler and linker, you can use

extern "C" IMAGE_DOS_HEADER __ImageBase;
like image 26
user9004592 Avatar answered Dec 11 '25 08:12

user9004592