Things you shouldn’t do, part 1 – DllMain is special

A lot of people have written about things not to do in your DllMain.  Like here, and here and here.

One other thing not to do in your DllMain is to call LoadLibraryEx.  As others have written, DllMain’s a really special place to be.  If you do anything more complicated than initializing critical sections, or allocating thread local storage blocks, or calling DisableThreadLibraryCalls, you’re potentially asking for trouble.

Sometimes, however the interaction is much more subtle.  For example, if your DLL uses COM, you might be tempted to call CoInitializeEx in your DllMain.  The problem is that that under certain circumstances, CoInitializeEx can call LoadLibraryEx.  And calling LoadLibraryEx is one of the things that EXPLICITLY is forbidden during DllMain (You must not call LoadLibrary in the entry-point function).


Comments (5)

  1. Anonymous says:

    CoInitializeEx is amazingly wrong in DllMain because it’s not your thread. COM initialization is a per-thread concept. DLL_PROCESS_ATTACH and DLL_PROCESS_DETACH do not necessarily occur on the same thread. And you aren’t going to get DLL_THREAD_ATTACH for pre-existing threads and you’re not going to get DLL_THREAD_DETACH for threads that exist when you unload.

    In other words, there is no way you can do this correctly. Which is good because you’re not supposed to do it at all anyway.

  2. Anonymous says:

    Would it make much sense to have a processor before compiling to warn about "obvious stupidities" along with a link to explain why it is so. I mean about stupidities regarding to higher level concepts than just syntax/language related things.

  3. Anonymous says:

    Funny you should mention that 🙂

    We’ve got an internal tool called "prefast" that does many of these checks:

    I believe that this is one of the prefast warnings. Having said that, you’d be surprised at the number of times people make this mistake – both inside and outside Microsoft.

Skip to main content