Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GetModuleHandle() work?

Tags:

windows

I am reading < windows via c/c++ >, it describes GetModuleHandle() API as below:

When you call this function, you pass a zero-terminated string that specifies the name of an executable or DLL file loaded into the calling process's address space. If the system finds the specified executable or DLL name, GetModuleHandle returns the base address where that executable or DLL;s file image is loaded.

I am wondering where does the system look for the file name? When I loaded some file into my process address space, is there some centralized table to store the mapping of all the loaded files' names and their load addresses? If we search based on a string match, is it kind of low efficiency?

Many thanks for your insigts.

like image 664
smwikipedia Avatar asked Nov 12 '10 00:11

smwikipedia


People also ask

What is Hmodule?

HMODULE. A handle to a module. The is the base address of the module in memory. HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.

What is module handle?

In fact the module handle is nothing more than the base address of the module. From which the preceding statement can be inferred.


2 Answers

The loaded module info is maintained as a linked list in process' PEB, in a struct named PEB_LDR_DATA. If you get the PEB pointer, you can traverse through this list and get information like DLL name, base address, entry point, size etc. Check out these pages:
http://msdn.microsoft.com/en-us/library/aa813708.aspx
http://www.codeproject.com/KB/threads/CmdLine.aspx

like image 86
swatkat Avatar answered Oct 26 '22 01:10

swatkat


It looks in the loader (the Windows name for the dynamic linker)'s internal data structure.

GetModuleHandle only works for DLLs that you have loaded in the current process. Whenever the loader loads a DLL into the process, it of course maintains a data structure that includes the module's name. No need to visit the file system.

LdrInitializeThunk runs in user space to start the process of pulling in the DLLs.

like image 33
bmargulies Avatar answered Oct 25 '22 23:10

bmargulies