diff --git a/AGENTS.md b/AGENTS.md index fbb0bab..718e849 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,9 +90,9 @@ All hooks are installed and removed from the DLL load/unload notification — no | Managed module | Hook flags | Extra | | --- | --- | --- | -| engine (`hw.dll`, or the blob engine) | `CreateThread \| WaitForSingleObject \| Sleep` | network-only `TerminateThread`/`select` IAT hooks and `NET_QueuePacket`/`NET_Shutdown` inline hooks; `FreeLibrary` IAT hook only when the game directory is `svencoop` | -| `GameUI.dll` | `CreateThread \| WaitForSingleObject` | `FreeLibrary` IAT hook on **GameUI's** import table | -| `ServerBrowser.dll` | `CreateThread \| WaitForSingleObject` | — | +| engine (`hw.dll`, or the blob engine) | `CreateThread \| WaitForSingleObject \| Sleep` | network-only `TerminateThread`/`select` IAT hooks and `NET_QueuePacket`/`NET_Shutdown` inline hooks; `FreeLibrary` IAT/BlobIAT hook for all families | +| `GameUI.dll` | `CreateThread \| WaitForSingleObject \| Socket` | `FreeLibrary` IAT hook on **GameUI's** import table | +| `ServerBrowser.dll` | `CreateThread \| WaitForSingleObject \| Socket` | — | | `server.dll` | `CreateThread` only | enabled only when the game directory is `svencoop` | Two deliberate gates: @@ -110,7 +110,9 @@ at hook transaction commit, so they must not be checked for null immediately after enqueueing the hook. Both handles and per-engine state are cleared during engine unload. Other engine families retain their existing shutdown behavior. -The `FreeLibrary` hooks are how the plugin catches the unload of modules it does not own: `NewFreeLibrary_Engine` waits for the **`server.dll`** manager when the module being freed is the tracked one, and `NewFreeLibrary_GameUI` does the same for the **`ServerBrowser.dll`** manager. Both then forward to the real `FreeLibrary`. +The `FreeLibrary` hooks catch unloads before the loader lock: `NewFreeLibrary_Engine` waits for the matching **GameUI** or **server.dll** manager, and `NewFreeLibrary_GameUI` waits for **ServerBrowser**. The engine hook is installed for every PE/BLOB family; server.dll tracking remains Sven-only. Both handlers then forward to real `FreeLibrary`. + +`hookflag_Socket` installs `select` and `recvfrom` IAT hooks for present wsock32.dll/ws2_32.dll imports. Non-main worker select waits are capped at 20 ms; during manager termination select clears the fd sets and returns zero, while recvfrom returns SOCKET_ERROR/WSAEWOULDBLOCK. Legacy CSocketThread sockets are nonblocking; this breaks continuous receive without exiting under the socket lock. The loop unlocks and reaches the existing zero-timeout shutdown poll. No SO_RCVTIMEO option is modified. Never replace TerminateThread with a join in CSocketThread's destructor: it already holds the socket lock and can run under the loader lock. ### 3. Thread managers (`src/ThreadManager.cpp`) @@ -150,7 +152,7 @@ Actual waiting only happens when the engine reports `DLL_CLOSE` or `DLL_RESTART` - `GetEngineDLLState()` returns `(*eng)->GetState()` and `DLL_INACTIVE` when the slot is null — the slot is dereferenced exactly once - `Engine_WaitForShutdown` (from `ExitGame`) applies that gate to the engine manager; its `hModule` / `hBlobModule` parameters are unused in the body -- `ServerDLL_WaitForShutdown` and `ServerBrowser_WaitForShutdown` apply the same gate and are triggered by the `FreeLibrary` hooks above +- `GameUI_WaitForShutdown`, `ServerDLL_WaitForShutdown` and `ServerBrowser_WaitForShutdown` apply the same gate and are triggered by the `FreeLibrary` hooks above Each path calls `StartTermination()` and then `WaitForAliveThreadsToShutdown()` on its own manager. @@ -249,7 +251,7 @@ README). These tests do not replace live hook routing/shutdown verification. | `cof-5936` (Cry of Fear) | ✅ | | Any build absent from the catalog | ❌ fatal at `LoadEngine` | -Catalog coverage is not a correctness statement. Two further Sven Co-op specific gates are applied at runtime: the engine `FreeLibrary` hook and `server.dll` tracking are both limited to a `svencoop` game directory, and `GameUI.dll` / `ServerBrowser.dll` are skipped when they use the Steam callback model. +Catalog coverage is not a correctness statement. The engine `FreeLibrary` hook covers PE and BLOB engines of every family. Only `server.dll` tracking is limited to a `svencoop` game directory; `GameUI.dll` / `ServerBrowser.dll` are skipped when they use the Steam callback model. ## Important Constants, Macros and Types @@ -259,7 +261,7 @@ static_assert(METAHOOK_API_VERSION >= 109, ...); // in src/privatehook.cpp: Res #define Sys_Error(msg, ...) g_pMetaHookAPI->SysError("[" MHPluginName "] " msg, __VA_ARGS__); // src/ThreadManager.h — per-manager hook selection -hookflag_CreateThread = 1, hookflag_WaitForSingleObject = 2, hookflag_Sleep = 4 +hookflag_CreateThread = 1, hookflag_WaitForSingleObject = 2, hookflag_Sleep = 4, hookflag_Socket = 8 // src/enginedef.h — IEngine::GetState() values; only DLL_CLOSE / DLL_RESTART wait DLL_INACTIVE 0, DLL_ACTIVE 1, DLL_PAUSED 2, DLL_CLOSE 3, DLL_TRANS 4, DLL_RESTART 5 @@ -291,7 +293,7 @@ Runtime configuration: `ThreadGuard.dll` must be listed in the host's `metahook/ - Preserve the MetaHook API, plugin exports and calling conventions. Match the naming, indentation and comment style of the files you touch - Resolve engine symbols only through the host gamedata contract. Do not add a signature-scan fallback for `eng`; keep the catalog name `eng` (not `engine`) and the fatal `Could not resolve gamedata symbol: ...` diagnostic - Keep the wrapper semantics explicit: `NewCreateThread` must still duplicate the handle before handing it to a manager and must return the original handle, and the `Sleep(1)` / `WaitForSingleObject(0)` short-circuits must stay gated on `StartTermination` and, for `Sleep`, on the non-main-thread check -- Keep the termination gate (`DLL_CLOSE` / `DLL_RESTART` via `(*eng)->GetState()`) and the per-module hook flags intact; the `svencoop` game-directory gates for `server.dll` and the engine `FreeLibrary` hook are deliberate +- Keep the termination gate (`DLL_CLOSE` / `DLL_RESTART` via `(*eng)->GetState()`) and per-module hook flags intact; `server.dll` tracking is Sven-only, while the engine `FreeLibrary` hook must protect GameUI on every PE/BLOB family - The fixed `MAXIMUM_WAIT_OBJECTS` handle pool and its "already signaled slot" reclamation are part of the design; a full pool must keep failing loudly rather than silently dropping a thread - The `#if 0` closed-thread path is intentionally disabled. Do not re-enable it as part of an unrelated change - When gamedata usage changes, update `scripts/manifests/threadguard.json` in the same change diff --git a/CMakeLists.txt b/CMakeLists.txt index d85a83d..f30266c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -50,7 +50,7 @@ target_compile_options(threadguard_settings INTERFACE /permissive include(cmake/Sources.cmake) add_library(ThreadGuard SHARED ${THREADGUARD_SOURCES}) -target_link_libraries(ThreadGuard PRIVATE threadguard_settings) +target_link_libraries(ThreadGuard PRIVATE threadguard_settings ws2_32) target_compile_options(ThreadGuard PRIVATE /MP /Zi) target_link_options(ThreadGuard PRIVATE /DEBUG /SUBSYSTEM:WINDOWS $<$:/INCREMENTAL> diff --git a/README.md b/README.md index 197e363..dcd7bc0 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,28 @@ Managed modules: It also fixes a Valve bug where the `_restart` command did not shut the server down properly, leaking resources such as `CSteam3Server`: the hooked `_restart` runs `shutdownserver` first. +The engine's `FreeLibrary` import is hooked on both PE and BLOB engines. During +shutdown/restart it joins GameUI's managed workers before unloading GameUI; +GameUI's own `FreeLibrary` hook already does the same for ServerBrowser. This +keeps their socket-thread destructors from killing live workers under the loader +lock and abandoning CRT locks. Legacy GameUI/ServerBrowser worker `select` waits +are capped at 20 ms. After termination starts, `select` reports no ready sockets +and `recvfrom` reports `WSAEWOULDBLOCK`, so the nonblocking drain loop releases its +locks and reaches the existing shutdown-event check. Main-thread socket calls +and socket timeout options are unchanged. Both Winsock import DLL names are +supported; callback-only module exclusions remain intact. + +The GameUI change was checked with Debug/Release builds and handler tests for +idle/continuous UDP receive and unload ordering. Real HL 3266 debugger evidence +shows its GameUI socket worker exiting before the DLL destructor; two restart +runs exited 0. Repeated runs also exposed heap corruption during reload and an +engine allocator shutdown hang after both network joins had completed, so the +full HL 3266 installation is not considered a consistently passing restart test. +HL 10210 and CoF 5936 exit tests and Sven 10257's map/restart/quit test exited 0. +Other snapshots retain catalog coverage but were not launched for this change. +Teardown diagnostics use OutputDebugStringA because the GameUI console can +already be shut down; ordinary CLI console capture does not receive them. + Network threads shut down cooperatively on all 11 supported Windows engine snapshots (`hl-*`, including BLOB, `svencoop-*`, and `cof-*`). Killing this worker with `TerminateThread` can abandon a Steam lock and hang shutdown. ThreadGuard diff --git a/README.zh-CN.md b/README.zh-CN.md index 58f5a5a..28484b4 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,6 +17,10 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 该插件还修复了 Valve 的一个 bug:`_restart` 命令没有正确关闭服务器,导致 `CSteam3Server` 对象出现资源泄漏。被 hook 后的 `_restart` 会先执行 `shutdownserver`以正确释放这些资源。 +普通 PE 与 BLOB 引擎都安装 `FreeLibrary` hook,在关闭或重启时,先等待 GameUI 的受管线程退出,再卸载 GameUI;GameUI 自身的 `FreeLibrary` hook 保留对 ServerBrowser 的同类保护,避免 socket 线程在持有 loader lock 的析构阶段被强杀、遗留 CRT 锁。旧版 GameUI/ServerBrowser 工作线程的 `select` 等待限制为 20 ms;收到终止请求后,`select` 返回无就绪 socket,`recvfrom` 返回 `WSAEWOULDBLOCK`,使非阻塞收包循环正常释放锁,再到达原有的退出事件检查。主线程的 socket 调用及 socket 超时选项不变,兼容两种 Winsock DLL 导入名称,并保留仅使用回调模型的模块排除规则。 + +GameUI 修复的 Debug / Release 构建和测试通过,覆盖空闲及持续 UDP 收包、卸载前等待顺序。真实 HL 3266 调试记录确认 GameUI socket 线程在 DLL 析构前退出,两轮重启测试返回 0;重复测试也出现重新加载期间的堆损坏,以及两轮网络线程均已完成等待后发生的引擎分配器退出卡住,因此不能视为该完整安装的重启已稳定通过。HL 10210、CoF 5936 的退出测试及 Sven 10257 的加载地图、重启、退出测试返回 0。其他快照保留目录覆盖,本次未逐一启动。关闭阶段的诊断使用 `OutputDebugStringA`,因为 GameUI 控制台可能已经关闭;普通 CLI 控制台捕获不会收到这些日志。 + 全部 11 个受支持的 Windows 引擎快照(`hl-*`,包括 BLOB;`svencoop-*`;`cof-*`)使用网络线程协作退出。直接 `TerminateThread` 可能使工作线程遗留 Steam 锁,从而挂起退出。ThreadGuard 通过 `NET_ThreadFunc` 识别每次创建,持有独立的 duplicate 句柄,并核对 `dwNetThreadId` 的运行时值。引擎针对该线程的 `TerminateThread` 调用改为发出退出请求并等待真实线程结束;网络线程在已经解锁的循环末尾 `Sleep(1)` 中调用 `ExitThread(0)`。其他线程的终止调用保留原行为。 仅将该网络线程的 `select` 等待上限设为 20 ms,更短的超时保持原值。收到退出请求后,`NET_QueuePacket` 返回无包,使持续收包的循环也能正常解锁并走到 Sleep。不会提前清零网络状态,不关闭调用方拥有的句柄,也不在等待超时后回退强杀。创建时先发布身份再恢复线程,重建或重新加载引擎时复位退出请求。参见 [issue #4](https://github.com/MetaHookSv/ThreadGuard/issues/4)。 diff --git a/src/ThreadManager.cpp b/src/ThreadManager.cpp index e61c9be..47a95d3 100644 --- a/src/ThreadManager.cpp +++ b/src/ThreadManager.cpp @@ -38,6 +38,8 @@ static bool NetworkExitRequested() static void NetworkTrace(const char* event, DWORD id) { + // The worker can log during DLL/FLS teardown after the GameUI console has + // shut down. Do not call the engine console from this thread/phase. char message[160]; sprintf_s(message, "[ThreadGuard] network thread %lu: %s\n", id, event); OutputDebugStringA(message); @@ -296,6 +298,39 @@ void WINAPI NewSleep(DWORD dwMilliseconds) return Sleep(dwMilliseconds); } +static int WSAAPI NewSocketSelect(int nfds, fd_set* read, fd_set* write, fd_set* except, const timeval* timeout) +{ + auto manager = FindThreadManagerByVirtualAddress(_ReturnAddress()); + if (manager && (HANDLE)GetCurrentThreadId() != g_MainThreadId) + { + if (manager->OnSleep(1)) + { + if (read) FD_ZERO(read); + if (write) FD_ZERO(write); + if (except) FD_ZERO(except); + return 0; + } + const timeval poll = { 0, kNetworkPollMicroseconds }; + if (!timeout || timeout->tv_sec > 0 || timeout->tv_usec > poll.tv_usec) + return select(nfds, read, write, except, &poll); + } + return select(nfds, read, write, except, timeout); +} + +static int WSAAPI NewSocketRecvFrom(SOCKET socket, char* buffer, int length, int flags, sockaddr* from, int* fromLength) +{ + auto manager = FindThreadManagerByVirtualAddress(_ReturnAddress()); + // CSocketThread uses nonblocking sockets. Break its drain loop without + // exiting while it owns the socket-list lock; the loop unlocks normally + // before observing termination at WaitForSingleObject(event, 0). + if (manager && manager->OnSleep(1)) + { + WSASetLastError(WSAEWOULDBLOCK); + return SOCKET_ERROR; + } + return recvfrom(socket, buffer, length, flags, from, fromLength); +} + class CThreadManager : public IThreadManager { @@ -322,6 +357,9 @@ class CThreadManager : public IThreadManager //for hw.dll hook_t* m_pHook_Sleep; + static constexpr unsigned kSocketImportLibraryCount = 2; + static constexpr unsigned kSocketHooksPerLibrary = 2; + hook_t* m_pHook_Socket[kSocketImportLibraryCount * kSocketHooksPerLibrary]; std::atomic m_bStartTermination; public: @@ -353,6 +391,7 @@ class CThreadManager : public IThreadManager m_pHook_CreateThread = NULL; m_pHook_WaitForSingleObject = NULL; m_pHook_Sleep = NULL; + memset(m_pHook_Socket, 0, sizeof(m_pHook_Socket)); m_bStartTermination = false; } @@ -418,6 +457,25 @@ class CThreadManager : public IThreadManager if (flags & hookflag_Sleep) m_pHook_Sleep = g_pMetaHookAPI->IATHook(m_hModule, "kernel32.dll", "Sleep", NewSleep, NULL); + if (flags & hookflag_Socket) + { + unsigned index = 0; + for (auto dll : { "wsock32.dll", "ws2_32.dll" }) + { + if (g_pMetaHookAPI->ModuleHasImportEx(m_hModule, dll, "select")) + { + m_pHook_Socket[index] = g_pMetaHookAPI->IATHook(m_hModule, dll, "select", NewSocketSelect, NULL); + if (!m_pHook_Socket[index]) Sys_Error("Could not hook socket select import!"); + } + ++index; + if (g_pMetaHookAPI->ModuleHasImportEx(m_hModule, dll, "recvfrom")) + { + m_pHook_Socket[index] = g_pMetaHookAPI->IATHook(m_hModule, dll, "recvfrom", NewSocketRecvFrom, NULL); + if (!m_pHook_Socket[index]) Sys_Error("Could not hook socket recvfrom import!"); + } + ++index; + } + } } else if (m_hBlobModule) { @@ -434,6 +492,11 @@ class CThreadManager : public IThreadManager void UnistallHook(void) override { + for (auto& hook : m_pHook_Socket) + { + if (hook) g_pMetaHookAPI->UnHook(hook); + hook = NULL; + } #if 0 if (m_pHook_DllMain) { diff --git a/src/ThreadManager.h b/src/ThreadManager.h index ca86ecb..c99469b 100644 --- a/src/ThreadManager.h +++ b/src/ThreadManager.h @@ -6,6 +6,7 @@ const int hookflag_CreateThread = 1; const int hookflag_WaitForSingleObject = 2; const int hookflag_Sleep = 4; +const int hookflag_Socket = 8; class IThreadManager : public IBaseInterface { diff --git a/src/privatehook.cpp b/src/privatehook.cpp index 46358af..a5458da 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -42,6 +42,7 @@ IThreadManager* g_ThreadManager_ServerDLL = NULL; IEngine** eng = NULL; void ServerDLL_WaitForShutdown(HMODULE hModule); +void GameUI_WaitForShutdown(HMODULE hModule); void ServerBrowser_WaitForShutdown(HMODULE hModule); int GetEngineDLLState() @@ -54,6 +55,10 @@ int GetEngineDLLState() BOOL WINAPI NewFreeLibrary_Engine(HMODULE hModule) { + if (g_ThreadManager_GameUI && g_ThreadManager_GameUI->GetModule() == hModule) + { + GameUI_WaitForShutdown(hModule); + } if (g_ThreadManager_ServerDLL && g_ThreadManager_ServerDLL->GetModule() == hModule) { ServerDLL_WaitForShutdown(hModule); @@ -133,18 +138,20 @@ void Engine_InstallHook(HMODULE hModule, BlobHandle_t hBlobModule) g_ThreadManager_Engine = CreateThreadManagerForModule(hModule); g_ThreadManager_Engine->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Sleep); - if (0 == stricmp(g_pMetaHookAPI->GetGameDirectory(), "svencoop")) - { - g_pHook_FreeLibrary_Engine = g_pMetaHookAPI->IATHook(hModule, "kernel32.dll", "FreeLibrary", NewFreeLibrary_Engine, NULL); - } + g_pHook_FreeLibrary_Engine = g_pMetaHookAPI->IATHook(hModule, "kernel32.dll", "FreeLibrary", NewFreeLibrary_Engine, NULL); } else if (hBlobModule) { g_ThreadManager_Engine = CreateThreadManagerForBlob(hBlobModule); g_ThreadManager_Engine->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Sleep); + g_pHook_FreeLibrary_Engine = g_pMetaHookAPI->BlobIATHook(hBlobModule, "kernel32.dll", "FreeLibrary", NewFreeLibrary_Engine, NULL); } if (g_ThreadManager_Engine) + { + if (!g_pHook_FreeLibrary_Engine) + Sys_Error("Could not install engine FreeLibrary hook!"); NetworkThread_InstallHook(g_ThreadManager_Engine); + } } void Engine_UninstallHook(HMODULE hModule, BlobHandle_t hBlobModule) @@ -187,11 +194,24 @@ void GameUI_InstallHook(HMODULE hModule) return; g_ThreadManager_GameUI = CreateThreadManagerForModule(hModule); - g_ThreadManager_GameUI->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject); + g_ThreadManager_GameUI->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Socket); g_pHook_FreeLibrary_GameUI = g_pMetaHookAPI->IATHook(hModule, "kernel32.dll", "FreeLibrary", NewFreeLibrary_GameUI, NULL); } +void GameUI_WaitForShutdown(HMODULE hModule) +{ + // Join before FreeLibrary enters the loader lock and the socket destructor. + if (g_ThreadManager_GameUI && (GetEngineDLLState() == DLL_CLOSE || GetEngineDLLState() == DLL_RESTART)) + { + g_ThreadManager_GameUI->StartTermination(); + g_ThreadManager_GameUI->WaitForAliveThreadsToShutdown(); + // GameUI's console may already be shut down; keep teardown diagnostics + // independent of engine/VGUI callbacks, even on the main thread. + OutputDebugStringA("[ThreadGuard] GameUI: threads stopped before FreeLibrary\n"); + } +} + void GameUI_UnistallHook(HMODULE hModule) { if (g_pHook_FreeLibrary_GameUI) @@ -256,7 +276,7 @@ void ServerBrowser_InstallHook(HMODULE hModule) return; g_ThreadManager_ServerBrowser = CreateThreadManagerForModule(hModule); - g_ThreadManager_ServerBrowser->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject); + g_ThreadManager_ServerBrowser->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Socket); } void ServerBrowser_UninstallHook(HMODULE hModule) diff --git a/tests/network_hooks_test.cpp b/tests/network_hooks_test.cpp index 3f2a753..947d6ac 100644 --- a/tests/network_hooks_test.cpp +++ b/tests/network_hooks_test.cpp @@ -1,12 +1,22 @@ // Exercise the actual handlers with owned Win32 threads and a loop that either // blocks in select or keeps finding packets. The host API provides only a fatal -// diagnostic stub. IAT installation and symbol resolution require a game run. +// diagnostic stub. The unload routing test replaces FreeLibrary only to assert +// that joining precedes unloading. IAT installation and symbol resolution still +// require a game run. #include "../src/ThreadManager.cpp" #include #include +static BOOL WINAPI TestFreeLibrary(HMODULE module); +#define FreeLibrary TestFreeLibrary +#include "../src/privatehook.cpp" +#undef FreeLibrary + metahook_api_t* g_pMetaHookAPI = NULL; HANDLE g_MainThreadId = NULL; +int g_iEngineType = 0; +DWORD g_dwEngineBuildnum = 0; +mh_dll_info_t g_EngineDLLInfo = {}; #define CHECK(condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); std::abort(); } } while (0) @@ -23,18 +33,21 @@ class TestManager : public IThreadManager { public: std::vector handles; - void StartTermination() override {} - void WaitForAliveThreadsToShutdown() override {} + std::atomic stopping{ false }; + HMODULE module = NULL; + unsigned joined = 0; + void StartTermination() override { stopping = true; } + void WaitForAliveThreadsToShutdown() override { CHECK(stopping); ++joined; } void OnCreateThread(HANDLE thread) override { handles.push_back(thread); } - bool OnWaitForSingleObject(HANDLE, DWORD) override { return false; } - bool OnSleep(DWORD) override { return false; } + bool OnWaitForSingleObject(HANDLE, DWORD) override { return stopping; } + bool OnSleep(DWORD) override { return stopping && (HANDLE)GetCurrentThreadId() != g_MainThreadId; } void InstallHook(int) override {} void UnistallHook() override {} PVOID GetImageBase() const override { return NULL; } ULONG GetImageSize() const override { return 0; } PVOID GetTextBase() const override { return NULL; } ULONG GetTextSize() const override { return MAXDWORD; } - HMODULE GetModule() const override { return NULL; } + HMODULE GetModule() const override { return module; } BlobHandle_t GetBlobModule() const override { return NULL; } void CloseDuplicates() { @@ -43,6 +56,71 @@ class TestManager : public IThreadManager } }; +class TestEngine : public IEngine +{ +public: + int state = DLL_ACTIVE; + bool Load(bool, char*, char*) override { return true; } + void Unload() override {} + void SetState(int value) override { state = value; } + int GetState() override { return state; } + void SetSubState(int) override {} + int GetSubState() override { return 0; } + int Frame() override { return 0; } + double GetFrameTime() override { return 0; } + double GetCurTime() override { return 0; } + void TrapKey_Event(int, bool) override {} + void TrapMouse_Event(int, bool) override {} + void StartTrapMode() override {} + bool IsTrapping() override { return false; } + bool CheckDoneTrapping(int&, int&) override { return false; } + int GetQuitting() override { return 0; } + void SetQuitting(int) override {} +}; + +static TestManager* unloadManager; +static HMODULE expectedModule; +static unsigned expectedJoins; +static unsigned unloadCalls; +static BOOL WINAPI TestFreeLibrary(HMODULE module) +{ + CHECK(expectedModule == module); + CHECK(expectedJoins == unloadManager->joined); + ++unloadCalls; + return TRUE; +} + +static void CheckUnloadRouting() +{ + TestEngine engine; + IEngine* enginePointer = &engine; + eng = &enginePointer; + TestManager manager; + manager.module = (HMODULE)0x1234; + unloadManager = &manager; + g_ThreadManager_GameUI = &manager; + for (int state : { DLL_ACTIVE, DLL_CLOSE, DLL_RESTART }) + { + engine.state = state; + manager.stopping = false; + expectedModule = (HMODULE)0x5678; + expectedJoins = manager.joined; + CHECK(NewFreeLibrary_Engine(expectedModule)); + CHECK(!manager.stopping); + expectedModule = manager.module; + if (state != DLL_ACTIVE) ++expectedJoins; + CHECK(NewFreeLibrary_Engine(expectedModule)); + CHECK((state != DLL_ACTIVE) == manager.stopping); + } + g_ThreadManager_GameUI = NULL; + g_ThreadManager_ServerBrowser = &manager; + ++expectedJoins; + CHECK(NewFreeLibrary_GameUI(manager.module)); + g_ThreadManager_ServerBrowser = NULL; + CHECK(7 == unloadCalls); + eng = NULL; +} + static DWORD engineThreadId; static SOCKET socketHandle = INVALID_SOCKET; static HANDLE shutdownWorker = NULL; @@ -102,6 +180,84 @@ static DWORD WINAPI Worker(void*) } static DWORD WINAPI OtherWorker(void*) { Sleep(INFINITE); return 0; } + +struct SocketContext +{ + SOCKET socket; + sockaddr_in address; + HANDLE started; + HANDLE stop; + CRITICAL_SECTION lock; + bool flood; +}; + +static DWORD WINAPI SocketWorker(void* argument) +{ + auto context = static_cast(argument); + while (WAIT_OBJECT_0 != NewWaitForSingleObject(context->stop, 0)) + { + fd_set read; + FD_ZERO(&read); + FD_SET(context->socket, &read); + if (!context->flood) SetEvent(context->started); + if (NewSocketSelect(0, &read, NULL, NULL, NULL) > 0) + { + EnterCriticalSection(&context->lock); + char packet; + while (NewSocketRecvFrom(context->socket, &packet, 1, 0, NULL, NULL) == 1) + { + // Always leave another datagram queued: draining must observe stop. + CHECK(1 == sendto(context->socket, &packet, 1, 0, + (sockaddr*)&context->address, sizeof(context->address))); + SetEvent(context->started); + } + CHECK(WSAEWOULDBLOCK == WSAGetLastError()); + LeaveCriticalSection(&context->lock); + } + } + return 0; +} + +static void CheckSocketShutdown(TestManager& manager) +{ + for (bool flood : { false, true }) + { + SocketContext context = {}; + context.flood = flood; + context.socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + CHECK(INVALID_SOCKET != context.socket); + context.address.sin_family = AF_INET; + context.address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + CHECK(0 == bind(context.socket, (sockaddr*)&context.address, sizeof(context.address))); + int size = sizeof(context.address); + CHECK(0 == getsockname(context.socket, (sockaddr*)&context.address, &size)); + u_long nonblocking = 1; + CHECK(0 == ioctlsocket(context.socket, FIONBIO, &nonblocking)); + context.started = CreateEvent(NULL, TRUE, FALSE, NULL); + context.stop = CreateEvent(NULL, TRUE, FALSE, NULL); + InitializeCriticalSection(&context.lock); + if (flood) CHECK(1 == sendto(context.socket, "x", 1, 0, (sockaddr*)&context.address, size)); + manager.stopping = false; + HANDLE worker = CreateThread(NULL, 0, SocketWorker, &context, 0, NULL); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(context.started, 5000)); + manager.StartTermination(); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 2000)); + CHECK(TryEnterCriticalSection(&context.lock)); + LeaveCriticalSection(&context.lock); + // The main thread's socket calls still forward even during termination. + if (flood) + { + char packet; + CHECK(1 == NewSocketRecvFrom(context.socket, &packet, 1, 0, NULL, NULL)); + } + CloseHandle(worker); + CloseHandle(context.started); + CloseHandle(context.stop); + DeleteCriticalSection(&context.lock); + closesocket(context.socket); + } + manager.stopping = false; +} static DWORD WINAPI FinishedWorker(void*) { return 0; } struct SpawnContext { IThreadManager* manager; HANDLE childFinished; }; static DWORD WINAPI ChildWorker(void* event) @@ -129,6 +285,7 @@ int main() api.SysError = Fatal; g_pMetaHookAPI = &api; g_MainThreadId = (HANDLE)GetCurrentThreadId(); + CheckUnloadRouting(); TestManager manager; AddThreadManager(&manager); g_NetworkManager = &manager; @@ -136,6 +293,7 @@ int main() g_pfn_select = select; WSADATA data; CHECK(0 == WSAStartup(MAKEWORD(2, 2), &data)); + CheckSocketShutdown(manager); entered = CreateEvent(NULL, TRUE, FALSE, NULL); InitializeCriticalSection(&networkLock); // Networking disabled: still forward resource cleanup on each invocation.