Why you shouldn’t touch things in DllMain

One topic that comes up on the Microsoft newsgroups every once and awhile is whether it is really that bad to be doing complicated things in DllMain.

The answer I almost always give is yes, you should always stay away from that.

This is a particularly insidious topic, as many people do things in DllMain anyway, despite MSDN’s warnings to the contrary, see that it seems to work on their computer, and ship it in their product / program / whatever.  Unfortunately, this often ends up with hard to debug problems that only fail on a particular customer computer – the kind that you really don’t want to get stuck debugging remotely.  The reason for this is that many of the things that can go wrong in DllMain are environment specific.  This is because depending on whether a particular DLL that you are calling inside of DllMain when you break the rules is loaded your DLL was loaded or not will often make the difference.

If you dynamically load a DLL in DllMain and it has not already been loaded yet, you will get back a valid HMODULE, but in reality the initializer function for the new DLL will not be called until after your DllMain returns.  However, if the DLL had already been loaded by something else and your LoadLibrary call just incremented a reference count, then DllMain has already been called for the DLL.  Where this gets ugly is if you call a function that relies on some state setup by DllMain, but on your development/test boxes, the DLL in question had already been loaded for some reason.  If on a customer computer, you end up being the first to load the DLL, you’ll have mysterious corruption and/or crashes resulting from this which never repro in the lab for you.

So, stay away from complicated things in DllMain.  There are other reasons too, but this is the big one for current OS releases (of course, Vista and future versions may add other things that can go wrong if you break the rules).

If you are interested, Michael Grier has an excellent series on this topic to help you understand just what can go wrong in DllMain.

Comments are closed.