Questions about DLLMain and the loader lock

Best Practices for Creating DLLs – A document from Microsoft –
have a discussion about the loader and the loader lock, there’re
so many things you can’t do in DLLMain.

“DLLs often have complex interdependencies that implicitly define
the order in which they must be loaded. The library loader
efficiently analyzes these dependencies, calculates the correct
load order, and loads the DLLs in that order.”

“Use the memory management function from the dynamic C Run-Time
(CRT). If the CRT DLL is not initialized, calls to these functions
can cause the process to crash.”

Q1: If your DLL depends on CRT DLL, then the correct load order is
CRT DLL load first(and be initialized first), so why CRT DLL is
not initialized ? How it happens ? A lot of C++ projects are using
global objects, singletons, they will be initialized when loader
calls the entry point, operator new and malloc will be used to
allocate memory. Is it not safe ?

I have a DLL module – a kind of profiler, it will sends some
profiling data to a server via socket. If there is no data, it
doesn’t initialize the socket. So WSAStartup is called only at the
first time that data generated. This DLL works very well. Until
one day, WSAStartup is failed, because profiling data is generated
from a global object of a DLL – WSAStartup function should not be
called from the DllMain function in a application DLL
– It’s hard
to think.

Q2: How do I know if my function is called from DLLMain ? Is it
knowable about the loader lock is currently locked or not ?

If I know it, maybe I could do some deferred initialization.

Source: dll

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.