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:
- Avoid using new and delete operator and prefer HGLOBAL memory allocation
- Avoid dealing with thread terminations here.
Could you correct me if I am wrong, explain me if ever, or point to a technical article that would deal with these issues.
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.
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.