I used to unload an injected library by calling FreeLibraryAndExitThread
from a thread that was created using CreateThread
.
The need to unload the library from a different thread rendered this approach impossible. Now I'm using TerminateThread
(as it doesn't terminate the thread it's called from, but the one that is passed) and FreeLibrary
separately. However as the WinAPI docs suggest this creates a "race condition" and crashes the process. Is there any way to fix this?
Old code:
HMODULE g_hModule{ NULL };
BOOL WINAPI DllMain(HMODULE hModule, DWORD fwdReason, LPVOID lpReserved) {
g_hModule = hModule;
if (fwdReason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hModule);
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)main, 0, 0, 0);
}
return TRUE;
}
void Unload(int nExitCode) {
FreeLibraryAndExitThread(g_hModule, (DWORD)nExitCode);
}
New code:
HMODULE g_hModule{ NULL };
HANDLE g_hThread{ NULL };
BOOL WINAPI DllMain(HMODULE hModule, DWORD fwdReason, LPVOID lpReserved) {
g_hModule = hModule;
if (fwdReason == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hModule);
g_hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)main, 0, 0, 0);
}
return TRUE;
}
void Unload(int nExitCode) {
TerminateThread(g_hThread, (DWORD)nExitCode);
FreeLibrary(g_hModule);
}
Thanks in advance for any help!