Why not call the FreeLibrary function from the entry point function?

I am writing a DLL that needs to call a separate DLL dynamically several times. I would like to save the download and then just unload it when my DLL is unloaded. But, according to Microsoft, a bad idea .

The entry point function should perform simple initialization tasks and should not call any other loading or terminating DLL. For example, in an entry point function, you should not directly or indirectly call the LoadLibrary function or the LoadLibraryEx function. Additionally, you should not call FreeLibrary when the process is terminating.

Here is the abusive code. Can someone explain why I should not call LoadLibrary and FreeLibrary from my DLL entry point?

BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_DETACH : if (hLogLib != NULL) FreeLibrary(hLogLib); break; } return TRUE; } 
+4
source share
3 answers

I think I found the answer .

The entry point function should only perform simple initialization or completion tasks. It should not call the LoadLibrary or LoadLibraryEx function (or the function that calls these functions), as this can create dependency cycles in the DLL load order. This may cause the dll to be used before the system executes its initialization code. Likewise, the login function should not call the FreeLibrary function (or the function that calls FreeLibrary) during the process termination, as this may lead to the use of the DLL after the system has executed the completion code.

+4
source

You cannot call LoadLibrary from your entry point, because the DllMain function is executed inside the OS loader lock, and any attempts to re-capture this loader lock (for example, by calling LoadLibrary) will lead to a deadlock.

+2
source

Do not do anything because of the consequences inside DLLMain. Jokes aside. The FreeLibrary call is even worse because it will only sometimes be a dead end if it happens that your free refcount decrement is zero and the library is actually freed.

+1
source

All Articles