How to get HANDLE module from func ptr in Win32?

I am working on binding my own calls to a virtual machine, and one of the possibilities is the ability to search for standard libc functions by name at runtime. In windows this becomes a bit of a hassle because I need to get the handle to the msvcrt module that is currently loaded into this process. Usually it is msvcrt.dll, but it can be other options (msvcr100.dll, etc.), and the call to GetModuleHandle ("msvcrt") may fail if a variant with a different name is used.

What I would like to do is reverse the search, take a pointer to a function 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 that does not fall into the manual handle of process handlers and symbol tables? And vice versa, if I think too much about the problem, is there an easier way to search for the libc function by name on win32?

+7
c winapi
Jul 18 2018-11-18T00:
source share
3 answers
 MEMORY_BASIC_INFORMATION mbi; HMODULE mod; if (VirtualQuery( vfunc, &mbi, sizeof(mbi) )) { mod = (HMODULE)mbi.AllocationBase; } 
+8
Jul 18 2018-11-18T00:
source share

In fact, there is a documented way to get the module load address using the :: GetModuleHandleEx () API. The only possible drawback of this feature is that it is not supported on Win2K, which currently cannot be an obstacle. Here is an example:

 HMODULE hmodule = NULL; ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast<LPCTSTR>(address), &hmodule); // hmodule should now refer to the module containing the target address. 

For reference: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683200(v=vs.85).aspx

UPD: you can also specify the GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT flag to avoid blocking semantics in the found module.

+14
Aug 13 2018-12-12T00:
source share

Unfortunately, you will have to go through the modules as you feared. It's not so bad. Here is the idea, some code is written in notepad:

 MODULEENTRY32 me = {0}; HANDLE hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, 0 ); me.dwSize = sizeof me; Module32First( hSnapshot, &me ); if( me.modBaseAddr <= funcPtr && ( me.modBaseAddr + me.modBaseSize ) > funcPtr ) { ... break; } do { } while( Module32Next( hSnapshot, &me ) ); CloseHandle( hSnapshot ); 
0
Jul 18 2018-11-18T00:
source share



All Articles