Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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`)

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
$<$<CONFIG:Debug>:/INCREMENTAL>
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)。
Expand Down
63 changes: 63 additions & 0 deletions src/ThreadManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
{

Expand All @@ -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<bool> m_bStartTermination;
public:
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
{
Expand Down
1 change: 1 addition & 0 deletions src/ThreadManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
32 changes: 26 additions & 6 deletions src/privatehook.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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);
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading