extern "C" DLL_PUBLIC void MHUD2_Start() { try { QUEUE_LOG(mhud2::Log::LOG_INFO, "MissingHUD2 injected and starting."); // Initialize any static objects we require that don't involve an OpenGL context DLLPreferences::GetInstance(); ResourceLoader::Initialize(dll_handle); MemReader::GetMemoryReader(); // Hook the OpenGL SwapBuffers function via IAT redirection GDISwapBuffers *gdi_swapbuffers = GDISwapBuffers::GetInstance(); IATHook::InitIATHook(GetModuleHandleW(WCHAR_ISAAC_MODULE_NAME), "gdi32.dll", "SwapBuffers", (LPVOID)&gdiSwapBuffersDetour); // Enable the IAT hooks IATHook::EnableIATHook("SwapBuffers", (LPVOID*)gdi_swapbuffers->GetEndpointAddr()); } catch (std::runtime_error &e) { QUEUE_LOG(mhud2::Log::LOG_ERROR, "Error occured during MHUD2 initilization: " + std::string(e.what())); FreeLibraryAndExitThread(dll_handle, EXIT_FAILURE); } catch (boost::interprocess::interprocess_exception &ie) { FreeLibraryAndExitThread(dll_handle, EXIT_FAILURE); } }
extern "C" DLL_PUBLIC void MHUD2_Stop() { QUEUE_LOG(mhud2::Log::LOG_INFO, "MissingHUD2 exiting."); // Tell our SwapBuffers detour to cleanup it's OpenGL stuff GDISwapBuffers *gdi_swapbuffers = GDISwapBuffers::GetInstance(); gdi_swapbuffers->WaitForCleanup(); try { // Disable IAT hooks IATHook::DisableIATHook("SwapBuffers"); // Wait for the hooks to be no longer active // aka. for Rebirth to exit our detours for the last time std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // Clean-up global static objects DLLPreferences::Destroy(); GDISwapBuffers::Destroy(); ResourceLoader::Destroy(); MemReader::Destroy(); MHUD::MsgQueue::Destroy(MSG_QUEUE_DLL_TO_APP); } catch (std::runtime_error &e) { QUEUE_LOG(mhud2::Log::LOG_ERROR, "Error occured during MHUD2 cleanup: " + std::string(e.what())); FreeLibraryAndExitThread(dll_handle, EXIT_FAILURE); } // Exit our DLL, Rebirth should be a lot less informative now! FreeLibraryAndExitThread(dll_handle, EXIT_SUCCESS); }
DWORD WINAPI SuicideCheck(LPVOID lpThreadParameter) { Sleep(5000); //todo: Figure out a way to detect how to close. //if (shouldKillMyself()) { //pipe:=CreateFile(pchar('\\.\pipe\'+pipename), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0); WCHAR datapipename[256]; swprintf(datapipename, 256,L"\\\\.\\pipe\\cemonodc_pid%d", GetCurrentProcessId()); HANDLE pipe; pipe=CreateFileW(datapipename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if ((pipe) && (pipe!=INVALID_HANDLE_VALUE)) { unsigned char command=MONOCMD_TERMINATE; DWORD bw; WriteFile(pipe, &command, 1, &bw, NULL); return 0; } else { TerminateThread(DataCollectorThread, -1); FreeLibraryAndExitThread(g_hInstance, -1); } } }
DWORD WINAPI DataCollectorEntry(LPVOID lpThreadParameter) { CPipeServer *pw; #ifdef NDEBUG ZWSETINFORMATIONTHREAD ZwSetInformationThread=(ZWSETINFORMATIONTHREAD)GetProcAddress(GetModuleHandleA("ntdll.dll"), "ZwSetInformationThread"); if (ZwSetInformationThread) { int r=ZwSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, NULL, 0); if (r!=0) { OutputDebugStringA("No debug safety"); } } #endif pw=new CPipeServer(); pw->Start(); DataCollectorThread=0; delete pw; if (SuicideThread) TerminateThread(SuicideThread, 0); Sleep(1000); FreeLibraryAndExitThread(g_hInstance, 0); return 0; }
DWORD WINAPI thread_function(LPVOID param) { everquest_chat_helper_write_chat_text(APPLICATION_NAME " loaded."); Sleep(1000); while (1) { if (everquest_function_is_in_game() == false) { Sleep(100); continue; } if (mem.is_foreground_window_current_process_id() == true) { if ( (KEYDOWN(VK_CONTROL)) && (KEYDOWN(VK_ALT)) && (KEYDOWN(VK_BACK)) ) { break; } } if ( (change_height_minimum > 0) && (change_height_maximum > 0) ) { float player_height = everquest_function_get_player_height(); if (change_height_use_minimum == true) { if (player_height < change_height_minimum) { everquest_function_set_player_height(change_height_minimum); } } if (change_height_use_maximum == true) { if (player_height > change_height_maximum) { everquest_function_set_player_height(change_height_maximum); } } } Sleep(10); } everquest_chat_helper_write_chat_text(APPLICATION_NAME " unloaded."); Sleep(1000); FreeLibraryAndExitThread(module_global, 0); return 0; }
HRESULT StartScavenging(LPVOID pSynchronous) { HRESULT hr = S_OK; CCriticalSection cs(&g_csInitClb); hr = ScavengeDownloadCache(); if(FAILED(hr)) goto exit; exit: HRESULT hrRet = cs.Lock(); if (FAILED(hrRet)) { return hrRet; } g_ScavengingThreadId=0; cs.Unlock(); if (!pSynchronous) FreeLibraryAndExitThread( g_hFusionMod, hr); return S_OK; }
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: //MessageBoxA( NULL, "[PLUGIN LOADED]", "libcod", MB_OK ); g_hModule = hinstDLL; DisableThreadLibraryCalls(hinstDLL); // maybe add a check if this .dll is injected, because that would probably crash now... this dll is intended to be called from the patched .exe's restore_entry_function(); CloseHandle(CreateThread(NULL, 0, &MyThread, NULL, 0, &g_threadID)); break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_PROCESS_DETACH: Com_Printf("[PLUGIN UNLOADED]\n"); FreeLibraryAndExitThread(g_hModule, 0); break; case DLL_THREAD_DETACH: Com_Printf("[THREAD DETACH]\n"); break; } return TRUE; // succesful }
static DWORD WINAPI QuitThread (void *pv) { FreeLibraryAndExitThread((HMODULE)pv, 0); #if _MSC_VER < 1400 return 0; // never returns #endif }
static void __cdecl common_end_thread(unsigned int const return_code) throw() { __acrt_ptd* const ptd = __acrt_getptd_noexit(); if (!ptd) { ExitThread(return_code); } __acrt_thread_parameter* const parameter = ptd->_beginthread_context; if (!parameter) { ExitThread(return_code); } if (parameter->_initialized_apartment) { __acrt_RoUninitialize(); } if (parameter->_thread_handle != INVALID_HANDLE_VALUE && parameter->_thread_handle != nullptr) { CloseHandle(parameter->_thread_handle); } if (parameter->_module_handle != INVALID_HANDLE_VALUE && parameter->_module_handle != nullptr) { FreeLibraryAndExitThread(parameter->_module_handle, return_code); } else { ExitThread(return_code); } }
DWORD WINAPI QueryRecycleBinThreadProc(void* pParam) { // NOTE: Do not use CRT functions (since thread was created with CreateThread())! SHQUERYRBINFO rbi = {0}; rbi.cbSize = sizeof(SHQUERYRBINFO); SHQueryRecycleBin(NULL, &rbi); g_BinCount = (double)rbi.i64NumItems; g_BinSize = (double)rbi.i64Size; EnterCriticalSection(&g_CriticalSection); HMODULE module = NULL; if (g_FreeInstanceInThread) { DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; GetModuleHandleEx(flags, (LPCWSTR)DllMain, &module); g_FreeInstanceInThread = false; } g_Thread = false; LeaveCriticalSection(&g_CriticalSection); if (module) { // Decrement the ref count and possibly unload the module if this is // the last instance. FreeLibraryAndExitThread(module, 0); } return 0; }
DWORD CALLBACK ExploitThread(LPVOID hModule) { CoInitialize(nullptr); DoDfsvcExploit(); CoUninitialize(); FreeLibraryAndExitThread((HMODULE)hModule, 0); }
void D3DHooks::DelayedUnload() { Logger::GetInstance()->LogEvent("Event", "Delay unloading the dll...detach event should come next in 500ms"); // Unload this dll fully from the process // Give enough time for the hooked function to complete and return Sleep(500); FreeLibraryAndExitThread(GlobalHook::GetInstance()->GetHInstance(), 0); }
unsigned int WINAPI BackgroundJobProcessor::StaticThreadProc(void *lpParam) { Assert(lpParam); #ifdef _M_X64_OR_ARM64 #ifdef RECYCLER_WRITE_BARRIER Memory::RecyclerWriteBarrierManager::OnThreadInit(); #endif #endif #if !defined(_UCRT) HMODULE dllHandle = NULL; if (!GetModuleHandleEx(0, AutoSystemInfo::GetJscriptDllFileName(), &dllHandle)) { dllHandle = NULL; } #endif ParallelThreadData * threadData = static_cast<ParallelThreadData *>(lpParam); BackgroundJobProcessor *const processor = threadData->processor; // Indicate to the constructor that the thread has fully started. threadData->threadStartedOrClosing.Set(); #if DBG threadData->backgroundPageAllocator.SetConcurrentThreadId(GetCurrentThreadId()); #endif #ifdef DISABLE_SEH processor->Run(threadData); #else __try { processor->Run(threadData); } __except(ExceptFilter(GetExceptionInformation())) { Assert(false); } #endif // Indicate to Close that the thread is about to exit. This has to be done before CoUninitialize because CoUninitialize // may require the loader lock and if Close was called while holding the loader lock during DLL_THREAD_DETACH, it could // end up waiting forever, causing a deadlock. threadData->threadStartedOrClosing.Set(); #if !defined(_UCRT) if (dllHandle) { FreeLibraryAndExitThread(dllHandle, 0); } else #endif { return 0; } }
//----------------------------------------------------------------------------- // Thread callback //----------------------------------------------------------------------------- DWORD WINAPI HandlerAuxThreadProc( LPVOID lpParameter // thread data ) { IPCFuncCallHandler * pHandler = (IPCFuncCallHandler *) lpParameter; HANDLER_CALLBACK pfnCallback = pHandler->m_pfnCallback; DWORD dwErr = 0; DWORD dwWaitRet; HANDLE lpHandles[] = {pHandler->m_hShutdownThread, pHandler->m_hStartEnum}; DWORD dwHandleCount = 2; PAL_TRY { do { dwWaitRet = WaitForMultipleObjects(dwHandleCount, lpHandles, FALSE /*Wait Any*/, INFINITE); dwErr = GetLastError(); // If we are in terminate mode then exit this helper thread. if (pHandler->m_fShutdownAuxThread) break; // Keep the 0th index for the terminate thread so that we never miss it // in case of multiple events. note that the ShutdownAuxThread flag above it purely // to protect us against some bug in waitForMultipleObjects. if ((dwWaitRet-WAIT_OBJECT_0) == 0) break; // execute callback if wait succeeded if ((dwWaitRet-WAIT_OBJECT_0) == 1) { (*pfnCallback)(); SetEvent(pHandler->m_hDoneEnum); dwErr = GetLastError(); } } while (dwWaitRet != WAIT_FAILED); } PAL_FINALLY { if (!SetEvent (pHandler->m_hAuxThreadShutdown)) { dwErr = GetLastError(); _ASSERTE (!"HandlerAuxTHreadProc: SetEvent(m_hAuxThreadShutdown) failed"); } FreeLibraryAndExitThread (pHandler->m_hCallbackModule, 0); // Above call doesn't return } PAL_ENDTRY return 0; }
DWORD CheckHookThread(LPVOID param) { CheckHook(); // this makes sure that we remove the reference to the shim dll and unload from // the target process. That minimises the impact of having the dll inserted into // every process FreeLibraryAndExitThread((HMODULE)param, 0); return 0; }
DWORD WINAPI ThreadFunc(LPVOID lpram){ g_mainDlg = new CMainDataDlg; g_mainDlg->DoModal(); delete g_mainDlg; FreeLibraryAndExitThread(theApp.m_hInstance, 1); return TRUE; }
void EjectDLL() { PresentHook->UnHook(); MH_DisableHook(&SetCursorPos); MH_Uninitialize(); Sleep(2000); TerminateThread(InitThread, 0); FreeConsole(); FreeLibraryAndExitThread(DllInst, 0); }
DWORD __stdcall ThreadEntry(LPVOID) { Log::Log("Initializing API\n"); if (!GW::Initialize()){ MessageBoxA(0, "Initialize Failed at finding all addresses, contact Developers about this.", "GWToolbox++ API Error", 0); FreeLibraryAndExitThread(dllmodule, EXIT_SUCCESS); return EXIT_SUCCESS; } Log::Log("Installing dx hooks\n"); GW::Render::SetRenderCallback([](IDirect3DDevice9* device) { GWToolbox::Instance().Draw(device); }); GW::Render::SetResetCallback([](IDirect3DDevice9* device) { ImGui_ImplDX9_InvalidateDeviceObjects(); }); Log::Log("Installed dx hooks\n"); Log::InitializeChat(); Log::Log("Installed chat hooks\n"); while (!tb_destroyed) { // wait until destruction Sleep(100); #ifdef _DEBUG if (GetAsyncKeyState(VK_END) & 1) { GWToolbox::Instance().StartSelfDestruct(); break; } #endif } Sleep(100); Sleep(100); Log::Log("Closing log/console, bye!\n"); Log::Terminate(); Sleep(100); FreeLibraryAndExitThread(dllmodule, EXIT_SUCCESS); }
VOID DLLEXPORT NORETURN WINAPI UninstallHandler(DWORD dw) { SetErrorMode(0); SetUnhandledExceptionFilter(NULL); if (dw > 0) MessageBox(NULL, "Exception handling restored to default mode.", "noexcept.dll", MB_ICONINFORMATION | MB_SETFOREGROUND); FreeLibraryAndExitThread(hModDLL, dw); }
DWORD WINAPI NetworkThreadProc(void* pParam) { // NOTE: Do not use CRT functions (since thread was created by CreateThread())! MeasureData* measure = (MeasureData*)pParam; const DWORD bufferSize = sizeof(ICMP_ECHO_REPLY) + 32; BYTE buffer[bufferSize]; double value = 0.0; HANDLE hIcmpFile = IcmpCreateFile(); if (hIcmpFile != INVALID_HANDLE_VALUE) { IcmpSendEcho(hIcmpFile, measure->destAddr, NULL, 0, NULL, buffer, bufferSize, measure->timeout); IcmpCloseHandle(hIcmpFile); ICMP_ECHO_REPLY* reply = (ICMP_ECHO_REPLY*)buffer; value = (reply->Status != IP_SUCCESS) ? measure->timeoutValue : reply->RoundTripTime; if (!measure->finishAction.empty()) { RmExecute(measure->skin, measure->finishAction.c_str()); } } HMODULE module = NULL; EnterCriticalSection(&g_CriticalSection); if (measure->threadActive) { measure->value = value; measure->threadActive = false; } else { // Thread is not attached to an existing measure any longer, so delete // unreferenced data. delete measure; DWORD flags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT; GetModuleHandleEx(flags, (LPCWSTR)DllMain, &module); } LeaveCriticalSection(&g_CriticalSection); if (module) { // Decrement the ref count and possibly unload the module if this is // the last instance. FreeLibraryAndExitThread(module, 0); } return 0; }
DWORD PALAPI CreateTestThread(LPVOID lpParam) { /* Test access to DLL.*/ TestDll(lpParam, 1); /*Free library and exit thread.*/ FreeLibraryAndExitThread(lpParam, (DWORD)0); /* NOT REACHED */ /*Infinite loop, we should not get here.*/ while(1); return (DWORD)0; }
DWORD WINAPI TopMenuCore::beginRun(LPVOID lpParameter) { DWORD exitCode = 0; try { TopMenuCore core((HINSTANCE)lpParameter); if(!core.run()) { exitCode = 1; } } catch(...) { } FreeLibraryAndExitThread((HINSTANCE)lpParameter, exitCode); return exitCode; }
VOID CALLBACK ExitThreadApc(ULONG_PTR Context) { PWAH_HELPER_CONTEXT HelperContext = (PWAH_HELPER_CONTEXT)Context; HMODULE DllHandle = HelperContext->DllHandle; /* Close the file handle */ CloseHandle(HelperContext->FileHandle); /* Free the context */ HeapFree(GlobalHeap, 0, HelperContext); /* Exit the thread and library */ FreeLibraryAndExitThread(DllHandle, ERROR_SUCCESS); }
// -------------------------------------------------------------------------- // This function frees this dll, allowing the operating system to remove // the code from memory and releasing the reference to the dll on disk. // After this call this dll can not be used any more. // // THIS FUNCTION DOES NOT RETURN !!! // -------------------------------------------------------------------------- JNIEXPORT void JNICALL Java_com_izforge_izpack_util_os_ShellLink_FreeLibrary (JNIEnv *env, jobject obj, jstring name) { // convert the name from Java string type const char *libraryName = (env)->GetStringUTFChars (name, 0); // get a module handle HMODULE handle = GetModuleHandle (libraryName); // release the string object (env)->ReleaseStringUTFChars (name, libraryName); // now we are rady to free the library FreeLibraryAndExitThread (handle, 0); }
DWORD WINAPI WrapperThreadProc(void *threadData) { ThreadData *td = (ThreadData *)threadData; td->wrapperThreadId = GetCurrentThreadId(); HANDLE thread = (HANDLE)_beginthreadex(NULL, 0, CRTThreadProc, td, 0, NULL); WaitForSingleObject(thread, INFINITE); DWORD retCode; GetExitCodeThread(thread, &retCode); CloseHandle(thread); HMODULE thisDLL = td->thisDLL; HANDLE processHeap = td->processHeap; HeapFree(processHeap, 0, td); FreeLibraryAndExitThread(thisDLL, 42); }
HRESULT CSysTray::SysTrayThreadProc() { WCHAR strFileName[MAX_PATH]; GetModuleFileNameW(g_hInstance, strFileName, MAX_PATH); HMODULE hLib = LoadLibraryW(strFileName); CoInitializeEx(NULL, COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED); Create(NULL); HRESULT ret = SysTrayMessageLoop(); CoUninitialize(); FreeLibraryAndExitThread(hLib, ret); }
DWORD CALLBACK ExploitThread(LPVOID hModule) { CoInitialize(nullptr); try { DoFlashBrokerExploitJunction(); } catch (_com_error& e) { DebugPrintf("Error: %ls\n", e.ErrorMessage()); } CoUninitialize(); FreeLibraryAndExitThread((HMODULE)hModule, 0); }
extern "C" DLL_EXPORT BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: g_hModule = hinstDLL; DisableThreadLibraryCalls(hinstDLL); CloseHandle(CreateThread(NULL, NULL, &tExtend, NULL, NULL, &g_threadID)); break; case DLL_PROCESS_DETACH: case DLL_THREAD_DETACH: delete game; FreeLibraryAndExitThread(g_hModule, 0); break; } return TRUE; }
DWORD WINAPI thread_load(LPVOID param) { mem.enable_debug_privileges(); mem.set_process_by_id(GetCurrentProcessId()); if (mem.get_process_id() == 0) { FreeLibraryAndExitThread(module_global, 0); return 0; } load_config(); CreateThread(NULL, 0, &thread_function, NULL, 0, NULL); return 0; }
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { if(ul_reason_for_call == DLL_PROCESS_ATTACH) { if(!DataMgr.Create()) FreeLibraryAndExitThread((HMODULE)hModule,0); OutputDebugString(TEXT("CM_HOOK_DLL_PROCESS_ATTACH")); } if(ul_reason_for_call == DLL_PROCESS_DETACH) { OutputDebugString(TEXT("CM_HOOK_DLL_PROCESS_DETACH")); CMHooker.UnAllHookApi(); } return TRUE; }