Why am I getting the "LoaderLock was detected" warning when debugging?

DenaliHardtail picture DenaliHardtail · May 20, 2009 · Viewed 21.2k times · Source

I'm developing an add-on for AutoCAD 2009. The project output is a class library. When I attempt to debug and load the class library, I get this "LoaderLock was detected message." I've been writing these add-ons for awhile and this is the first message of this type I've seen.

  1. Where do I start trying to figure this out?
  2. What is LoaderLock and why is it bothering me now?

LoaderLock was detected Message: Attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

I went to Debug -> Exceptions -> "Managed Debugging Assistants", found "LoaderLock" and unchecked the "Thrown" checkbox.

I can debug again but what did I do and why did I have to do it? Will this cause other problems for me?

Answer

Michael picture Michael · May 20, 2009

The loader lock is a process-wide lock used by the system to synchronize access to loading DLL's into a process address space. Functions that load DLL's, free DLL's, query DLL info, etc., all acquire the loader lock. What typically impacts developers the most is that the loader lock is held while DllMain is running as well - this means that an OS lock that you aren't normally aware of can be held while running your code.

The loader lock can be viewed as being at a very low level in the lock-hierarchy. Code running under the loader lock during DllMain can be the cause of deadlocks. For instance, the CLR has its own set of internal locks which it could hold while loading DLL's. If you call managed code from within your DllMain, you could cause the CLR on your thread to acquire one of these locks while holding the loader lock. If the CLR on another thread had acquired that lock (causing the origin thread in DllMain to block) and then tried to load a DLL which would acquire the loader lock, your process would deadlock.

It sounds like the CLR is trying to preemptively detect running managed code under the loader lock. When you see the stack from this failure in the debugger, identify what is causing your managed code to be running from within a DllMain and remove it.