Udostępnij za pośrednictwem


The NT DLL Loader: FreeLibrary()

Let's review the loader's modus operandi and derive the (once again simple!) rules for what the heck is going on.

When someone calls FreeLibrary(hInstance), the loader walks the closure of the dependencies for the module/instance in question and if their refcounts are not maxxed out ("pinned"), they are decremented.  Any modules whose refcounts are now zero are marked for unload.  This means that the loader finds all of those modules in the in-initialization-order list and runs their DLL_PROCESS_DETACH callouts in the opposite order of initialization.  Notice that the return value from DllMain() is ignored for DLL_PROCESS_DETACH - you cannot do anything which could fail.  After shutting down all those DLLs, they are unmapped and FreeLibrary() returns.

Notice that the ordering dragon reared its head again but also notice that as long as your init order made sense, it's very likely that your uninit order makes sense also so you tend not to hit so many problems here w.r.t. ordering.  Most LoadLibrary()/FreeLibrary() ordering issues are found in the LoadLibrary() path, not the unload path.  (In fact I can't recall a single instance of FreeLibrary() inducing a DLL_PROCESS_DETACH [basic] ordering issue.  Not that you can't imagine it but I can't recall ever having such a problem and as you know I like to talk about problems.)

Reentrancy problems tomorrow...  Just imagine, given this information, what happens if someone calls LoadLibrary() during DLL_PROCESS_DETACH...

Comments

  • Anonymous
    June 29, 2005
    The comment has been removed

  • Anonymous
    June 30, 2005
    > Most LoadLibrary()/FreeLibrary() ordering issues are found in the LoadLibrary() path, not the unload path.

    There seem to be ordering issues during process termination when a dll is loaded dynamically.

  • Anonymous
    July 20, 2005
    The comment has been removed

  • Anonymous
    August 01, 2005
    > Reentrancy problems tomorrow...

    If you need help making time go faster, see Larry Osterman's blog from last week.

  • Anonymous
    October 07, 2006
    Every programmer who ventures beyond his / her first hello world application has to deal with DLLs sooner

  • Anonymous
    September 11, 2008
    I found this list of article on Raymond's blog . Raymond's blog is one of the more interesting