diff --git a/AGENTS.md b/AGENTS.md index 7536991..c142a4a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,10 @@ It also fixes a Valve bug: the engine's `_restart` command did not shut the server down properly and leaked resources such as `CSteam3Server` — the hooked `_restart` runs `shutdownserver` first. +For SvEngine, Steam client shutdown is moved before `GL_Shutdown`, once per +engine lifetime. The engine's `SteamAPI_Shutdown` IAT call is suppressed because +it runs late on normal exit and is skipped on restart (MetaHookSv issue #898). + - **Project type**: Native C++ plugin (Windows DLL), MSVC x86 only - **Engine**: GoldSrc / SvEngine, with Sven Co-op specific gates (see Engine Compatibility) - **Framework**: MetaHookSV Plugin API (`IPluginsV4`, API 109 or newer; `LoadEngine` also rejects a launcher whose `MetaHookAPIVersion` is lower than the SDK constant) @@ -32,7 +36,7 @@ ThreadGuard/ │ └── VCLTL.cmake # VC-LTL 5.3.1 ├── scripts/ │ ├── build-ThreadGuard-x86-{Debug,Release}.bat -│ ├── manifests/threadguard.json # Gamedata manifest (one engine global) +│ ├── manifests/threadguard.json # eng global + 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 @@ -50,7 +54,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()`, registers `DllLoadNotification` and resolves the `eng` slot. 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` 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 @@ -74,6 +78,14 @@ Two deliberate gates: `InstallHook` uses `IATHook` for real modules and `BlobIATHook` for the blob engine, so only calls that go through that module's import table are intercepted. +SvEngine additionally installs an engine `SteamAPI_Shutdown` IAT hook and a +gamedata-resolved `GL_Shutdown(HWND, HDC, HGLRC)` cdecl inline hook. The former +suppresses the engine call; the latter calls the saved Steam API original once +before forwarding all three arguments. MetaHook fills saved original pointers +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`. ### 3. Thread managers (`src/ThreadManager.cpp`) @@ -161,7 +173,7 @@ Keep `cmake/Sources.cmake` as the explicit compile list (4 plugin units); `inclu ### gamedata -`scripts/manifests/threadguard.json` declares a single `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`). There are no function or patch records. +`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` → `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. diff --git a/CMakeLists.txt b/CMakeLists.txt index abb5feb..d85a83d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -62,9 +62,9 @@ set_target_properties(ThreadGuard PROPERTIES INTERPROCEDURAL_OPTIMIZATION_RELEAS install(TARGETS ThreadGuard RUNTIME DESTINATION svencoop/metahook/plugins) install(FILES "$" DESTINATION svencoop/metahook/plugins) -# ThreadGuard ships its own gamedata catalog, pruned to the single global it -# resolves, in a nested directory the launcher's catalog loader merges -# (metahook/gamedata/threadguard). The manifest lists that symbol; the +# ThreadGuard ships its own gamedata catalog, pruned to its engine symbols, +# in a nested directory the launcher's catalog loader merges +# (metahook/gamedata/threadguard). The manifest lists those symbols; the # synchronizer downloads the upstream catalog into a persistent cache, prunes # it, and publishes the result. option(THREADGUARD_SYNC_GAMEDATA "Download and prune ThreadGuard's gamedata catalog before building" ON) diff --git a/README.md b/README.md index 429a5de..59a1e48 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,24 @@ 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. +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 +that call and can leave Steam threads alive until process teardown. This keeps +the order `shutdownserver -> original _restart -> SteamAPI_Shutdown -> GL_Shutdown` +without exiting the launcher. See [issue #898](https://github.com/hzqst/MetaHookSv/issues/898). + +Verified on 2026-10-05 with Windows x86 Sven 10257 and MetaHook's normal exit +code 0 contract: the old ThreadGuard reproduced `0xC0000409` after +`osprey -> _restart -> quit`; the fixed DLL returned 0 for the same control. +Six further runs covered zero, one and three restarts, with HalflifeCLI both +enabled and disabled. Every restart restored `osprey` and native RCON, and all +six processes exited with 0. Renderer was temporarily disabled because of its +unrelated installed gamedata mismatch; plugin lists and temporary CLI config +were restored afterward. The Release build and all 11 gamedata snapshots passed +validation. Sven 8948 has Windows code-path and catalog verification only; +other engines and Renderer compatibility were not runtime-tested in this change. + # Install 1. Download and install [MetaHookSv](https://github.com/hzqst/MetaHookSv). @@ -23,7 +41,7 @@ It also fixes a Valve bug where the `_restart` command did not shut the server d 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 the plugin resolves at load time. +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. 5. Enjoy. diff --git a/README.zh-CN.md b/README.zh-CN.md index e8d9df5..7e9f274 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,6 +17,10 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 该插件还修复了 Valve 的一个 bug:`_restart` 命令没有正确关闭服务器,导致 `CSteam3Server` 对象出现资源泄漏。被 hook 后的 `_restart` 会先执行 `shutdownserver`以正确释放这些资源。 +对于 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 兼容性。 + ## 安装 1. 下载并安装 [MetaHookSv](https://github.com/hzqst/MetaHookSv)。 @@ -25,7 +29,7 @@ GoldSrc 的 Win32 线程代码在创建它的模块被卸载时可能仍在运 3. 在 `/SteamLibrary/steamapps/common/Sven Co-op/svencoop/metahook/configs/plugins.lst` 中添加 `ThreadGuard.dll`(单独占一行)。 -4. 保留随插件一同分发的 `svencoop/metahook/gamedata/threadguard` 目录:其中存放着插件在加载时解析的 `eng` 全局变量。 +4. 保留随插件一同分发的 `svencoop/metahook/gamedata/threadguard` 目录:其中存放着 `eng` 全局变量,以及 Sven Co-op 使用的 `GL_Shutdown` 函数。更新 DLL 时同时更新此目录。 5. 开始游戏。 diff --git a/scripts/manifests/threadguard.json b/scripts/manifests/threadguard.json index 37dc502..c6fc633 100644 --- a/scripts/manifests/threadguard.json +++ b/scripts/manifests/threadguard.json @@ -19,5 +19,13 @@ "engine": { "eng": "global" } - } + }, + "conditionalGroups": [ + { + "when": ["svencoop-8948", "svencoop-10257"], + "symbols": { + "GL_Shutdown": "function" + } + } + ] } diff --git a/src/plugins.cpp b/src/plugins.cpp index c2878c5..7ca3b10 100644 --- a/src/plugins.cpp +++ b/src/plugins.cpp @@ -52,9 +52,9 @@ void IPluginsV4::LoadEngine(cl_enginefunc_t *pEngfuncs) g_MainThreadId = (HANDLE)GetCurrentThreadId(); - g_pMetaHookAPI->RegisterLoadDllNotificationCallback(DllLoadNotification); - Engine_FillAddress(); + + g_pMetaHookAPI->RegisterLoadDllNotificationCallback(DllLoadNotification); } void IPluginsV4::LoadClient(cl_exportfuncs_t *pExportFunc) @@ -90,4 +90,4 @@ const char *IPluginsV4::GetVersion(void) return completeVersion; } -EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4); \ No newline at end of file +EXPOSE_SINGLE_INTERFACE(IPluginsV4, IPluginsV4, METAHOOK_PLUGIN_API_VERSION_V4); diff --git a/src/privatehook.cpp b/src/privatehook.cpp index d8d5bbe..a0db137 100644 --- a/src/privatehook.cpp +++ b/src/privatehook.cpp @@ -11,6 +11,29 @@ static_assert(METAHOOK_API_VERSION >= 109, "ThreadGuard resolves the engine IEng hook_t* g_pHook_FreeLibrary_Engine = NULL; hook_t* g_pHook_FreeLibrary_GameUI = NULL; +static hook_t* g_pHook_SteamAPI_Shutdown = NULL; +static hook_t* g_pHook_GL_Shutdown = NULL; +static void (__cdecl* g_pfn_SteamAPI_Shutdown)(void) = NULL; +static void (__cdecl* g_pfn_GL_Shutdown)(HWND, HDC, HGLRC) = NULL; +static bool g_bSteamShutdown = false; + +static void __cdecl NewSteamAPI_Shutdown(void) +{ + // SvEngine calls this too late on quit and skips it entirely on _restart. + // The GL_Shutdown hook owns the call for both paths. +} + +static void __cdecl NewGL_Shutdown(HWND window, HDC dc, HGLRC context) +{ + if (!g_bSteamShutdown) + { + g_bSteamShutdown = true; + g_pfn_SteamAPI_Shutdown(); + } + + g_pfn_GL_Shutdown(window, dc, context); +} + IThreadManager* g_ThreadManager_Engine = NULL; IThreadManager* g_ThreadManager_GameUI = NULL; IThreadManager* g_ThreadManager_ServerBrowser = NULL; @@ -63,12 +86,39 @@ 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); + if (g_iEngineType == ENGINE_SVENGINE) + { + g_pfn_GL_Shutdown = (decltype(g_pfn_GL_Shutdown))GamedataResolvePtr( + g_EngineDLLInfo.ImageBase, "engine", "GL_Shutdown", MH_GAMESYMBOL_KIND_FUNCTION); + } } void Engine_InstallHook(HMODULE hModule, BlobHandle_t hBlobModule) { if (hModule) { + if (g_iEngineType == ENGINE_SVENGINE) + { + g_bSteamShutdown = false; + g_pHook_SteamAPI_Shutdown = g_pMetaHookAPI->IATHook(hModule, + "steam_api.dll", "SteamAPI_Shutdown", NewSteamAPI_Shutdown, (void**)&g_pfn_SteamAPI_Shutdown); + // During LoadEngine, MetaHook fills the original pointer at transaction commit. + if (!g_pHook_SteamAPI_Shutdown) + { + Sys_Error("Could not hook engine SteamAPI_Shutdown import!"); + return; + } + g_pHook_GL_Shutdown = g_pMetaHookAPI->InlineHook((void*)g_pfn_GL_Shutdown, + NewGL_Shutdown, (void**)&g_pfn_GL_Shutdown); + if (!g_pHook_GL_Shutdown) + { + g_pMetaHookAPI->UnHook(g_pHook_SteamAPI_Shutdown); + g_pHook_SteamAPI_Shutdown = NULL; + Sys_Error("Could not hook engine GL_Shutdown!"); + return; + } + } + g_ThreadManager_Engine = CreateThreadManagerForModule(hModule); g_ThreadManager_Engine->InstallHook(hookflag_CreateThread | hookflag_WaitForSingleObject | hookflag_Sleep); @@ -86,6 +136,20 @@ void Engine_InstallHook(HMODULE hModule, BlobHandle_t hBlobModule) void Engine_UninstallHook(HMODULE hModule, BlobHandle_t hBlobModule) { + if (g_pHook_GL_Shutdown) + { + g_pMetaHookAPI->UnHook(g_pHook_GL_Shutdown); + g_pHook_GL_Shutdown = NULL; + } + if (g_pHook_SteamAPI_Shutdown) + { + g_pMetaHookAPI->UnHook(g_pHook_SteamAPI_Shutdown); + g_pHook_SteamAPI_Shutdown = NULL; + } + g_pfn_GL_Shutdown = NULL; + g_pfn_SteamAPI_Shutdown = NULL; + g_bSteamShutdown = false; + if (g_pHook_FreeLibrary_Engine) { g_pMetaHookAPI->UnHook(g_pHook_FreeLibrary_Engine); @@ -231,4 +295,4 @@ void DllLoadNotification(mh_load_dll_notification_context_t* ctx) ServerDLL_UninstallHook(ctx->hModule); } } -} \ No newline at end of file +}