diff --git a/AGENTS.md b/AGENTS.md index 718e849..778e3fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,10 +148,11 @@ handle already being waited on. The `#if 0` closed-thread path stays disabled. ### 4. Termination gates -Actual waiting only happens when the engine reports `DLL_CLOSE` or `DLL_RESTART`: +Module FreeLibrary waits require `DLL_CLOSE` or `DLL_RESTART`; the engine's +ExitGame lifecycle wait is unconditional when its manager exists: - `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 +- `Engine_WaitForShutdown` (from `ExitGame`) always requests and joins the engine manager before CRT detach. HL 3266's `CEngine::Unload` resets the state to `DLL_INACTIVE` before this callback; applying the module gate here lets old Steam workers outlive their heap and corrupt the next engine lifetime. Its `hModule` / `hBlobModule` parameters are unused in the body - `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. @@ -293,7 +294,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 per-module hook flags intact; `server.dll` tracking is Sven-only, while the engine `FreeLibrary` hook must protect GameUI on every PE/BLOB family +- Keep the module FreeLibrary termination gate (`DLL_CLOSE` / `DLL_RESTART` via `(*eng)->GetState()`) and per-module hook flags intact. Engine ExitGame must join regardless of runtime state; `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/README.md b/README.md index dcd7bc0..67a695e 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,15 @@ 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 +At the engine's `ExitGame` lifecycle callback, ThreadGuard always requests and +joins its remaining managed workers before CRT detach. It does not require +`GetState()` to still report closing or restarting: HL 3266's `CEngine::Unload` +has already reset it to `DLL_INACTIVE`. Skipping this join allowed old Steam +discovery workers to access allocations from the previous engine lifetime and +leave the small-block allocator locked after an access violation. The earlier +module-unload gates and network shutdown ordering remain unchanged. + +Before the ExitGame fix, 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 @@ -37,6 +45,14 @@ 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. +The ExitGame fix passed Debug/Release builds and both CTests, including a real +worker that must finish cleanup before the inactive-state lifecycle callback +returns. Five original HL 3266 BLOB map/restart/quit runs exited 0 without the +previous access violations. HL 10210 and CoF 5936 exit checks and Sven 10257's +map/restart/quit check also exited 0. All 11 catalog snapshots validated; the +other seven were not individually launched. The separate earlier heap-corruption +crash is not independently proven to have the same cause. + 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 28484b4..63dae04 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -21,6 +21,10 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 GameUI 修复的 Debug / Release 构建和测试通过,覆盖空闲及持续 UDP 收包、卸载前等待顺序。真实 HL 3266 调试记录确认 GameUI socket 线程在 DLL 析构前退出,两轮重启测试返回 0;重复测试也出现重新加载期间的堆损坏,以及两轮网络线程均已完成等待后发生的引擎分配器退出卡住,因此不能视为该完整安装的重启已稳定通过。HL 10210、CoF 5936 的退出测试及 Sven 10257 的加载地图、重启、退出测试返回 0。其他快照保留目录覆盖,本次未逐一启动。关闭阶段的诊断使用 `OutputDebugStringA`,因为 GameUI 控制台可能已经关闭;普通 CLI 控制台捕获不会收到这些日志。 +引擎的 `ExitGame` 生命周期回调会请求并等待剩余受管线程结束,再允许 CRT 卸载,不再要求 `GetState()` 仍处于关闭或重启状态:HL 3266 的 `CEngine::Unload` 此时已经把状态清为 `DLL_INACTIVE`。此前跳过等待,使旧 Steam 发现线程访问上一代引擎的失效内存,并在访问异常后遗留小块分配器锁。较早执行的模块卸载门禁和网络线程关闭顺序保持不变。 + +ExitGame 修复的 Debug / Release 构建和两组 CTest 均通过,新增真实线程测试确认状态已清零时仍须等待工作线程完成清理。原始 HL 3266 BLOB 的五次加载地图、重启、退出测试均返回 0,未再记录到上述访问异常;HL 10210、CoF 5936 的退出检查及 Sven 10257 的加载地图、重启、退出检查也返回 0。全部 11 个目录快照校验通过,其余七个未逐一实机启动。此前独立观察到的堆损坏崩溃尚未证明与此同源。 + 全部 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/privatehook.cpp b/src/privatehook.cpp index a5458da..284a556 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -79,7 +79,10 @@ BOOL WINAPI NewFreeLibrary_GameUI(HMODULE hModule) void Engine_WaitForShutdown(HMODULE hModule, BlobHandle_t hBlobModule) { - if (g_ThreadManager_Engine && (GetEngineDLLState() == DLL_CLOSE || GetEngineDLLState() == DLL_RESTART)) + // ExitGame runs after EngineAPI::Run returns and before the engine's CRT + // detach. CEngine::Unload may already have reset GetState() to DLL_INACTIVE; + // the lifecycle callback itself requires joining every remaining worker. + if (g_ThreadManager_Engine) { g_ThreadManager_Engine->StartTermination(); g_ThreadManager_Engine->WaitForAliveThreadsToShutdown(); diff --git a/tests/network_hooks_test.cpp b/tests/network_hooks_test.cpp index 947d6ac..2f17cae 100644 --- a/tests/network_hooks_test.cpp +++ b/tests/network_hooks_test.cpp @@ -121,6 +121,56 @@ static void CheckUnloadRouting() eng = NULL; } +struct EngineExitContext +{ + IThreadManager* manager; + HANDLE started; + HANDLE cleaned; +}; + +static DWORD WINAPI EngineExitWorker(void* argument) +{ + auto context = static_cast(argument); + SetEvent(context->started); + while (!context->manager->OnSleep(1)) Sleep(1); + // Resource cleanup must finish before the engine lifecycle callback returns. + SetEvent(context->cleaned); + return 0; +} + +static void CheckEngineExit() +{ + TestEngine engine; + IEngine* enginePointer = &engine; + for (int state : { DLL_INACTIVE, DLL_CLOSE, DLL_RESTART, DLL_ACTIVE, -1 }) + { + engine.state = state; + eng = state == -1 ? NULL : &enginePointer; + CThreadManager manager(NULL, NULL); + g_ThreadManager_Engine = &manager; + EngineExitContext context = { &manager, CreateEvent(NULL, TRUE, FALSE, NULL), + CreateEvent(NULL, TRUE, FALSE, NULL) }; + CHECK(context.started && context.cleaned); + HANDLE worker = CreateThread(NULL, 0, EngineExitWorker, &context, 0, NULL); + CHECK(worker != NULL); + HANDLE duplicate = NULL; + CHECK(DuplicateHandle(GetCurrentProcess(), worker, GetCurrentProcess(), &duplicate, + 0, FALSE, DUPLICATE_SAME_ACCESS)); + static_cast(manager).OnCreateThread(duplicate); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(context.started, 5000)); + Engine_WaitForShutdown(NULL, NULL); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(context.cleaned, 0)); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 0)); + Engine_WaitForShutdown(NULL, NULL); + CloseHandle(worker); + CloseHandle(context.started); + CloseHandle(context.cleaned); + } + eng = NULL; + g_ThreadManager_Engine = NULL; + Engine_WaitForShutdown(NULL, NULL); +} + static DWORD engineThreadId; static SOCKET socketHandle = INVALID_SOCKET; static HANDLE shutdownWorker = NULL; @@ -286,6 +336,7 @@ int main() g_pMetaHookAPI = &api; g_MainThreadId = (HANDLE)GetCurrentThreadId(); CheckUnloadRouting(); + CheckEngineExit(); TestManager manager; AddThreadManager(&manager); g_NetworkManager = &manager;