How to start a thread in DLLMain?

ⅰ亾dé卋堺 提交于 2020-06-13 12:27:44

问题


How can I start a thread in DLLMain means std :: thread - fundamentally. No means WinApi, and STL means. When I run the function in the flow, then I crash the application is called from this DLL. Thank you in advance.

This code gets the hash sum on the file (exe) and writes it to a file. (* .txt). But the application crash

void initialize()
{
    string buffer;
    thread t(calclulateHash, ref(buffer));
    t.detach();
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            initialize();
            break;
        }
    }
    return true;
}

回答1:


There are limitations on DllMain().

You shouldn't do any blocking calls in DllMain, because it is called from OS loader. Locking loader may prevent some thread to start and in general leads to bad things. Locking of any kind. If you are trying to acquire a lock that is currently held by a thread that needs OS loader lock (which you are being holding while executed from it), you’ll deadlock in best case scenario. Starting threads isn't allowed, because when you start thread.. you call this DllMain again through OS loader, but with DLL_THREAD_ATTACH parameter now. It leads to the same deadlock or illegal concurrent access to uninitialized memory of this module.

Calls to LoadLibrary/LoadLibraryEx are explicitly prohibited, because that requires OS loader lock. Other calls into kernel32 are fine, you can’t call into User32. And don’t use CRT memory management (unless you are linked statically), anything that calls to dynamic C runtime at all – use HeapAlloc and similar API instead. You'll cause call to SxS runtime library otherwise. You can't read the registry either. Any cross-binary calls are UB, the binary you've called into may not have been initialized or have already been unutilized.

Have a nice day.




回答2:


1 DllMain -> 2 New thread -> 3 call DllMain again with DLL_THREAD_ATTACH -> 4 without check, so New thread again -> 5 call DllMain again with DLL_THREAD_ATTACH; just like step 3;



来源:https://stackoverflow.com/questions/41354455/how-to-start-a-thread-in-dllmain

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