7

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.

smwikipedia
  • 61,609
  • 92
  • 309
  • 482

3 Answers3

11

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

swatkat
  • 4,785
  • 1
  • 23
  • 17
5

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.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • No, I mean linker. The Rtl code for the linker is in user space in modern Windows. There's no need at all for it to be in the kernel. – bmargulies Nov 12 '10 at 00:53
  • 4
    I'm going to pick a slight nit at your otherwise excellent answer. It's the loader, not the linker. The loader is what maps binaries into memory and fixes them up, the linker creates binaries out of object modules. – Larry Osterman Nov 12 '10 at 05:16
4

I wanted confirm (see the answer of swatkat), that in my information the implementation of GetModuleHandle() really look inside of Wine and ReactOS (and this). You will see the implementation of GetModuleHandle(). The developers of Wine and ReactOS disassemble the code of Windows and implemented his own code based on the results of disassemble. So the code do in the most cases the same as Windows code do.

If you want you can implement your own implementation of GetModuleHandle() base of VirtualAllocEx() only. See my old answer for details. (If you not yet know the handle returned by the function GetModuleHandle() is the Address of the corresponding module in the memory, so one need just find in any way the dll in the memory of the current process).

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798