-->

Loading/calling ntdll from DllMain

2019-08-27 20:18发布

问题:

One should not use functions other than those in kernel32.dll from DllMain:

From MS documentation:

Because Kernel32.dll is guaranteed to be loaded in the process address space when the entry-point function is called, calling functions in Kernel32.dll does not result in the DLL being used before its initialization code has been executed. Therefore, the entry-point function can call functions in Kernel32.dll that do not load other DLLs. For example, DllMain can create synchronization objects such as critical sections and mutexes, and use TLS. Unfortunately, there is not a comprehensive list of safe functions in Kernel32.dll.
...
Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.

My question:
But the documentation does not mention ntdll.dll. - Can I call LoadLibrary for "ntdll" and use functions in ntdll from DllMain:
1) during DLL_PROCESS_ATTACH (load and use functions of ntdll)?
2) during DLL_PROCESS_DETACH (use functions of previously loaded ntdll)?


Also, please, would somebody with 1500+ reputation like to create a new tag titled "dllmain" ?

回答1:

The answer to the question "is it safe in DllMain" always defaults to "no". In this case, calling LoadLibrary is never okay.

Generally speaking, calling anything in ntdll.dll is not recommended even places where it is safe to do so.