Why not call FreeLibrary from entry point function?

寵の児 提交于 2019-12-14 04:18:30

问题


I'm writing a DLL that needs to call a separate DLL dynamically multiple times. I would like to keep the callee loaded and then just unload it when my DLL is unloaded. But according to Microsoft, that's a bad idea.

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

Here's the offending code. Can somebody explain why I shouldn't call LoadLibrary and FreeLibrary from my DLL's 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;
}

回答1:


I think I've found the answer.

The entry-point function should perform only simple initialization or termination tasks. It must not call the LoadLibrary or LoadLibraryEx function (or a function that calls these functions), because this may create dependency loops in the DLL load order. This can result in a DLL being used before the system has executed its initialization code. Similarly, the entry-point function must not call the FreeLibrary function (or a function that calls FreeLibrary) during process termination, because this can result in a DLL being used after the system has executed its termination code.




回答2:


You can't call LoadLibrary from your entry point because the DllMain function runs inside an OS loader lock and any attempts to reacquire that loader lock (for instance, by calling LoadLibrary) will result in deadlock.




回答3:


Don't do anything of consequence inside of DLLMain. Seriously. Calling FreeLibrary is even worse because it'll only sometimes deadlock, if it happens that your free decrements the refcount to zero and the library is actually freed.



来源:https://stackoverflow.com/questions/1903008/why-not-call-freelibrary-from-entry-point-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!