0
votes

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
It doesn't mention ntdll.dll because it is an intentionally undocumented DLL. It contains the user mode code for the native operating system. Calling LoadLibrary() for it could never be a problem since a program cannot start without ntdll. Although a guarantee is hard to come by, it is undocumented ;) Whether calling an undocumented function from ntdll in DllMain() is a problem is something you'll have to find out the hard way, you didn't document the undocumented one you are trying to call.Hans Passant
Thanks, I guess that counts as an answer...Roland Pihlakas

1 Answers

0
votes

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.