Is it safe to call LoadLibrary from DllMain if you've used a kernel driver to ensure yours is the first library loaded?

StackOverflow https://stackoverflow.com/questions/13142801

Question

I've been looking at some hooking code which selectively loads a library into certain processes and then hooks certain native API functions (using Detours). The chain of events looks like this:

  • Kernel driver loads A.dll into every process.
  • A.dll::DllMain() decides whether to load B.dll (LoadLibraryEx) which contains actual Detours hooks.
  • B.dll runs for the duration of the process hooking said functions.

The second bullet here appears to break the DllMain rules specified here, but I'm trying to work out if the way the driver loads A.dll works around the limitations. Specifically, the kernel driver uses PsSetLoadImageNotifyRoutine to get notifications when each process starts and then queues an APC to call LoadLibraryEx on A.dll which means it's pretty much the first DLL loaded when the process starts. Does this circumvent the problems with calling LoadLibrary within DllMain?

Was it helpful?

Solution

Doesn't matter how the LoadLibraryEx was triggered. Once triggered, the DLL loading process is the same, and the same rules apply.

OTHER TIPS

The documentation very specifically says not to call LoadLibrary in DllMain. Even in the unlikely event that you figured out a safe way to make it work, it may not work in the next version (or even the next service pack) of Windows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top