开发者

How does GetModuleHandle() work?

开发者 https://www.devze.com 2023-01-24 11:00 出处:网络
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

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, G开发者_开发问答etModuleHandle 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.


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


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消