Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Module HANDLE from func ptr in Win32?

Tags:

c

winapi

I'm working on native call bindings for a virtual machine, and one of the features is to be able to look up standard libc functions by name at runtime. On windows this becomes a bit of a hassle because I need to get a handle to the msvcrt module that's currently loaded in the process. Normally this is msvcrt.dll, but it could be other variants as well (msvcr100.dll, etc) and a call to GetModuleHandle("msvcrt") could fail if a variant with a different name is used.

What I would like to be able to do is a reverse lookup, take a function pointer from libc (which I have in abundance) and get a handle to the module that provides it. Basically, something like this:

HANDLE hlibc = ReverseGetModuleHandle(fprintf); // Any func from libc should do the trick
void *vfunc = GetProcAddress(hlibc);

Is there such a thing in the win32 API, without descending into a manual walk of process handles and symbol tables? Conversely, if I am over-thinking the problem, is there an easier way to look up a libc function by name on win32?

like image 707
Whiteknight Avatar asked Jul 18 '11 14:07

Whiteknight


People also ask

How do I get a DLL handle?

'Ctrl+F' to find Handle or DLL.

What is Getmodulehandlew?

The GetModuleHandle function returns a handle to a mapped module without incrementing its reference count. However, if this handle is passed to the FreeLibrary function, the reference count of the mapped module will be decremented.

What is GetProcAddress?

GetProcAddress verifies that the specified ordinal is in the range 1 through the highest ordinal value exported in the . def file. The function then uses the ordinal as an index to read the function's address from a function table.

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.


2 Answers

MEMORY_BASIC_INFORMATION mbi;
HMODULE mod;
if (VirtualQuery( vfunc, &mbi, sizeof(mbi) ))
{
    mod = (HMODULE)mbi.AllocationBase;
}
like image 76
Joel Lucsy Avatar answered Sep 22 '22 07:09

Joel Lucsy


The documented way of obtaining the module handle is by using GetModuleHandleEx.

HMODULE hModule = NULL;

if(GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
       GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, // behave like GetModuleHandle
       (LPCTSTR)address, &hModule))
{
    // hModule should now refer to the module containing the target address.
}
like image 38
Arty Avatar answered Sep 22 '22 07:09

Arty