Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address range of a dynamically loaded library under Windows

I have a working program that loads plugins with LoadLibrary.

New requirement: at some point in the code, I'm given a pointer, and I need to test whether this pointer points into the code or static data of a plugin.

bool is_pointer_into_plugin(void *p, HMODULE h);

Equivalently, I need to retrieve the plugin into which a pointer points, if any. I also need to know if the pointer points into the main program's code or static data (and ideally, distinguish between read-only and read-write areas).

HMODULE plugin_containing_pointer(void *p);

Equivalently, I need to be able to retrieve the extent (address and size) at which a plugin is mapped. I also need this information for the main program.

How can I implement is_pointer_into_plugin, or plugin_containing_pointer, or something equivalent?

I can change the call to LoadLibrary if necessary. The lookup should be reasonably fast as possible, the load-time code doesn't need to be fast. Running the plugins in separate processes and communicating through shared memory is not an option. The program must run on Windows XP and up (and Linux, but that's another question).

The information I need is more or less what the Sysinternals utility listdlls reports, so I tried to find out how it's implemented. I saw a suggestion of using NtQueryInformationProcess to retrieve a PEB structure which links to a LDR_DATA_TABLE_ENTRY. Looks promising, but:

  • I can see a DllBase which looks like it might be the starting address of each DLL (is it?), but no size.
  • The documentation of NtQueryInformationProcess marks it as unportable, but doesn't suggest an alternative for what I'm trying to do.
  • On my system, the only fields in PEB are BeingDebugged and SessionId, plus some ReservedN byte arrays — not a good sign.

How can I enumerate the address range of the plugins, or test whether a pointer is within a plugin, or determine which plugin a pointer points into?

like image 666
Gilles 'SO- stop being evil' Avatar asked Oct 07 '22 12:10

Gilles 'SO- stop being evil'


1 Answers

GetModuleHandleEx with the GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS flag will tell you which module a pointer points into. From that you can study the module headers to figure out which section. But the entire exercise smells funny. Why do you care which plugin a pointer points to?

like image 55
Raymond Chen Avatar answered Oct 10 '22 02:10

Raymond Chen