Usage limitations during the DllMain Attach and De

2019-01-25 15:52发布

问题:

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.

回答1:

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:

  • http://blogs.msdn.com/b/oldnewthing/archive/2004/01/27/63401.aspx
  • http://blogs.msdn.com/b/oldnewthing/archive/2004/01/28/63880.aspx
  • http://blogs.msdn.com/b/oldnewthing/archive/2007/09/04/4731478.aspx
  • http://blogs.msdn.com/b/oldnewthing/archive/2010/01/15/9948740.aspx


回答2:

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.



回答3:

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

  1. Maybe other DllMain have already been executed, maybe not. Don't call functions from other DLL's

  2. Don't call the following things: "FreeLibrary/LoadLibrary/CreateProcess/ExitThread/GetStringType"

  3. Don't call functions from User32.dll, Gdi32.dll

  4. If CRT is not initialized don't use memory management functions from it (my opinion that is restricted only for initialization phase)

  5. You should understand in which thread context you are from documentation.

  6. It is legal to do the following: Create and initialize synchronization objects. Open, read from, and write to files.



标签: c++ winapi dll mfc