CRT and DLLMain Initialization

Quotes:

From the document "Best Practices for Creating DLLs" http://download.microsoft.com/download/a/f/7/af7777e5-7dcd-4800-8a0a-b18336565f5b/DLL_bestprac.doc Microsoft:

"DLLs often have complex interdependencies that implicitly determine the order in which they should be loaded. The loader library efficiently analyzes these dependencies, calculates the correct load order, and loads the DLLs in order." [1]

"(in DLLMain) Use the memory management function from dynamic C Run-Time (CRT). If the CRT DLL is not initialized, calls to these functions may cause the process to crash." [2]

From MSDN: http://msdn.microsoft.com/en-us/library/988ye33t.aspx

"The _DllMainCRTStartup function performs several actions, including calling _CRT_INIT, which initializes the C / C ++ runtime library and calls the C ++ constructors of static, non-local variables. Without this function, the time library will be left in an uninitialized state. [3]

"In addition to initializing the C runtime library, _DllMainCRTStartup calls a function called DllMain." [4]

Questions:

If your DLL depends on the CRT DLL, based on [1] , the CRT DLL will be loaded first (initialized first), so how can it be [2] ?

Based on [3] and [4], _DllMainCRTStartup will call _CRT_INIT, which initializes the CRT, so how can it be [2] ?

If the executable downloads your DLL using "Implicit binding", _DllMainCRTStartup (and DLLMain) of your DLL is called before entering the point (mainCRTStartup or WinMainCRTStartup) of the executable based on [3] - _DllMainCRTStartup calls _CRT_INIT, which initializes CRT, and then mainCRTS too, so what really happened to the CRT?

If your DLL is loaded before mainCRTStartup, is calling CRT functions inside DLLMain or other export functions safe or not?

Who will actually initialize the dll on CRT?

+2
source share
1 answer

You work on the assumption that the entry point for the DLL is always _DllMainCRTStartup . This is not the case; it is just the default linker. This may be all that the programmer wants it to be quickly and easily changed using the linker / ENTRYPOINT option. Microsoft cannot do anything to prevent this. Not a good practice, indicating that this was the point of this document.

Thus, failure [2] is easily caused if such a custom entry point also does not explicitly initialize the CRT. This not only includes initializing the state of the CRT environment, but also includes initializing the global state of the DLL, for example, calling C initializers, C ++ static object constructors, and distributing local variables. Something that the CRT DLL version cannot do. Keep in mind that _DllMainCRTStartup and _CRT_INIT are associated with the DLL itself, this code is not in the DLL version of CRT.

The dynamic native CRT execution state is initialized by the CRT DLL's own entry point, the Windows boot loader ensures that it runs first.

+7
source

Source: https://habr.com/ru/post/1274765/


All Articles