One colleague of mine has troubles during the DllMain Detach process. His bug seems not to appear in all cases, but fairly often.
While trying to help him, I kind of remembered of some usage limitations during the DllMain Attach and Detach process, but I am not sure I remember well since it was 2 year old technical discussions and it was not me working on thoses termination issues.
Namely I kind of remember that we should:
Could you correct me if I am wrong, explain me if ever, or point to a technical article that would deal with these issues.
DllMain is not mandatory. If you have some initialization code required to run when loading the dll, you should create a DllMain function, and treat the initialization there. Otherwise it's not required.
For each DLL that has not already been called with the DLL_PROCESS_ATTACH value, the system calls the DLL's entry-point function. This call is made in the context of the thread that caused the process address space to change, such as the primary thread of the process or the thread that called LoadLibrary.
It is just code and does not have an execution thread of its own. The thread execution starts in the program with main() (or WinMain). The program can choose to do all sorts of things, like loading a DLL and calling functions in it, or spawning other threads, or starting other programs and so on.
Avoid calling LoadLibrary and related APIs.
In addition to Steve's link, here are some good relevant posts from Raymond Chen's The Old New Thing:
Most problems arise due to conflicts over the loader lock. DllMain
should not be long-running, or use locks if it's avoidable.
Good background here.
Find documents with topics
[1] "Dll Main Entry Point"
[2] "Constraints of Delay Loading DLLs"
[3] "Dynamic-Link Library Best Practices"
[4] Jefrey Richter, Windows via C++, chapter 20.
(Sorry, I can not give URL references due to stackoverflow policy)
Summary
Maybe other DllMain have already been executed, maybe not. Don't call functions from other DLL's
Don't call the following things: "FreeLibrary/LoadLibrary/CreateProcess/ExitThread/GetStringType"
Don't call functions from User32.dll, Gdi32.dll
If CRT is not initialized don't use memory management functions from it (my opinion that is restricted only for initialization phase)
You should understand in which thread context you are from documentation.
It is legal to do the following: Create and initialize synchronization objects. Open, read from, and write to files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With