Snapshot for release 2026.10.13.1 (internal 90a2f4a)

This commit is contained in:
Tom Bohar 2026-10-13 14:25:48 -04:00
commit 1d86acdf27
218 changed files with 24019 additions and 1517 deletions

View file

@ -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

View file

@ -0,0 +1,277 @@
/*
* CrashLogFilter.h - which exceptions the native crash logger (SehTrampoline.c) writes.
*
* Pure decision logic: no Win32 calls, no globals. The logger keeps one clf_state and
* calls these under its own lock; native\SehTrampoline\tests\CrashLogFilterTests.c
* runs them directly.
*
* Why: the logger used to write every first-chance AV until a cap of 24 per process.
* Decal's .NET Framework plugins raise a handled null-reference AV in JIT code (clr.dll
* and mscorlib frames) about once a minute, the SAME address each time, so the cap was
* spent within minutes: one client's 24 entries (all within about five minutes) were all
* exAddr 0x433620C8, and its fatal AV at 20:25 under GameTickHooks.UseTimeDetour left
* nothing in native-crash.log.
*
* Now:
* - Logged codes: access violation, fail-fast, stack buffer overrun, stack overflow,
* heap corruption.
* - Each faulting address has a slot with its hit count and the time it was last
* written. The first sighting is written. A repeat is written again (with its count)
* when the count is a power of two, when 30 s have passed since that address was
* last written, or when the code is not an AV. So a contained AV that later recurs
* as the fatal one is not swallowed as "seen before": a fatal fault is usually a
* terminate from some handler, and then no last-chance filter ever runs.
* - Noise is classified, written once per address like the rest, and never charged to
* the AC limit:
* .NET Framework (Decal plugins): faulting module clr.dll, mscorwks.dll, mscorlib;
* managed (the engine's CoreCLR): coreclr.dll, clrjit.dll, System.Private.CoreLib;
* or no module at all (JIT code) with the nearest module-resolved code pointer on the
* stack in one of those. Only AVs are ever noise.
* - A first sighting of anything else (AC's faults) is charged to CLF_MAX_COUNTED, a
* flood guard on DISTINCT addresses only.
* - The last-chance (unhandled) entry is never charged to that limit and has its own
* small one (it happens once in a dying process; the limit only stops a loop).
* - A full address table evicts its least recently written NOISE slot. With no noise
* slot to evict, an AC address is still written (under the limit), just not tracked.
* - The last CLF_RING first-chance records, written or not, are kept in a ring (no I/O
* at exception time). A flush writes those that were not written one by one: the
* last-chance filter flushes, and so does the engine's crash-exit path (TerminateProcess
* and friends, through RC_FlushCrashLog). That recovers the case the dedupe alone
* cannot: the fatal hit of an address seen before, at a count that is not due a
* write, followed by a terminate from a handler, so no last-chance filter ever runs
* (checked with 5, 100 and 1000 contained hits before the fatal one).
*
* Times are GetTickCount milliseconds (32-bit; unsigned subtraction survives the wrap).
*/
#ifndef RYNTHCORE_CRASH_LOG_FILTER_H
#define RYNTHCORE_CRASH_LOG_FILTER_H
#define CLF_MAX_COUNTED 96
#define CLF_MAX_LAST_CHANCE 8
#define CLF_ADDR_SLOTS 128
#define CLF_RELOG_MS 30000u
#define CLF_CODE_ACCESS_VIOLATION 0xC0000005u
#define CLF_CODE_FAIL_FAST 0xC0000602u
#define CLF_CODE_STACK_BUFFER 0xC0000409u
#define CLF_CODE_STACK_OVERFLOW 0xC00000FDu
#define CLF_CODE_HEAP_CORRUPTION 0xC0000374u
/* What raised a fault. Anything but CLF_CLASS_AC is noise. */
typedef enum {
CLF_CLASS_AC = 0, /* AC, Decal native code, the engine's native code: counted */
CLF_CLASS_NETFX = 1, /* the .NET Framework (Decal's managed plugins) */
CLF_CLASS_MANAGED = 2, /* the engine's CoreCLR runtime and its JIT code */
} clf_class;
typedef enum {
CLF_SKIP_CODE = 0, /* not a code the logger writes */
CLF_LOG_COUNTED, /* write it; first sighting, charged to the limit */
CLF_LOG_NOISE, /* write it; first sighting of noise, not charged */
CLF_LOG_REPEAT, /* write it again; a repeat (see hits) */
CLF_LOG_LAST_CHANCE, /* write it; unhandled */
CLF_SKIP_REPEAT, /* a repeat not due to be written */
CLF_SKIP_CAP, /* limit reached */
} clf_decision;
typedef struct {
unsigned int addr;
unsigned int hits; /* sightings, the first included */
unsigned int lastWriteMs;
unsigned char cls; /* clf_class */
unsigned char used;
} clf_slot;
typedef struct {
clf_slot slots[CLF_ADDR_SLOTS];
unsigned int counted; /* AC first sightings charged to the limit */
unsigned int lastChance;
unsigned int noiseRepeats; /* noise repeats not written */
unsigned int otherRepeats; /* other repeats not written */
unsigned int overCap; /* not written: limit reached */
unsigned int untracked; /* AC addresses written but not tracked (table full of AC) */
} clf_state;
static int clf_is_logged_code(unsigned int code)
{
return code == CLF_CODE_ACCESS_VIOLATION || code == CLF_CODE_FAIL_FAST
|| code == CLF_CODE_STACK_BUFFER || code == CLF_CODE_STACK_OVERFLOW
|| code == CLF_CODE_HEAP_CORRUPTION;
}
static int clf_wide_ieq(const wchar_t* a, const char* b)
{
if (!a || !b) return 0;
for (;;) {
wchar_t ca = *a++;
char cb = *b++;
if (ca >= L'A' && ca <= L'Z') ca = (wchar_t)(ca - L'A' + L'a');
if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a');
if (ca != (wchar_t)(unsigned char)cb) return 0;
if (ca == 0) return 1;
}
}
/* Class of a module, by its leaf file name. */
static clf_class clf_module_class(const wchar_t* leaf)
{
if (clf_wide_ieq(leaf, "clr.dll") || clf_wide_ieq(leaf, "mscorwks.dll")
|| clf_wide_ieq(leaf, "mscorlib.dll") || clf_wide_ieq(leaf, "mscorlib.ni.dll"))
return CLF_CLASS_NETFX;
if (clf_wide_ieq(leaf, "coreclr.dll") || clf_wide_ieq(leaf, "clrjit.dll")
|| clf_wide_ieq(leaf, "System.Private.CoreLib.dll"))
return CLF_CLASS_MANAGED;
return CLF_CLASS_AC;
}
/*
* Class of a first-chance exception. faultClass: class of the faulting module (AC when in
* no module). faultInNoModule: the faulting address is in no module (JIT code).
* firstFrameClass: class of the nearest module-resolved code pointer on the stack.
*/
static clf_class clf_classify(unsigned int code, clf_class faultClass, int faultInNoModule, clf_class firstFrameClass)
{
if (code != CLF_CODE_ACCESS_VIOLATION) return CLF_CLASS_AC;
if (faultClass != CLF_CLASS_AC) return faultClass;
if (faultInNoModule) return firstFrameClass;
return CLF_CLASS_AC;
}
static clf_slot* clf_find(clf_state* s, unsigned int addr)
{
int i;
for (i = 0; i < CLF_ADDR_SLOTS; i++)
if (s->slots[i].used && s->slots[i].addr == addr) return &s->slots[i];
return 0;
}
static int clf_is_pow2(unsigned int v) { return v != 0 && (v & (v - 1)) == 0; }
/* A repeat at a tracked address. *hits gets the sighting count. */
static clf_decision clf_repeat(clf_state* s, clf_slot* slot, unsigned int code, unsigned int nowMs, unsigned int* hits)
{
slot->hits++;
if (hits) *hits = slot->hits;
if (clf_is_pow2(slot->hits) || nowMs - slot->lastWriteMs >= CLF_RELOG_MS || code != CLF_CODE_ACCESS_VIOLATION) {
slot->lastWriteMs = nowMs;
return CLF_LOG_REPEAT;
}
if (slot->cls != CLF_CLASS_AC) s->noiseRepeats++; else s->otherRepeats++;
return CLF_SKIP_REPEAT;
}
/* A free slot, else the least recently written noise slot, else none. */
static clf_slot* clf_take_slot(clf_state* s)
{
clf_slot* oldest = 0;
int i;
for (i = 0; i < CLF_ADDR_SLOTS; i++)
if (!s->slots[i].used) return &s->slots[i];
for (i = 0; i < CLF_ADDR_SLOTS; i++) {
clf_slot* c = &s->slots[i];
if (c->cls == CLF_CLASS_AC) continue;
if (!oldest || (int)(c->lastWriteMs - oldest->lastWriteMs) < 0) oldest = c;
}
return oldest;
}
/* First sighting of an address (clf_find found nothing). */
static clf_decision clf_new(clf_state* s, unsigned int code, unsigned int addr, clf_class cls, unsigned int nowMs)
{
clf_slot* slot;
if (cls == CLF_CLASS_AC) {
if (s->counted >= CLF_MAX_COUNTED) { s->overCap++; return CLF_SKIP_CAP; }
s->counted++;
}
slot = clf_take_slot(s);
if (slot) {
slot->addr = addr;
slot->hits = 1;
slot->lastWriteMs = nowMs;
slot->cls = (unsigned char)cls;
slot->used = 1;
} else {
s->untracked++;
}
(void)code;
return cls == CLF_CLASS_AC ? CLF_LOG_COUNTED : CLF_LOG_NOISE;
}
/* The whole first-chance decision in one call (the logger splits it to skip the module
* lookup for repeats). *hits gets the sighting count (1 for a first sighting). */
static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned int addr, clf_class cls,
unsigned int nowMs, unsigned int* hits)
{
clf_slot* slot;
if (hits) *hits = 1;
if (!clf_is_logged_code(code)) return CLF_SKIP_CODE;
slot = clf_find(s, addr);
if (slot) return clf_repeat(s, slot, code, nowMs, hits);
return clf_new(s, code, addr, cls, nowMs);
}
#define CLF_RING 16
/* One first-chance record kept for a later flush. */
typedef struct {
unsigned int seq; /* 1-based push number; 0 = empty */
unsigned int addr, code, eip, tid, tickMs, hits;
unsigned char written; /* written as an entry of its own when it happened */
} clf_rec;
/*
* The last CLF_RING first-chance records. Each record is offered to one flush only:
* a second flush (one exit path calling another) writes nothing new. Sequence numbers
* are 32-bit; a process would need 4 billion logged-code exceptions to wrap them.
*/
typedef struct {
clf_rec r[CLF_RING];
unsigned int pushed; /* records pushed in total */
unsigned int flushedTo; /* every record up to this seq has been offered to a flush */
} clf_ring;
static void clf_ring_push(clf_ring* g, unsigned int addr, unsigned int code, unsigned int eip,
unsigned int tid, unsigned int tickMs, unsigned int hits, int written)
{
clf_rec* x = &g->r[g->pushed % CLF_RING];
g->pushed++;
x->seq = g->pushed;
x->addr = addr;
x->code = code;
x->eip = eip;
x->tid = tid;
x->tickMs = tickMs;
x->hits = hits;
x->written = (unsigned char)(written ? 1 : 0);
}
/*
* Flush: copies into out[CLF_RING], oldest first, the held records that were not written
* and not offered to an earlier flush, and marks everything pushed so far as offered.
* Returns how many were copied. *older gets the records pushed since the last flush that
* the ring no longer holds (written or not).
*/
static int clf_ring_take(clf_ring* g, clf_rec* out, unsigned int* older)
{
unsigned int first = g->pushed > CLF_RING ? g->pushed - CLF_RING : 0; /* held: first+1..pushed */
unsigned int from = g->flushedTo, s;
int n = 0;
if (older) *older = from < first ? first - from : 0;
if (from < first) from = first;
for (s = from + 1; s <= g->pushed; s++) {
const clf_rec* x = &g->r[(s - 1) % CLF_RING];
if (!x->written) out[n++] = *x;
}
g->flushedTo = g->pushed;
return n;
}
/* The last-chance (unhandled) filter. Any code: whatever reaches it is fatal. */
static clf_decision clf_last_chance(clf_state* s)
{
if (s->lastChance >= CLF_MAX_LAST_CHANCE) return CLF_SKIP_CAP;
s->lastChance++;
return CLF_LOG_LAST_CHANCE;
}
#endif

View file

@ -26,12 +26,39 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
/* File version of this native module (bump with every behavioural change). */
#define RC_SEH_TRAMPOLINE_VERSION 6 /* v6: AwfulWaffle's crash logger (per-address dedupe, pid/date,
flush ring, RC_FlushCrashLog, module cache) merged with v3-v5;
v5: crash log handle opened once at install; no CreateFileW
while an exception is being dispatched */
/* 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 */
static void CrashLoggerFlushOnExit(void);
/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an
* access violation on this thread is about to be caught by our own __except. */
#define RC_SEH_ENTER() (++t_sehDepth)
#define RC_SEH_LEAVE() (--t_sehDepth)
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved)
{
(void)hModule; (void)ul_reason; (void)lpReserved;
(void)hModule;
/* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess),
* which is how AC's own crash handling ends the process: write out any recent
* first-chance AVs so a crash AC swallowed still leaves a trace. */
if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) {
CrashLoggerFlushOnExit();
}
return TRUE;
}
/* Diagnostic: native module version so the engine log can confirm which build is loaded. */
__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void)
{
return RC_SEH_TRAMPOLINE_VERSION;
}
/* ── Cdecl helpers ─────────────────────────────────────────────────────── */
/* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */
@ -40,14 +67,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result)
{
*out_result = NULL;
RC_SEH_ENTER();
__try {
*out_result = fn(arg);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -57,14 +87,17 @@ __declspec(dllexport) int __cdecl
SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result)
{
*out_result = NULL;
RC_SEH_ENTER();
__try {
*out_result = fn();
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = NULL;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -73,13 +106,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char);
__declspec(dllexport) int __cdecl
SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2)
{
RC_SEH_ENTER();
__try {
fn(arg1, arg2);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -95,13 +131,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s
__declspec(dllexport) int __cdecl
SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId)
{
RC_SEH_ENTER();
__try {
((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -152,14 +191,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg,
unsigned char* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -171,14 +213,17 @@ __declspec(dllexport) int __cdecl
SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_uint_noarg(fn, this_ptr);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
@ -209,36 +254,124 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2,
int* out_result)
{
*out_result = 0;
RC_SEH_ENTER();
__try {
*out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2);
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
RC_SEH_LEAVE();
*out_result = 0;
return 0;
}
RC_SEH_LEAVE();
return 1;
}
/* ── Process-wide native crash logger (VEH) ───────────────────────────────
/* -- Process-wide native crash logger (VEH + last-chance filter) -----------
* Logs the faulting 32-bit context + a module-resolved stack sweep to a
* dedicated file BEFORE the process dies, for the fatal exceptions that bypass
* NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and
* 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled
* managed exception or a stack-walk fail-fast in the plugin/engine).
* dedicated file BEFORE the process dies, for the exceptions that bypass the
* engine's managed handlers: 0xC0000005 (AV / corrupted state; CoreCLR will not
* let a managed catch handle one raised in AC code under a managed detour, it
* fail-fasts instead), 0xC0000602 (fail-fast), 0xC0000409 (stack buffer
* overrun), 0xC00000FD (stack overflow) and 0xC0000374 (heap corruption).
* The vectored handler is registered FIRST, so it sees an AV before CoreCLR
* turns it into anything: the entry names the real faulting address and module.
*
* Which entries are written is CrashLogFilter.h's rule (once per address, a repeat
* again at a power-of-two count or after 30 s; .NET Framework and CoreCLR noise not
* charged to the limit; a last-chance entry always). Each entry carries the process id,
* thread id, date and time.
*
* This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so
* unlike the removed managed CrashLogger VEH it cannot itself re-trigger a
* NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns
* EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly
* as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio /
* user32) so the build link line stays unchanged. Hardened: stack sweep in
* __try/__except, capped log count, dedicated file (no contention with the
* managed log). x86 (32-bit) context fields only — matches the WOW64 target.
* fail-fast on an AC-owned thread. It only OBSERVES: both handlers return
* EXCEPTION_CONTINUE_SEARCH (the last-chance one first calls the filter it
* replaced) so AC's own SEH / the runtime still proceed exactly as before. Uses
* only kernel32 APIs + hand-rolled formatting (no CRT stdio / user32) so the
* build link line stays unchanged. All buffers are static and used under one
* spin lock (with its owner's thread id, so a fault inside the logger on the same
* thread is passed on, never waited on): a stack overflow leaves the faulting
* thread about one page of stack. x86 (32-bit) context fields only.
*/
#include "CrashLogFilter.h"
/*
* Exception time does as little as it can: the address dedupe runs first (most
* exceptions are repeats and stop there), module names come from a cache built
* outside exception time (install, then RC_RefreshCrashLoggerModules from the engine's
* heartbeat), and the log file is opened once at install, so writing an entry is
* formatting plus WriteFile. Only an address the cache does not cover (a module loaded
* since the last refresh) falls back to GetModuleHandleExW, for the faulting address
* and eip only.
*
* NEVER call CreateFileW (or anything else the engine detours with a managed hook:
* CreateFileA, MessageBoxA/W, ExitProcess, TerminateProcess, RtlExitUserProcess,
* NtTerminateProcess) from the handlers, the flush or DllMain. DatFileShareHooks detours
* kernel32!CreateFileW with a MANAGED delegate; our VEH runs first, on the faulting thread,
* and for a fault in managed code that thread is still in cooperative GC mode, so entering
* the detour is a reverse P/Invoke from cooperative mode: CoreCLR's
* ReversePInvokeBadTransition -> HandleFatalError (event 1023, exit 0x80131506). Seven
* client deaths 2026-09-29..10-12 were that (fixed in v5). The file is opened once, from
* RC_InstallCrashLogger, a normal P/Invoke in preemptive mode.
*
* v6 (merge of AwfulWaffle's logger with v3-v5): AVs inside our own SEH_* wrappers
* (t_sehDepth > 0, which our __except catches) are not written one by one, only kept in
* the flush ring; the Client::UseTime guard (v4) writes its caught AV through this
* writer; process exit (DllMain) flushes ring records from the last 30 s, as v2-v5 did.
*/
#define CL_EXIT_FLUSH_WINDOW_MS 30000u /* ring records this recent are flushed at exit */
#define CL_MAX_GAMETICK 16 /* game-tick guard records per process */
#define CL_MOD_MAX 384
typedef struct {
unsigned int base, end; /* [base, end) */
unsigned char cls; /* clf_class */
char leaf[48]; /* ASCII leaf name, truncated */
} cl_mod;
typedef struct {
cl_mod mods[CL_MOD_MAX];
int count;
} cl_mod_table;
static wchar_t g_crashLogPath[MAX_PATH];
static volatile LONG g_crashCount = 0;
static HANDLE g_logHandle = INVALID_HANDLE_VALUE;
static PVOID g_vehHandle = NULL;
static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL;
static volatile LONG g_logOwner = 0; /* thread id holding the logger, 0 = free */
static clf_state g_filter; /* under g_logOwner */
static clf_ring g_ring; /* under g_logOwner: recent first-chance records */
static clf_rec g_flushRecs[CLF_RING];/* under g_logOwner */
static char g_buf[4096]; /* under g_logOwner */
static wchar_t g_wpath[MAX_PATH]; /* under g_logOwner */
static char g_fallbackLeaf[48]; /* under g_logOwner */
static cl_mod_table g_modTables[2]; /* double buffer: refresh builds the inactive one */
static volatile LONG g_modActive = -1; /* index of the published table, -1 = none */
static volatile LONG g_modRefreshing = 0;
static volatile LONG g_gameTickRecords = 0;
static __declspec(thread) int t_inUef; /* last-chance filter running (guards chain cycles) */
typedef BOOL (WINAPI *PFN_EnumMods)(HANDLE, HMODULE*, DWORD, LPDWORD);
typedef BOOL (WINAPI *PFN_ModInfo)(HANDLE, HMODULE, void*, DWORD);
typedef DWORD (WINAPI *PFN_BaseName)(HANDLE, HMODULE, LPWSTR, DWORD);
typedef struct { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } cl_modinfo;
static int cl_lock(void)
{
LONG me = (LONG)GetCurrentThreadId();
int i;
if (g_logOwner == me) return 0; /* faulted inside the logger: pass it on */
for (i = 0; i < 20000; i++) {
if (InterlockedCompareExchange(&g_logOwner, me, 0) == 0) return 1;
YieldProcessor();
if ((i & 0xFF) == 0xFF) SwitchToThread();
}
return 0; /* owner stuck (suspended?): skip this entry */
}
static void cl_unlock(void) { InterlockedExchange(&g_logOwner, 0); }
static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; }
@ -260,128 +393,428 @@ static char* cl_u(char* p, unsigned int v)
return p;
}
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
static char* cl_sym(char* p, unsigned int addr)
static char* cl_u2(char* p, unsigned int v) { if (v < 10) { *p++ = '0'; } return cl_u(p, v); }
/*
* Rebuild the module cache (NOT at exception time: it takes the loader lock). Builds the
* table no reader is using and publishes it with one interlocked store; refreshes are
* serialized and seconds apart, so a reader never sees its table rebuilt under it.
*/
__declspec(dllexport) void __cdecl
RC_RefreshCrashLoggerModules(void)
{
static PFN_EnumMods pEnum;
static PFN_ModInfo pInfo;
static PFN_BaseName pName;
HMODULE mods[CL_MOD_MAX];
DWORD needed = 0, n, i;
HANDLE self = GetCurrentProcess();
LONG active, next;
cl_mod_table* t;
if (InterlockedCompareExchange(&g_modRefreshing, 1, 0) != 0) return;
if (!pEnum) {
HMODULE k32 = GetModuleHandleW(L"kernel32.dll");
pEnum = (PFN_EnumMods)GetProcAddress(k32, "K32EnumProcessModules");
pInfo = (PFN_ModInfo)GetProcAddress(k32, "K32GetModuleInformation");
pName = (PFN_BaseName)GetProcAddress(k32, "K32GetModuleBaseNameW");
}
if (!pEnum || !pInfo || !pName || !pEnum(self, mods, sizeof(mods), &needed)) {
InterlockedExchange(&g_modRefreshing, 0);
return;
}
n = needed / sizeof(HMODULE);
if (n > CL_MOD_MAX) n = CL_MOD_MAX;
active = g_modActive;
next = active == 0 ? 1 : 0;
t = &g_modTables[next];
t->count = 0;
for (i = 0; i < n; i++) {
cl_modinfo mi;
wchar_t name[64];
DWORD len, k;
cl_mod* m;
if (!pInfo(self, mods[i], &mi, sizeof(mi))) continue;
len = pName(self, mods[i], name, 63);
name[len < 63 ? len : 63] = 0;
m = &t->mods[t->count++];
m->base = (unsigned int)(UINT_PTR)mi.lpBaseOfDll;
m->end = m->base + mi.SizeOfImage;
m->cls = (unsigned char)clf_module_class(name);
for (k = 0; k < sizeof(m->leaf) - 1 && name[k]; k++)
m->leaf[k] = name[k] < 128 ? (char)name[k] : '?';
m->leaf[k] = 0;
}
InterlockedExchange(&g_modActive, next);
InterlockedExchange(&g_modRefreshing, 0);
}
/* Cached module containing addr, or NULL. No API calls. */
static const cl_mod* cl_mod_cached(unsigned int addr)
{
LONG a = g_modActive;
const cl_mod_table* t;
int i;
if (a < 0) return NULL;
t = &g_modTables[a];
for (i = 0; i < t->count; i++)
if (addr >= t->mods[i].base && addr < t->mods[i].end) return &t->mods[i];
return NULL;
}
/*
* Module of addr: the cache, then (allowFallback) the loader. Under the lock. Returns
* the leaf and sets *base and *cls, or NULL (no module: JIT code or garbage).
*/
static const char* cl_module(unsigned int addr, int allowFallback, unsigned int* base, clf_class* cls)
{
const cl_mod* m = cl_mod_cached(addr);
HMODULE hm = NULL;
DWORD n, i, leaf = 0, k;
if (m) { *base = m->base; *cls = (clf_class)m->cls; return m->leaf; }
if (!allowFallback) return NULL;
/* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) {
wchar_t wpath[MAX_PATH];
DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH);
DWORD i, leaf = 0;
for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; }
for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; }
if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) return NULL;
n = GetModuleFileNameW(hm, g_wpath, MAX_PATH);
if (n >= MAX_PATH) n = MAX_PATH - 1;
g_wpath[n] = 0;
for (i = 0; i < n; i++) { if (g_wpath[i] == L'\\' || g_wpath[i] == L'/') leaf = i + 1; }
*base = (unsigned int)(UINT_PTR)hm;
*cls = clf_module_class(g_wpath + leaf);
for (k = 0; k < sizeof(g_fallbackLeaf) - 1 && g_wpath[leaf + k]; k++)
g_fallbackLeaf[k] = g_wpath[leaf + k] < 128 ? (char)g_wpath[leaf + k] : '?';
g_fallbackLeaf[k] = 0;
return g_fallbackLeaf;
}
/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */
static char* cl_sym(char* p, unsigned int addr, int allowFallback)
{
unsigned int base;
clf_class cls;
const char* leaf = cl_module(addr, allowFallback, &base, &cls);
if (leaf) {
p = cl_str(p, leaf);
p = cl_str(p, "+");
p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm);
p = cl_hex(p, addr - base);
} else {
p = cl_hex(p, addr);
}
return p;
}
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
/* Class of the nearest cached-module code pointer on the stack (AC if none found). */
static clf_class cl_first_frame_class(unsigned int esp)
{
DWORD code = ep->ExceptionRecord->ExceptionCode;
if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) {
return EXCEPTION_CONTINUE_SEARCH;
clf_class result = CLF_CLASS_AC;
__try {
unsigned int* sp = (unsigned int*)(UINT_PTR)esp;
int i;
for (i = 0; i < 512; i++) {
unsigned int v = sp[i];
const cl_mod* m;
if (v <= 0x00401000u || v >= 0x7FFF0000u) continue;
m = cl_mod_cached(v);
if (m) { result = (clf_class)m->cls; break; }
}
}
if (InterlockedIncrement(&g_crashCount) > 24) {
return EXCEPTION_CONTINUE_SEARCH;
__except (EXCEPTION_EXECUTE_HANDLER) { result = CLF_CLASS_AC; }
return result;
}
static void cl_write(const char* p, DWORD n)
{
DWORD wr;
if (g_logHandle != INVALID_HANDLE_VALUE) WriteFile(g_logHandle, p, n, &wr, NULL);
}
/* Append " pid=N tid=N date=YYYY-MM-DD time=HH:MM:SS" (local time). */
static char* cl_stamp(char* p)
{
SYSTEMTIME st;
p = cl_str(p, " pid=");
p = cl_u(p, GetCurrentProcessId());
p = cl_str(p, " tid=");
p = cl_u(p, GetCurrentThreadId());
GetLocalTime(&st);
p = cl_str(p, " date=");
p = cl_u(p, st.wYear); p = cl_str(p, "-");
p = cl_u2(p, st.wMonth); p = cl_str(p, "-");
p = cl_u2(p, st.wDay);
p = cl_str(p, " time=");
p = cl_u2(p, st.wHour); p = cl_str(p, ":");
p = cl_u2(p, st.wMinute); p = cl_str(p, ":");
p = cl_u2(p, st.wSecond);
return p;
}
static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits)
{
char* p = g_buf;
CONTEXT* c = ep->ContextRecord;
DWORD code = ep->ExceptionRecord->ExceptionCode;
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
if (g_logHandle == INVALID_HANDLE_VALUE) return;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (");
p = cl_str(p, kind);
p = cl_str(p, ") ====\r\n code=");
p = cl_hex(p, code);
p = cl_str(p, " exAddr=");
p = cl_sym(p, exAddr, 1);
if (hits > 1) { p = cl_str(p, " repeat="); p = cl_u(p, hits); }
p = cl_stamp(p);
if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) {
unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0];
unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1];
p = cl_str(p, " access=");
p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ"));
p = cl_str(p, " dataAddr=");
p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */
}
p = cl_str(p, "\r\n logged=");
p = cl_u(p, g_filter.counted);
p = cl_str(p, "/");
p = cl_u(p, CLF_MAX_COUNTED);
p = cl_str(p, " noiseRepeats=");
p = cl_u(p, g_filter.noiseRepeats);
p = cl_str(p, " otherRepeats=");
p = cl_u(p, g_filter.otherRepeats);
p = cl_str(p, " overCap=");
p = cl_u(p, g_filter.overCap);
p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip, 1);
p = cl_str(p, " esp="); p = cl_hex(p, c->Esp);
p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp);
p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax);
p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx);
p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx);
p = cl_str(p, " edx="); p = cl_hex(p, c->Edx);
p = cl_str(p, " esi="); p = cl_hex(p, c->Esi);
p = cl_str(p, " edi="); p = cl_hex(p, c->Edi);
p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n");
cl_write(g_buf, (DWORD)(p - g_buf));
__try {
unsigned int* sp = (unsigned int*)(UINT_PTR)c->Esp;
int i, emitted = 0;
for (i = 0; i < 4096 && emitted < 96; i++) {
unsigned int v = sp[i];
if (v > 0x00401000u && v < 0x7FFF0000u && cl_mod_cached(v)) {
char* q = g_buf;
q = cl_str(q, " +");
q = cl_hex(q, (unsigned int)(i * 4));
q = cl_str(q, " ");
q = cl_sym(q, v, 0);
q = cl_str(q, "\r\n");
cl_write(g_buf, (DWORD)(q - g_buf));
emitted++;
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
const char* m = " <stack sweep faulted>\r\n";
cl_write(m, (DWORD)lstrlenA(m));
}
{
HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; }
SetFilePointer(h, 0, NULL, FILE_END);
{
char buf[4096];
char* p = buf;
CONTEXT* c = ep->ContextRecord;
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
DWORD wr;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code=");
p = cl_hex(p, code);
p = cl_str(p, " exAddr=");
p = cl_sym(p, exAddr);
p = cl_str(p, " tid=");
p = cl_u(p, GetCurrentThreadId());
{
SYSTEMTIME st; GetLocalTime(&st);
p = cl_str(p, " time=");
p = cl_u(p, st.wHour); p = cl_str(p, ":");
if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":");
if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond);
}
if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) {
unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0];
unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1];
p = cl_str(p, " access=");
p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ"));
p = cl_str(p, " dataAddr=");
p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */
}
p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip);
p = cl_str(p, " esp="); p = cl_hex(p, c->Esp);
p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp);
p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax);
p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx);
p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx);
p = cl_str(p, " edx="); p = cl_hex(p, c->Edx);
p = cl_str(p, " esi="); p = cl_hex(p, c->Esi);
p = cl_str(p, " edi="); p = cl_hex(p, c->Edi);
p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n");
WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL);
__try {
unsigned int* sp = (unsigned int*)c->Esp;
int i, emitted = 0;
for (i = 0; i < 4096 && emitted < 96; i++) {
unsigned int v = sp[i];
if (v > 0x00401000u && v < 0x7FFF0000u) {
HMODULE hm = NULL;
if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) {
char* q = buf;
q = cl_str(q, " +");
q = cl_hex(q, (unsigned int)(i * 4));
q = cl_str(q, " ");
q = cl_sym(q, v);
q = cl_str(q, "\r\n");
WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL);
emitted++;
}
}
}
}
__except (EXCEPTION_EXECUTE_HANDLER) {
const char* m = " <stack sweep faulted>\r\n";
WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL);
}
{
const char* e = "==== END NATIVE CRASH ====\r\n";
WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL);
}
}
CloseHandle(h);
const char* e = "==== END NATIVE CRASH ====\r\n";
cl_write(e, (DWORD)lstrlenA(e));
}
}
/*
* Under the lock: write the recent first-chance records that were not written one by one
* (clf_ring_take), oldest first, so the log ends with the newest, usually the fatal hit.
* Module names from the cache only: no loader call on a dying process.
*/
static void cl_flush_locked(const char* reason, unsigned int code, unsigned int maxAgeMs)
{
unsigned int older = 0;
int n = clf_ring_take(&g_ring, g_flushRecs, &older), i;
char* p;
if (maxAgeMs != 0) {
/* v6: process exit (DllMain) keeps only the recent records, as v2-v5 did; a
* contained AV from long before a normal exit is not crash evidence. */
unsigned int now = GetTickCount();
int k = 0;
for (i = 0; i < n; i++)
if (now - g_flushRecs[i].tickMs <= maxAgeMs) g_flushRecs[k++] = g_flushRecs[i];
n = k;
}
if (n == 0 || g_logHandle == INVALID_HANDLE_VALUE) return;
p = g_buf;
p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (flush: ");
p = cl_str(p, reason);
p = cl_str(p, ") ====\r\n code=");
p = cl_hex(p, code);
p = cl_stamp(p);
p = cl_str(p, "\r\n recent first-chance records not written one by one, oldest first (");
p = cl_u(p, (unsigned int)n);
p = cl_str(p, " held");
if (older) { p = cl_str(p, ", "); p = cl_u(p, older); p = cl_str(p, " older ones no longer held"); }
p = cl_str(p, "):\r\n");
cl_write(g_buf, (DWORD)(p - g_buf));
for (i = 0; i < n; i++) {
const clf_rec* x = &g_flushRecs[i];
p = g_buf;
p = cl_str(p, " exAddr=");
p = cl_sym(p, x->addr, 0);
p = cl_str(p, " code=");
p = cl_hex(p, x->code);
p = cl_str(p, " eip=");
p = cl_sym(p, x->eip, 0);
p = cl_str(p, " tid=");
p = cl_u(p, x->tid);
p = cl_str(p, " tick=");
p = cl_u(p, x->tickMs);
p = cl_str(p, " repeat=");
p = cl_u(p, x->hits);
p = cl_str(p, "\r\n");
cl_write(g_buf, (DWORD)(p - g_buf));
}
{
const char* e = "==== END NATIVE CRASH ====\r\n";
cl_write(e, (DWORD)lstrlenA(e));
}
}
static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep)
{
DWORD code = ep->ExceptionRecord->ExceptionCode;
if (!clf_is_logged_code(code)) {
return EXCEPTION_CONTINUE_SEARCH; /* cheap exit, no lock, for C++/CLR throws */
}
if (!cl_lock()) { return EXCEPTION_CONTINUE_SEARCH; }
if (code == CLF_CODE_ACCESS_VIOLATION && t_sehDepth > 0) {
/* v6 (v2's rule): an SEH_* wrapper's __except catches this AV (the game-tick guard
* writes its own record), so it is not written one by one. Kept in the flush ring
* only, in case a handler further up turns the process exit into a crash. */
clf_ring_push(&g_ring, (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress, code,
ep->ContextRecord->Eip, GetCurrentThreadId(), GetTickCount(), 1, 0);
cl_unlock();
return EXCEPTION_CONTINUE_SEARCH;
}
{
unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress;
unsigned int now = GetTickCount();
unsigned int hits = 1;
int written = 0;
clf_slot* slot = clf_find(&g_filter, exAddr);
if (slot) {
/* A repeat: decided without touching any module. */
if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) {
cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits);
written = 1;
}
} else {
unsigned int base;
clf_class faultCls = CLF_CLASS_AC;
const char* leaf = cl_module(exAddr, 1, &base, &faultCls);
clf_class cls = clf_classify(code, leaf ? faultCls : CLF_CLASS_AC, leaf == NULL,
leaf == NULL && code == CLF_CODE_ACCESS_VIOLATION ? cl_first_frame_class(ep->ContextRecord->Esp) : CLF_CLASS_AC);
clf_decision d = clf_new(&g_filter, code, exAddr, cls, now);
if (d == CLF_LOG_COUNTED)
cl_write_entry(ep, "first-chance", 1);
else if (d == CLF_LOG_NOISE)
cl_write_entry(ep, cls == CLF_CLASS_NETFX
? "first-chance, .NET Framework noise, not counted"
: "first-chance, managed (CoreCLR) noise, not counted", 1);
written = d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE;
}
/* Kept for a flush (memory only): the fatal hit is often one not written here. */
clf_ring_push(&g_ring, exAddr, code, ep->ContextRecord->Eip, GetCurrentThreadId(), now, hits, written);
}
cl_unlock();
return EXCEPTION_CONTINUE_SEARCH;
}
/* Install the VEH once. logPath = wide path to the dedicated crash log. */
/* Last chance: nothing handled it. Logged, then the filter this one replaced decides. */
static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep)
{
LONG verdict = EXCEPTION_CONTINUE_SEARCH;
/* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */
if (t_inUef) { return EXCEPTION_CONTINUE_SEARCH; }
t_inUef = 1;
if (cl_lock()) {
cl_flush_locked("last chance", ep->ExceptionRecord->ExceptionCode, 0);
if (clf_last_chance(&g_filter) == CLF_LOG_LAST_CHANCE)
cl_write_entry(ep, "LAST-CHANCE, unhandled", 1);
cl_unlock();
}
if (g_prevFilter && g_prevFilter != CrashLastChance) {
verdict = g_prevFilter(ep);
}
t_inUef = 0;
return verdict;
}
/*
* A crash exit is under way (the engine's TerminateProcess / NtTerminateProcess /
* ExitProcess / RtlExitUserProcess detours, for a crash code): write the recent
* first-chance records not written one by one. Each record is written once, so the
* second of two nested exit paths writes nothing. exitCode 0 is the engine's priming
* call and does nothing.
*/
__declspec(dllexport) void __cdecl
RC_FlushCrashLog(unsigned int exitCode)
{
if (exitCode == 0) return;
if (!cl_lock()) return;
cl_flush_locked("crash exit", exitCode, 0);
cl_unlock();
}
/* DllMain, process exit (v2-v5 behaviour): ring records from the last 30 s that were not
* written one by one. AC's own crash handling ends with ExitProcess, sometimes with a code
* the engine does not count as a crash. Cache-only module names; no loader call. */
static void CrashLoggerFlushOnExit(void)
{
if (g_logHandle == INVALID_HANDLE_VALUE) { return; }
if (!cl_lock()) { return; }
cl_flush_locked("process exit", 0, CL_EXIT_FLUSH_WINDOW_MS);
cl_unlock();
}
/*
* Install the VEH once and (re-)assert the last-chance filter. logPath = wide path to the
* dedicated crash log, opened HERE (a normal P/Invoke, preemptive mode; never from a
* handler, see the CreateFileW note above) for the life of the process (append, shared
* for reading, writing and deleting). Safe to call more than once (every engine
* generation does): a later call re-installs the filter if AC or a runtime replaced it,
* and a different path switches files. Also (re)builds the module cache.
*/
__declspec(dllexport) void __cdecl
RC_InstallCrashLogger(const wchar_t* logPath)
{
if (g_vehHandle) { return; }
if (logPath) {
int i = 0;
for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; }
g_crashLogPath[i] = 0;
LPTOP_LEVEL_EXCEPTION_FILTER prev;
if (logPath && logPath[0]) {
int i = 0, same = 1;
for (; logPath[i] && i < MAX_PATH - 1; i++) {
if (g_crashLogPath[i] != logPath[i]) { same = 0; }
}
if (g_crashLogPath[i] != 0) { same = 0; }
if ((!same || g_logHandle == INVALID_HANDLE_VALUE) && cl_lock()) {
HANDLE h;
for (i = 0; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; }
g_crashLogPath[i] = 0;
h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h != INVALID_HANDLE_VALUE) {
HANDLE old = g_logHandle;
g_logHandle = h;
if (old != INVALID_HANDLE_VALUE) { CloseHandle(old); }
}
cl_unlock();
}
}
RC_RefreshCrashLoggerModules();
if (!g_vehHandle) {
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
}
prev = SetUnhandledExceptionFilter(CrashLastChance);
if (prev != CrashLastChance) {
g_prevFilter = prev;
}
g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh);
}
/* ── Tagged-text parser guard (native MinHook detour body) ────────────────
@ -437,3 +870,87 @@ __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 through the logger's writer (v6), capped at
* CL_MAX_GAMETICK records per process. No CreateFileW here either (see the logger). */
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)
{
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; }
if (cl_lock()) {
unsigned int base = 0;
clf_class cls;
const char* leaf = cl_module(f->exAddr, 1, &base, &cls);
if (leaf && f->module && f->moduleCap > 0) {
int k = 0;
for (; leaf[k] && k < f->moduleCap - 1; k++) { f->module[k] = leaf[k]; }
f->module[k] = 0;
}
if (InterlockedIncrement(&g_gameTickRecords) <= CL_MAX_GAMETICK) {
cl_write_entry(ep, "AV CAUGHT IN GAME TICK (Client::UseTime guard; tick dropped, client kept running)", 1);
}
cl_unlock();
if (leaf && f->module && f->module[0]) {
f->exAddr -= base; /* module-relative when resolved */
}
}
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;
}

View file

@ -0,0 +1,241 @@
/*
* CrashLogFilterTests.c - offline checks for CrashLogFilter.h (the native crash logger's
* filter). Build and run with Run-CrashLogFilterTests.ps1 (x86 MSVC). Exit 0 = pass.
*/
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include "../CrashLogFilter.h"
static int g_checks, g_failed;
static void check(int ok, const char* what)
{
g_checks++;
if (ok) return;
g_failed++;
printf("[FAIL] %s\n", what);
}
#define AV CLF_CODE_ACCESS_VIOLATION
#define FC(s, code, addr, cls, now) clf_first_chance((s), (code), (addr), (cls), (now), &hits)
static int is_write(clf_decision d)
{
return d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE || d == CLF_LOG_REPEAT;
}
/* Seen in a real log: handled .NET Framework AVs at ONE address spent the old cap,
* and the fatal AC fault later was never written. */
static void netfx_noise_never_spends_the_limit(void)
{
static clf_state s;
unsigned int hits, i, written = 0;
for (i = 0; i < 500; i++)
if (is_write(FC(&s, AV, 0x433620C8u, CLF_CLASS_NETFX, 1000 + i * 10))) written++;
/* first + the power-of-two repeats 2,4,8,16,32,64,128,256 = 9 entries for 500 hits */
check(written == 9, "500 hits of one JIT-code AV: 9 entries (first + powers of two)");
check(s.counted == 0, "and never charged to the limit");
check(s.noiseRepeats == 491, "skipped repeats are counted as noise");
check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 7000) == CLF_LOG_COUNTED, "a later AC fault is still written");
}
/* A contained AV at a known address that later goes fatal. */
static void known_address_going_fatal_is_written(void)
{
static clf_state s;
unsigned int hits, i;
clf_decision d;
for (i = 0; i < 3; i++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000 + i);
d = FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1010);
check(d == CLF_LOG_REPEAT && hits == 4, "3 contained AVs, then a 4th (fatal) at the same address: written, repeat=4");
{
static clf_state t;
unsigned int now = 5000;
for (i = 0; i < 1000; i++) FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + i); /* within 1 s */
d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31000);
check(d == CLF_LOG_REPEAT && hits == 1001, "1000 repeats, then the same address 31 s later: written");
d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31001);
check(d == CLF_SKIP_REPEAT, "and the next one right after is not");
}
{
static clf_state u;
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 100);
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 101);
FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 102); /* hits 3: skipped */
d = FC(&u, CLF_CODE_HEAP_CORRUPTION, 0x00500000u, CLF_CLASS_AC, 103);
check(d == CLF_LOG_REPEAT, "a non-AV code at a known address is always written");
}
{
static clf_state w; /* the 32-bit tick wrap */
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF000u);
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF001u);
FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF002u);
d = FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0x00007000u); /* ~32 s later, past the wrap */
check(d == CLF_LOG_REPEAT, "the 30 s relog survives the GetTickCount wrap");
}
}
static void ac_faults_limited_per_distinct_address(void)
{
static clf_state s;
unsigned int hits, a;
for (a = 0; a < 50; a++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000);
check(s.counted == 1, "a repeating AC fault is charged once");
for (a = 1; a < CLF_MAX_COUNTED; a++)
check(FC(&s, AV, 0x00500000u + a * 16, CLF_CLASS_AC, 1000) == CLF_LOG_COUNTED,
"distinct addresses written up to the limit");
check(FC(&s, AV, 0x00700000u, CLF_CLASS_AC, 1000) == CLF_SKIP_CAP, "past the limit: skipped");
check(FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000) != CLF_SKIP_CAP,
"a known address is decided as a repeat, never by the limit");
}
static void codes(void)
{
static clf_state s;
unsigned int hits;
check(FC(&s, 0xC00000FDu, 0x1000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack overflow is logged");
check(FC(&s, 0xC0000374u, 0x2000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "heap corruption is logged");
check(FC(&s, 0xC0000409u, 0x3000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack buffer overrun is logged");
check(FC(&s, 0xC0000602u, 0x4000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "fail-fast is logged");
check(FC(&s, 0xE06D7363u, 0x5000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a C++ exception is not");
check(FC(&s, 0x80000003u, 0x6000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a breakpoint is not");
}
static void classification(void)
{
check(clf_module_class(L"clr.dll") == CLF_CLASS_NETFX && clf_module_class(L"MSCORLIB.NI.DLL") == CLF_CLASS_NETFX
&& clf_module_class(L"mscorwks.dll") == CLF_CLASS_NETFX && clf_module_class(L"mscorlib.dll") == CLF_CLASS_NETFX,
"the .NET Framework modules, any case");
check(clf_module_class(L"coreclr.dll") == CLF_CLASS_MANAGED && clf_module_class(L"clrjit.dll") == CLF_CLASS_MANAGED
&& clf_module_class(L"System.Private.CoreLib.dll") == CLF_CLASS_MANAGED,
"the engine's CoreCLR modules are managed noise");
check(clf_module_class(L"acclient.exe") == CLF_CLASS_AC && clf_module_class(L"clr.dllx") == CLF_CLASS_AC
&& clf_module_class(0) == CLF_CLASS_AC, "AC and near-misses are not noise");
check(clf_classify(AV, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_NETFX, "an AV in clr.dll is .NET Framework noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_NETFX) == CLF_CLASS_NETFX, "JIT code under clr frames: .NET Framework noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_MANAGED) == CLF_CLASS_MANAGED, "JIT code under CoreCLR frames: managed noise");
check(clf_classify(AV, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_MANAGED, "an AV in coreclr.dll: managed noise");
check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_AC) == CLF_CLASS_AC, "no module under AC frames: AC");
check(clf_classify(AV, CLF_CLASS_AC, 0, CLF_CLASS_NETFX) == CLF_CLASS_AC, "an AV in an AC module is AC whatever is below it");
check(clf_classify(CLF_CODE_STACK_OVERFLOW, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "a stack overflow is never noise");
check(clf_classify(CLF_CODE_HEAP_CORRUPTION, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "heap corruption is never noise");
}
static void managed_noise_is_its_own_bucket(void)
{
static clf_state s;
unsigned int hits, a;
for (a = 0; a < 40; a++)
check(FC(&s, AV, 0x70000000u + a * 16, CLF_CLASS_MANAGED, 1) == CLF_LOG_NOISE, "managed noise written once per address");
check(s.counted == 0, "and never charged to the AC limit");
}
static void last_chance_is_separate(void)
{
static clf_state s;
unsigned int hits, a;
int i, logged = 0;
for (a = 0; a < CLF_MAX_COUNTED + 5; a++)
FC(&s, AV, 0x00700000u + a * 16, CLF_CLASS_AC, 1);
check(s.counted == CLF_MAX_COUNTED, "first-chance limit reached");
check(clf_last_chance(&s) == CLF_LOG_LAST_CHANCE, "the unhandled one is still written");
for (i = 0; i < 20; i++)
if (clf_last_chance(&s) == CLF_LOG_LAST_CHANCE) logged++;
check(logged == CLF_MAX_LAST_CHANCE - 1, "last-chance has its own small limit");
}
static void full_table_evicts_oldest_noise(void)
{
static clf_state s;
unsigned int hits, a;
clf_decision d;
for (a = 0; a < CLF_ADDR_SLOTS; a++)
FC(&s, AV, 0x40000000u + a * 16, CLF_CLASS_NETFX, 1000 + a); /* noise fills it, 0x40000000 oldest */
check(s.counted == 0, "table full of .NET Framework addresses");
d = FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5000);
check(d == CLF_LOG_COUNTED, "an AC fault is written");
check(clf_find(&s, 0x0055FA24u) != 0, "and tracked, in the evicted slot");
check(clf_find(&s, 0x40000000u) == 0, "the least recently written noise slot was evicted");
check(clf_find(&s, 0x40000010u) != 0, "the next one was not");
check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5001) == CLF_LOG_REPEAT && hits == 2, "so its repeat is deduped");
d = FC(&s, AV, 0x41000000u, CLF_CLASS_NETFX, 6000);
check(d == CLF_LOG_NOISE, "a new .NET Framework address is written, evicting an older one");
check(clf_find(&s, 0x0055FA24u) != 0, "AC slots are never evicted");
}
#define FATAL_ADDR 0x00401234u
/* N contained hits at one address, then the fatal one, then
* a terminate from a handler, so no last-chance filter runs. The fatal hit (N+1) is not due
* a write, so only the ring's flush can put it in the log. */
static void fatal_repeat_recovered_by_flush(unsigned int n)
{
clf_state s;
clf_ring g;
clf_rec out[CLF_RING];
unsigned int hits, i, older, now = 5000;
clf_decision d;
int got;
memset(&s, 0, sizeof s);
memset(&g, 0, sizeof g);
for (i = 0; i < n; i++) {
d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + i);
clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + i, hits, is_write(d));
}
d = FC(&s, AV, FATAL_ADDR, CLF_CLASS_AC, now + n + 1500); /* the fatal hit, 1.5 s later */
check(d == CLF_SKIP_REPEAT && hits == n + 1, "fatal hit N+1 is not due a write: the dedupe alone loses it");
clf_ring_push(&g, FATAL_ADDR, AV, FATAL_ADDR, 77, now + n + 1500, hits, is_write(d));
got = clf_ring_take(&g, out, &older);
check(got >= 1, "the flush has records");
check(got >= 1 && out[got - 1].addr == FATAL_ADDR && out[got - 1].hits == n + 1
&& out[got - 1].tickMs == now + n + 1500, "the flush ends with the fatal hit (N+1)");
for (i = 0; i < (unsigned int)got; i++)
check(!out[i].written, "a flush never repeats a record written on its own");
check(clf_ring_take(&g, out, &older) == 0, "a second flush writes nothing");
}
static void ring_order_overflow_and_written(void)
{
clf_ring g;
clf_rec out[CLF_RING];
unsigned int i, older;
int got;
memset(&g, 0, sizeof g);
clf_ring_push(&g, 0x10, AV, 0, 1, 1, 1, 1); /* written */
clf_ring_push(&g, 0x20, AV, 0, 1, 2, 2, 0);
clf_ring_push(&g, 0x30, AV, 0, 1, 3, 1, 1); /* written */
clf_ring_push(&g, 0x40, AV, 0, 1, 4, 3, 0);
got = clf_ring_take(&g, out, &older);
check(got == 2 && out[0].addr == 0x20 && out[1].addr == 0x40, "only unwritten records, oldest first");
check(older == 0, "nothing lost under the ring size");
for (i = 0; i < 40; i++) clf_ring_push(&g, 0x1000 + i, AV, 0, 1, 100 + i, 2, 0);
got = clf_ring_take(&g, out, &older);
check(got == CLF_RING, "40 unwritten since the last flush: the ring holds the newest 16");
check(older == 24, "and reports the 24 it no longer holds");
check(out[0].addr == 0x1000 + 24 && out[CLF_RING - 1].addr == 0x1000 + 39, "newest 16, oldest first");
clf_ring_push(&g, 0x9999, AV, 0, 1, 500, 2, 0);
got = clf_ring_take(&g, out, &older);
check(got == 1 && out[0].addr == 0x9999 && older == 0, "after a flush, only what came since");
}
int main(void)
{
fatal_repeat_recovered_by_flush(5);
fatal_repeat_recovered_by_flush(100);
fatal_repeat_recovered_by_flush(1000);
ring_order_overflow_and_written();
netfx_noise_never_spends_the_limit();
known_address_going_fatal_is_written();
ac_faults_limited_per_distinct_address();
codes();
classification();
managed_noise_is_its_own_bucket();
last_chance_is_separate();
full_table_evicts_oldest_noise();
printf("%d check(s), %d failed.\n", g_checks, g_failed);
return g_failed == 0 ? 0 : 1;
}

View file

@ -0,0 +1,28 @@
# Run-CrashLogFilterTests.ps1
# Builds and runs CrashLogFilterTests.c (x86 MSVC, the same toolchain as the DLL).
# -OutDir: where the test exe goes (default: native\SehTrampoline\tests\bin). Exit 0 = pass.
param([string]$OutDir = (Join-Path $PSScriptRoot "bin"))
$ErrorActionPreference = "Stop"
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" `
-latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
-property installationPath 2>$null
if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 }
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
$exe = Join-Path $OutDir "CrashLogFilterTests.exe"
& $cl /nologo /W4 /WX "$PSScriptRoot\CrashLogFilterTests.c" /Fo"$OutDir\\" /Fe"$exe" /link /MACHINE:X86
if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE }
& $exe
exit $LASTEXITCODE