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;
}
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.