The documentation says "The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count)."
This causes a significant problem and it's unclear how to solve it. Now about the problem. Suppose we have an executable E that explicitly depends on a DLL library L1 that dynamically loads a DLL library L2 via LoadLibrary. When E finishes and the process starts terminating L2 can be unloaded before L1. This can be problematic if L1 has an object with static storage duration which contains some of the resources obtained from from L2 because those resources will start destroying at L1 unloading time which means a call to already unloaded L2 will result in a crash.
One of the possible solutions (of even the only one) is not to destroy the object with static storage duration. The drawback of this solution is that L1 can potentially be loaded/unloaded dynamically multiple times, which increases the memory leak. This can be mitigated by using DllMain where we could check whether the process terminates or the library is unloaded via FreeLibrary.
So far everything seems to work just fine. But there is more. Suppose we want L1 to be a static library that links with a DLL library named L_SHIM. So now the executable E is linked with the L_SHIM and the whole DllMain trick doesn't work anymore. Actually, nothing seems to work if we are not allowed to modify L_SHIM library.
Has anybody had to solve a problem like this? I'd appreciate any thoughts about possible solutions.