- Detailed how to override MSVC CRT’s initialization
Default DLL entry point _DllMainCRTStartup#
In Windows, all DLLs can contain an optional entry-point function, usually called
DllMain, that is called for both initialization and termination. This gives you an opportunity to allocate or release additional resources as needed.
Windows calls the entry-point function in four situations: process attach, process detach, thread attach, and thread detach.
- process attach When a DLL is loaded into a process address space, either when an application that uses it is loaded, or when the application requests the DLL at runtime, the operating system creates a separate copy of the DLL data
- Thread attach occurs when the process the DLL is loaded in creates a new thread
- Thread detach occurs when the thread terminates, and process detach is when the DLL is no longer required and is released by an application.
The operating system makes a separate call to the DLL entry point for each of these events, passing a reason argument for each event type. For example, the OS sends
DLL_PROCESS_ATTACH as the reason argument to signal process attach.
The VCRuntime library provides an entry-point function called
_DllMainCRTStartup to handle default initialization and termination operations
On process attach, the
- sets up buffer security checks
- initializes the CRT and other libraries
- initializes run-time type information
- initializes and calls constructors for static and non-local data
- initializes thread-local storage, increments an internal static counter for each attach
- and then calls a user- or library-supplied
DllMainOn process detach, the function goes through these steps in reverse.
- It calls
- decrements the internal counter
- calls destructors
- calls CRT termination functions and registered
- notifies any other libraries of termination
When the attachment counter goes to zero, the function returns
FALSEto indicate to Windows that the DLL can be unloaded. The
_DllMainCRTStartupfunction is also called during thread attach and thread detach. In these cases, the VCRuntime code does no additional initialization or termination on its own, and just calls
DllMainto pass the message along If
FALSEfrom process attach, signaling failure,
DllMainagain and passes
DLL_PROCESS_DETACHas the reason argument, then goes through the rest of the termination process.