fix(engine): catch native faults in Client::UseTime instead of crashing
See Changelog/2026-10-11-gametick-chatclient-guard.md.
This commit is contained in:
parent
46f8975295
commit
b77c631b8b
6 changed files with 260 additions and 7 deletions
46
Changelog/2026-10-11-gametick-chatclient-guard.md
Normal file
46
Changelog/2026-10-11-gametick-chatclient-guard.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# Game-tick crash guard (chatclient.dll null read)
|
||||
|
||||
RynthCore.SehTrampoline.dll native version 4 (previous: 3).
|
||||
|
||||
## The crash
|
||||
|
||||
On 2026-10-11 two idle clients died in the same second. Both CoreCLR dumps show the same fault on
|
||||
AC's main thread:
|
||||
|
||||
- AC's `Client::UseTime` called into `chatclient.dll` (Turbine's chat client in the AC folder).
|
||||
Three calls in, a `rep movsd` copy of about 2 MB read from address 0
|
||||
(`chatclient.dll+0x1050`, read of 0x00000000).
|
||||
- Both clients at once, both idle: most likely a bad or oversized message from the chat server.
|
||||
- The fault unwound into the engine's managed `UseTime` detour. CoreCLR treats a native access
|
||||
violation there as an unhandled exception and ends the process, so AC's own handlers never ran.
|
||||
Windows reported the follow-on fault in `coreclr.dll+0x2c27ae`, which is the runtime's fail-fast
|
||||
path, not the cause.
|
||||
- `native-crash.log` had no record: a null read is held back until the process exits normally,
|
||||
and the fail-fast skipped that.
|
||||
|
||||
## The fix
|
||||
|
||||
- `native/SehTrampoline/SehTrampoline.c`: new export `SEH_GameTickThiscall` calls
|
||||
`int __thiscall fn(this)` under `__try`. On an access violation it returns 0 with the faulting
|
||||
address (module-relative), the data address and the module name, and writes a full record
|
||||
(registers and stack sweep) to `native-crash.log`, at most 16 per process.
|
||||
- `Compatibility/GameTickHooks.cs`: AC's original `UseTime` goes through that wrapper when the
|
||||
loaded trampoline is version 4 or later. A caught fault drops that one tick, logs an `[ERR]`
|
||||
line, and returns 1 so AC's game loop keeps running (0 would make AC shut down). After 5 faults
|
||||
within 30 seconds the guard turns itself off for the session, so a client whose state is
|
||||
really broken still ends instead of spinning.
|
||||
- `Compatibility/SehTrampoline.cs`: the P/Invoke, and `NativeVersion` (cached). A running client
|
||||
keeps the trampoline DLL it started with, so a hot-reloaded engine meeting a v3 DLL logs
|
||||
"native AV guard OFF" and calls `UseTime` directly, as before.
|
||||
- `native/SehTrampoline/Build-SehTrampoline.ps1`: `-NoDeploy` builds into `bin\` without
|
||||
copying to the runtime folder.
|
||||
- `scripts/Publish-EngineCoreClr.ps1`: a trampoline DLL held by a running client is now moved
|
||||
aside (`.old-<time>`) like the loader and shim, so new launches get the new one. Before, it
|
||||
was skipped with a warning and every launch stayed on the old version until all clients closed.
|
||||
|
||||
## Tests
|
||||
|
||||
- The engine builds in Release (CoreCLR host).
|
||||
- An x86 harness against the new DLL: a clean call returns its value, a null read is caught and
|
||||
attributed to the right module, and a call after the caught fault works. Version reports 4.
|
||||
- Not yet seen in game: the chat-server fault can't be reproduced on demand.
|
||||
|
|
@ -1,6 +1,9 @@
|
|||
# Build-SehTrampoline.ps1
|
||||
# Compiles RynthCore.SehTrampoline.dll (x86 MSVC) and copies to the runtime.
|
||||
# Run from anywhere; finds VS automatically via vswhere.
|
||||
# -NoDeploy: build into bin\ only; leave C:\Games\RynthCore\Runtime untouched.
|
||||
|
||||
param([switch]$NoDeploy)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
|
|
@ -32,6 +35,7 @@ if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE
|
|||
|
||||
$size = (Get-Item "$out\RynthCore.SehTrampoline.dll").Length
|
||||
Write-Host "Built: RynthCore.SehTrampoline.dll ($size bytes)"
|
||||
if ($NoDeploy) { return }
|
||||
|
||||
$runtimeDst = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll"
|
||||
Copy-Item "$out\RynthCore.SehTrampoline.dll" $runtimeDst -Force
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@
|
|||
#include <windows.h>
|
||||
|
||||
/* File version of this native module (bump with every behavioural change). */
|
||||
#define RC_SEH_TRAMPOLINE_VERSION 3 /* v3: CoreCLR-hosted engine AVs logged immediately */
|
||||
#define RC_SEH_TRAMPOLINE_VERSION 4 /* v4: SEH_GameTickThiscall (Client::UseTime guard) */
|
||||
|
||||
/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */
|
||||
static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */
|
||||
|
|
@ -780,3 +780,92 @@ __declspec(dllexport) unsigned int __cdecl RC_TagParserSkipCount(void)
|
|||
{
|
||||
return (unsigned int)g_tagParserSkips;
|
||||
}
|
||||
|
||||
/* ── Game-tick guard (v4) ─────────────────────────────────────────────────
|
||||
* Client::UseTime (0x00411FA0) is detoured by a MANAGED hook. An AV inside AC's tick
|
||||
* (e.g. chatclient.dll+0x1050 copying a ~2 MB chat-server message from a null buffer,
|
||||
* 2026-10-11, two clients in the same second) unwinds into that managed frame, which
|
||||
* CoreCLR treats as an unhandled exception and fail-fasts; AC's own handlers further
|
||||
* up never run. This wrapper catches the AV in native code first.
|
||||
*
|
||||
* The filter runs on the faulting thread before unwinding, so it records the faulting
|
||||
* address, the data address and the module name, and writes a full record (registers +
|
||||
* stack sweep) to the crash log, capped at CL_MAX_GAMETICK records per process. */
|
||||
#define CL_MAX_GAMETICK 16
|
||||
static volatile LONG g_gameTickRecords = 0;
|
||||
|
||||
typedef struct {
|
||||
unsigned int exAddr;
|
||||
unsigned int dataAddr;
|
||||
char* module;
|
||||
int moduleCap;
|
||||
} GT_FAULT;
|
||||
|
||||
/* int __thiscall fn(this) — no stack args; EAX is returned whole, as AC's caller tests AL. */
|
||||
static int __cdecl _helper_thiscall_int_noarg(void* fn_ptr, void* this_ptr)
|
||||
{
|
||||
int result = 0;
|
||||
__asm {
|
||||
mov ecx, this_ptr
|
||||
call fn_ptr
|
||||
mov result, eax
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static int gt_filter(PEXCEPTION_POINTERS ep, GT_FAULT* f)
|
||||
{
|
||||
HMODULE hm = NULL;
|
||||
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
f->exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
|
||||
f->dataAddr = ep->ExceptionRecord->NumberParameters >= 2
|
||||
? (unsigned int)ep->ExceptionRecord->ExceptionInformation[1] : 0;
|
||||
if (f->module && f->moduleCap > 0) {
|
||||
f->module[0] = 0;
|
||||
/* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */
|
||||
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)f->exAddr, &hm) && hm) {
|
||||
cl_module_leaf(hm, f->module, f->moduleCap, 0);
|
||||
f->exAddr -= (unsigned int)(UINT_PTR)hm; /* module-relative when resolved */
|
||||
}
|
||||
}
|
||||
if (!t_inLogger && InterlockedIncrement(&g_gameTickRecords) <= CL_MAX_GAMETICK) {
|
||||
CL_SLOT* s;
|
||||
t_inLogger = 1;
|
||||
s = cl_claim_slot();
|
||||
if (s) {
|
||||
s->len = cl_format(s->text, CL_SLOT_BYTES, ep,
|
||||
"AV CAUGHT IN GAME TICK (Client::UseTime guard; tick dropped, client kept running)");
|
||||
cl_append_file(s->text, s->len);
|
||||
InterlockedExchange(&s->state, CL_SLOT_DONE);
|
||||
}
|
||||
t_inLogger = 0;
|
||||
}
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
}
|
||||
|
||||
/* Calls int __thiscall fn(this) under SEH. Returns 1 when the call completed, 0 when an
|
||||
* AV was caught; on 0, *out_exAddr is module-relative if module[0] != 0, else absolute. */
|
||||
__declspec(dllexport) int __cdecl
|
||||
SEH_GameTickThiscall(void* fn, void* this_ptr, int* out_result,
|
||||
unsigned int* out_exAddr, unsigned int* out_dataAddr,
|
||||
char* module, int moduleCap)
|
||||
{
|
||||
GT_FAULT f;
|
||||
f.exAddr = 0; f.dataAddr = 0; f.module = module; f.moduleCap = moduleCap;
|
||||
*out_result = 0; *out_exAddr = 0; *out_dataAddr = 0;
|
||||
if (module && moduleCap > 0) { module[0] = 0; }
|
||||
RC_SEH_ENTER();
|
||||
__try {
|
||||
*out_result = _helper_thiscall_int_noarg(fn, this_ptr);
|
||||
}
|
||||
__except(gt_filter(GetExceptionInformation(), &f)) {
|
||||
RC_SEH_LEAVE();
|
||||
*out_exAddr = f.exAddr;
|
||||
*out_dataAddr = f.dataAddr;
|
||||
return 0;
|
||||
}
|
||||
RC_SEH_LEAVE();
|
||||
return 1;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,8 +85,17 @@ if (-not $EngineOnly) {
|
|||
$sameSeh = (Test-Path $sehDest) -and ((Resolve-Path $seh).Path -eq $sehDest -or
|
||||
(Get-FileHash $seh).Hash -eq (Get-FileHash $sehDest).Hash)
|
||||
if (-not $sameSeh) {
|
||||
# Same move-aside as the loader and shim: a locked copy would otherwise keep every
|
||||
# new launch on the old trampoline until all clients close.
|
||||
try { Copy-Item $seh $sehDest -Force -ErrorAction Stop }
|
||||
catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." }
|
||||
catch {
|
||||
try {
|
||||
Rename-Item $sehDest ("RynthCore.SehTrampoline.dll.old-{0:yyyyMMddHHmmss}" -f (Get-Date)) -ErrorAction Stop
|
||||
Copy-Item $seh $sehDest -Force -ErrorAction Stop
|
||||
Write-Host "RynthCore.SehTrampoline.dll was in use: moved the old one aside; new launches get the new one."
|
||||
}
|
||||
catch { Write-Warning "RynthCore.SehTrampoline.dll changed but is in use by a running client; it gets the new one when it restarts." }
|
||||
}
|
||||
}
|
||||
|
||||
# App-local runtime: the win-x86 runtime pack the SDK restores (same version the engine was built against).
|
||||
|
|
|
|||
|
|
@ -49,10 +49,21 @@ internal static class GameTickHooks
|
|||
|
||||
private static ThisCallBoolDelegate? _originalUseTime;
|
||||
private static ThisCallBoolDelegate? _useTimeDetour;
|
||||
private static IntPtr _originalUseTimePtr;
|
||||
private static IntPtr _targetAddress;
|
||||
private static int _installed;
|
||||
private static int _exitLatch;
|
||||
|
||||
// Native SEH guard around AC's tick (SehTrampoline v4+). A native AV that unwinds into
|
||||
// this managed detour is fatal under CoreCLR; caught natively, it drops one tick instead.
|
||||
// More than MaxTickFaults within TickFaultWindowMs means AC's state is broken rather than
|
||||
// one bad message, so the guard turns itself off and the next fault ends the client.
|
||||
private const int MaxTickFaults = 5;
|
||||
private const long TickFaultWindowMs = 30_000;
|
||||
private static bool _tickGuard;
|
||||
private static int _tickFaults;
|
||||
private static long _tickFaultWindowStart;
|
||||
|
||||
// Verified unique + lands exactly at UseTimeVa offline (tools/pe_pattern.py).
|
||||
// Replaces the prior warn-only prologue check; null = wildcard (rel32 call operand).
|
||||
private static readonly byte?[] UseTimePattern = [ 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0xE8, null, null, null, null, 0x84, 0xC0, 0x74 ];
|
||||
|
|
@ -87,12 +98,14 @@ internal static class GameTickHooks
|
|||
_targetAddress = resolved.Address;
|
||||
_useTimeDetour = UseTimeDetour;
|
||||
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
|
||||
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
|
||||
MinHook.HookCreate(_targetAddress, detourPtr));
|
||||
_originalUseTimePtr = MinHook.HookCreate(_targetAddress, detourPtr);
|
||||
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(_originalUseTimePtr);
|
||||
_tickGuard = SehTrampoline.IsAvailable && SehTrampoline.NativeVersion >= 4;
|
||||
Thread.MemoryBarrier();
|
||||
MinHook.Enable(_targetAddress);
|
||||
Volatile.Write(ref _installed, 1);
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick.");
|
||||
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick; " +
|
||||
(_tickGuard ? "native AV guard on." : $"native AV guard OFF (SehTrampoline v{SehTrampoline.NativeVersion}, needs v4)."));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
|
@ -136,8 +149,19 @@ internal static class GameTickHooks
|
|||
|
||||
// Run AC's own game-logic + physics + animation pass.
|
||||
int result;
|
||||
try { result = _originalUseTime!(thisPtr); }
|
||||
catch { result = 0; }
|
||||
if (_tickGuard)
|
||||
{
|
||||
result = SehTrampoline.GameTickThiscall(_originalUseTimePtr, thisPtr, out bool avCaught,
|
||||
out uint exAddr, out uint dataAddr, out string module);
|
||||
// 0 would end AC's game loop; a dropped tick must keep it running.
|
||||
if (avCaught)
|
||||
result = OnTickFault(exAddr, dataAddr, module);
|
||||
}
|
||||
else
|
||||
{
|
||||
try { result = _originalUseTime!(thisPtr); }
|
||||
catch { result = 0; }
|
||||
}
|
||||
|
||||
// ── Game loop is exiting — quiesce BEFORE AC's teardown ──────────────
|
||||
// AC's main loop is `do { } while (UseTime() != 0)`; a 0 return means
|
||||
|
|
@ -214,4 +238,34 @@ internal static class GameTickHooks
|
|||
// MUST return Client::UseTime's own bool — AC loops do/while on it.
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs a native AV caught inside Client::UseTime and returns the value the detour hands
|
||||
/// back to AC's loop (always 1: keep running). Turns the guard off once faults exceed
|
||||
/// the budget, so a client with corrupted state still dies instead of spinning.
|
||||
/// </summary>
|
||||
private static int OnTickFault(uint exAddr, uint dataAddr, string module)
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
if (_tickFaults == 0 || now - _tickFaultWindowStart > TickFaultWindowMs)
|
||||
{
|
||||
_tickFaultWindowStart = now;
|
||||
_tickFaults = 0;
|
||||
}
|
||||
_tickFaults++;
|
||||
|
||||
string where = module.Length > 0 ? $"{module}+0x{exAddr:X}" : $"0x{exAddr:X8}";
|
||||
try
|
||||
{
|
||||
RynthLog.Error($"GameTickHooks: access violation inside Client::UseTime at {where} (data 0x{dataAddr:X8}); " +
|
||||
$"tick dropped, client kept running (fault {_tickFaults}/{MaxTickFaults} in {TickFaultWindowMs / 1000}s). Full record in native-crash.log.");
|
||||
if (_tickFaults >= MaxTickFaults)
|
||||
{
|
||||
_tickGuard = false;
|
||||
RynthLog.Error("GameTickHooks: Client::UseTime fault budget exhausted; native AV guard OFF for this session.");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,6 +82,32 @@ internal static class SehTrampoline
|
|||
/// </summary>
|
||||
public static bool IsAvailable => _available;
|
||||
|
||||
private static int _nativeVersion = -1;
|
||||
|
||||
/// <summary>
|
||||
/// Version of the loaded native DLL (0 when unavailable, 1 when it predates the version
|
||||
/// export). A running client keeps the DLL it started with, so a newer engine can meet
|
||||
/// an older trampoline; gate newer exports on this.
|
||||
/// </summary>
|
||||
public static uint NativeVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
int cached = System.Threading.Volatile.Read(ref _nativeVersion);
|
||||
if (cached >= 0)
|
||||
return (uint)cached;
|
||||
uint version = 0;
|
||||
if (_available)
|
||||
{
|
||||
try { version = _SehTrampolineVersion(); }
|
||||
catch (EntryPointNotFoundException) { version = 1; }
|
||||
catch { version = 0; }
|
||||
}
|
||||
System.Threading.Volatile.Write(ref _nativeVersion, (int)version);
|
||||
return version;
|
||||
}
|
||||
}
|
||||
|
||||
// ── P/Invoke declarations ──────────────────────────────────────────────
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrUint",
|
||||
|
|
@ -112,6 +138,11 @@ internal static class SehTrampoline
|
|||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern unsafe int _ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* arg2, int* outResult);
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_GameTickThiscall",
|
||||
CallingConvention = CallingConvention.Cdecl)]
|
||||
private static extern unsafe int _GameTickThiscall(IntPtr fn, IntPtr thisPtr, int* outResult,
|
||||
uint* outExAddr, uint* outDataAddr, byte* module, int moduleCap);
|
||||
|
||||
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_InstallCrashLogger",
|
||||
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
|
||||
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
|
||||
|
|
@ -207,4 +238,24 @@ internal static class SehTrampoline
|
|||
avCaught = _ThiscallIntUintPtr(fn, thisPtr, arg1, outStruct, &result) == 0;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// int __thiscall fn(this) — Client::UseTime. Requires <see cref="NativeVersion"/> >= 4.
|
||||
/// On a caught AV: avCaught=true, result 0, and the fault location; <paramref name="exAddr"/>
|
||||
/// is relative to <paramref name="module"/> when that is non-empty, else absolute.
|
||||
/// The native side also writes the full record to native-crash.log.
|
||||
/// </summary>
|
||||
public static unsafe int GameTickThiscall(IntPtr fn, IntPtr thisPtr, out bool avCaught,
|
||||
out uint exAddr, out uint dataAddr, out string module)
|
||||
{
|
||||
const int ModuleCap = 64;
|
||||
byte* name = stackalloc byte[ModuleCap];
|
||||
int result;
|
||||
uint ex, data;
|
||||
avCaught = _GameTickThiscall(fn, thisPtr, &result, &ex, &data, name, ModuleCap) == 0;
|
||||
exAddr = ex;
|
||||
dataAddr = data;
|
||||
module = avCaught ? (Marshal.PtrToStringAnsi((IntPtr)name) ?? string.Empty) : string.Empty;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue