diff --git a/AGENTS.md b/AGENTS.md index 2ab0efc..fbb0bab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,27 @@ it runs late on normal exit and is skipped on restart (MetaHookSv issue #898). - **Framework**: MetaHookSV Plugin API (`IPluginsV4`, API 109 or newer; `LoadEngine` also rejects a launcher whose `MetaHookAPIVersion` is lower than the SDK constant) - **Main dependencies**: MetaHook SDK (public API, `include/HLSDK`, `include/Interface`), the engine's `IEngine` interface, and the Win32 threading/module APIs. **No third-party library is linked and no Capstone headers are needed** +Issue #4 adds cooperative network-thread shutdown on all 11 Windows/BLOB engine +snapshots. The engine's `TerminateThread` import requests exit only for the +tracked `NET_ThreadFunc` worker whose ID matches `*dwNetThreadId`, then waits for +the real thread object. The worker exits in its unlocked `Sleep(1)` loop tail. +Only that worker's `select` waits are capped at 20 ms; after a request, +`NET_QueuePacket` returns false so continuous receive traffic cannot starve the +sleep boundary. Steam shutdown ordering from #898 is unchanged. + +`NET_Shutdown(void)` is hooked at entry to request and join the tracked worker +before the original function touches lag queues or sockets. Binary verification +of all 11 Windows snapshots found socket closure before the original late stop, +with worker select outside net_cs. The known Host_Shutdown and Sven +RunListenServer callers do not hold net_cs at this entry. Do not extrapolate +from reconstructed source or classic Linux: hl-8684/10210 hw.so has no active +network worker, whereas Sven hw.so does. Original cleanup and repeated calls +remain intact; general NET_Config(false) transitions do not stop the worker. +The entry hook waits using a fresh owned duplicate obtained under the state +mutex, then waits and closes it outside that mutex. A live identity mismatch +is fatal before cleanup; an already-signaled retained object is safe even if +the engine has cleared its public thread ID. + ## Project Structure ``` @@ -26,6 +47,7 @@ ThreadGuard/ │ ├── privatehook.h # Engine_FillAddress / Engine_WaitForShutdown / DllLoadNotification │ ├── ThreadManager.cpp # Manager registry, the three API wrappers, CThreadManager │ ├── ThreadManager.h # IThreadManager interface and the hookflag_* values +│ ├── NetworkThreadState.h # Atomic identity/request and owned duplicate handle │ ├── exportfuncs.cpp # EngineCommand_InstallHook and the `_restart` fix │ ├── exportfuncs.h # EngineCommand_InstallHook declaration │ └── enginedef.h # IEngine state constants (DLL_INACTIVE … DLL_RESTART) @@ -36,7 +58,7 @@ ThreadGuard/ │ └── VCLTL.cmake # VC-LTL 5.3.1 ├── scripts/ │ ├── build-ThreadGuard-x86-{Debug,Release}.bat -│ ├── manifests/threadguard.json # eng global + SvEngine GL_Shutdown +│ ├── manifests/threadguard.json # eng + network symbols + SvEngine GL_Shutdown │ ├── sync-gamedata.py # Prunes the upstream catalog into the build tree │ └── validate-gamedata.py # Validates it before the plugin target builds ├── thirdparty/cache/ # Ignored VC-LTL binary cache @@ -46,7 +68,9 @@ ThreadGuard/ └── CMakeLists.txt # Windows MSVC x86 build and install rules ``` -There is no `docs/` directory, no assets and no test suite. +There is no `docs/` directory or checked-in asset tree. `tests/` is a standalone +Win32 CMake project with thread-state and actual-handler tests. Its host API is +a fatal-error stub; it does not test real IAT installation or symbol resolution. ## Core Modules @@ -54,7 +78,7 @@ There is no `docs/` directory, no assets and no test suite. `IPluginsV4` exported through `EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4)`: -- `LoadEngine`: rejects a mismatched host with `Sys_Error("MetaHookAPIVersion too low! expect %d, got %d !")`, collects the file system and engine type/buildnum, copies `cl_enginefunc_t`, records `g_MainThreadId` with `GetCurrentThreadId()`, resolves `eng` and (SvEngine only) `GL_Shutdown`, then registers `DllLoadNotification`. It installs **no** hooks directly +- `LoadEngine`: rejects a mismatched host with `Sys_Error("MetaHookAPIVersion too low! expect %d, got %d !")`, collects the file system and engine type/buildnum, copies `cl_enginefunc_t`, records `g_MainThreadId` with `GetCurrentThreadId()`, resolves `eng`, `NET_ThreadFunc`, `dwNetThreadId`, `NET_QueuePacket`, `NET_Shutdown` and (SvEngine only) `GL_Shutdown`, then registers `DllLoadNotification`. It installs **no** hooks directly - `LoadClient`: copies the export table and calls `EngineCommand_InstallHook()` (the `_restart` fix) - `ExitGame`: calls `Engine_WaitForShutdown(GetEngineModule(), GetBlobEngineModule())` - `Shutdown`: unregisters the DLL-notification callback @@ -66,7 +90,7 @@ 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` | `FreeLibrary` IAT hook on the **engine's** import table, only when the game directory is `svencoop` | +| 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` | — | | `server.dll` | `CreateThread` only | enabled only when the game directory is `svencoop` | @@ -94,15 +118,31 @@ The registry is a `std::vector` behind `g_ThreadManagerLock`; ` The three wrappers are installed into `kernel32.dll` import slots: -- `NewCreateThread` calls the real `CreateThread` **first**, then attributes the call with `FindThreadManagerByVirtualAddress(_ReturnAddress())` — the `.text` range decides ownership. The returned handle is duplicated (`DuplicateHandle(..., THREAD_ALL_ACCESS, FALSE, DUPLICATE_SAME_ACCESS)`) and the duplicate is handed to `OnCreateThread`, so the manager owns a handle whose lifetime it controls; the **original** handle is returned to the caller unchanged. An unused `originalCreationFlags` local remains in the function +- `NewCreateThread` attributes the call with `FindThreadManagerByVirtualAddress(_ReturnAddress())`. Only the engine's exact `NET_ThreadFunc` entry is created suspended long enough to reset/publish its identity and retain its duplicate; the caller's original suspended flag is respected. Other threads retain the original creation flags. The returned handle is also duplicated for `OnCreateThread`, and the **original** is returned unchanged - `NewWaitForSingleObject` only intercepts `dwMilliseconds == 0` (the polling shape). While the manager is terminating, `OnWaitForSingleObject` returns true and the wrapper reports `WAIT_OBJECT_0` immediately instead of polling; every other timeout forwards to the real call -- `NewSleep` only intercepts `dwMilliseconds == 1`. While terminating, `OnSleep` returns true for any thread except `g_MainThreadId`, and the wrapper calls `ExitThread(0)` +- `NewSleep` only intercepts `dwMilliseconds == 1`. For the current tracked network thread, it calls `ExitThread(0)` only after an independent atomic request. All supported Windows callbacks were verified to use this engine Sleep import only at the unlocked loop tail (also confirmed by the user). Other workers retain the `StartTermination`/non-main-thread gate -Both "while terminating" behaviours are gated on `m_bStartTermination`, a plain `bool` set by `StartTermination` (no atomics; the flag is one-way). +Both "while terminating" behaviours are gated on the one-way atomic +`m_bStartTermination`. The engine manager also requests cooperative network exit +here as a fallback for shutdown paths that skip the original TerminateThread call. `OnCreateThread` takes `m_ThreadListLock`, tries `AddAliveThread` for a free slot, and on a full pool calls `FindAndRemoveSignaledAliveThread` (a `WaitForSingleObject(handle, 0)` scan) to reclaim a slot whose thread has already exited. If that also fails it calls `g_pMetaHookAPI->SysError("Failed to insert thread to thread manager!")` — a full pool fails loudly rather than dropping a thread. -`WaitForAliveThreadsToShutdown` snapshots the alive handles under `m_ThreadListLock`, then calls `WaitForMultipleObjects(numThreads, hThreads, TRUE, INFINITE)`, clears `m_hAliveThread` (outside the lock) and `CloseHandle`s each snapshot handle. A `#if 0` block that used to move them into `m_hClosedThread` is disabled. +Reclamation closes the old manager-owned duplicate before replacing its slot. +`NetworkThreadState` owns a separate duplicate until recreation or engine unload; +reset rejects a still-running worker. Stop requests verify the target handle's +ID and the engine DWORD, reject self-wait, and handle already-signaled threads +without mistaking a reused ID for a live predecessor. No registry/list/state +lock or RAII guard remains active across the blocking wait or `ExitThread`. +The worker retires its active atomic ID before ExitThread, so reuse after death +cannot make a different worker inherit its exit request. The retained duplicate +still identifies the old object for repeated stop calls until reset. + +`WaitForAliveThreadsToShutdown` moves alive handles into a local batch and clears +their slots under `m_ThreadListLock`, then waits and closes that owned batch +outside the lock. It repeats to include children registered by a terminating +parent. A failed wait is fatal. This prevents slot reclamation from closing a +handle already being waited on. The `#if 0` closed-thread path stays disabled. ### 4. Termination gates @@ -173,7 +213,12 @@ Keep `cmake/Sources.cmake` as the explicit compile list (4 plugin units); `inclu ### gamedata -`scripts/manifests/threadguard.json` declares the `engine` / **`eng`** global — the catalog symbol name is `eng`, not `engine` — across 11 engine snapshots (`cof-5936`, `hl-10210`, `hl-3248`, `hl-3266`, `hl-3329`, `hl-3647`, `hl-4554`, `hl-6153`, `hl-8684`, `svencoop-10257`, `svencoop-8948`). A conditional group additionally requires the `GL_Shutdown` function for both Sven snapshots. There are no patch records. +`scripts/manifests/threadguard.json` declares `eng`, `dwNetThreadId` (globals) and +`NET_ThreadFunc`, `NET_QueuePacket`, `NET_Shutdown` (functions) across all 11 snapshots +(`cof-5936`, `hl-10210`, `hl-3248`, `hl-3266`, `hl-3329`, `hl-3647`, `hl-4554`, +`hl-6153`, `hl-8684`, `svencoop-10257`, `svencoop-8948`). A conditional group +requires `GL_Shutdown` for both Sven snapshots. `NET_StartThread` is deliberately +not required: HL25 inlines it. There are no patch records or local scan fallbacks. `scripts/manifests/threadguard.json` → `scripts/sync-gamedata.py` → pruned catalog under `build/x86//assets/svencoop/metahook/gamedata/threadguard`, validated by `scripts/validate-gamedata.py` before the plugin target builds. Disable with `-DTHREADGUARD_SYNC_GAMEDATA=OFF`. When gamedata usage changes, update the manifest in the same change. @@ -187,7 +232,9 @@ Select **LaunchGame** and press F5; **DeployGame** builds, stages and copies the ### CI -`.github/workflows/livebuild.yml` and `release.yml` build and package the plugin. There is no test suite to run. +`.github/workflows/livebuild.yml` and `release.yml` build and package the plugin. +Run the separate `tests/` CMake project with Win32 Debug/Release and CTest (see +README). These tests do not replace live hook routing/shutdown verification. ## Engine Compatibility @@ -251,7 +298,7 @@ Runtime configuration: `ThreadGuard.dll` must be listed in the host's `metahook/ - Do not modify external sources or third-party sources; MetaHook is a read-only build input - MSVC x86 only. Keep the static CRT / VC-LTL and warning-level settings in `CMakeLists.txt` in sync with the other standalone plugin repositories - `README.md` and `README.zh-CN.md` are a pair: keep the managed-module table and build options consistent in both -- Verification distinguishes build checks from a real game run: there is no test suite here, and the hook routing, the shutdown wait and the `_restart` fix can only be observed in a live game. Claims about in-game behavior must not be made without evidence. Documentation changes need content, path and format checks, not a plugin rebuild +- Verification distinguishes handler tests from a real game run: actual IAT routing, gamedata resolution and `_restart` integration require a live game. Debugger output reports the network stop request, safe Sleep exit and signaled wait. Claims about in-game behavior must not be made without evidence. Documentation changes need content, path and format checks, not a plugin rebuild ## Related Links diff --git a/README.md b/README.md index b807ac4..197e363 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,30 @@ 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. +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 +identifies each creation through `NET_ThreadFunc`, tracks its own duplicate +handle, and checks the live `dwNetThreadId` value. The engine's target +`TerminateThread` call instead requests exit and waits for the real thread to +finish. The worker calls `ExitThread(0)` from its unlocked `Sleep(1)` loop tail. +Other threads' termination calls keep their original behavior. + +The `NET_Shutdown` entry hook requests and joins this worker before calling the +original shutdown. All 11 Windows binaries close sockets before their original +thread stop, and the worker calls `select` outside the network lock. Waiting at +entry prevents that shutdown from closing sockets under an in-flight `select` +and prevents the worker from repopulating the lag queues during cleanup. The +original function still owns queue cleanup, socket closure and lock destruction. +Repeated shutdown and disabled threaded networking retain original cleanup. + +Only this worker's `select` waits are capped at 20 ms (shorter waits are kept). +After an exit request, `NET_QueuePacket` returns no packet, allowing even a busy +receive loop to unlock and reach that sleep. No network flags are cleared early, +no caller-owned handles are closed, and there is no timeout fallback to a forced +kill. Creation publishes the identity before resuming the worker, and recreation +or engine reload resets the request. See [issue #4](https://github.com/MetaHookSv/ThreadGuard/issues/4). + On Windows Sven Co-op 8948/10257, ThreadGuard also closes the Steam client before `GL_Shutdown`, once per engine lifetime. SvEngine's original late `SteamAPI_Shutdown` import call is suppressed; its restart path otherwise skips @@ -41,10 +65,33 @@ other engines and Renderer compatibility were not runtime-tested in this change. 3. Add `ThreadGuard.dll` in `/SteamLibrary/steamapps/common/Sven Co-op/svencoop/metahook/configs/plugins.lst` as a newline. -4. Keep the `svencoop/metahook/gamedata/threadguard` directory shipped next to the plugin: it carries the `eng` global and, for Sven Co-op, the `GL_Shutdown` function. Update this catalog together with the DLL. +4. Keep the `svencoop/metahook/gamedata/threadguard` directory shipped next to the plugin: it carries `eng`, `NET_ThreadFunc`, `dwNetThreadId`, `NET_QueuePacket`, `NET_Shutdown`, and, for Sven Co-op, `GL_Shutdown`. Update this catalog together with the DLL. `NET_StartThread` is not required because HL25 inlines it. 5. Enjoy. +Verified on 2026-10-06: Debug and Release targeted tests passed, including 100 +real-thread stop/recreate cycles, infinite select, continuous receive and handle +reclamation. Sven 10257 passed 50 input-command exits and five controls. HL 10210, +HL 3266 BLOB and CoF 5936 recorded the request, safe Sleep exit and signaled wait, +and exited with code 0. The CoF input-command scenario lost RCON before quit; its +dump was retained and that scenario is not counted as passing. Other snapshots +have symbol generation, catalog validation and static call-path coverage only. + +After adding the pre-cleanup entry hook, the ordering regression first failed +with a live worker in the original resource callback, then passed in Debug and +Release. The 100-cycle handler test includes idle/busy workers, real socket +closure after join, repeated shutdown and disabled networking. Live verification +passed eight Sven 10257 cases (including disconnect, restart and no-network) +and one shutdown each on HL 10210, HL 3266 BLOB and CoF 5936. All exited with 0; +threaded runs logged the completed wait before original resource cleanup. +Game DLLs, launcher, catalogs and temporary configuration were restored. + +BLOB engines require MetaHook's ordinal-import fix: the loader records ordinal +imports and matches their original export addresses for named `BlobIATHook` and +`BlobHasImportEx` queries. No hardcoded ordinal or `select_import` gamedata is +needed. Publishing this change also requires upstream `NET_QueuePacket` symbols +for all 11 snapshots; local verification used the generated, validated catalog. + ## F5 debugging (optional) Install MetaHook and enable this plugin in the game's `plugins.lst` first. Configure a standalone Visual Studio Win32 solution: @@ -78,3 +125,19 @@ scripts\build-ThreadGuard-x86-Release.bat -DMETAHOOK_SOURCE_PATH=D:\MetaHook The path is the repository root that provides `include/metahook.h`, `include/HLSDK` and `include/Interface`. ThreadGuard resolves its symbols from the MetaHook gamedata catalog, links no third-party library and needs no Capstone headers. Pass `-DTHREADGUARD_SYNC_GAMEDATA=OFF` to build without downloading gamedata. + +## Targeted tests + +```powershell +cmake -S tests -B build/tests -A Win32 -DMETAHOOK_SOURCE_PATH=D:/MetaHookSv/MetaHook +cmake --build build/tests --config Release +ctest --test-dir build/tests -C Release --output-on-failure +``` + +Repeat with `Debug` for the debug configuration. These standalone tests use real +Win32 threads, sockets, locks and waits, but provide only the host's fatal-error +callback. They cover handler behavior, not MetaHook's IAT installation or gamedata +resolution; those require live game verification. The handler test includes 100 +stop/recreate cycles with idle sockets and continuous packets, creation failure, +suspended creation, non-target forwarding and handle counts. Debugger output +records the real stop request, safe sleep exit and signaled wait in a game run. diff --git a/README.zh-CN.md b/README.zh-CN.md index be0fd12..58f5a5a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,10 +17,22 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 该插件还修复了 Valve 的一个 bug:`_restart` 命令没有正确关闭服务器,导致 `CSteam3Server` 对象出现资源泄漏。被 hook 后的 `_restart` 会先执行 `shutdownserver`以正确释放这些资源。 +全部 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)。 + 对于 Windows Sven Co-op 8948/10257,ThreadGuard 还会在 `GL_Shutdown` 之前关闭 Steam 客户端,每轮引擎生命周期只调用一次。引擎原来的晚调用通过 `SteamAPI_Shutdown` IAT hook 屏蔽;否则其重启路径会跳过这次关闭,使 Steam 线程遗留到进程退出。处理顺序为 `shutdownserver -> 原始 _restart -> SteamAPI_Shutdown -> GL_Shutdown`,随后允许 launcher 重新加载引擎。参见 [issue #898](https://github.com/hzqst/MetaHookSv/issues/898)。 2026-10-05 实机验证:Windows x86 Sven 10257,MetaHook 正常退出契约为 0。旧版 ThreadGuard 在 `osprey -> _restart -> quit` 后复现 `0xC0000409`,修复后相同对照返回 0。另分别启用和禁用 HalflifeCLI,测试不重启、重启一次、连续重启三次,共六组;每次重启后均确认 `osprey` 和原生 RCON 可用,六组均以 0 退出。Renderer 因已安装版本的独立 gamedata 不匹配问题临时禁用;测试后恢复插件列表和临时 CLI 配置。Release 构建及全部 11 个 gamedata 快照校验通过。8948 仅核实 Windows 调用路径和符号产物,本次未实机验证其他引擎及 Renderer 兼容性。 +2026-10-06 网络线程修复验证:Debug / Release 定向测试均通过,包含真实线程的 100 次停止/重建、无限 select、持续收包及句柄回收。Sven 10257 的 50 次输入命令退出和五组对照均返回 0;HL 10210、HL 3266 BLOB 和 CoF 5936 的网络线程退出调试记录均包含请求、安全 Sleep 退出和等待 signaled,进程返回 0。CoF 输入命令场景在 quit 前失去 RCON 响应,已保留 dump,未计为该场景通过。其余快照仅完成符号生成、目录校验及静态调用路径核验,未逐一实机运行。 + +BLOB 引擎需要包含 ordinal 导入修复的 MetaHook:加载器记录 ordinal 导入,并通过原始导出地址支持 `BlobIATHook` / `BlobHasImportEx` 按名称查询 `select`。插件不依赖硬编码 ordinal 或 `select_import` gamedata。发布本修复前,还需发布上游全部 11 个快照的 `NET_QueuePacket` 符号;本地验证使用已生成并通过校验的目录。 + +`NET_Shutdown` 入口 hook 会先请求并等待该网络线程结束,再进入原关闭函数。实际核验的 11 个 Windows 二进制均先关闭 socket、后停止线程,而工作线程的 `select` 在网络锁外;提前等待可防止该关闭路径与在途 `select` 并发,也避免清理期间重新填入 lag 队列。队列清理、socket 关闭和锁销毁仍由原函数负责。重复关闭及未启用网络线程时,原资源清理仍正常执行。 + +补充关闭入口 hook 后,顺序回归测试先复现“原资源回调执行时线程仍存活”,修复后 Debug / Release 均通过。100 次 handler 循环覆盖空闲与持续收包、等待后关闭真实 socket、重复关闭和禁用网络线程。随后实测 Sven 10257 共 8 组(含断线、重启、禁用网络线程),以及 HL 10210、HL 3266 BLOB、CoF 5936 各一次退出,全部返回 0;启用网络线程的场景均记录到等待结束后才进入原资源清理。测试用 DLL、启动器、目录和临时配置均已恢复。 + ## 安装 1. 下载并安装 [MetaHookSv](https://github.com/hzqst/MetaHookSv)。 @@ -29,7 +41,7 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 3. 在 `/SteamLibrary/steamapps/common/Sven Co-op/svencoop/metahook/configs/plugins.lst` 中添加 `ThreadGuard.dll`(单独占一行)。 -4. 保留随插件一同分发的 `svencoop/metahook/gamedata/threadguard` 目录:其中存放着 `eng` 全局变量,以及 Sven Co-op 使用的 `GL_Shutdown` 函数。更新 DLL 时同时更新此目录。 +4. 保留随插件一同分发的 `svencoop/metahook/gamedata/threadguard` 目录:其中包含 `eng`、`NET_ThreadFunc`、`dwNetThreadId`、`NET_QueuePacket`、`NET_Shutdown`,以及 Sven Co-op 使用的 `GL_Shutdown`。更新 DLL 时同时更新此目录。HL25 已内联 `NET_StartThread`,因此不要求该符号。 5. 开始游戏。 @@ -66,3 +78,13 @@ scripts\build-ThreadGuard-x86-Release.bat -DMETAHOOK_SOURCE_PATH=D:\MetaHook 该路径为仓库根目录,需提供 `include/metahook.h`、`include/HLSDK` 与 `include/Interface`。 ThreadGuard 从 MetaHook 的 gamedata 目录解析其符号,不链接任何第三方库,也不需要 Capstone 头文件。传入 `-DTHREADGUARD_SYNC_GAMEDATA=OFF` 可在不下载 gamedata 的情况下构建。 + +## 定向测试 + +```powershell +cmake -S tests -B build/tests -A Win32 -DMETAHOOK_SOURCE_PATH=D:/MetaHookSv/MetaHook +cmake --build build/tests --config Release +ctest --test-dir build/tests -C Release --output-on-failure +``` + +将 `Release` 换成 `Debug` 可测试调试配置。独立测试使用真实 Win32 线程、socket、锁和等待函数,但只提供宿主的致命错误回调,用于验证 handler 行为;真实 IAT 安装及 gamedata 解析仍需游戏实测。handler 测试包含空闲 socket 和持续取包条件下的 100 次停止/重建,以及创建失败、挂起创建、非目标转发和句柄计数检查。实机调试输出记录退出请求、安全 Sleep 退出及真实等待 signaled 三个阶段。 diff --git a/scripts/manifests/threadguard.json b/scripts/manifests/threadguard.json index c6fc633..31dbf99 100644 --- a/scripts/manifests/threadguard.json +++ b/scripts/manifests/threadguard.json @@ -17,7 +17,11 @@ ], "symbols": { "engine": { - "eng": "global" + "eng": "global", + "NET_ThreadFunc": "function", + "dwNetThreadId": "global", + "NET_QueuePacket": "function", + "NET_Shutdown": "function" } }, "conditionalGroups": [ diff --git a/src/NetworkThreadState.h b/src/NetworkThreadState.h new file mode 100644 index 0000000..8bd73d3 --- /dev/null +++ b/src/NetworkThreadState.h @@ -0,0 +1,116 @@ +#pragma once + +#include +#include +#include + +// Creation/reset belong to the engine's serialized start/stop lifecycle. +// Readers on the worker only touch the published atomic identity and request. +class NetworkThreadState +{ +public: + enum class StopResult { NotTarget, Requested, Stopped, SelfWait, Failed }; + + bool PrepareCreate() { return Reset(); } + + bool Track(HANDLE thread) + { + std::lock_guard lock(m_lock); + const DWORD id = GetThreadId(thread); + if (m_thread || !id) + return false; + if (!DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), + &m_thread, 0, FALSE, DUPLICATE_SAME_ACCESS)) + return false; + m_exitRequested.store(false); + m_threadId.store(id); + return true; + } + + bool IsThread(DWORD currentId, DWORD engineId) const + { + return currentId != 0 && currentId == engineId && currentId == m_threadId.load(); + } + + bool ShouldExit(DWORD currentId, DWORD engineId) const + { + return IsThread(currentId, engineId) && m_exitRequested.load(); + } + + void RetireCurrentThread() + { + DWORD id = GetCurrentThreadId(); + m_threadId.compare_exchange_strong(id, 0); + } + + StopResult RequestStop(HANDLE thread, DWORD engineId, DWORD currentId = GetCurrentThreadId()) + { + std::lock_guard lock(m_lock); + return RequestStopLocked(thread, engineId, currentId); + } + + StopResult RequestTrackedStop(DWORD engineId, HANDLE* waitHandle = NULL) + { + std::lock_guard lock(m_lock); + if (waitHandle) + *waitHandle = NULL; + if (!m_thread) + return StopResult::NotTarget; + // A repeated shutdown may already have cleared the engine's ID. An + // exited object is safe; a live identity mismatch must block cleanup. + const auto result = WaitForSingleObject(m_thread, 0) == WAIT_OBJECT_0 + ? StopResult::Stopped : RequestStopLocked(m_thread, engineId, GetCurrentThreadId()); + if (result == StopResult::NotTarget) + return StopResult::Failed; + if (waitHandle && (result == StopResult::Requested || result == StopResult::Stopped) + && !DuplicateHandle(GetCurrentProcess(), m_thread, GetCurrentProcess(), + waitHandle, 0, FALSE, DUPLICATE_SAME_ACCESS)) + return StopResult::Failed; + return result; + } + + bool Reset() + { + std::lock_guard lock(m_lock); + if (m_thread && WaitForSingleObject(m_thread, 0) != WAIT_OBJECT_0) + return false; + m_threadId.store(0); + m_exitRequested.store(false); + if (m_thread) + CloseHandle(m_thread); + m_thread = NULL; + return true; + } + +private: + StopResult RequestStopLocked(HANDLE thread, DWORD engineId, DWORD currentId) + { + if (!m_thread) + return StopResult::NotTarget; + const DWORD id = GetThreadId(thread); + // Keep the object identity for repeated stops even after the worker + // retires its active ID immediately before ExitThread. + if (!id || id != engineId || id != GetThreadId(m_thread)) + return StopResult::NotTarget; + if (id == currentId) + return StopResult::SelfWait; + + const DWORD state = WaitForSingleObject(m_thread, 0); + if (state == WAIT_OBJECT_0) + { + // A finished thread's ID can be reused. Never request exit for a new + // live thread merely because it has the old numeric ID. + return WaitForSingleObject(thread, 0) == WAIT_OBJECT_0 + ? StopResult::Stopped : StopResult::NotTarget; + } + if (state != WAIT_TIMEOUT) + return StopResult::Failed; + m_exitRequested.store(true); + return StopResult::Requested; + } + + std::mutex m_lock; + HANDLE m_thread = NULL; + std::atomic m_threadId{ 0 }; + std::atomic m_exitRequested{ false }; +}; diff --git a/src/ThreadManager.cpp b/src/ThreadManager.cpp index 29b0044..e61c9be 100644 --- a/src/ThreadManager.cpp +++ b/src/ThreadManager.cpp @@ -1,14 +1,191 @@ +#include #include "metahook.h" #include "ThreadManager.h" +#include "NetworkThreadState.h" +#include "plugins.h" #include #include #include +#include static std::mutex g_ThreadManagerLock; static std::vector g_ThreadManagers; extern HANDLE g_MainThreadId; +static NetworkThreadState g_NetworkThread; +static IThreadManager* g_NetworkManager = NULL; +static LPTHREAD_START_ROUTINE g_NetworkEntry = NULL; +static DWORD* g_NetworkThreadId = NULL; +static int (__cdecl* g_pfn_NET_QueuePacket)(int) = NULL; +static void (__cdecl* g_pfn_NET_Shutdown)(void) = NULL; +static int (WSAAPI* g_pfn_select)(int, fd_set*, fd_set*, fd_set*, const timeval*) = NULL; +static hook_t* g_pHook_NetworkTerminate = NULL; +static hook_t* g_pHook_NetworkSelect = NULL; +static hook_t* g_pHook_NET_QueuePacket = NULL; +static hook_t* g_pHook_NET_Shutdown = NULL; +static constexpr long kNetworkPollMicroseconds = 20000; + +static bool IsNetworkThread() +{ + return g_NetworkThreadId && g_NetworkThread.IsThread(GetCurrentThreadId(), *g_NetworkThreadId); +} + +static bool NetworkExitRequested() +{ + return g_NetworkThreadId && g_NetworkThread.ShouldExit(GetCurrentThreadId(), *g_NetworkThreadId); +} + +static void NetworkTrace(const char* event, DWORD id) +{ + char message[160]; + sprintf_s(message, "[ThreadGuard] network thread %lu: %s\n", id, event); + OutputDebugStringA(message); +} + +static bool WaitForNetworkThread(HANDLE thread) +{ + // No registry, state or manager-list lock is held here. This is the + // real Win32 wait, never the engine's zero-timeout polling wrapper. + const DWORD wait = WaitForSingleObject(thread, INFINITE); + if (wait != WAIT_OBJECT_0) + { + Sys_Error("Waiting for network thread failed (wait %lu, error %lu)!", wait, GetLastError()); + return false; + } + NetworkTrace("thread signaled; engine cleanup may continue", GetThreadId(thread)); + return true; +} + +static BOOL WINAPI NewTerminateThread(HANDLE thread, DWORD exitCode) +{ + if (g_NetworkThreadId && FindThreadManagerByVirtualAddress(_ReturnAddress()) == g_NetworkManager) + { + const auto result = g_NetworkThread.RequestStop(thread, *g_NetworkThreadId); + if (result == NetworkThreadState::StopResult::SelfWait || result == NetworkThreadState::StopResult::Failed) + { + Sys_Error("Cannot safely stop network thread (self wait or invalid tracked handle)!"); + return FALSE; + } + if (result == NetworkThreadState::StopResult::Requested || result == NetworkThreadState::StopResult::Stopped) + { + NetworkTrace("cooperative stop requested", GetThreadId(thread)); + return WaitForNetworkThread(thread) ? TRUE : FALSE; + } + } + return TerminateThread(thread, exitCode); +} + +static int WSAAPI NewNetworkSelect(int nfds, fd_set* read, fd_set* write, fd_set* except, const timeval* timeout) +{ + // Bound this worker's waits even before a stop is requested: an already + // blocked select cannot observe a later atomic request. Preserve shorter + // timeouts and every other thread's original select semantics. + const timeval poll = { 0, kNetworkPollMicroseconds }; + if (IsNetworkThread() && (!timeout || timeout->tv_sec > 0 || timeout->tv_usec > poll.tv_usec)) + timeout = &poll; + return g_pfn_select(nfds, read, write, except, timeout); +} + +static int __cdecl NewNET_QueuePacket(int source) +{ + // False takes the normal no-packet path. The loop still unlocks and hands + // any already received message to its queue before reaching Sleep(1). + if (NetworkExitRequested()) + return 0; + return g_pfn_NET_QueuePacket(source); +} + +static void __cdecl NewNET_Shutdown(void) +{ + // All supported Windows engines close sockets before their late thread + // stop. Their worker's select is outside net_cs, so join before entering + // the original shutdown (and before it acquires net_cs to clear lag data). + HANDLE thread = NULL; + const auto result = g_NetworkThread.RequestTrackedStop(*g_NetworkThreadId, &thread); + if (result == NetworkThreadState::StopResult::SelfWait || result == NetworkThreadState::StopResult::Failed) + { + Sys_Error("Cannot safely stop network thread before resource shutdown!"); + return; + } + if (thread) + { + NetworkTrace("NET_Shutdown: cooperative stop requested", GetThreadId(thread)); + const bool stopped = WaitForNetworkThread(thread); + CloseHandle(thread); + if (!stopped) + return; + NetworkTrace("NET_Shutdown: network thread stopped before resource cleanup", *g_NetworkThreadId); + } + // Preserve the engine's resource cleanup and its later (now idempotent) + // TerminateThread call; do not clear IDs, flags, sockets or engine handles. + g_pfn_NET_Shutdown(); +} + +void NetworkThread_Configure(LPTHREAD_START_ROUTINE entry, DWORD* threadId, void* queuePacket, void* shutdown) +{ + g_NetworkEntry = entry; + g_NetworkThreadId = threadId; + g_pfn_NET_QueuePacket = (decltype(g_pfn_NET_QueuePacket))queuePacket; + g_pfn_NET_Shutdown = (decltype(g_pfn_NET_Shutdown))shutdown; +} + +void NetworkThread_InstallHook(IThreadManager* manager) +{ + g_NetworkManager = manager; + const auto module = manager->GetModule(); + const auto blob = manager->GetBlobModule(); + const char* socketModule = NULL; + for (const auto name : { "ws2_32.dll", "wsock32.dll" }) + { + if (module ? g_pMetaHookAPI->ModuleHasImportEx(module, name, "select") + : g_pMetaHookAPI->BlobHasImportEx(blob, name, "select")) + { + socketModule = name; + break; + } + } + if (!socketModule) + { + Sys_Error("Could not find engine select import for cooperative network shutdown!"); + return; + } + if (module) + { + g_pHook_NetworkTerminate = g_pMetaHookAPI->IATHook(module, "kernel32.dll", "TerminateThread", NewTerminateThread, NULL); + g_pHook_NetworkSelect = g_pMetaHookAPI->IATHook(module, socketModule, "select", NewNetworkSelect, (void**)&g_pfn_select); + } + else + { + g_pHook_NetworkTerminate = g_pMetaHookAPI->BlobIATHook(blob, "kernel32.dll", "TerminateThread", NewTerminateThread, NULL); + g_pHook_NetworkSelect = g_pMetaHookAPI->BlobIATHook(blob, socketModule, "select", NewNetworkSelect, (void**)&g_pfn_select); + } + g_pHook_NET_QueuePacket = g_pMetaHookAPI->InlineHook((void*)g_pfn_NET_QueuePacket, NewNET_QueuePacket, (void**)&g_pfn_NET_QueuePacket); + g_pHook_NET_Shutdown = g_pMetaHookAPI->InlineHook((void*)g_pfn_NET_Shutdown, NewNET_Shutdown, (void**)&g_pfn_NET_Shutdown); + if (!g_pHook_NetworkTerminate || !g_pHook_NetworkSelect || !g_pHook_NET_QueuePacket || !g_pHook_NET_Shutdown) + Sys_Error("Could not install cooperative network shutdown hooks!"); +} + +void NetworkThread_UninstallHook() +{ + if (!g_NetworkThread.Reset()) + { + Sys_Error("Network thread is still running during engine unload!"); + return; + } + for (auto hook : { g_pHook_NET_Shutdown, g_pHook_NET_QueuePacket, g_pHook_NetworkSelect, g_pHook_NetworkTerminate }) + if (hook) + g_pMetaHookAPI->UnHook(hook); + g_pHook_NET_QueuePacket = g_pHook_NetworkSelect = g_pHook_NetworkTerminate = NULL; + g_pHook_NET_Shutdown = NULL; + g_pfn_NET_QueuePacket = NULL; + g_pfn_NET_Shutdown = NULL; + g_pfn_select = NULL; + g_NetworkEntry = NULL; + g_NetworkThreadId = NULL; + g_NetworkManager = NULL; +} + IThreadManager * FindThreadManagerByVirtualAddress(PVOID VirtualAddress) { std::lock_guard lock(g_ThreadManagerLock); @@ -33,13 +210,26 @@ HANDLE WINAPI NewCreateThread( LPDWORD lpThreadId ) { - DWORD originalCreationFlags = dwCreationFlags; + auto ThreadManager = FindThreadManagerByVirtualAddress(_ReturnAddress()); + const bool network = g_NetworkEntry && lpStartAddress == g_NetworkEntry && ThreadManager == g_NetworkManager; + if (network && !g_NetworkThread.PrepareCreate()) + { + Sys_Error("Cannot recreate a network thread before its predecessor exits!"); + return NULL; + } - auto hThreadHandle = CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); + // Publish identity before the worker can enter its first blocking select. + // Preserve the caller's suspended state, entry point and original handle. + auto hThreadHandle = CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, + network ? dwCreationFlags | CREATE_SUSPENDED : dwCreationFlags, lpThreadId); if (hThreadHandle) { - auto ThreadManager = FindThreadManagerByVirtualAddress(_ReturnAddress()); + if (network && !g_NetworkThread.Track(hThreadHandle)) + { + Sys_Error("Could not retain network thread identity (error %lu)!", GetLastError()); + return hThreadHandle; + } if (ThreadManager) { @@ -49,6 +239,8 @@ HANDLE WINAPI NewCreateThread( ThreadManager->OnCreateThread(hNewThreadHandle); } } + if (network && !(dwCreationFlags & CREATE_SUSPENDED) && ResumeThread(hThreadHandle) == (DWORD)-1) + Sys_Error("Could not resume network thread (error %lu)!", GetLastError()); } return hThreadHandle; @@ -77,6 +269,18 @@ void WINAPI NewSleep(DWORD dwMilliseconds) { if (dwMilliseconds == 1) { + if (IsNetworkThread()) + { + if (NetworkExitRequested()) + { + // Verified for all supported Windows engines: this worker calls + // Sleep(1) only at the unlocked loop tail. No RAII scope is active. + NetworkTrace("safe Sleep(1); exiting", GetCurrentThreadId()); + g_NetworkThread.RetireCurrentThread(); + ExitThread(0); + } + return Sleep(dwMilliseconds); + } auto ThreadManager = FindThreadManagerByVirtualAddress(_ReturnAddress()); if (ThreadManager) @@ -119,7 +323,7 @@ class CThreadManager : public IThreadManager //for hw.dll hook_t* m_pHook_Sleep; - bool m_bStartTermination; + std::atomic m_bStartTermination; public: CThreadManager(HMODULE hModule, BlobHandle_t hBlob) { @@ -338,9 +542,10 @@ class CThreadManager : public IThreadManager { if (m_hAliveThread[i]) { - if (WAIT_OBJECT_0 == WaitForSingleObject(m_hAliveThread[i], 0)) - { - m_hAliveThread[i] = 0; + if (WAIT_OBJECT_0 == WaitForSingleObject(m_hAliveThread[i], 0)) + { + CloseHandle(m_hAliveThread[i]); + m_hAliveThread[i] = 0; if (pIndex) *pIndex = i; return true; @@ -372,53 +577,57 @@ class CThreadManager : public IThreadManager void StartTermination(void) override { + if (this == g_NetworkManager && g_NetworkThreadId) + { + // Preserve the old ExitGame fallback when an engine shutdown path + // reaches the manager without first calling TerminateThread. + const auto result = g_NetworkThread.RequestTrackedStop(*g_NetworkThreadId); + if (result == NetworkThreadState::StopResult::SelfWait || result == NetworkThreadState::StopResult::Failed) + Sys_Error("Cannot request network thread exit during engine termination!"); + } m_bStartTermination = true; } void WaitForAliveThreadsToShutdown(void) override { - HANDLE hThreads[MAXIMUM_WAIT_OBJECTS] = { 0 }; - DWORD numThreads = 0; - - if (1) + for (;;) { - std::lock_guard lock(m_ThreadListLock); - for (DWORD i = 0; i < _ARRAYSIZE(m_hAliveThread); ++i) + HANDLE hThreads[MAXIMUM_WAIT_OBJECTS] = { 0 }; + DWORD numThreads = 0; { - if (m_hAliveThread[i] != 0) + std::lock_guard lock(m_ThreadListLock); + for (DWORD i = 0; i < _ARRAYSIZE(m_hAliveThread); ++i) { - hThreads[numThreads] = m_hAliveThread[i]; - numThreads++; + if (m_hAliveThread[i] != 0) + { + hThreads[numThreads++] = m_hAliveThread[i]; + // Transfer ownership to this batch before dropping the lock. + m_hAliveThread[i] = NULL; + } } } - } - - if (numThreads != 0) - WaitForMultipleObjects(numThreads, hThreads, TRUE, INFINITE); - - memset(m_hAliveThread, 0, sizeof(m_hAliveThread)); + if (!numThreads) + return; + if (WaitForMultipleObjects(numThreads, hThreads, TRUE, INFINITE) != WAIT_OBJECT_0) + { + Sys_Error("Waiting for managed threads failed (error %lu)!", GetLastError()); + return; + } #if 0 - if (1) - { - std::lock_guard lock(m_ThreadListLock); - - for (DWORD i = 0; i < numThreads; ++i) { - if (hThreads[i] && !FindClosedThread(hThreads[i])) + std::lock_guard lock(m_ThreadListLock); + for (DWORD i = 0; i < numThreads; ++i) { - AddClosedThread(hThreads[i]); + if (hThreads[i] && !FindClosedThread(hThreads[i])) + AddClosedThread(hThreads[i]); } } - } #endif - - for (DWORD i = 0; i < numThreads; ++i) - { - if (hThreads[i]) - { + for (DWORD i = 0; i < numThreads; ++i) CloseHandle(hThreads[i]); - } + // A tracked parent can create a child while we are joining it. + // Drain that newly registered batch before permitting module unload. } } @@ -524,4 +733,4 @@ IThreadManager* CreateThreadManagerForBlob(BlobHandle_t hBlob) } return NULL; -} \ No newline at end of file +} diff --git a/src/ThreadManager.h b/src/ThreadManager.h index f15600d..ca86ecb 100644 --- a/src/ThreadManager.h +++ b/src/ThreadManager.h @@ -34,4 +34,8 @@ void AddThreadManager(IThreadManager* p); void DeleteThreadManager(IThreadManager* p); IThreadManager* FindThreadManagerByVirtualAddress(PVOID VirtualAddress); IThreadManager* CreateThreadManagerForModule(HMODULE hModule); -IThreadManager* CreateThreadManagerForBlob(BlobHandle_t hBlob); \ No newline at end of file +IThreadManager* CreateThreadManagerForBlob(BlobHandle_t hBlob); + +void NetworkThread_Configure(LPTHREAD_START_ROUTINE entry, DWORD* threadId, void* queuePacket, void* shutdown); +void NetworkThread_InstallHook(IThreadManager* manager); +void NetworkThread_UninstallHook(); diff --git a/src/privatehook.cpp b/src/privatehook.cpp index a0db137..46358af 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -86,6 +86,17 @@ void Engine_FillAddress(void) // gamedata provides the address of the engine module's global IEngine* slot, // so GetEngineDLLState keeps dereferencing it exactly once. eng = (decltype(eng))GamedataResolvePtr(g_EngineDLLInfo.ImageBase, "engine", "eng", MH_GAMESYMBOL_KIND_GLOBAL); + // Match the actual CreateThread entry, including engines where NET_StartThread + // is inlined (HL25) or shared as a tail block (old HL/BLOB). + auto networkEntry = (LPTHREAD_START_ROUTINE)GamedataResolvePtr( + g_EngineDLLInfo.ImageBase, "engine", "NET_ThreadFunc", MH_GAMESYMBOL_KIND_FUNCTION); + auto networkId = (DWORD*)GamedataResolvePtr( + g_EngineDLLInfo.ImageBase, "engine", "dwNetThreadId", MH_GAMESYMBOL_KIND_GLOBAL); + auto queuePacket = GamedataResolvePtr( + g_EngineDLLInfo.ImageBase, "engine", "NET_QueuePacket", MH_GAMESYMBOL_KIND_FUNCTION); + auto shutdown = GamedataResolvePtr( + g_EngineDLLInfo.ImageBase, "engine", "NET_Shutdown", MH_GAMESYMBOL_KIND_FUNCTION); + NetworkThread_Configure(networkEntry, networkId, queuePacket, shutdown); if (g_iEngineType == ENGINE_SVENGINE) { g_pfn_GL_Shutdown = (decltype(g_pfn_GL_Shutdown))GamedataResolvePtr( @@ -132,10 +143,14 @@ void Engine_InstallHook(HMODULE hModule, BlobHandle_t hBlobModule) g_ThreadManager_Engine = CreateThreadManagerForBlob(hBlobModule); g_ThreadManager_Engine->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Sleep); } + if (g_ThreadManager_Engine) + NetworkThread_InstallHook(g_ThreadManager_Engine); } void Engine_UninstallHook(HMODULE hModule, BlobHandle_t hBlobModule) { + NetworkThread_UninstallHook(); + eng = NULL; if (g_pHook_GL_Shutdown) { g_pMetaHookAPI->UnHook(g_pHook_GL_Shutdown); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..127534f --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,29 @@ +cmake_minimum_required(VERSION 3.21) +cmake_policy(SET CMP0091 NEW) +project(ThreadGuardTests LANGUAGES CXX) +if(NOT WIN32 OR NOT MSVC OR NOT CMAKE_SIZEOF_VOID_P EQUAL 4) + message(FATAL_ERROR "ThreadGuard tests require Windows MSVC x86 (-A Win32).") +endif() +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +set(METAHOOK_SOURCE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../MetaHook" CACHE PATH "Local MetaHook SDK") +if(NOT EXISTS "${METAHOOK_SOURCE_PATH}/include/metahook.h") + message(FATAL_ERROR "Set METAHOOK_SOURCE_PATH to the MetaHook SDK checkout.") +endif() +enable_testing() +add_executable(network_thread_state_test network_thread_state_test.cpp) +add_executable(network_hooks_test network_hooks_test.cpp) +target_include_directories(network_hooks_test PRIVATE + "${METAHOOK_SOURCE_PATH}/include" + "${METAHOOK_SOURCE_PATH}/include/HLSDK/common" + "${METAHOOK_SOURCE_PATH}/include/HLSDK/engine" + "${METAHOOK_SOURCE_PATH}/include/HLSDK/cl_dll" + "${METAHOOK_SOURCE_PATH}/include/HLSDK/public" + "${METAHOOK_SOURCE_PATH}/include/HLSDK/pm_shared" + "${METAHOOK_SOURCE_PATH}/include/Interface" + "${METAHOOK_SOURCE_PATH}/include/SourceSDK" + "${METAHOOK_SOURCE_PATH}/include/SourceSDK/tier0" + "${METAHOOK_SOURCE_PATH}/include/SourceSDK/tier1") +target_link_libraries(network_hooks_test PRIVATE ws2_32) +add_test(NAME network_thread_state COMMAND network_thread_state_test) +add_test(NAME network_handlers COMMAND network_hooks_test) +set_tests_properties(network_thread_state network_handlers PROPERTIES TIMEOUT 30) diff --git a/tests/network_hooks_test.cpp b/tests/network_hooks_test.cpp new file mode 100644 index 0000000..3f2a753 --- /dev/null +++ b/tests/network_hooks_test.cpp @@ -0,0 +1,250 @@ +// 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. +#include "../src/ThreadManager.cpp" +#include +#include + +metahook_api_t* g_pMetaHookAPI = NULL; +HANDLE g_MainThreadId = NULL; + +#define CHECK(condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); std::abort(); } } while (0) + +static void Fatal(const char* format, ...) +{ + va_list args; + va_start(args, format); + vfprintf(stderr, format, args); + va_end(args); + std::abort(); +} + +class TestManager : public IThreadManager +{ +public: + std::vector handles; + void StartTermination() override {} + void WaitForAliveThreadsToShutdown() override {} + void OnCreateThread(HANDLE thread) override { handles.push_back(thread); } + bool OnWaitForSingleObject(HANDLE, DWORD) override { return false; } + bool OnSleep(DWORD) override { return false; } + 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; } + BlobHandle_t GetBlobModule() const override { return NULL; } + void CloseDuplicates() + { + for (HANDLE h : handles) { CHECK(WAIT_OBJECT_0 == WaitForSingleObject(h, 0)); CloseHandle(h); } + handles.clear(); + } +}; + +static DWORD engineThreadId; +static SOCKET socketHandle = INVALID_SOCKET; +static HANDLE shutdownWorker = NULL; +static unsigned shutdownCalls = 0; +static HANDLE entered; +static CRITICAL_SECTION networkLock; +static std::atomic flood{ false }; +static std::atomic packets{ 0 }; +static int __cdecl Packet(int) { ++packets; return flood.load() ? 1 : 0; } + +static void OpenSocket() +{ + socketHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + CHECK(INVALID_SOCKET != socketHandle); + sockaddr_in address = {}; + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + CHECK(0 == bind(socketHandle, (sockaddr*)&address, sizeof(address))); +} + +static void __cdecl ShutdownResources() +{ + // Match the binary's ordering: resource cleanup precedes its late stop. + // The hook must have joined before ANY original cleanup starts. + if (shutdownWorker) + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(shutdownWorker, 0)); + CHECK(TryEnterCriticalSection(&networkLock)); + if (socketHandle != INVALID_SOCKET) + { + CHECK(0 == closesocket(socketHandle)); + socketHandle = INVALID_SOCKET; + } + LeaveCriticalSection(&networkLock); + if (shutdownWorker) + CHECK(NewTerminateThread(shutdownWorker, 0)); + ++shutdownCalls; +} + +static DWORD WINAPI Worker(void*) +{ + SetEvent(entered); + for (;;) + { + fd_set read; + FD_ZERO(&read); + FD_SET(socketHandle, &read); + if (!flood.load()) NewNetworkSelect(0, &read, NULL, NULL, NULL); + bool more; + do + { + EnterCriticalSection(&networkLock); + more = NewNET_QueuePacket(0) != 0; + LeaveCriticalSection(&networkLock); + } while (more); + NewSleep(1); + } +} + +static DWORD WINAPI OtherWorker(void*) { Sleep(INFINITE); return 0; } +static DWORD WINAPI FinishedWorker(void*) { return 0; } +struct SpawnContext { IThreadManager* manager; HANDLE childFinished; }; +static DWORD WINAPI ChildWorker(void* event) +{ + Sleep(100); + SetEvent((HANDLE)event); + return 0; +} +static DWORD WINAPI SpawningWorker(void* context) +{ + auto spawn = (SpawnContext*)context; + Sleep(30); + HANDLE child = CreateThread(NULL, 0, ChildWorker, spawn->childFinished, 0, NULL); + CHECK(child != NULL); + HANDLE duplicate = NULL; + CHECK(DuplicateHandle(GetCurrentProcess(), child, GetCurrentProcess(), &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)); + spawn->manager->OnCreateThread(duplicate); + CloseHandle(child); + return 0; +} + +int main() +{ + metahook_api_t api = {}; + api.SysError = Fatal; + g_pMetaHookAPI = &api; + g_MainThreadId = (HANDLE)GetCurrentThreadId(); + TestManager manager; + AddThreadManager(&manager); + g_NetworkManager = &manager; + NetworkThread_Configure(Worker, &engineThreadId, (void*)Packet, (void*)ShutdownResources); + g_pfn_select = select; + WSADATA data; + CHECK(0 == WSAStartup(MAKEWORD(2, 2), &data)); + entered = CreateEvent(NULL, TRUE, FALSE, NULL); + InitializeCriticalSection(&networkLock); + // Networking disabled: still forward resource cleanup on each invocation. + NewNET_Shutdown(); + NewNET_Shutdown(); + CHECK(2 == shutdownCalls); + OpenSocket(); + DWORD handlesBefore = 0, handlesAfter = 0; + NetworkTrace("handler test initialized", GetCurrentThreadId()); + GetProcessHandleCount(GetCurrentProcess(), &handlesBefore); + CHECK(NULL == NewCreateThread(NULL, SIZE_T(-1), Worker, NULL, + STACK_SIZE_PARAM_IS_A_RESERVATION, &engineThreadId)); + for (unsigned iteration = 0; iteration < 100; ++iteration) + { + if (socketHandle == INVALID_SOCKET) OpenSocket(); + flood.store((iteration & 1) != 0); + ResetEvent(entered); + HANDLE worker = NewCreateThread(NULL, 0, Worker, NULL, + iteration == 0 ? CREATE_SUSPENDED : 0, &engineThreadId); + CHECK(worker != NULL); + if (iteration == 0) + { + CHECK(WAIT_TIMEOUT == WaitForSingleObject(entered, 20)); + CHECK(1 == ResumeThread(worker)); + } + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(entered, 5000)); + Sleep(5); + CHECK(WAIT_TIMEOUT == WaitForSingleObject(worker, 0)); + const ULONGLONG start = GetTickCount64(); + if (iteration == 99) + { + CThreadManager shutdownManager(NULL, NULL); + g_NetworkManager = &shutdownManager; + static_cast(shutdownManager).StartTermination(); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 2000)); + g_NetworkManager = &manager; + } + else if (iteration % 3 == 0) + { + shutdownWorker = worker; + const unsigned before = shutdownCalls; + NewNET_Shutdown(); + NewNET_Shutdown(); + CHECK(before + 2 == shutdownCalls); + shutdownWorker = NULL; + } + else + CHECK(NewTerminateThread(worker, 0)); + CHECK(GetTickCount64() - start < 2000); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 0)); + CHECK(!g_NetworkThread.IsThread(engineThreadId, engineThreadId)); + CHECK(!g_NetworkThread.ShouldExit(engineThreadId, engineThreadId)); + CHECK(NewTerminateThread(worker, 0)); + CHECK(TryEnterCriticalSection(&networkLock)); + LeaveCriticalSection(&networkLock); + CHECK(g_NetworkThread.Reset()); + CloseHandle(worker); + manager.CloseDuplicates(); + } + // Match the handle-count baseline even if the last cycle closed its socket. + if (socketHandle == INVALID_SOCKET) OpenSocket(); + // Non-network TerminateThread calls still reach Win32 with their exit code. + DWORD otherId; + HANDLE other = NewCreateThread(NULL, 0, OtherWorker, NULL, 0, &otherId); + CHECK(NewTerminateThread(other, 42)); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(other, 5000)); + DWORD code = 0; + CHECK(GetExitCodeThread(other, &code) && code == 42); + CloseHandle(other); + manager.CloseDuplicates(); + GetProcessHandleCount(GetCurrentProcess(), &handlesAfter); + std::fprintf(stderr, "handles: before=%lu after=%lu\n", handlesBefore, handlesAfter); + CHECK(handlesBefore == handlesAfter); + // More than a pool's worth of stopped/recreated workers reuses signaled + // slots. The displaced manager duplicate must be closed, too. + CThreadManager pool(NULL, NULL); + IThreadManager& poolApi = pool; + for (unsigned i = 0; i <= MAXIMUM_WAIT_OBJECTS; ++i) + { + HANDLE h = CreateThread(NULL, 0, FinishedWorker, NULL, 0, NULL); + CHECK(h != NULL && WAIT_OBJECT_0 == WaitForSingleObject(h, 5000)); + HANDLE duplicate = NULL; + CHECK(DuplicateHandle(GetCurrentProcess(), h, GetCurrentProcess(), &duplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)); + poolApi.OnCreateThread(duplicate); + CloseHandle(h); + } + poolApi.WaitForAliveThreadsToShutdown(); + GetProcessHandleCount(GetCurrentProcess(), &handlesAfter); + CHECK(handlesBefore == handlesAfter); + HANDLE childFinished = CreateEvent(NULL, TRUE, FALSE, NULL); + CHECK(childFinished != NULL); + SpawnContext spawn = { &poolApi, childFinished }; + HANDLE parent = CreateThread(NULL, 0, SpawningWorker, &spawn, CREATE_SUSPENDED, NULL); + CHECK(parent != NULL); + HANDLE parentDuplicate = NULL; + CHECK(DuplicateHandle(GetCurrentProcess(), parent, GetCurrentProcess(), &parentDuplicate, 0, FALSE, DUPLICATE_SAME_ACCESS)); + poolApi.OnCreateThread(parentDuplicate); + CHECK(1 == ResumeThread(parent)); + poolApi.WaitForAliveThreadsToShutdown(); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(childFinished, 0)); + CloseHandle(parent); + CloseHandle(childFinished); + GetProcessHandleCount(GetCurrentProcess(), &handlesAfter); + CHECK(handlesBefore == handlesAfter); + CHECK(packets.load() > 0); + DeleteCriticalSection(&networkLock); + CloseHandle(entered); + closesocket(socketHandle); + WSACleanup(); + DeleteThreadManager(&manager); + std::puts("PASS 100 handler stop/recreate cycles: idle select, continuous packets, unlocked exit, forwarding, no handle growth"); +} diff --git a/tests/network_thread_state_test.cpp b/tests/network_thread_state_test.cpp new file mode 100644 index 0000000..6187f6d --- /dev/null +++ b/tests/network_thread_state_test.cpp @@ -0,0 +1,72 @@ +#include "../src/NetworkThreadState.h" +#include +#include + +#define CHECK(condition) do { if (!(condition)) { std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); std::abort(); } } while (0) + +static DWORD WINAPI WaitForRelease(void* event) +{ + WaitForSingleObject(event, INFINITE); + return 0; +} + +int main() +{ + NetworkThreadState state; + const DWORD mainThread = GetCurrentThreadId(); + CHECK(!state.IsThread(mainThread, mainThread)); + CHECK(state.PrepareCreate()); + // A failed CreateThread leaves no identity or exit request behind. + CHECK(!state.IsThread(mainThread, mainThread)); + CHECK(state.PrepareCreate()); + HANDLE release = CreateEvent(NULL, TRUE, FALSE, NULL); + CHECK(release != NULL); + DWORD id = 0; + HANDLE worker = CreateThread(NULL, 0, WaitForRelease, release, 0, &id); + CHECK(worker != NULL); + CHECK(state.Track(worker)); + CHECK(state.IsThread(id, id)); + CHECK(!state.IsThread(mainThread, id)); + CHECK(!state.IsThread(id, mainThread)); + CHECK(!state.ShouldExit(id, id)); + CHECK(!state.PrepareCreate()); + CHECK(NetworkThreadState::StopResult::NotTarget == state.RequestStop(GetCurrentThread(), id)); + CHECK(NetworkThreadState::StopResult::NotTarget == state.RequestStop(worker, mainThread)); + HANDLE waitHandle = NULL; + CHECK(NetworkThreadState::StopResult::Failed == state.RequestTrackedStop(mainThread, &waitHandle)); + CHECK(NULL == waitHandle); + CHECK(!state.ShouldExit(id, id)); + CHECK(NetworkThreadState::StopResult::Requested == state.RequestTrackedStop(id, &waitHandle)); + CHECK(NULL != waitHandle && waitHandle != worker); + CHECK(NetworkThreadState::StopResult::Requested == state.RequestStop(worker, id)); + CHECK(state.ShouldExit(id, id)); + CHECK(!state.ShouldExit(mainThread, id)); + CHECK(NetworkThreadState::StopResult::Requested == state.RequestStop(worker, id)); + CHECK(!state.Reset()); + SetEvent(release); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 5000)); + CHECK(NetworkThreadState::StopResult::Stopped == state.RequestStop(worker, id)); + // The state owns a duplicate, never the engine's original handle. + CHECK(state.Reset()); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(waitHandle, 0)); + CloseHandle(waitHandle); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 0)); + CloseHandle(worker); + ResetEvent(release); + CHECK(state.PrepareCreate()); + worker = CreateThread(NULL, 0, WaitForRelease, release, 0, &id); + CHECK(worker != NULL && state.Track(worker)); + CHECK(!state.ShouldExit(id, id)); + CHECK(NetworkThreadState::StopResult::SelfWait == state.RequestStop(worker, id, id)); + CHECK(!state.ShouldExit(id, id)); + SetEvent(release); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(worker, 5000)); + // Repeated cleanup is safe after the engine has cleared its public ID. + CHECK(NetworkThreadState::StopResult::Stopped == state.RequestTrackedStop(0, &waitHandle)); + CHECK(WAIT_OBJECT_0 == WaitForSingleObject(waitHandle, 0)); + CloseHandle(waitHandle); + CHECK(state.Reset()); + CloseHandle(worker); + CloseHandle(release); + std::puts("PASS network identity, requests, failed creation, repeated stop, rebuild and handle ownership"); +}