diff --git a/native/SehTrampoline/Build-SehTrampoline.ps1 b/native/SehTrampoline/Build-SehTrampoline.ps1 index 99449bc..55e1894 100644 --- a/native/SehTrampoline/Build-SehTrampoline.ps1 +++ b/native/SehTrampoline/Build-SehTrampoline.ps1 @@ -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 native\SehTrampoline\bin only (no copy to the live Runtime). + +param([switch]$NoDeploy) $ErrorActionPreference = "Stop" @@ -33,6 +36,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) { Write-Host "-NoDeploy: not copied to the runtime."; exit 0 } $runtimeDst = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" Copy-Item "$out\RynthCore.SehTrampoline.dll" $runtimeDst -Force Write-Host "Deployed to $runtimeDst" diff --git a/native/SehTrampoline/CrashLogFilter.h b/native/SehTrampoline/CrashLogFilter.h new file mode 100644 index 0000000..03014f0 --- /dev/null +++ b/native/SehTrampoline/CrashLogFilter.h @@ -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 diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index a458eeb..e445c78 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -220,25 +220,91 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, 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. + */ + +#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; + +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,118 +326,358 @@ 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 = " \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); + const char* e = "==== END NATIVE CRASH ====\r\n"; + cl_write(e, (DWORD)lstrlenA(e)); + } +} - { - char buf[4096]; - char* p = buf; - CONTEXT* c = ep->ContextRecord; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; - DWORD wr; +/* + * 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 older = 0; + int n = clf_ring_take(&g_ring, g_flushRecs, &older), i; + char* p; + 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)); + } +} - 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 = " \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); +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; } + { + 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; } - CloseHandle(h); + /* 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; +} + +/* Last chance: nothing handled it. Logged, then the filter this one replaced decides. */ +static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep) +{ + if (cl_lock()) { + cl_flush_locked("last chance", ep->ExceptionRecord->ExceptionCode); + 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) { + return g_prevFilter(ep); } return EXCEPTION_CONTINUE_SEARCH; } -/* Install the VEH once. logPath = wide path to the dedicated crash log. */ +/* + * 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); + cl_unlock(); +} + +/* + * Install the VEH and the last-chance filter once. logPath = wide path to the dedicated + * crash log, opened here for the life of the process (append, shared for reading and + * deleting). Also builds the first module cache. + */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { @@ -380,8 +686,13 @@ RC_InstallCrashLogger(const wchar_t* logPath) int i = 0; for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } g_crashLogPath[i] = 0; + g_logHandle = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } + RC_RefreshCrashLoggerModules(); g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + g_prevFilter = SetUnhandledExceptionFilter(CrashLastChance); } /* ── Tagged-text parser guard (native MinHook detour body) ──────────────── diff --git a/native/SehTrampoline/tests/CrashLogFilterTests.c b/native/SehTrampoline/tests/CrashLogFilterTests.c new file mode 100644 index 0000000..5c1469c --- /dev/null +++ b/native/SehTrampoline/tests/CrashLogFilterTests.c @@ -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 +#include +#include +#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; +} diff --git a/native/SehTrampoline/tests/Run-CrashLogFilterTests.ps1 b/native/SehTrampoline/tests/Run-CrashLogFilterTests.ps1 new file mode 100644 index 0000000..399ee41 --- /dev/null +++ b/native/SehTrampoline/tests/Run-CrashLogFilterTests.ps1 @@ -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 diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index cbcf9ed..5208660 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -3104,6 +3104,27 @@ internal partial class MainWindow : Window // thread not draining the marshalled-action queue), and a stale heartbeat // file. private readonly Dictionary _wedgeZeroFpsSinceUtc = new(); + // PIDs held off for a full-memory dump, and since when (DumpInProgressRule.Decide caps the + // hold at MaxHold). Kept while held or expired, dropped once no dump is in progress. + private readonly Dictionary _dumpHoldSinceUtc = new(); + + // Last write of the newest acclient_oom__*.dmp in the shared Dumps folder, or null. + private static DateTime? NewestOomDumpWriteUtc(int pid) + { + try + { + string dir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps"); + if (!Directory.Exists(dir)) return null; + DateTime? newest = null; + foreach (string f in Directory.EnumerateFiles(dir, $"{RynthCore.Install.DumpInProgressRule.OomDumpPrefix}{pid}_*.dmp")) + { + DateTime w = File.GetLastWriteTimeUtc(f); + if (newest == null || w > newest) newest = w; + } + return newest; + } + catch { return null; } + } // fps (1), plug pump rate (2), login (3), qd = main-thread queue depth (4, optional on older engines). private static readonly System.Text.RegularExpressions.Regex WedgeHbRegex = new(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?", System.Text.RegularExpressions.RegexOptions.Compiled); @@ -3184,6 +3205,35 @@ internal partial class MainWindow : Window int read = fs.Read(buf, 0, (int)want); tail = System.Text.Encoding.UTF8.GetString(buf, 0, read); + // The engine's OUT OF MEMORY full-memory dump suspends every thread for minutes: + // the log goes silent and the main thread looks hung, but killing now would cut + // the dump short. Hold off both kills below while it is being written + // (DumpInProgressRule); the restart for the box that follows is unchanged. + DateTime holdNow = DateTime.UtcNow; + DateTime? heldSince = _dumpHoldSinceUtc.TryGetValue(pid, out DateTime hs) ? hs : null; + var hold = RynthCore.Install.DumpInProgressRule.Decide(tail, fi.LastWriteTimeUtc, NewestOomDumpWriteUtc(pid), heldSince, holdNow); + if (hold == RynthCore.Install.DumpInProgressRule.Hold.Holding) + { + if (heldSince == null) + { + _dumpHoldSinceUtc[pid] = holdNow; + LauncherDiag.Info($"WEDGE: PID {pid} is writing a full-memory dump - kill held off until it ends (at most {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min)."); + } + continue; + } + if (hold == RynthCore.Install.DumpInProgressRule.Hold.Expired) + { + if (heldSince is DateTime heldAt && heldAt != DateTime.MinValue) + { + _dumpHoldSinceUtc[pid] = DateTime.MinValue; // logged; stays expired until the signs clear + LauncherDiag.Info($"WEDGE: PID {pid} dump hold expired after {RynthCore.Install.DumpInProgressRule.MaxHold.TotalMinutes:0} min - kill checks resume."); + } + } + else + { + _dumpHoldSinceUtc.Remove(pid); + } + if (hbStale) { KillWedgedClient(process, pid, activeContexts, activeSessions, diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 0446f2a..dea6361 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -58,6 +58,7 @@ + diff --git a/src/RynthCore.App.Avalonia/UsageStats.cs b/src/RynthCore.App.Avalonia/UsageStats.cs index 456a3e3..84ee228 100644 --- a/src/RynthCore.App.Avalonia/UsageStats.cs +++ b/src/RynthCore.App.Avalonia/UsageStats.cs @@ -22,7 +22,8 @@ namespace RynthCore.App.Avalonia; /// - the RynthCore version; /// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins /// only as a count, never by name (a private plugin's name could identify its author); -/// - how many crash_*.dmp files the engine wrote since the last report (a count only); +/// - how many crash dumps were written since the last report (a count only): the engine's +/// Logs\dumps\crash_*.dmp and CoreCLR's Logs\dumps\clr_*.dmp; /// - the Windows major version ("10" or "11"). /// Never: character, account or server names, file paths, or anything else identifying. /// @@ -221,18 +222,30 @@ internal sealed class UsageStats return "other"; } - /// crash_*.dmp files written after (hang dumps are not crashes). + /// + /// Crash dump names counted: the engine's crash_*.dmp and the CoreCLR fatal-error dumps the + /// loader asks for in the same folder (clr_*.dmp, Loader.c ConfigureCrashDumps). + /// + private static readonly string[] CrashDumpPatterns = { "crash_*.dmp", "clr_*.dmp" }; + + /// + /// Crash dumps (crash_*.dmp, clr_*.dmp) written after . Hang dumps + /// and the OUT OF MEMORY dumps are not crashes. + /// public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow) { try { if (!Directory.Exists(dir)) return 0; int n = 0; - foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp")) + foreach (string pattern in CrashDumpPatterns) { - DateTime t = File.GetLastWriteTimeUtc(f); - if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++; - if (n >= MaxCrashes) break; + foreach (string f in Directory.EnumerateFiles(dir, pattern)) + { + DateTime t = File.GetLastWriteTimeUtc(f); + if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++; + if (n >= MaxCrashes) return n; + } } return n; } diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 1544ef3..814ae0b 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -246,6 +246,35 @@ internal static class AcMainThreadQueue _ => false, }; + /// + /// Stops and cancels: the teardown group that still runs after a world transition (every + /// other entry queued during one is dropped). Never dropped as stale either. + /// + private static bool IsTeardown(in Entry e) => IsTeardownKind(e.Kind, e.A, e.B); + + /// + /// The ONE teardown predicate: the enqueue side (ActionRing admission, the teardown reserve) + /// and the drain side (which entries survive a world transition) both ask it. + /// + internal static bool IsTeardownKind(ActionKind kind, uint a, uint b) => kind switch + { + ActionKind.SetAutoRun => a == 0, + ActionKind.SetMotion => b == 0, + ActionKind.StopMovement or ActionKind.StopCompletely or ActionKind.CancelAttack + or ActionKind.CloseContainer => true, + _ => false, + }; + + // World-transition drops: counted, and folded into the rate-limited stale summary line. + private static long _transitionDropped; + public static long TransitionDroppedCount => Interlocked.Read(ref _transitionDropped); + + private static void NoteTransitionDrop(string what, long ageMs) + { + Interlocked.Increment(ref _transitionDropped); + NoteStale(what + " (queued during a death/portal/teleport)", ageMs, dropped: true); + } + private static string Describe(in Entry e) => e.Kind switch { ActionKind.SetAutoRun => e.A != 0 ? "SetAutoRun(on)" : "SetAutoRun(off)", @@ -256,38 +285,64 @@ internal static class AcMainThreadQueue _ => e.Kind.ToString(), }; + // The ring (ActionRing: storage, FIFO, admission). 256 entries, the top 32 for teardown + // only, so a ring a bot filled with starts still takes its stops and cancels. private const int Capacity = 256; // power of two - private const int Mask = Capacity - 1; - private static readonly Entry[] _slots = new Entry[Capacity]; - private static readonly object _producerLock = new(); - - // Monotonic counters. Producers advance _tail under _producerLock; the sole - // consumer (main thread) advances _head. - private static int _head; - private static int _tail; + private const int TeardownReserve = 32; + private static readonly ActionRing _ring = new(Capacity, TeardownReserve); private static long _dropped; + private static long _transitionRejected; + /// Entries refused because the ring was full (a running total; the heartbeat's qdrop). public static long DroppedCount => Interlocked.Read(ref _dropped); + /// Non-teardown entries refused while the player was in a world transition. + public static long TransitionRejectedCount => Interlocked.Read(ref _transitionRejected); + + // -- The mutator gate ---------------------------------------------------------- + // Every AC-mutating helper (ClientHelperHooks, CombatActionHooks, MovementActionHooks, + // CommandInterpreterHooks, ClientCombatHooks, PlayerPhysicsHooks, PlayerTrade, + // PlayerTraining) opens with the same line: + // if (AcMainThreadQueue.MustQueue(teardown: )) return Enqueue...; + // Off AC's main thread it queues (as always). ON the main thread it also queues while a + // world transition holds the drains, unless it is being called BY a drain (IsDraining) + // or is teardown: render-thread host actions (ImGui panels, the EndScene plugin calls) + // used to run straight into a world AC was tearing down, around the gate. The queue + // then refuses or holds it like any other queued work (WorldTransitionState). + private static int _drainDepth; // AC main thread only + + /// AC main thread only: a drain is dispatching queued work right now. + public static bool IsDraining => _drainDepth > 0; + + /// AC main thread only: a direct call now would run into a world transition. + public static bool ShouldDefer() => !IsDraining && PlayerLifecycleLog.HoldQueuedWork(NowMs); + + /// + /// The one gate every mutator opens with: true = queue instead of calling AC now. + /// : a stop or cancel (IsTeardownKind), which runs at once on + /// the main thread even in a transition. + /// + public static bool MustQueue(bool teardown) => + MutatorGate.MustQueue(MainThreadGuard.IsOnMainThread(), teardown, IsDraining, HoldNow); + + // Cached (no allocation per call): main thread only, asked only by MutatorGate on it. + private static readonly Func HoldNow = () => PlayerLifecycleLog.HoldQueuedWork(NowMs); + private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0) { - lock (_producerLock) - { - int tail = _tail; - int head = Volatile.Read(ref _head); - if (tail - head >= Capacity) - { - // Full. Drop rather than block or fall back to an off-thread AC - // mutation — a dropped movement/attack tick self-corrects on the - // next bot tick; an off-thread mutation can crash the client. - Interlocked.Increment(ref _dropped); - return false; - } - - _slots[tail & Mask] = new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)); - Volatile.Write(ref _tail, tail + 1); - return true; - } + bool teardown = IsTeardownKind(kind, a, b); + // Dead / portaling / settling: a start queued now would be dropped when the window + // ends anyway (WorldTransitionState), so it is refused here and never takes a slot a + // stop needs. Stops and cancels are always taken (the reserve keeps room for them). + var r = _ring.TryEnqueue(new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)), + teardown, PlayerLifecycleLog.InWorldTransition); + if (r == ActionRing.Admit.Queued) return true; + // Full: drop rather than block or fall back to an off-thread AC mutation - a dropped + // movement/attack tick self-corrects on the next bot tick; an off-thread mutation can + // crash the client. + if (r == ActionRing.Admit.Full) Interlocked.Increment(ref _dropped); + else Interlocked.Increment(ref _transitionRejected); + return false; } // ── Typed enqueue helpers (called by the public action methods when they @@ -336,19 +391,33 @@ internal static class AcMainThreadQueue // CommandInterpreter turn, which would change the steering behaviour. private static int _directHeadingPending; private static uint _directHeadingBits; + private static long _directHeadingAt; public static bool EnqueueDirectHeading(float headingDegrees) { Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees)); + Interlocked.Exchange(ref _directHeadingAt, NowMs); Volatile.Write(ref _directHeadingPending, 1); return true; } // Main thread only (from Drain). Same order as the pre-queue code: the direct // snap first, the CommandInterpreter turn only when there is no player. + // World transition: the pending heading is held; once the window ends a heading set + // during it is stale (the bot steers again from where it landed) and is dropped. private static void DrainDirectHeading() { + if (Volatile.Read(ref _directHeadingPending) == 0) return; + long now = NowMs; + long at = Interlocked.Read(ref _directHeadingAt); + WorldTransitionState.Verdict v = PlayerLifecycleLog.DecideQueued(now, at, teardown: false); + if (v == WorldTransitionState.Verdict.Hold) return; if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return; + if (v == WorldTransitionState.Verdict.Drop) + { + NoteTransitionDrop("heading", now - at); + return; + } float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits)); try { @@ -371,18 +440,25 @@ internal static class AcMainThreadQueue // selects mid-gesture too). Lock-free and allocation-free. private static int _overlaySelectPending; private static uint _overlaySelectId; + private static long _overlaySelectAt; public static bool EnqueueOverlaySelect(uint objectId) { if (objectId == 0) return false; Volatile.Write(ref _overlaySelectId, objectId); + Interlocked.Exchange(ref _overlaySelectAt, NowMs); Volatile.Write(ref _overlaySelectPending, 1); return true; } - // Main thread only (from Drain). + // Main thread only (from Drain). World transition: held, and kept when the window ends: + // it is the user's own click, and SelectFromOverlay re-checks the object still exists. private static void DrainOverlaySelect() { + if (Volatile.Read(ref _overlaySelectPending) == 0) return; + if (PlayerLifecycleLog.DecideQueued(NowMs, Interlocked.Read(ref _overlaySelectAt), teardown: true) + == WorldTransitionState.Verdict.Hold) + return; if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return; uint id = Volatile.Read(ref _overlaySelectId); try { ClientHelperHooks.SelectFromOverlay(id); } @@ -491,6 +567,14 @@ internal static class AcMainThreadQueue private static long _drainDeferSinceMs; public static void Drain() + { + // IsDraining: the helpers this dispatches run their AC call directly (MustQueue). + _drainDepth++; + try { DrainCore(); } + finally { _drainDepth--; } + } + + private static void DrainCore() { if (_disarmed) { @@ -524,14 +608,23 @@ internal static class AcMainThreadQueue // and 0xC8 appraisal sends too, contradicting that invariant. Each // drains only while ITS OWN queue is non-empty, so moving them here // costs nothing when they're empty (the common case). + // World transition gate (dead / portal / landblock jump, WorldTransitionState): AC is + // tearing objects down and loading new ones, so nothing queued that mutates the game + // runs now. Chat output (AC's own text window) and the char-select service still do. + long gateNow = NowMs; + bool holding = PlayerLifecycleLog.HoldQueuedWork(gateNow); + DrainChat(); - DrainChatCommands(); + if (!holding) DrainChatCommands(); // held: their own 15 s age limit still applies DrainRequestIds(); DrainQueryHealth(); // Vendor buy/sell: a packet send through the client's own SendShopEvent, not a // motion, so it sits with the non-gesture queues above. Also polls whether the // vendor window is still open. Idle fast path when no vendor is open. - try { VendorTrade.MainThreadTick(); } catch { } + if (!holding) + { + try { VendorTrade.MainThreadTick(); } catch { } + } // Char-select service: publishes the UIFlow mode, runs a pending auto-login // LogOnCharacter request and snapshots the native character list (throttled). // Pre-login this runs from the Client::UseTime drain (EndScene is not hooked @@ -541,14 +634,19 @@ internal static class AcMainThreadQueue // Plugin heading snap (coalesced slot). Before the ring and its gesture // defer: the pre-queue raw write landed immediately, gesture or not, and // ahead of the SetAutoRun a nav tick queues right after it. Keep both. + // Both are latest-value slots (a heading, a select): held through a world transition, + // then decided by their own drains (a stale heading dropped, a user's select kept). DrainDirectHeading(); // Overlay click-to-select (Radar dot / nameplate click): also before the // gesture defer, so a click selects at once even while the bot swings. DrainOverlaySelect(); - int head = _head; // only the main thread writes _head - int tail = Volatile.Read(ref _tail); + // In a world transition the ring is held whole (FIFO kept): nothing runs, nothing is + // dropped yet. Once it ends, the loop below drops what was queued during it, except + // stops and cancels, which run in order as one teardown group. + if (holding) + return; // ── Gesture-phase serialization (extends the 56e6946 anim-walk guard // to the whole ring) ───────────────────────────────────────────────── @@ -562,7 +660,7 @@ internal static class AcMainThreadQueue // drop: dropping arbitrary item/movement actions desyncs the bot far // worse than a late injection, and the pre-2026-06-12 behavior was // "always inject" anyway, so proceeding past the cap is never worse). - if (head != tail) + if (_ring.Count > 0) { // In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate). if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) @@ -576,16 +674,20 @@ internal static class AcMainThreadQueue } long runAt = NowMs; int epochNow = Volatile.Read(ref _loginEpoch); - while (head != tail) + // Bounded to what is queued now plus a capacity's worth: an action that re-queues + // itself can never spin the main thread. + int budget = Capacity * 2; + while (budget-- > 0 && _ring.TryDequeue(out Entry e)) { - Entry e = _slots[head & Mask]; - Volatile.Write(ref _head, ++head); - long age = runAt - e.At; + if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop) + { + NoteTransitionDrop(Describe(e), age); + continue; + } if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e))) { NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true); - tail = Volatile.Read(ref _tail); continue; } if (age > LateActionLogMs) @@ -719,8 +821,6 @@ internal static class AcMainThreadQueue // not managed exceptions and won't be caught here — but these // now run on the correct thread, which is the whole point.) } - - tail = Volatile.Read(ref _tail); } } @@ -733,22 +833,41 @@ internal static class AcMainThreadQueue // Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog // of appraisals can never crowd out combat/movement actions or get gesture-deferred: // an appraisal is just a packet send and doesn't perturb AC's motion/UI state. - private static readonly System.Collections.Generic.Queue<(uint Id, long At, int Epoch)> _requestIdQueue = new(); - private static readonly object _requestIdLock = new(); + // A request for an object that already has one pending is merged into it, as the + // QueryHealth slot does: the one appraisal reply answers every caller (PendingIdQueue). private const int MaxRequestIdQueue = 256; + private static readonly PendingIdQueue _requestIdQueue = new(MaxRequestIdQueue); + private static readonly object _requestIdLock = new(); + // Merge only into an entry the drain will still send: half the stale limit leaves room + // for a drain that runs late (a stalled main thread). + private const long RequestIdMergeMaxAgeMs = RequestIdMaxAgeMs / 2; - // Pump/Timer-thread enqueue. Drops (returns false) if the queue is full. + /// RequestId calls absorbed by an already-pending request for the same object. + public static long RequestIdMergedCount + { + get { lock (_requestIdLock) return _requestIdQueue.MergedTotal; } + } + + // Pump/Timer-thread enqueue. Drops (returns false) if the queue is full. A request for an + // object already waiting returns true without queueing a second send. public static bool EnqueueRequestId(uint objectId) { if (objectId == 0) return false; + // Dead / portaling / settling: an appraisal queued now is dropped when the window + // ends, so it is refused here (the caller sees false and may ask again later). Nor + // does a request merge into an entry from before the last held drain: that entry is + // dropped when the drain reaches it, and the merged request would go with it. + if (PlayerLifecycleLog.InWorldTransition) return false; + long mergeOnlyAfter = PlayerLifecycleLog.LastBlockedMs; lock (_requestIdLock) { - if (_requestIdQueue.Count >= MaxRequestIdQueue) + PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), + RequestIdMergeMaxAgeMs, mergeOnlyAfter); + if (r == PendingIdQueue.Result.Full) { Interlocked.Increment(ref _dropped); return false; } - _requestIdQueue.Enqueue((objectId, NowMs, Volatile.Read(ref _loginEpoch))); return true; } } @@ -760,22 +879,37 @@ internal static class AcMainThreadQueue // Bounded like DrainChatCommands: a re-queue never spins the main thread. int budget; lock (_requestIdLock) budget = _requestIdQueue.Count; + if (budget == 0) return; long now = NowMs; + // World transition (dead / portal / landblock jump): hold every appraisal; once it + // ends, those queued during it are dropped (WorldTransitionState). + if (PlayerLifecycleLog.HoldQueuedWork(now)) return; int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { - (uint Id, long At, int Epoch) item; + PendingIdQueue.Item item; lock (_requestIdLock) { - if (_requestIdQueue.Count == 0) return; - item = _requestIdQueue.Dequeue(); + if (!_requestIdQueue.TryDequeue(out item)) return; } if (item.Epoch != epoch || now - item.At > RequestIdMaxAgeMs) { NoteStale($"RequestId(0x{item.Id:X8})", now - item.At, dropped: true); continue; } - try { CombatActionHooks.RequestId(item.Id); } catch { } + if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop) + { + NoteTransitionDrop($"RequestId(0x{item.Id:X8})", now - item.At); + continue; + } + bool sent = false; + try { sent = CombatActionHooks.RequestId(item.Id); } catch { } + // AutoId's re-appraisal window starts at the real send, not at the queueing: + // a request dropped here (stale, transition) leaves the object due again. + if (sent) + { + try { AutoIdService.OnSent(item.Id, now); } catch { } + } } } @@ -819,6 +953,7 @@ internal static class AcMainThreadQueue int budget; lock (_queryHealthLock) budget = _queryHealthQueue.Count; long now = NowMs; + if (PlayerLifecycleLog.HoldQueuedWork(now)) return; // world transition: hold int epoch = Volatile.Read(ref _loginEpoch); while (budget-- > 0) { @@ -834,6 +969,11 @@ internal static class AcMainThreadQueue NoteStale($"QueryHealth(0x{item.Id:X8})", now - item.At, dropped: true); continue; } + if (PlayerLifecycleLog.DecideQueued(now, item.At, teardown: false) == WorldTransitionState.Verdict.Drop) + { + NoteTransitionDrop($"QueryHealth(0x{item.Id:X8})", now - item.At); + continue; + } try { CombatActionHooks.QueryHealth(item.Id); } catch { } } } @@ -958,9 +1098,7 @@ internal static class AcMainThreadQueue // tick — they already handle a false return without wedging. At ~frame-rate drain // the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be // marshalled, closing the off-thread object-graph corruption class at its source. - private static int _castPending; - private static uint _castTargetId; - private static uint _castSpellId; + private static readonly CastSlot _cast = new(); // writes under _castLock private static readonly object _castLock = new(); // Ticks DrainCasts has deferred the pending cast because a motion gesture was @@ -969,30 +1107,27 @@ internal static class AcMainThreadQueue // plugin's no-chat-resolve machinery already retries casts that produce no // chat, so a drop degrades to one retry cycle, never a wedge. private static long _castDeferDrops; - private static long _castQueuedAt; // TickCount64 when the pending cast was queued (2026-10-06) + /// Casts dropped after deferring CastDeferTickCap ticks (stuck gesture). public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops); // Pump-thread enqueue. Returns false (caller retries next tick) if a cast is - // already pending. + // already pending, or during a world transition (CastSlot): the drain would only hold + // it and then drop it, and the slot would refuse every newer cast meanwhile. public static bool EnqueueCast(uint targetId, uint spellId) { + CastSlot.Admit admit; lock (_castLock) - { - if (_castPending != 0) return false; - _castTargetId = targetId; - _castSpellId = spellId; - _castQueuedAt = NowMs; - _castStopWaitNoted = false; - _castPending = 1; - return true; - } + admit = _cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition); + if (admit == CastSlot.Admit.RejectedTransition) + Interlocked.Increment(ref _transitionRejected); + return admit == CastSlot.Admit.Queued; } - // Casts that waited for a movement stop queued ahead of them (counted once per cast). + // Casts that waited for a movement stop queued ahead of them (counted once per cast; + // the per-cast flag is CastSlot.StopWaitNoted, reset by each new cast). private static long _castStopWaits; - private static bool _castStopWaitNoted; /// Casts that waited one or more ticks for a stop queued ahead of them. public static long CastStopWaitCount => Interlocked.Read(ref _castStopWaits); @@ -1008,29 +1143,28 @@ internal static class AcMainThreadQueue /// /// True when the action ring holds a movement stop queued at or before . - /// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so - /// their times rise from head to tail and the walk stops at the first newer one. + /// Main thread only (the ring's sole consumer). An entry's time is taken before ActionRing's + /// producer lock, so two producers can land slightly out of time order: the walk checks every + /// queued entry (at most Capacity) instead of stopping at the first newer one (CastStopRules). /// - private static bool StopQueuedAtOrBefore(long castQueuedAt) - { - int head = _head; - int tail = Volatile.Read(ref _tail); - for (int i = head; i != tail; i++) - { - ref readonly Entry e = ref _slots[i & Mask]; - if (e.At > castQueuedAt) return false; - if (IsMovementStop(e)) return true; - } - return false; - } + private static bool StopQueuedAtOrBefore(long castQueuedAt) => + CastStopRules.AnyStopAtOrBefore(_ring, castQueuedAt, static e => e.At, static e => IsMovementStop(e)); // Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick). // Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the - // cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline). + // cast directly via the SEH trampoline (targeted: FreeHandsAndCastSpell with the target + // passed explicitly, no SelectItem; self: ClientMagicSystem::CastSpell). public static void DrainCasts() + { + _drainDepth++; + try { DrainCastsCore(); } + finally { _drainDepth--; } + } + + private static void DrainCastsCore() { if (_disarmed) return; // engine teardown in progress - if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path + if (Volatile.Read(ref _cast.Pending) == 0) return; // alloc-free fast path // ── Anim-walk race guard (dump-proven 2026-06-12) ──────────────────── // DrainCasts runs PRE-tick (selection timing), but a cast initiates a @@ -1049,7 +1183,23 @@ internal static class AcMainThreadQueue // CastDeferMaxMs the cast is dropped and logged with its age. RynthAi waits up to 7 s // for a cast's answer before it sends another (ActionPacer), so a drop here can't // leave two casts in flight. - long castAge = NowMs - Volatile.Read(ref _castQueuedAt); + // World transition (dead / portal / landblock jump): hold the cast; a cast queued + // during it is dropped once it ends (WorldTransitionState). Before the gesture check: + // nothing about the player's motion is read while AC is tearing the world down. + long nowCast = NowMs; + long queuedAt = Volatile.Read(ref _cast.QueuedAt); + WorldTransitionState.Verdict castVerdict = PlayerLifecycleLog.DecideQueued(nowCast, queuedAt, teardown: false); + if (castVerdict == WorldTransitionState.Verdict.Hold) + return; + if (castVerdict == WorldTransitionState.Verdict.Drop) + { + uint droppedSpell; + lock (_castLock) { droppedSpell = _cast.SpellId; _cast.Pending = 0; } + NoteTransitionDrop($"CastSpell({droppedSpell})", nowCast - queuedAt); + return; + } + + long castAge = nowCast - queuedAt; if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) { if (castAge <= CastDeferMaxMs) @@ -1057,7 +1207,7 @@ internal static class AcMainThreadQueue // Gesture stuck past the deadline — drop the cast instead of injecting // into a wedged motion graph; the plugin retries via no-chat-resolve. uint dropped; - lock (_castLock) { dropped = _castSpellId; _castPending = 0; } + lock (_castLock) { dropped = _cast.SpellId; _cast.Pending = 0; } Interlocked.Increment(ref _castDeferDrops); NoteStale($"CastSpell({dropped}) behind a gesture", castAge, dropped: true); return; @@ -1070,13 +1220,13 @@ internal static class AcMainThreadQueue // locomotion still on, and the queued stops followed as extra MoveToStates. Wait (at // most until EndScene drains the ring, about one frame; the ring's own gesture defer // is shorter than CastDeferMaxMs) while one is queued; past the limit cast anyway. - if (StopQueuedAtOrBefore(Volatile.Read(ref _castQueuedAt))) + if (StopQueuedAtOrBefore(queuedAt)) { if (castAge <= CastDeferMaxMs) { - if (!_castStopWaitNoted) + if (!_cast.StopWaitNoted) { - _castStopWaitNoted = true; + _cast.StopWaitNoted = true; Interlocked.Increment(ref _castStopWaits); try { Net.FlightRecorder.Mark(Net.FlightMark.Note, text: "cast waits for a movement stop queued before it"); } catch { } } @@ -1085,7 +1235,7 @@ internal static class AcMainThreadQueue } // ── The stop goes a server answer ahead of the cast (2026-10-12, PreCastStopRules) ── - long castStamp = Volatile.Read(ref _castQueuedAt); + long castStamp = queuedAt; if (_preStopFor != castStamp) { _preStopFor = castStamp; _preStopSent = false; } long nowMs = NowMs; PreCastStep step = PreCastStopRules.Decide( @@ -1122,10 +1272,10 @@ internal static class AcMainThreadQueue uint target, spell; lock (_castLock) { - if (_castPending == 0) return; - target = _castTargetId; - spell = _castSpellId; - _castPending = 0; + if (_cast.Pending == 0) return; + target = _cast.TargetId; + spell = _cast.SpellId; + _cast.Pending = 0; } if (castAge > LateActionLogMs) NoteStale($"CastSpell({spell})", castAge, dropped: false); diff --git a/src/RynthCore.Engine/Compatibility/ActionRing.cs b/src/RynthCore.Engine/Compatibility/ActionRing.cs new file mode 100644 index 0000000..9a8a077 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ActionRing.cs @@ -0,0 +1,123 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ActionRing.cs +// +// The storage and admission policy of AcMainThreadQueue's action ring: a fixed ring of +// entries, many producers (under one lock), ONE consumer (AC's main thread), FIFO. +// +// Admission: during a world transition the drain holds the ring +// (WorldTransitionState), and a bot keeps queueing starts at ~60 Hz meanwhile, so the +// ring used to fill and then refuse the stops and cancels that matter most. Now: +// - while the caller says a transition is on, non-teardown entries are refused at +// once (they would be dropped when it ends anyway); +// - the top TeardownReserve slots only take teardown entries (stops and cancels), so a +// ring filled by starts before the transition was seen still takes a stop. +// What counts as teardown is the caller's (AcMainThreadQueue.IsTeardownKind, the same +// predicate its drain uses). +// +// Pure: no engine state. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class ActionRing where T : struct +{ + public enum Admit + { + Queued, + /// No room (for a non-teardown entry: none below the teardown reserve). + Full, + /// A world transition is on and the entry is not teardown. + RejectedTransition, + } + + private readonly T[] _slots; + private readonly int _mask; + private readonly int _reserve; + private readonly object _lock = new(); + // Monotonic counters. Producers advance _tail under _lock; the sole consumer advances _head. + private int _head; + private int _tail; + + public ActionRing(int capacityPowerOfTwo, int teardownReserve) + { + if (capacityPowerOfTwo <= 0 || (capacityPowerOfTwo & (capacityPowerOfTwo - 1)) != 0) + throw new System.ArgumentOutOfRangeException(nameof(capacityPowerOfTwo)); + if (teardownReserve < 0 || teardownReserve >= capacityPowerOfTwo) + throw new System.ArgumentOutOfRangeException(nameof(teardownReserve)); + _slots = new T[capacityPowerOfTwo]; + _mask = capacityPowerOfTwo - 1; + _reserve = teardownReserve; + } + + public int Capacity => _slots.Length; + public int TeardownReserve => _reserve; + + /// Entries waiting (any thread; a snapshot). + public int Count => Volatile.Read(ref _tail) - Volatile.Read(ref _head); + + /// Producer side, any thread. + public Admit TryEnqueue(in T entry, bool teardown, bool inTransition) + { + lock (_lock) + { + if (inTransition && !teardown) + return Admit.RejectedTransition; + int tail = _tail; + int used = tail - Volatile.Read(ref _head); + int limit = teardown ? _slots.Length : _slots.Length - _reserve; + if (used >= limit) + return Admit.Full; + _slots[tail & _mask] = entry; + Volatile.Write(ref _tail, tail + 1); + return Admit.Queued; + } + } + + /// Consumer only: the oldest entry, without removing it. + public bool TryPeek(out T entry) + { + int head = _head; + if (head == Volatile.Read(ref _tail)) + { + entry = default; + return false; + } + entry = _slots[head & _mask]; + return true; + } + + /// + /// Consumer only: the entry places behind the oldest (0 = the + /// oldest), without removing anything. False past the newest entry. + /// + public bool TryPeekAt(int offset, out T entry) + { + int head = _head; + if (offset < 0 || offset >= Volatile.Read(ref _tail) - head) + { + entry = default; + return false; + } + entry = _slots[(head + offset) & _mask]; + return true; + } + + /// Consumer only: removes the oldest entry (after a successful TryPeek). + public void Pop() + { + int head = _head; + if (head == Volatile.Read(ref _tail)) return; + _slots[head & _mask] = default; + Volatile.Write(ref _head, head + 1); + } + + /// Consumer only: removes and returns the oldest entry. + public bool TryDequeue(out T entry) + { + if (!TryPeek(out entry)) return false; + Pop(); + return true; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AddressSpace.cs b/src/RynthCore.Engine/Compatibility/AddressSpace.cs new file mode 100644 index 0000000..3155ca0 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AddressSpace.cs @@ -0,0 +1,87 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AddressSpace.cs +// +// Free user address space and the LARGEST free block, in MB. acclient is 32-bit, so +// "out of memory" usually means fragmentation, not exhaustion: 300 MB may be free in +// total while no single block can take a 16 MB allocation. vafree alone (the +// heartbeat's GlobalMemoryStatusEx total) cannot show that; valargest can. +// +// Walks the regions with VirtualQuery (a few thousand calls, no allocation). Any +// thread; the heartbeat thread calls it once a second and PluginManager around each +// plugin load and unload during a reload. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +internal static class AddressSpace +{ + private const uint MEM_FREE = 0x10000; + + [StructLayout(LayoutKind.Sequential)] + private struct MEMORY_BASIC_INFORMATION + { + public nuint BaseAddress; + public nuint AllocationBase; + public uint AllocationProtect; + public nuint RegionSize; // sequential layout pads after the uint on x64 + public uint State; + public uint Protect; + public uint Type; + } + + [DllImport("kernel32.dll")] + private static extern nuint VirtualQuery(nuint lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, nuint dwLength); + + /// + /// Total free and largest free block of this process's address space, in MB, or + /// (-1, -1) on failure. Never throws. + /// + public static (long FreeMb, long LargestFreeMb) FreeAndLargestMb() + { + try + { + ulong free = 0, largest = 0; + nuint addr = 0; + nuint size = (nuint)Marshal.SizeOf(); + int guard = 0; + while (guard++ < 1_000_000) + { + if (VirtualQuery(addr, out MEMORY_BASIC_INFORMATION mbi, size) == 0) + break; + ulong region = mbi.RegionSize; + if (region == 0) + break; + Accumulate(mbi.State == MEM_FREE, region, ref free, ref largest); + nuint next = mbi.BaseAddress + mbi.RegionSize; + if (next <= addr) + break; // wrapped past the top + addr = next; + } + if (guard <= 1) + return (-1, -1); + return ((long)(free >> 20), (long)(largest >> 20)); + } + catch + { + return (-1, -1); + } + } + + /// Pure: fold one region into the running totals. + public static void Accumulate(bool isFree, ulong regionBytes, ref ulong freeBytes, ref ulong largestBytes) + { + if (!isFree) return; + freeBytes += regionBytes; + if (regionBytes > largestBytes) largestBytes = regionBytes; + } + + /// "free=NNNMB largest=NNNMB", for the reload log lines. + public static string Describe() + { + var (free, largest) = FreeAndLargestMb(); + return free < 0 ? "free=? largest=?" : $"free={free}MB largest={largest}MB"; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs index 2334a06..5afef9d 100644 --- a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -80,6 +80,9 @@ internal static class AppraisalHooks // Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray at +0x30) private static readonly Dictionary _spellIdCache = new(); private static readonly object _cacheLock = new(); + // Objects the CLIENT released, whose data is kept a while (ReleasedObjectRetention). + private static readonly ReleasedObjectRetention _released = new(); + private static readonly List _expiredScratch = new(); public static bool IsInstalled => _hookInstalled; public static string StatusMessage => _statusMessage; @@ -114,19 +117,64 @@ internal static class AppraisalHooks _bags.Clear(); _spellIdCache.Clear(); _failedRollLogged.Clear(); + _released.Clear(); } } - /// Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook). + /// + /// Drops everything cached for an object: the SERVER deleted it (0xF747, SmartBoxHooks / + /// ServerMessageStream), or its kept-after-release time ran out. Any thread. + /// public static void EvictObject(uint guid) + { + lock (_cacheLock) + EvictLocked(guid); + } + + // Caller holds _cacheLock. + private static void EvictLocked(uint guid) + { + _appraisedGuids.Remove(guid); + _lastIdTime.Remove(guid); + _bags.Remove(guid); + _spellIdCache.Remove(guid); + _failedRollLogged.Remove(guid); + _released.Forget(guid); + } + + /// + /// The CLIENT released an object (AC's BeingDeleted: it left the client's view). Its data is + /// kept for ReleasedObjectRetention.RetainMs, so a re-create inside that time still finds it + /// (AutoId then skips the re-appraisal). Main thread (the BeingDeleted detour). + /// + public static void OnClientRelease(uint guid, long nowMs) { lock (_cacheLock) { - _appraisedGuids.Remove(guid); - _lastIdTime.Remove(guid); - _bags.Remove(guid); - _spellIdCache.Remove(guid); - _failedRollLogged.Remove(guid); + if (!_appraisedGuids.Contains(guid) && !_bags.ContainsKey(guid)) return; + if (!_released.OnRelease(guid, nowMs)) + EvictLocked(guid); // the kept-released bound is full: drop it now + } + } + + /// The object was created again: its data is current, not merely kept. + public static void MarkLive(uint guid) + { + lock (_cacheLock) + _released.Forget(guid); + } + + /// Drops the data of objects released longer ago than the retention time. Timer thread. + public static int ExpireReleased(long nowMs) + { + lock (_cacheLock) + { + _expiredScratch.Clear(); + int n = _released.Expire(nowMs, _expiredScratch); + foreach (uint g in _expiredScratch) + EvictLocked(g); + _expiredScratch.Clear(); + return n; } } @@ -150,10 +198,7 @@ internal static class AppraisalHooks if (t < oldestTime) { oldestTime = t; oldest = g; } } if (oldest == 0) return; - _bags.Remove(oldest); - _appraisedGuids.Remove(oldest); - _lastIdTime.Remove(oldest); - _spellIdCache.Remove(oldest); + EvictLocked(oldest); } } diff --git a/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs new file mode 100644 index 0000000..a51c979 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs @@ -0,0 +1,191 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/AutoIdEligibility.cs +// +// Which created objects AutoIdService appraises (the decision only; AutoIdService +// does the queueing and the sends). +// +// Before: a client-side release of an object (ACCObjectMaint::DeleteObject, or the +// Decal bridge's delete event) forgot that it had been appraised, so every time the +// client re-created it the engine appraised it again: some objects 16 times in 26 +// minutes. Now each object keeps the time its last appraisal was SENT, across client +// releases, and a re-create inside the window (default 10 minutes) is not appraised +// again, unless: +// - the SERVER deleted the object (0xF747 ObjectDelete): it really went away, and +// what comes back under that id is appraised fresh; or +// - the appraisal data is no longer cached (the caller says so): re-appraising is +// then the only way to get it back, so the window never leaves an object with +// nothing cached. +// A release before the queued appraisal went out records no time, so the next create +// is appraised. A create while the object is still live is a duplicate and ignored. +// +// Bounded: at most MaxTracked objects. Prune (from the drain timer, never the create +// path) drops entries that no longer decide anything (released and outside the window +// or never sent), then the oldest released ones. Past the bound a create is still +// admitted, only not tracked. +// +// Pure: no engine state, no locking (the caller locks), and no allocation after +// construction (pre-sized; Dictionary.Remove during enumeration is allowed on +// .NET Core 3+). Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class AutoIdEligibility +{ + public const long DefaultWindowMs = 10L * 60 * 1000; + public const int DefaultMaxTracked = 8192; + + public enum CreateDecision + { + /// Queue an appraisal. + Appraise, + /// Appraised recently and still cached: skip. + SkipRecent, + /// Already live (a second create for it): skip. + SkipDuplicate, + } + + private struct Entry + { + public bool Live; // created and not released since + public long LastSentMs; // when its last appraisal was sent; 0 = none since tracking (re)started + } + + private readonly Dictionary _map; + private readonly long _windowMs; + private readonly int _maxTracked; + + public AutoIdEligibility(long windowMs = DefaultWindowMs, int maxTracked = DefaultMaxTracked) + { + _windowMs = windowMs; + _maxTracked = maxTracked; + _map = new Dictionary(maxTracked + 1); + } + + public int Count => _map.Count; + public int MaxTracked => _maxTracked; + public long WindowMs => _windowMs; + + /// Re-creates skipped because the last appraisal is recent and still cached. + public long SkippedRecentTotal { get; private set; } + + /// Creates admitted while the map was full (appraised, not tracked). + public long UntrackedAdmits { get; private set; } + + /// + /// The client created . : the + /// engine still holds appraisal data for it (AppraisalHooks). + /// + public CreateDecision OnCreate(uint id, long nowMs, bool appraisalCached) + { + if (_map.TryGetValue(id, out Entry e)) + { + if (e.Live) + return CreateDecision.SkipDuplicate; + e.Live = true; + bool recent = e.LastSentMs != 0 && nowMs - e.LastSentMs < _windowMs; + _map[id] = e; + if (recent && appraisalCached) + { + SkippedRecentTotal++; + return CreateDecision.SkipRecent; + } + return CreateDecision.Appraise; + } + + if (_map.Count >= _maxTracked) + { + UntrackedAdmits++; + return CreateDecision.Appraise; + } + _map[id] = new Entry { Live = true, LastSentMs = 0 }; + return CreateDecision.Appraise; + } + + /// + /// The appraisal for was sent: called from the main-thread drain + /// after CombatActionHooks.RequestId succeeded, never at queue time, so a request the + /// drain dropped (stale, a world transition, a new login) records nothing. + /// + public void OnSent(uint id, long nowMs) + { + if (_map.TryGetValue(id, out Entry e)) + { + e.LastSentMs = nowMs == 0 ? 1 : nowMs; + _map[id] = e; + } + } + + /// The client released ; its appraisal time is kept. + public void OnClientRelease(uint id) + { + if (_map.TryGetValue(id, out Entry e) && e.Live) + { + e.Live = false; + _map[id] = e; + } + } + + /// + /// The server deleted : the next create under that id is appraised. + /// Liveness is left to the client's own release (it may come before or after this). + /// + public void OnServerDelete(uint id) + { + if (_map.TryGetValue(id, out Entry e)) + { + e.LastSentMs = 0; + _map[id] = e; + } + } + + /// True while is created and not released (or untracked). + public bool IsLive(uint id) => !_map.TryGetValue(id, out Entry e) || e.Live; + + /// + /// Keep the map under its bound. First drops entries that decide nothing any more + /// (released, and never sent or outside the window), then, if still at the bound, + /// the released entries sent longest ago. Live entries are never dropped. + /// Returns how many were removed. + /// + public int Prune(long nowMs) + { + int removed = 0; + foreach (KeyValuePair kv in _map) + { + Entry e = kv.Value; + if (!e.Live && (e.LastSentMs == 0 || nowMs - e.LastSentMs >= _windowMs)) + { + _map.Remove(kv.Key); + removed++; + } + } + + // Still over three quarters full: drop released entries oldest first, in a few + // passes with a shrinking age cut (window/2, /4, /8, then any age). One linear + // pass each, so a prune never costs more than five walks of the map. + int target = _maxTracked * 3 / 4; + for (int pass = 1; pass <= 4 && _map.Count > target; pass++) + { + long minAge = pass < 4 ? _windowMs >> pass : long.MinValue; + foreach (KeyValuePair kv in _map) + { + if (_map.Count <= target) break; + if (kv.Value.Live) continue; + if (pass < 4 && nowMs - kv.Value.LastSentMs < minAge) continue; + _map.Remove(kv.Key); + removed++; + } + } + return removed; + } + + /// + /// Fix 2 rule for the selected-target priority appraisal: the target's appraisal is + /// cached and was received less than ago. + /// + public static bool IsAppraisalFresh(bool cached, long lastIdUnixSec, long nowUnixSec, long windowMs) => + cached && lastIdUnixSec > 0 && (nowUnixSec - lastIdUnixSec) * 1000 < windowMs; +} diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index 6421c20..5770cb4 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -7,6 +7,10 @@ // // Objects are queued from CreateObjectHooks and drained by a background timer // with rate-limiting to avoid flooding the server. +// +// Which creates get an appraisal is AutoIdEligibility's rule: an object the client +// released and re-created is not appraised again within 10 minutes of the last one +// while its data is still cached, unless the server deleted it (see that file). // ============================================================================ using System; @@ -23,8 +27,16 @@ internal static class AutoIdService // Max RequestId calls per drain tick private const int MaxPerTick = 3; - // Skip objects already appraised this session - private static readonly ConcurrentDictionary _sent = new(); + // How long an appraisal stays good enough not to repeat: a client re-create inside + // this window, and the selected-target priority appraisal, skip an object whose + // appraisal is cached and this recent. + private const long ReappraiseWindowMs = AutoIdEligibility.DefaultWindowMs; + + // Per-object appraisal bookkeeping. Written on AC's main thread (create, client + // release), the plugin pump (server delete) and the drain timer; every access holds + // _gate, for a few dictionary operations only. + private static readonly AutoIdEligibility _eligibility = new(ReappraiseWindowMs); + private static readonly object _gate = new(); // Pending queue private static readonly ConcurrentQueue _queue = new(); @@ -32,6 +44,17 @@ internal static class AutoIdService private static Timer? _drainTimer; private static bool _started; + private static long _skippedPriorityFresh; + + /// Re-creates not appraised because a recent appraisal is still cached. + public static long SkippedRecentCount + { + get { lock (_gate) return _eligibility.SkippedRecentTotal; } + } + + /// Selected-target priority appraisals skipped because the target's data is cached and fresh. + public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh); + public static void Start() { if (_started) @@ -56,7 +79,8 @@ internal static class AutoIdService } /// - /// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour. + /// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour + /// (AC's main thread) and the Decal bridge's create event. /// public static void Enqueue(uint objectId) { @@ -68,23 +92,57 @@ internal static class AutoIdService if (playerId != 0 && objectId == playerId) return; - // Skip if already sent this session - if (!_sent.TryAdd(objectId, 0)) - return; + // Created again: data kept since a client release is current again (and still cached + // if the release was inside ReleasedObjectRetention's time). + AppraisalHooks.MarkLive(objectId); + bool cached = AppraisalHooks.HasAppraisalData(objectId); + AutoIdEligibility.CreateDecision decision; + lock (_gate) + decision = _eligibility.OnCreate(objectId, Environment.TickCount64, cached); - _queue.Enqueue(objectId); + if (decision == AutoIdEligibility.CreateDecision.Appraise) + _queue.Enqueue(objectId); } /// - /// Remove an object from the sent set (e.g. when it's destroyed and may be recreated). + /// The CLIENT released an object (ACCObjectMaint::DeleteObject, or the Decal bridge's + /// delete event). A queued appraisal for it is skipped; its last appraisal time is kept, + /// so a re-create inside the window is not appraised again. /// - public static void Evict(uint objectId) + public static void OnClientRelease(uint objectId) { - _sent.TryRemove(objectId, out _); + if (objectId == 0) return; + lock (_gate) + _eligibility.OnClientRelease(objectId); + } + + /// + /// The SERVER deleted an object (0xF747 ObjectDelete, from the server message stream on + /// the plugin pump). Whatever is created under that id next is appraised. + /// + public static void OnServerDelete(uint objectId) + { + if (objectId == 0) return; + lock (_gate) + _eligibility.OnServerDelete(objectId); + // It really went away: its kept identify data goes too. + AppraisalHooks.EvictObject(objectId); + } + + /// + /// The 0xC8 for really went out (AcMainThreadQueue's drain, on + /// AC's main thread, for every RequestId caller). Starts its re-appraisal window. + /// + public static void OnSent(uint objectId, long nowMs) + { + if (objectId == 0) return; + lock (_gate) + _eligibility.OnSent(objectId, nowMs); } // Last target we issued a priority appraisal for (fires once per target change). private static uint _lastPriorityTarget; + private static long _lastPruneMs; private static void DrainTick(object? state) { @@ -92,20 +150,35 @@ internal static class AutoIdService { if (!CombatActionHooks.HasRequestId) return; + // Dead / portaling / settling: AcMainThreadQueue refuses appraisals now, so the + // backlog waits here instead of being dequeued into a refusal and lost. + if (PlayerLifecycleLog.InWorldTransition) + return; + long now = Environment.TickCount64; int sent = 0; // Combat-target priority: when the selected target CHANGES, appraise it // immediately — enqueued ahead of the create-order backlog so a fast kill // still gets its max-HP appraisal out first instead of waiting behind the // whole spawn. Fires once per change (guarded), so no per-tick re-appraisal. + // Skipped when the target's appraisal is already cached and fresh: selecting + // something identified a minute ago asked the server again for nothing. uint target = SelectedTargetHooks.ReadCurrentSelectedId(); if (target != 0 && target != _lastPriorityTarget) { _lastPriorityTarget = target; uint playerId = ClientHelperHooks.GetPlayerId(); - if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target)) - sent++; + if (target != playerId) + { + bool fresh = AutoIdEligibility.IsAppraisalFresh( + AppraisalHooks.HasAppraisalData(target), AppraisalHooks.GetLastIdTime(target), + DateTimeOffset.UtcNow.ToUnixTimeSeconds(), ReappraiseWindowMs); + if (fresh) + Interlocked.Increment(ref _skippedPriorityFresh); + else if (AcMainThreadQueue.EnqueueRequestId(target)) + sent++; + } } while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId)) @@ -113,20 +186,41 @@ internal static class AutoIdService // Object may have been destroyed between enqueue and drain if (objectId == 0) continue; - // Deleted since it was queued: Evict took it out of _sent. Skip it without - // spending one of the 3 requests per tick. After a big landblock change (the - // 585 deletes of 2026-10-02) the queue otherwise kept asking the server to - // appraise gone objects at 30 a second for half a minute, and live ones waited. - // A delete-then-recreate is queued again by Enqueue, so nothing live is lost. - if (!_sent.ContainsKey(objectId)) + // Released since it was queued: skip it without spending one of the 3 + // requests per tick. After a big landblock change (the 585 deletes of + // one jump) the queue otherwise kept asking the server to appraise gone + // objects at 30 a second for half a minute, and live ones waited. A + // release-then-recreate is decided again by Enqueue, so nothing live is lost. + bool live; + lock (_gate) live = _eligibility.IsLive(objectId); + if (!live) continue; // Marshal onto AC's main thread (EndScene drain) — the Timer thread must // not call the native 0xC8 send directly (off-thread heap alloc + non-atomic - // UI-counter increment). EnqueueRequestId is the marshalled path. + // UI-counter increment). EnqueueRequestId is the marshalled path. The + // appraisal counts as sent only when the main thread sends it (OnSent, from + // AcMainThreadQueue.DrainRequestIds): a queued request that is dropped there + // leaves the object due again. AcMainThreadQueue.EnqueueRequestId(objectId); sent++; } + + // Keep the bookkeeping bounded. Here, off AC's main thread: the create path + // never prunes. + if (now - _lastPruneMs >= 10_000) + { + _lastPruneMs = now; + int removed; + lock (_gate) + removed = _eligibility.Count > _eligibility.MaxTracked / 2 ? _eligibility.Prune(now) : 0; + if (removed > 0) + RynthLog.Verbose($"Compat: AutoIdService pruned {removed} appraisal record(s)."); + // Identify data kept after a client release: dropped once its time is up. + int expired = AppraisalHooks.ExpireReleased(now); + if (expired > 0) + RynthLog.Verbose($"Compat: AppraisalHooks dropped {expired} released object(s) past the retention time."); + } } catch { } } diff --git a/src/RynthCore.Engine/Compatibility/CastSlot.cs b/src/RynthCore.Engine/Compatibility/CastSlot.cs new file mode 100644 index 0000000..1172107 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CastSlot.cs @@ -0,0 +1,59 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CastSlot.cs +// +// AcMainThreadQueue's single-outstanding cast slot (SelectItem + CastSpell pair): one +// pending cast at a time, taken by DrainCasts on AC's game-logic tick. +// +// A cast is refused outright during a world transition (dead, in portal space, or the +// settle window after a teleport): the drain would only hold it and then drop it, and +// meanwhile the slot would refuse every newer cast. The caller (BuffManager / +// CombatManager) already treats false as "retry next tick". Refused like the action ring +// refuses non-teardown work during a transition (ActionRing.Admit.RejectedTransition). +// +// Pure: no engine state, no locking (AcMainThreadQueue holds _castLock for every write; +// DrainCasts reads Pending and QueuedAt with Volatile, hence public fields). Compiled +// into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class CastSlot +{ + public enum Admit + { + Queued, + /// A cast is already pending; nothing changed. + Busy, + /// A world transition is in progress; nothing changed. + RejectedTransition, + } + + public int Pending; + public uint TargetId; + public uint SpellId; + /// TickCount64 when the pending cast was queued. + public long QueuedAt; + /// + /// The drain has counted this cast's wait for a movement stop queued before it (once per + /// cast). Reset by every queued cast; set by DrainCasts on the main thread. + /// + public bool StopWaitNoted; + + /// Under the caller's lock. The slot is written only when this returns Queued. + public Admit TryEnqueue(uint targetId, uint spellId, long nowMs, bool inTransition) + { + if (inTransition) return Admit.RejectedTransition; + if (Pending != 0) return Admit.Busy; + TargetId = targetId; + SpellId = spellId; + // Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can + // tear on x86. The time and the stop-wait reset first, then the flag that publishes + // them (a release store, so the drain's Volatile.Read of Pending sees both). + Volatile.Write(ref QueuedAt, nowMs); + StopWaitNoted = false; + Volatile.Write(ref Pending, 1); + return Admit.Queued; + } +} diff --git a/src/RynthCore.Engine/Compatibility/CastStopRules.cs b/src/RynthCore.Engine/Compatibility/CastStopRules.cs new file mode 100644 index 0000000..f021b59 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CastStopRules.cs @@ -0,0 +1,38 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CastStopRules.cs +// +// The cast drain's question about the action ring: is a movement stop queued at or +// before the pending cast? (AcMainThreadQueue.StopQueuedAtOrBefore: such a stop runs +// first, so the cast's own stop is not sent while AC's locomotion is still on.) +// +// Every queued entry is checked. An entry's time is taken before ActionRing's producer +// lock, so two producers can land slightly out of time order, and a walk that stopped +// at the first entry newer than the cast could miss an older stop queued behind it. +// +// Pure: no engine state. Consumer side of the ring only (AC's main thread). Compiled +// into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class CastStopRules +{ + /// + /// True when any entry in was queued at or before + /// (by ) and is a movement stop + /// (by ). Pass static lambdas: nothing is allocated per call. + /// + public static bool AnyStopAtOrBefore(ActionRing ring, long castQueuedAt, + Func queuedAt, Func isStop) where T : struct + { + int count = ring.Count; + for (int i = 0; i < count; i++) + { + if (!ring.TryPeekAt(i, out T e)) break; + if (queuedAt(e) <= castQueuedAt && isStop(e)) return true; + } + return false; + } +} diff --git a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs index a26f98e..a3b5166 100644 --- a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs @@ -177,7 +177,7 @@ internal static class ClientCombatHooks // MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal // as ONE queue entry (not split into four) so the sequence stays atomic // relative to the drain loop's other actions. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power); try diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index b706fb1..2d5bc81 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -371,7 +371,7 @@ internal static class ClientHelperHooks // (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes // this on the main thread, where the gate is satisfied and it runs directly. // SelectItem() funnels through here, so this one gate covers both. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSetSelectedObject(objectId); if (_setSelectedObject == null) @@ -400,7 +400,7 @@ internal static class ClientHelperHooks /// public static bool SelectFromOverlay(uint objectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueOverlaySelect(objectId); if (objectId == 0 || _setSelectedObject == null) @@ -433,7 +433,7 @@ internal static class ClientHelperHooks // main thread (via the OnEndScene drain), not off the pump thread. Off-thread // UseObject mutated AC's animation sequence (CSequence) and corrupted it -> // the CSequence::update_internal AV captured after looting was enabled. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseObject(objectId); if (_useObject == null || !IsValidObjectId(objectId)) @@ -466,7 +466,7 @@ internal static class ClientHelperHooks // Marshal onto AC's main thread (off-thread use-on-target mutates AC's // object/animation graph and corrupts it — see UseObject). Drain re-invokes // this on the main thread, where the gate is satisfied and it runs directly. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId); if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId)) @@ -492,7 +492,7 @@ internal static class ClientHelperHooks public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId); if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId)) @@ -517,7 +517,7 @@ internal static class ClientHelperHooks { // Marshal onto AC's main thread — off-thread item moves race AC's per-tick // object/container bookkeeping (the looting null-deref AV class). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount); if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0) @@ -547,7 +547,7 @@ internal static class ClientHelperHooks public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount); if (_moveItemInternal == null) return false; @@ -604,7 +604,7 @@ internal static class ClientHelperHooks /// public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount); if (_moveItemInternal == null) return false; @@ -656,7 +656,7 @@ internal static class ClientHelperHooks /// public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId); if (_eventStackableMerge == null) return false; @@ -714,7 +714,7 @@ internal static class ClientHelperHooks /// public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot); if (_eventPutItemInContainer == null) return false; @@ -749,7 +749,7 @@ internal static class ClientHelperHooks // Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's // per-tick object/container bookkeeping (the looting null-deref AV class), // exactly like MoveItemExternal / MergeStackInternal. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount); if (_eventGiveObjectRequest == null) return false; @@ -795,7 +795,7 @@ internal static class ClientHelperHooks public static bool WieldItem(uint objectId, uint equipMask) { // Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0 && AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask); @@ -825,7 +825,7 @@ internal static class ClientHelperHooks public static bool DropItem(uint objectId) { // Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventDropItem != null && IsValidObjectId(objectId) && AcMainThreadQueue.EnqueueDropItem(objectId); @@ -859,7 +859,7 @@ internal static class ClientHelperHooks public static bool CloseContainer(uint containerId) { // An inventory game-action send, like DropItem / WieldItem: main thread only. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return _eventNoLongerViewingContents != null && IsValidObjectId(containerId) && AcMainThreadQueue.EnqueueCloseContainer(containerId); @@ -1151,7 +1151,7 @@ internal static class ClientHelperHooks // same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with // one consumer, so open -> add -> execute keep their order. Drain calls // back into this method on the main thread, where the gate is satisfied. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageOpen(toolId); try @@ -1193,7 +1193,7 @@ internal static class ClientHelperHooks // queued entry carries only the item id: on the main thread this method // runs again and re-reads the instance, since the panel may have closed // or been rebuilt in between. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageAddItem(itemId); try @@ -1228,7 +1228,7 @@ internal static class ClientHelperHooks // Off-thread: same shape as SalvagePanelAddItem (instance re-read on the // main thread when the entry drains). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageExecute(); try diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index 7755d56..4ec9061 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -332,7 +332,7 @@ internal static class CombatActionHooks public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel); if (_meleeAttack == null) @@ -350,7 +350,7 @@ internal static class CombatActionHooks public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel); if (_missileAttack == null) @@ -373,7 +373,7 @@ internal static class CombatActionHooks // (CSequence) state on the thread that updates it — eliminating the // off-thread-mutation corruption class (e.g. the CSequence::update_internal // AV). On the main thread (incl. the drain) this executes directly. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode); // Prefer the CLIENT-level entry point. _changeCombatMode is bound by @@ -412,7 +412,7 @@ internal static class CombatActionHooks // same gate. Queued in the action ring so it keeps FIFO order after an attack // that is already queued (it used to run at once and could overtake it). The // drain re-enters here on the main thread, where the gate passes. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueCancelAttack(); try @@ -435,7 +435,7 @@ internal static class CombatActionHooks // so off-thread calls go to the non-gesture QueryHealth queue and the drain // re-enters here on the main thread. Callers ignore the result and read the // async 0x01C0 reply, so "queued" is enough. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId); try @@ -461,7 +461,7 @@ internal static class CombatActionHooks // here on the main thread, where this gate passes and the packet is sent. // Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps // the bool's meaning ("requested"). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueRequestId(objectId); try @@ -504,24 +504,23 @@ internal static class CombatActionHooks // which the drain-before order is intended to fix. On the main thread (the // UseTime drain, or any main-thread caller) this falls through to the direct // cast below. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId); - // Call ClientMagicSystem::CastSpell directly off the plugin pump thread. - // This is the proven-working casting path (buffs + combat resolve in - // chat). The earlier EndScene-marshalled variant (AcMainThreadQueue, - // drained from OnEndScene) was REVERTED 2026-05-19: EndScene fires AC's - // IncrementBusyCount but is not the context that drives the cast state - // machine to completion, so combat casts never produced a projectile / - // damage / "You cast" chat — busy leaked, AC's single cast slot jammed - // "Casting " client-wide, and even manual casting died. Do NOT - // re-introduce queue/EndScene marshalling for casts. - // The documented object-teardown AV (0x0055FA24 [null+0x40] / - // 0x00416C86 [null+0x28]) is contained per-callsite by the SEH - // trampoline below (__try/__except in RynthCore.SehTrampoline.dll), - // which is the correct fix for that AV. AC's CastSpell reads its - // "currently selected target" when targetIsSelected=1; SelectItem - // first so AC's selection matches the caller's intent. + // From here on we are ON AC's main thread: the Client::UseTime cast drain + // (AcMainThreadQueue.DrainCasts, before AC's tick) or another main-thread caller. + // Nothing below runs on the plugin pump. What was REVERTED earlier is the + // EndScene drain for casts: EndScene is not the context that drives the cast state + // machine to completion (busy leaked, AC's single cast slot jammed client-wide); + // EngineFrameController's EndScene drain still never runs casts. + // Two native paths, each through the SEH trampoline (__try/__except in + // RynthCore.SehTrampoline.dll), which contains the object-teardown AV + // (0x0055FA24 [null+0x40] / 0x00416C86 [null+0x28]) per call: + // targeted (targetId != 0): GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spell, + // target), the target passed explicitly, NO SelectItem; + // self (targetId == 0): ClientMagicSystem::CastSpell(spell, targetIsSelected=0). + // While the player is dead, portaling or settling after a landblock jump the drain + // holds the cast and drops it once the transition ends (WorldTransitionState). if (_castSpellClient != null) { try diff --git a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs index 80aa85e..036d104 100644 --- a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs @@ -163,7 +163,7 @@ internal static class CommandInterpreterHooks // motion graph the CSequence-AV corruption class kills. Off-thread // callers marshal through the action ring (drained post-tick, // gesture-gated) like every other mutator. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: !enabled)) return AcMainThreadQueue.EnqueueSetAutoRun(enabled); int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls); if (!TryBindDelegates()) @@ -269,7 +269,7 @@ internal static class CommandInterpreterHooks public static bool SetMotion(uint motion, bool enabled) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: !enabled)) return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun if (!TryBindDelegates() || _setMotion == null) return false; @@ -287,7 +287,7 @@ internal static class CommandInterpreterHooks public static bool StopCompletely() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun if (!TryBindDelegates() || _stopCompletely == null) return false; @@ -305,7 +305,7 @@ internal static class CommandInterpreterHooks public static bool TurnToHeading(float headingDegrees) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls); if (!TryBindDelegates() || _turnToHeading == null) @@ -398,7 +398,7 @@ internal static class CommandInterpreterHooks public static bool TapJump() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTapJump(); if (!TryBindDelegates()) return false; @@ -419,7 +419,7 @@ internal static class CommandInterpreterHooks public static bool CommenceJump() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueCommenceJump(); if (!TryBindDelegates()) return false; @@ -437,7 +437,7 @@ internal static class CommandInterpreterHooks public static bool DoJump(bool autonomous) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous); if (!TryBindDelegates()) return false; diff --git a/src/RynthCore.Engine/Compatibility/CrashExitRule.cs b/src/RynthCore.Engine/Compatibility/CrashExitRule.cs new file mode 100644 index 0000000..d4d724f --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CrashExitRule.cs @@ -0,0 +1,24 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CrashExitRule.cs +// +// Is a process exit code a CRASH exit? ProcessExitHooks passes a crash exit straight to +// the original (no managed work on a dying process) after flushing the native crash +// logger's recent first-chance records. +// +// A crash exit is an error-severity status or exception code (both top bits set, +// 0xC0000000 and up): 0xC0000005 an access violation, 0xC0000409 a stack buffer overrun, +// 0xC0000374 heap corruption, and the software exception codes a runtime exits with on an +// unhandled exception, 0xE0434352 (CLR) and 0xE06D7363 (C++). +// EXCEPT 0xFFFFFFFF: ExitProcess(-1) is an ordinary "exit with failure", not a fault. The +// old rule (code >= 0xC0000000) took it for a crash and skipped the orderly shutdown +// of the process. +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +namespace RynthCore.Engine.Compatibility; + +internal static class CrashExitRule +{ + public static bool IsCrashExit(uint code) => (code & 0xC0000000u) == 0xC0000000u && code != 0xFFFFFFFFu; +} diff --git a/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs index edef128..a2ddd4d 100644 --- a/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs +++ b/src/RynthCore.Engine/Compatibility/DecalBridgeHost.cs @@ -426,7 +426,7 @@ internal static unsafe class DecalBridgeHost case BridgeRecordKind.ReleaseObject: PaletteCache.Remove(arg0); PluginManager.QueueDeleteObject(arg0); - AutoIdService.Evict(arg0); + AutoIdService.OnClientRelease(arg0); break; case BridgeRecordKind.ChangeObject: diff --git a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs index 3f8df11..7d078df 100644 --- a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs @@ -72,7 +72,7 @@ internal static class DeleteObjectHooks { PaletteCache.Remove(objectId); PluginManager.QueueDeleteObject(objectId); - AutoIdService.Evict(objectId); + AutoIdService.OnClientRelease(objectId); } return _originalDeleteObject!(thisPtr, objectId); diff --git a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs index 6befe71..49fe936 100644 --- a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs +++ b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs @@ -104,6 +104,15 @@ internal static class EngineStatusMetrics w.WriteNumber("queueDropped", queueDropped); w.WriteNumber("reconciles", reconciles); w.WriteNumber("forceClears", forceClears); + // AC's main thread frozen (message box or stale beat) and plugin ticks paused for it + // (MainThreadFreeze). pluginTicksPausedMs is a running total: a plugin's stall + // detector subtracts its change over the window it measured. + bool frozen = false; long stallMs = 0, pausedMs = 0; + try { frozen = MainThreadFreeze.Paused; stallMs = MainThreadFreeze.MainThreadStallMs; pausedMs = MainThreadFreeze.PausedTotalMs; } + catch { } + w.WriteBoolean("mainThreadFrozen", frozen); + w.WriteNumber("mainThreadStallMs", stallMs); + w.WriteNumber("pluginTicksPausedMs", pausedMs); // Player stats, read on the main thread by PrefetchPlayerStats and served here off-thread // (the plugin pump can't read these live). deaths all-time; rates/session = whole-session. diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index c3c78f9..023b98d 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -111,15 +111,6 @@ internal static class GameTickHooks // Diag (diag/logoff-origin): 1 Hz sample of the client's own input-idle clock. try { LogoffOriginProbe.SampleIdleOnGameThread(); } catch { } - // Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's - // selection and the cast initiates, then THIS SAME UseTime call processes it to - // completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the - // tick landed self-buffs but not targeted casts: the selection set at the end of - // tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is - // pending. Must never throw into AC's native frame. - try { AcMainThreadQueue.DrainCasts(); } - catch { } - // Refresh TeleportStateHooks' main-thread cache every real game tick. This // detour (unlike EndScene) fires on AC's true main thread in EVERY mode // including Decal-coexistence (no D3D9 hook there) — without this, @@ -130,10 +121,21 @@ internal static class GameTickHooks try { portaling = TeleportStateHooks.IsPortaling; } catch { } // Death / portal space / teleport lines, for lining crashes up with what - // the character was doing (PlayerLifecycleLog). + // the character was doing (PlayerLifecycleLog). Also the world-transition state the + // AcMainThreadQueue drains gate on: sampled BEFORE the cast drain below, so a cast queued + // as the player dies is held in this same tick, not run into the death. try { PlayerLifecycleLog.SampleOnGameThread(portaling); } catch { } + // Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's + // selection and the cast initiates, then THIS SAME UseTime call processes it to + // completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the + // tick landed self-buffs but not targeted casts: the selection set at the end of + // tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is + // pending. Must never throw into AC's native frame. + try { AcMainThreadQueue.DrainCasts(); } + catch { } + // Run AC's own game-logic + physics + animation pass. int result; try { result = _originalUseTime!(thisPtr); } @@ -185,6 +187,18 @@ internal static class GameTickHooks // site) is already post-physics in the frame, so it was never the // trigger. (Casts stay PRE-tick above — their selection-timing // requirement, and they go through the separate cast slot.) + // Re-sample the world-transition state first: a death, a portal entry or a + // landblock jump can begin INSIDE AC's tick above, and the pre-tick sample would + // let this drain run queued work into it. Edges are logged once whichever sample + // sees them. + try + { + bool portalingAfter = false; + try { portalingAfter = TeleportStateHooks.IsPortaling; } + catch { } + PlayerLifecycleLog.SampleOnGameThread(portalingAfter); + } + catch { } try { AcMainThreadQueue.Drain(); } catch { } // Main-thread snapshots the pump reads instead of AC memory (player id, diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 73027f6..eaf9660 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -135,6 +135,11 @@ internal static class HeartbeatLogger // flooding the ring; flat = fine. long dropped = 0; try { dropped = AcMainThreadQueue.DroppedCount; } catch { } + // qrej = marshalled actions and casts refused during a world transition + // (dead / portal / settle window), a running total kept apart from qdrop: a + // jump in qrej around a teleport is the gate working, not a flood. + long rejected = 0; + try { rejected = AcMainThreadQueue.TransitionRejectedCount; } catch { } // rec = busy reconciles (cast/item-action), fcl = force-clears. // Soak health: rec climbs during combat/loot; fcl stays flat. long rec = 0, fcl = 0; @@ -155,8 +160,28 @@ internal static class HeartbeatLogger catch { } // vafree = free address space (MB): reloads leak engine/plugin copies, // so a client that dies mid-reload can be checked for running out. + // valargest = the largest free block (MB): a 32-bit client fails an + // allocation on fragmentation long before vafree reaches 0. string vaField = ""; - try { long free = AddressSpaceMb().FreeMb; if (free >= 0) vaField = $" vafree={free}MB"; } + try + { + long free = AddressSpaceMb().FreeMb; + if (free >= 0) vaField = $" vafree={free}MB"; + long largest = AddressSpace.FreeAndLargestMb().LargestFreeMb; + if (largest >= 0) vaField += $" valargest={largest}MB"; + } + catch { } + // Crash logger module cache (native): rebuilt every 10 s here, so a fault + // never has to call the loader to name a module. + if (tick % 10 == 1) + { + try { SehTrampoline.RefreshCrashLoggerModules(); } catch { } + } + // Safety net for the main-thread message box count (MainThreadFreeze). + MessageBoxHooks.ReconcileStaleMainThreadCount(); + // pump=paused = plugin ticks paused because AC's main thread is frozen + // (MainThreadFreeze); omitted while running. + try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; } catch { } // req=/s = the client is waiting on an item request (it refuses // every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both @@ -168,7 +193,7 @@ internal static class HeartbeatLogger string vpField = ""; try { vpField = D3D9.VideoPatch.OnHeartbeat(draw); } catch { } - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); + RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} qrej={rejected} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}{vpField}"); // Every 60 s: garbage collections and the time they paused the process. // Under the CoreCLR host the engine and managed plugins share one GC, so a diff --git a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs index 75464d9..fab95f8 100644 --- a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs +++ b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs @@ -105,17 +105,27 @@ internal static class MainThreadSnapshots try { EnchantmentHooks.PrefetchWatchedObjectEnchantments(); } catch { } // Inventory panel: sends the one requested item action, watches it, and // captures the packs (throttled; returns at once while the panel is closed - // and nothing is in flight). Only while the player object is live. - try { InventoryModel.MainThreadTick(); } catch { } + // and nothing is in flight). Only while the player object is live, and held + // through a world transition (dead / portal / landblock jump): it SENDS item + // actions, and those wait like the AcMainThreadQueue's (WorldTransitionState). + if (!PlayerLifecycleLog.InWorldTransition) + { + try { InventoryModel.MainThreadTick(); } catch { } + } // Skills panel: ranks, XP spent and buffs (500 ms, only while the panel is open). // After the enchantment snapshot so its buffs are this tick's. try { PlayerProgressHooks.Prefetch(); } catch { } } - // Aelrynth skill mastery: the /mastery-data request after login, on panel open - // and after a raise (only on Aelrynth; a few compares when nothing is wanted). - try { MasteryFeed.MainThreadTick(playerLive); } catch { } - // Aelrynth account vault (the Inventory panel's Vault view): reads on request only. - try { VaultFeed.MainThreadTick(playerLive); } catch { } + // Both send server commands (a mastery raise, a vault withdraw), so like the + // Inventory panel they wait out a world transition; their requests stay pending. + if (!PlayerLifecycleLog.InWorldTransition) + { + // Aelrynth skill mastery: the /mastery-data request after login, on panel open + // and after a raise (only on Aelrynth; a few compares when nothing is wanted). + try { MasteryFeed.MainThreadTick(playerLive); } catch { } + // Aelrynth account vault (the Inventory panel's Vault view): reads on request only. + try { VaultFeed.MainThreadTick(playerLive); } catch { } + } } } diff --git a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs index cf264b6..5570429 100644 --- a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs @@ -52,6 +52,13 @@ internal static class MessageBoxHooks private static volatile string? _openDescription; private static long _openedAtTicks; private static int _openCount; + // Boxes open on AC's MAIN thread: the main thread is inside a modal loop, so the plugin + // pump's freeze gate (MainThreadFreeze) pauses plugin ticks at once. + private static int _mainThreadOpenCount; + + /// Message boxes open right now on AC's main thread. Any thread. + public static int MainThreadOpenCount => Volatile.Read(ref _mainThreadOpenCount); + public static void Initialize() { @@ -114,34 +121,58 @@ internal static class MessageBoxHooks { MessageBoxDelegate? original = wide ? _originalW : _originalA; string? description = null; + bool counted = false; long opened = Environment.TickCount64; + int result = 0; try { - description = Opened(text, caption, type, wide); - } - catch { /* observation only: never block the dialog */ } - - int result = original != null ? original(hWnd, text, caption, type) : 0; - - try - { - long secs = (Environment.TickCount64 - opened) / 1000; - RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); - if (Interlocked.Decrement(ref _openCount) <= 0) + try { - Interlocked.Exchange(ref _openCount, 0); - _openDescription = null; + // Counted first: the freeze gate must see the box even if the rest throws. + bool mainThread = MainThreadGuard.IsOnMainThread(); + if (mainThread) + { + Interlocked.Increment(ref _mainThreadOpenCount); + counted = true; + } + string body = Read(text, wide); + // AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never + // writes a dump, and the launcher later kills the client as wedged. Decide and + // write ONE full-memory dump now, before anything here allocates more (the stack + // walk and the description below), and before the box shows (this thread waits: + // the box would hold it anyway, and the user's OK must not let AC run on and + // exit mid-dump). + if (OutOfMemoryBoxRule.IsOutOfMemoryBox(body, mainThread)) + CrashDump.WriteOutOfMemoryDumpOnce(Flatten(body)); + description = Opened(body, caption, type, wide, mainThread); } + catch { /* observation only: never block the dialog */ } + + result = original != null ? original(hWnd, text, caption, type) : 0; + } + finally + { + // First, and whatever happened above: a leaked count would pause plugin ticks for good. + if (counted && Interlocked.Decrement(ref _mainThreadOpenCount) < 0) + Interlocked.Exchange(ref _mainThreadOpenCount, 0); + try + { + long secs = (Environment.TickCount64 - opened) / 1000; + if (Interlocked.Decrement(ref _openCount) <= 0) + { + Interlocked.Exchange(ref _openCount, 0); + _openDescription = null; + } + RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); + } + catch { } } - catch { } return result; } - private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide) + private static string Opened(string body, IntPtr caption, uint type, bool wide, bool mainThread) { - string body = Read(text, wide); string title = Read(caption, wide); - bool mainThread = MainThreadGuard.IsOnMainThread(); // The first frame outside user32 and this file: who asked for the dialog. string caller = "?"; @@ -165,6 +196,63 @@ internal static class MessageBoxHooks return description; } + // -- Stale main-thread count (safety net) ------------------------------------ + // The count is decremented in Show's finally, so it should never leak; if it ever reads + // non-zero while AC's main thread owns no dialog window for 30 s, it is reset (and + // logged), so a leak can never pause plugin ticks for good. Heartbeat thread, 1 Hz. + private const long StaleCountResetMs = 30_000; + private static long _countWithoutBoxSinceMs; + + private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern bool EnumThreadWindows(uint threadId, EnumThreadWndProc callback, IntPtr lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder name, int max); + + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr hWnd); + + private static bool MainThreadOwnsDialog() + { + uint tid = MainThreadGuard.MainThreadId; + if (tid == 0) return false; + bool found = false; + var name = new System.Text.StringBuilder(64); + EnumThreadWindows(tid, (h, _) => + { + name.Clear(); + if (GetClassNameW(h, name, name.Capacity) > 0 && name.ToString() == "#32770" && IsWindowVisible(h)) + { + found = true; + return false; + } + return true; + }, IntPtr.Zero); + return found; + } + + /// Heartbeat thread, about once a second. Never throws. + public static void ReconcileStaleMainThreadCount() + { + try + { + long now = Environment.TickCount64; + // The OOM dump runs before the box window exists: counted, no dialog yet, legitimately. + if (MainThreadOpenCount <= 0 || CrashDump.FullDumpInProgress || MainThreadOwnsDialog()) + { + _countWithoutBoxSinceMs = 0; + return; + } + if (_countWithoutBoxSinceMs == 0) { _countWithoutBoxSinceMs = now; return; } + if (now - _countWithoutBoxSinceMs < StaleCountResetMs) return; + int was = Interlocked.Exchange(ref _mainThreadOpenCount, 0); + _countWithoutBoxSinceMs = 0; + RynthLog.Warn($"MessageBoxHooks: main-thread box count was {was} with no dialog open on AC's main thread for {StaleCountResetMs / 1000}s - reset to 0."); + } + catch { } + } private static string Read(IntPtr p, bool wide) { if (p == IntPtr.Zero) return ""; diff --git a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs index 13617dd..00f404c 100644 --- a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs @@ -151,7 +151,7 @@ internal static class MovementActionHooks public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey); int n = System.Threading.Interlocked.Increment(ref _doMovementCalls); @@ -179,7 +179,7 @@ internal static class MovementActionHooks public static bool StopMovement(uint motion, int holdKey = HoldKeyRun) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey); int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls); @@ -207,7 +207,7 @@ internal static class MovementActionHooks public static bool JumpNonAutonomous(float extent) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueJump(extent); if (_jumpNonAutonomous == null) @@ -231,7 +231,7 @@ internal static class MovementActionHooks if (_autonomyLevel == null) return false; - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSetAutonomyLevel(level); try diff --git a/src/RynthCore.Engine/Compatibility/MutatorGate.cs b/src/RynthCore.Engine/Compatibility/MutatorGate.cs new file mode 100644 index 0000000..e69f443 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MutatorGate.cs @@ -0,0 +1,28 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MutatorGate.cs +// +// The decision behind AcMainThreadQueue.MustQueue, the one line every AC-mutating helper +// opens with: call AC now, or queue the call? +// - off AC's main thread: queue (AC is single-threaded); +// - on it, called BY a queue drain: call now (the drain already applied the gate); +// - on it, a stop or cancel (teardown): call now, even in a world transition; +// - on it otherwise: queue while a world transition holds the drains (render-thread host +// actions used to run straight into a world AC was tearing down), else call now. +// holding is asked last and only when it matters (it is main-thread state). +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class MutatorGate +{ + public static bool MustQueue(bool onMainThread, bool teardown, bool draining, Func holding) + { + if (!onMainThread) return true; + if (draining || teardown) return false; + return holding(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs new file mode 100644 index 0000000..63727b6 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs @@ -0,0 +1,112 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PendingIdQueue.cs +// +// The pending queue behind AcMainThreadQueue's RequestId (0xC8 appraisal) slot. +// A bounded FIFO of (object id, enqueue time, login epoch) that MERGES a request +// for an object already waiting, the way the QueryHealth slot does: one appraisal +// reply answers every caller that asked for it. Before this, AutoId's priority +// appraisal, its create backlog and the plugins' RequestIdFn each queued their own +// copy; one dump had 437 of 3211 identifies repeat an object within 125 ms. +// +// A pending entry only absorbs a new request while it is from the same login and +// young enough that the drain will still send it (MergeMaxAgeMs). An entry the drain +// would drop as stale, or one from an earlier login, takes no merges: the new +// request is queued on its own so it is not lost with the old one. +// +// Pure data structure: no engine state, no locking (the caller holds its lock), and +// no allocation after construction (a fixed ring). Compiled into +// tools\EngineRobustnessTests. +// ============================================================================ + +namespace RynthCore.Engine.Compatibility; + +internal sealed class PendingIdQueue +{ + public enum Result + { + /// Added as a new pending request. + Queued, + /// The object already had a pending request; nothing added. + Merged, + /// The queue is full; the request was not taken. + Full, + } + + public readonly struct Item + { + public readonly uint Id; + public readonly long At; + public readonly int Epoch; + + public Item(uint id, long at, int epoch) + { + Id = id; + At = at; + Epoch = epoch; + } + } + + private readonly Item[] _ring; + private int _head; // index of the oldest item + private int _count; + + public PendingIdQueue(int capacity) + { + if (capacity <= 0) throw new System.ArgumentOutOfRangeException(nameof(capacity)); + _ring = new Item[capacity]; + } + + public int Count => _count; + public int Capacity => _ring.Length; + + /// Requests absorbed by an already-pending entry since construction. + public long MergedTotal { get; private set; } + + /// + /// Queue a request for , or merge it into a pending one for the + /// same object from the same that is at most + /// old at and was queued AFTER + /// (the last moment a world transition held the + /// drains: an entry from before then is dropped when the drain reaches it, and a request + /// merged into it would be lost with it). + /// + public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0) + { + for (int i = 0; i < _count; i++) + { + ref readonly Item q = ref _ring[(_head + i) % _ring.Length]; + if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs + && (mergeOnlyAfterMs <= 0 || q.At > mergeOnlyAfterMs)) // 0 = no transition: no floor + { + MergedTotal++; + return Result.Merged; + } + } + if (_count >= _ring.Length) + return Result.Full; + _ring[(_head + _count) % _ring.Length] = new Item(id, nowMs, epoch); + _count++; + return Result.Queued; + } + + public bool TryDequeue(out Item item) + { + if (_count == 0) + { + item = default; + return false; + } + item = _ring[_head]; + _ring[_head] = default; + _head = (_head + 1) % _ring.Length; + _count--; + return true; + } + + public void Clear() + { + System.Array.Clear(_ring); + _head = 0; + _count = 0; + } +} diff --git a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs index a21bd1c..f997a5b 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs @@ -10,8 +10,14 @@ // teleport. With these lines a crash can be lined up with what the character // was doing. // +// Also the world-transition gate (WorldTransitionState): while the player is dead, +// portaling, or settling after either or after a landblock jump, AcMainThreadQueue +// holds every queued game-mutating call instead of running it into a world AC is +// tearing down (a client died right after a death recall's landblock jump). +// // Sampled from GameTickHooks.UseTimeDetour on AC's main thread, before AC's -// tick, so the reads see a consistent world. Alloc-free except on an edge. +// tick and before the cast drain, so the reads see a consistent world and the gate +// knows about a death in the same tick. Alloc-free except on an edge. // ============================================================================ using System; @@ -21,20 +27,46 @@ namespace RynthCore.Engine.Compatibility; internal static class PlayerLifecycleLog { - private static bool _init; + // Main thread only (the UseTime sample and both main-thread drains). + private static readonly WorldTransitionState _state = new(); + private static long _settleUntil; // published copy for other threads private static volatile bool _portaling, _dead; - private static long _transitionUntil; - private const long TransitionSettleMs = 5_000; + private static long _portalEnteredAt, _diedAt; /// - /// Dead, in portal space, or within 5 s after either: AC is tearing down and - /// loading the world, so nothing should poke at its state (BusyCountHooks' - /// force-clear). As of the last game tick; any thread. + /// Dead, in portal space, or within 5 s after either or after a landblock jump: AC is + /// tearing down and loading the world, so nothing should poke at its state + /// (BusyCountHooks' force-clear). As of the last game tick; any thread. /// public static bool InWorldTransition => - _dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _transitionUntil); - private static uint _landblock; - private static long _portalEnteredAt, _diedAt; + _dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil); + + /// + /// AC main thread only (the queue drains): true = hold everything queued now (see + /// WorldTransitionState for the rule). + /// + public static bool HoldQueuedWork(long nowMs) + { + bool hold = _state.CheckHolding(nowMs); + if (hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs); + return hold; + } + + /// AC main thread only: what a drain does with one queued item (WorldTransitionState.Decide). + public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown) + { + WorldTransitionState.Verdict v = _state.Decide(nowMs, queuedAtMs, teardown); + if (v == WorldTransitionState.Verdict.Hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs); + return v; + } + + private static long _lastBlockedPublished; + + /// + /// The last moment a drain was held by a world transition (0 = never), for other threads: + /// queued work from at or before it is dropped when the drains reach it. + /// + public static long LastBlockedMs => Interlocked.Read(ref _lastBlockedPublished); /// AC main thread, once per game tick. public static void SampleOnGameThread(bool portaling) @@ -52,51 +84,44 @@ internal static class PlayerLifecycleLog cell = c; uint landblock = cell >> 16; - if (!_init) - { - _init = true; - _portaling = portaling; - _dead = dead; - _landblock = landblock; - return; - } - long now = Environment.TickCount64; - if (dead || portaling || _dead || _portaling) - Interlocked.Exchange(ref _transitionUntil, now + TransitionSettleMs); - if (dead != _dead) - { - if (dead) - { - _diedAt = now; - RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8})."); - } - else - RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}."); - _dead = dead; - } + WorldTransitionState.Edge edges = _state.Sample(now, dead, portaling, landblock); + _dead = _state.Dead; + _portaling = _state.Portaling; + Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs); + if (edges == WorldTransitionState.Edge.None) + return; - if (portaling != _portaling) + if ((edges & WorldTransitionState.Edge.Died) != 0) { - if (portaling) - { - _portalEnteredAt = now; - string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : ""; - RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8})."); - } - else - RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}."); - _portaling = portaling; + _diedAt = now; + RynthLog.Info($"[Lifecycle] player DIED (health 0/{maxHealth}) in landblock 0x{landblock:X4} (cell 0x{cell:X8})."); } + if ((edges & WorldTransitionState.Edge.Revived) != 0) + RynthLog.Info($"[Lifecycle] player alive again (health {health}/{maxHealth}) {Ago(_diedAt, now)} after death, landblock 0x{landblock:X4}."); + if ((edges & WorldTransitionState.Edge.PortalEntered) != 0) + { + _portalEnteredAt = now; + string why = _diedAt != 0 && now - _diedAt < 30_000 ? " (death portal)" : ""; + RynthLog.Info($"[Lifecycle] portal space ENTERED{why} from landblock 0x{landblock:X4} (cell 0x{cell:X8})."); + } + if ((edges & WorldTransitionState.Edge.PortalExited) != 0) + RynthLog.Info($"[Lifecycle] portal space EXITED into landblock 0x{landblock:X4} (cell 0x{cell:X8}) after {Ago(_portalEnteredAt, now)}."); + if ((edges & WorldTransitionState.Edge.LandblockJump) != 0) + RynthLog.Info($"[Lifecycle] landblock jump 0x{_state.PreviousLandblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s."); + } - if (landblock != 0 && _landblock != 0 && landblock != _landblock) - { - int dx = (int)((landblock >> 8) & 0xFF) - (int)((_landblock >> 8) & 0xFF); - int dy = (int)(landblock & 0xFF) - (int)(_landblock & 0xFF); - if (Math.Abs(dx) > 1 || Math.Abs(dy) > 1) - RynthLog.Info($"[Lifecycle] landblock jump 0x{_landblock:X4} -> 0x{landblock:X4}{(portaling ? " (in portal space)" : "")}."); - } - if (landblock != 0) _landblock = landblock; + /// + /// AC main thread (SmartBoxHooks, after AC handled 0xF751 PlayerTeleport): a teleport starts + /// now. The settle window runs from here, published at once for the enqueue side. + /// + public static void OnTeleportMessage() + { + long now = Environment.TickCount64; + bool started = _state.OnTeleportMessage(now); + Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs); + if (started) + RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s."); } private static string Ago(long since, long now) => diff --git a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs index 8f60197..f502798 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs @@ -385,7 +385,7 @@ internal static class PlayerPhysicsHooks // Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain // calls back in here on the main thread (and falls back to the // CommandInterpreter turn there when there is no player, as before). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg); int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls); @@ -457,7 +457,7 @@ internal static class PlayerPhysicsHooks // raw write racing AC's own motion-graph tick is a guaranteed torn // write, not just an AV risk. Reachable off-thread via Jumper.cs's // ReleaseJump on the Decal-coexistence pump thread. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC); if (!TryGetCMotionInterp(out IntPtr cmi)) diff --git a/src/RynthCore.Engine/Compatibility/PlayerTrade.cs b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs index ac7f2e6..63966dc 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerTrade.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs @@ -141,7 +141,7 @@ internal static unsafe class PlayerTrade /// Ask to trade (0x01F6 OpenTradeNegotiations). public static bool Open(uint targetId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventOpenTradeNegotiations != null && targetId != 0 && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0); if (_eventOpenTradeNegotiations == null || targetId == 0) return false; @@ -153,7 +153,7 @@ internal static unsafe class PlayerTrade /// Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free. public static bool Add(uint itemId, uint slot) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventAddToTrade != null && itemId != 0 && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot); if (_eventAddToTrade == null || itemId == 0) return false; @@ -165,7 +165,7 @@ internal static unsafe class PlayerTrade /// Empty both sides of the window (0x0204 ResetTrade). public static bool Reset() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0); if (_eventResetTrade == null) return false; byte rv = _eventResetTrade(); @@ -176,7 +176,7 @@ internal static unsafe class PlayerTrade /// Close the trade (0x01F7 CloseTradeNegotiations). public static bool Close() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0); if (_eventCloseTradeNegotiations == null) return false; byte rv = _eventCloseTradeNegotiations(); @@ -187,7 +187,7 @@ internal static unsafe class PlayerTrade /// Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade). public static bool Accept() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0); if (_tradeSystemAcceptTrade == null) return false; IntPtr system = TradeSystemWithTrade(); @@ -200,7 +200,7 @@ internal static unsafe class PlayerTrade /// Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade). public static bool Decline() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0); if (_tradeSystemDeclineTrade == null) return false; IntPtr system = TradeSystemWithTrade(); diff --git a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs index bce841f..36c9705 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs @@ -121,7 +121,7 @@ internal static unsafe class PlayerTraining RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world"); return false; } - if (defer || !MainThreadGuard.IsOnMainThread()) + if (defer || AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp); byte rv = kind switch diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index a537b87..a8f95b1 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -47,28 +47,6 @@ internal static class ProcessExitHooks [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint NtTerminateProcessDelegate(IntPtr processHandle, uint exitStatus); - // kernel32!RaiseFailFastException — what __fastfail() / abort() / FailFast - // route through. Doesn't take an exit code; takes EXCEPTION_RECORD + CONTEXT. - // We don't need the params, just the call-site capture. - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate void RaiseFailFastExceptionDelegate(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags); - - // ntdll!RtlFailFast(NTSTATUS) — internally executes `int 0x29` (the - // __fastfail intrinsic). The kernel handles 0x29 directly and terminates - // the process WITHOUT re-entering user mode through ExitProcess / - // TerminateProcess / RaiseFailFastException. Hooking RtlFailFast itself - // is the only way to capture this path before the kernel takes over. - // Used by: stack-cookie failures (/GS), heap corruption checks, CRT - // abort paths on newer toolchains, NTDLL's own internal asserts. - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate void RtlFailFastDelegate(uint code); - - // ntdll!RtlFailFast2(NTSTATUS, EXCEPTION_RECORD*) — newer variant that - // also passes an exception record. Same semantics: the kernel terminates - // the process via int 0x29 without revisiting user mode. - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - private delegate void RtlFailFast2Delegate(uint code, IntPtr pExceptionRecord); - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr GetModuleHandleW(string? lpModuleName); @@ -103,43 +81,9 @@ internal static class ProcessExitHooks private static RtlExitUserProcessDelegate? _rtlExitOriginal; private static NtTerminateProcessDelegate? _ntTermDetour; private static NtTerminateProcessDelegate? _ntTermOriginal; - private static RaiseFailFastExceptionDelegate? _failFastDetour; - private static RaiseFailFastExceptionDelegate? _failFastOriginal; - private static RtlFailFastDelegate? _rtlFailFastDetour; - private static RtlFailFastDelegate? _rtlFailFastOriginal; - private static RtlFailFast2Delegate? _rtlFailFast2Detour; - private static RtlFailFast2Delegate? _rtlFailFast2Original; - private static int _installed; private static int _logged; // ensure we log at most once even if both fire - // Re-entrancy latch for the fail-fast family (RaiseFailFastException, - // RtlFailFast, RtlFailFast2). In the NativeAOT-inside-acclient environment - // a fail-fast does NOT terminate the way it does in a normal process: the - // runtime/AC exception machinery swallows or continues the fail-fast - // exception, so kernel32!RaiseFailFastException RETURNS instead of killing - // the process. Its caller then re-invokes it, hitting our MinHook again → - // detour re-enters → calls the original again → ~190K-deep recursion that - // exhausts the 8 MB stack and AVs in ntdll (the recursing code is this - // exit logger itself, so nothing downstream can ever log it). Latch is - // process-wide and never reset — a fail-fast is terminal by contract; - // there is no "recovery", we only need to die cleanly and once. - private static int _inFailFast; - - /// - /// Terminate without any possibility of re-entering a ProcessExitHooks - /// detour. Each call target is a MinHook *trampoline* (relocated original - /// prologue + jump PAST our hook), so none of them route back through our - /// detours. Used to break the fail-fast bounce. - /// - private static void HardTerminateNoReentry(uint code) - { - try { _ntTermOriginal?.Invoke(new IntPtr(-1), code); } catch { } - try { _rtlExitOriginal?.Invoke(code); } catch { } - try { _exitOriginal?.Invoke(code); } catch { } - try { Environment.Exit(unchecked((int)code)); } catch { } - } - public static void Initialize() { if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0) @@ -178,23 +122,13 @@ internal static class ProcessExitHooks RynthLog.Info($"ProcessExitHooks: hooked kernel32!TerminateProcess @ 0x{terminateTarget.ToInt32():X8}."); } - // ── DO NOT HOOK RaiseFailFastException (proven fatal 2026-05-16) ── - // Dump analysis of the every-few-minutes silent crash showed a - // 190K-deep stack overflow whose repeating frame pair is - // ...RaiseFailFastExceptionDelegate - // ↔ RhpReversePInvokeAttachOrTrapThread2. The NativeAOT reverse- - // P/Invoke transition that enters a managed detour for this export - // itself re-triggers RaiseFailFastException, so the detour recurses - // through the transition shim BEFORE any managed code (incl. any - // re-entrancy guard) can run. Unfixable from the managed side — the - // only correct action is to not hook it. A real fail-fast then - // terminates cleanly (as designed) instead of our hook converting - // it into the guaranteed stack-overflow crash. Same applies to - // ntdll!RtlFailFast / RtlFailFast2 below. The other exit hooks - // (ExitProcess/TerminateProcess/RtlExitUserProcess/NtTerminate) are - // safe — exiting the process does not re-enter those from within - // the transition, and they log clean interceptions. - + // DO NOT HOOK RaiseFailFastException, RtlFailFast or RtlFailFast2 (proven fatal + // in practice): the reverse-P/Invoke transition into a managed detour for those + // exports re-triggered the fail-fast itself (190K-deep recursion through the + // transition shim, before any managed guard could run). Their detour bodies were + // dead code and are gone, so nothing can switch them back on by + // accident: a managed body on the fail-fast path turns a crash that would leave + // a dump into a silent one. // ntdll-level hooks — catch paths that bypass kernel32 entirely. IntPtr ntdll = GetModuleHandleW("ntdll.dll"); if (ntdll != IntPtr.Zero) @@ -223,38 +157,6 @@ internal static class ProcessExitHooks RynthLog.Info($"ProcessExitHooks: hooked ntdll!NtTerminateProcess @ 0x{ntTermTarget.ToInt32():X8}."); } - // RtlFailFast / RtlFailFast2 — NOT HOOKED. Same NativeAOT - // reverse-P/Invoke re-entry recursion as RaiseFailFastException - // (see the block above). Hooking these with a managed detour - // is the every-few-minutes crash. Leave them alone; a genuine - // fail-fast terminates cleanly. (On this Windows build the - // GetProcAddress for these also failed historically anyway.) - if (false && ntdll != IntPtr.Zero) - { - HookExport(ntdll, "RtlFailFast", out IntPtr rtlFailFastTarget); - if (rtlFailFastTarget != IntPtr.Zero) - { - _rtlFailFastDetour = RtlFailFastDetour; - IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFastDetour); - IntPtr trampoline = MinHook.HookCreate(rtlFailFastTarget, detourPtr); - _rtlFailFastOriginal = Marshal.GetDelegateForFunctionPointer(trampoline); - Thread.MemoryBarrier(); - MinHook.Enable(rtlFailFastTarget); - RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast @ 0x{rtlFailFastTarget.ToInt32():X8}."); - } - - HookExport(ntdll, "RtlFailFast2", out IntPtr rtlFailFast2Target); - if (rtlFailFast2Target != IntPtr.Zero) - { - _rtlFailFast2Detour = RtlFailFast2Detour; - IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFast2Detour); - IntPtr trampoline = MinHook.HookCreate(rtlFailFast2Target, detourPtr); - _rtlFailFast2Original = Marshal.GetDelegateForFunctionPointer(trampoline); - Thread.MemoryBarrier(); - MinHook.Enable(rtlFailFast2Target); - RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast2 @ 0x{rtlFailFast2Target.ToInt32():X8}."); - } - } } } catch (Exception ex) @@ -272,6 +174,15 @@ internal static class ProcessExitHooks private static void ExitProcessDetour(uint exitCode) { + // A crash exit goes straight to the original, before any managed work (IsCrashExit). + // The reverse-P/Invoke transition into this detour is the only managed step left; a + // native pass-through would remove that too; it is possible but not done here. + if (IsCrashExit(exitCode)) + { + SehTrampoline.FlushCrashLog(exitCode); // native, allocation-free + _exitOriginal!(exitCode); + return; + } LogTermination("ExitProcess", IntPtr.Zero, exitCode); // Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this, // hooks stay installed, our threads (TickPump, Avalonia STA) keep @@ -283,44 +194,45 @@ internal static class ProcessExitHooks catch { /* original never returns; swallow if it somehow does */ } } + // A crash exit: an NTSTATUS error or exception code (0xC0000000 and up: 0xC0000005 an + // access violation, 0xE0434352 a CLR exception). The process is dying of a fault, often + // from inside the runtime's own fatal-error path; managed work here (logging, a + // MiniDumpWriteDump) can deadlock or fault again there and leave nothing at all. So a crash + // exit is passed straight to the original. The evidence comes from places that do not + // need managed code on the way out: the native crash logger (SehTrampoline.c, its vectored + // handler sees the fault first) and CoreCLR's own createdump (native\Loader\Loader.c, ConfigureCrashDumps). This + // replaces the managed crash dump written here before, which left nothing for real crashes. + // The one call made first, SehTrampoline.FlushCrashLog, is a raw native call: it writes + // the crash logger's recent first-chance records that were not written one by one (the + // fatal hit of an address seen before is usually among them; a terminate from a handler + // never reaches the last-chance filter). Which codes count: CrashExitRule. + private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code); + private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode) { - // Only log when terminating ourselves — TerminateProcess on other - // process handles is a normal Process.Kill and not what we're hunting. - // hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle. + // Only log when terminating ourselves: TerminateProcess on other process handles is a + // normal Process.Kill and not what we're hunting. hProcess == -1 is the pseudo-handle. bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle(); if (selfKill) { - LogTermination("TerminateProcess", hProcess, exitCode); - DumpCrashOnce("TerminateProcess", exitCode); + if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode); + else LogTermination("TerminateProcess", hProcess, exitCode); } try { return _terminateOriginal!(hProcess, exitCode); } catch { return false; } } - - // A crash exit (an NTSTATUS error code, 0xC0000000 and up: 0xC0000005 is an access - // violation) on the way out: write a minidump once, while the faulting frames are still on - // the stack. The runtime ends the process with TerminateProcess after a native AV under one - // of our detours, so no unhandled exception ever reaches a crash watcher (procdump -e saw - // nothing for Lucy's Town Network crashes, 10-01 19:46 and 10-02 15:55). - private static int _crashDumped; - private static void DumpCrashOnce(string via, uint code) - { - if (code < 0xC0000000u || System.Threading.Interlocked.Exchange(ref _crashDumped, 1) != 0) return; - try - { - if (CrashDump.WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash")) - RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})"); - } - catch { } - } - [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess(); private static void RtlExitUserProcessDetour(uint exitStatus) { + if (IsCrashExit(exitStatus)) // see ExitProcessDetour + { + SehTrampoline.FlushCrashLog(exitStatus); + _rtlExitOriginal!(exitStatus); + return; + } LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus); try { EngineLifecycle.Shutdown(); } catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); } @@ -333,57 +245,14 @@ internal static class ProcessExitHooks bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle(); if (selfKill) { - LogTermination("NtTerminateProcess", processHandle, exitStatus); - DumpCrashOnce("NtTerminateProcess", exitStatus); + // A second flush (TerminateProcess calls this) writes nothing: records are written once. + if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus); + else LogTermination("NtTerminateProcess", processHandle, exitStatus); } try { return _ntTermOriginal!(processHandle, exitStatus); } catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ } } - private static void RaiseFailFastExceptionDetour(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags) - { - if (Interlocked.Exchange(ref _inFailFast, 1) != 0) - { - // Re-entered: the original bounced back through our hook instead - // of terminating. Forwarding again is the 190K-deep stack-overflow - // recursion. Break it — die now, non-recursively. - HardTerminateNoReentry(dwFlags); - return; - } - LogTermination("RaiseFailFastException", IntPtr.Zero, dwFlags); - try { _failFastOriginal!(pExceptionRecord, pContext, dwFlags); } - catch { } - // A real fail-fast never returns. In this environment it can — don't - // let the caller spin re-raising it; terminate deterministically. - HardTerminateNoReentry(dwFlags); - } - - private static void RtlFailFastDetour(uint code) - { - if (Interlocked.Exchange(ref _inFailFast, 1) != 0) - { - HardTerminateNoReentry(code); - return; - } - LogTermination("RtlFailFast", IntPtr.Zero, code); - try { _rtlFailFastOriginal!(code); } - catch { /* original never returns */ } - HardTerminateNoReentry(code); - } - - private static void RtlFailFast2Detour(uint code, IntPtr pExceptionRecord) - { - if (Interlocked.Exchange(ref _inFailFast, 1) != 0) - { - HardTerminateNoReentry(code); - return; - } - LogTermination("RtlFailFast2", IntPtr.Zero, code); - try { _rtlFailFast2Original!(code, pExceptionRecord); } - catch { /* original never returns */ } - HardTerminateNoReentry(code); - } - /// ExitProcess/TerminateProcess was called: the process is closing. public static bool TerminationIntercepted => Volatile.Read(ref _logged) != 0; diff --git a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs index 2407ccc..51824cb 100644 --- a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs @@ -456,7 +456,9 @@ internal static class PropertyUpdateHooks if (objectId != 0) { EvictObject(objectId); - AppraisalHooks.EvictObject(objectId); + // A client release keeps the identify data a while (a server delete, + // 0xF747, evicts it): see ReleasedObjectRetention. + AppraisalHooks.OnClientRelease(objectId, Environment.TickCount64); } } } diff --git a/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs new file mode 100644 index 0000000..1ffb902 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs @@ -0,0 +1,77 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ReleasedObjectRetention.cs +// +// How long AppraisalHooks keeps an object's identify data after the CLIENT released it +// (AC's BeingDeleted, which fires for every object leaving the client's view). +// +// Before: the data was evicted on every client release, so when the +// object came back into view AutoId found nothing cached and appraised it again: the +// 10-minute re-appraisal window (AutoIdEligibility) almost never applied. Now the data is +// kept for RetainMs after a client release and dropped: +// - when RetainMs has passed (Expire, from AutoIdService's timer); +// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject); +// - at a session clear (logout), and under AppraisalHooks' object cap. +// A re-create (OnLive) makes the object current again. +// +// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock). +// Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class ReleasedObjectRetention +{ + public const long DefaultRetainMs = 10L * 60 * 1000; + public const int DefaultMaxReleased = 4096; + + private readonly Dictionary _releasedAt; + private readonly long _retainMs; + private readonly int _max; + + public ReleasedObjectRetention(long retainMs = DefaultRetainMs, int maxReleased = DefaultMaxReleased) + { + _retainMs = retainMs; + _max = maxReleased; + _releasedAt = new Dictionary(maxReleased + 1); + } + + public int Count => _releasedAt.Count; + public long RetainMs => _retainMs; + + /// + /// The client released (which has cached data). Returns true when the + /// data is kept for now; false when it must be dropped at once (the bound is reached and + /// nothing has expired to make room). + /// + public bool OnRelease(uint id, long nowMs) + { + if (_releasedAt.ContainsKey(id)) { _releasedAt[id] = nowMs; return true; } + if (_releasedAt.Count >= _max) return false; + _releasedAt[id] = nowMs == 0 ? 1 : nowMs; + return true; + } + + /// The object is current again (re-created), or its data was dropped for another reason. + public void Forget(uint id) => _releasedAt.Remove(id); + + public bool IsReleased(uint id) => _releasedAt.ContainsKey(id); + + /// Released ids whose data has outlived RetainMs: removed here and added to . + public int Expire(long nowMs, List expired) + { + int n = 0; + foreach (KeyValuePair kv in _releasedAt) + { + if (nowMs - kv.Value < _retainMs) continue; + expired.Add(kv.Key); + n++; + } + for (int i = expired.Count - n; i < expired.Count; i++) + _releasedAt.Remove(expired[i]); + return n; + } + + public void Clear() => _releasedAt.Clear(); +} diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index b731a79..879fa3d 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -28,6 +28,7 @@ using System; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -50,6 +51,66 @@ internal static class SehTrampoline { try { _InstallCrashLogger(logPath); } catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } + ResolveFlushCrashLog(); + } + + // RC_FlushCrashLog, resolved once here (0 = a DLL older than the export). Called through a + // raw unmanaged function pointer, so the crash path binds and compiles nothing: the call + // is primed below with code 0, which the native side ignores. + private static nint _flushCrashLog; + + private static unsafe void ResolveFlushCrashLog() + { + try + { + nint module = GetModuleHandleW("RynthCore.SehTrampoline.dll"); + nint fn = module == 0 ? 0 : GetProcAddress(module, "RC_FlushCrashLog"); + if (fn == 0) + { + RynthLog.Compat("SehTrampoline: RC_FlushCrashLog not exported (older DLL); crash exits will not flush the crash log's recent records."); + return; + } + ((delegate* unmanaged[Cdecl])fn)(0); // prime: code 0 is a no-op + _flushCrashLog = fn; + } + catch (Exception ex) { RynthLog.Compat($"SehTrampoline: RC_FlushCrashLog unavailable - {ex.GetType().Name}: {ex.Message}"); } + } + + /// + /// A crash exit is under way (ProcessExitHooks): write the crash logger's recent first-chance + /// records that were not written one by one, such as the fatal repeat of an address seen + /// before. Native and allocation-free; writes each record once, so a second call (one exit + /// path calling another) writes nothing. + /// + public static unsafe void FlushCrashLog(uint exitCode) + { + nint fn = _flushCrashLog; + if (fn == 0 || exitCode == 0) return; + ((delegate* unmanaged[Cdecl])fn)(exitCode); + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleHandleW")] + private static extern nint GetModuleHandleW(string name); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi, EntryPoint = "GetProcAddress", ExactSpelling = true)] + private static extern nint GetProcAddress(nint module, string name); + + private static int _moduleRefreshUnavailable; + + /// + /// Rebuilds the crash logger's module cache (module names at exception time come from it, + /// so the handler never calls the loader). Heartbeat thread, every few seconds. A DLL + /// older than the export is tolerated: the first failure stops the calls. + /// + public static void RefreshCrashLoggerModules() + { + if (!_available || Volatile.Read(ref _moduleRefreshUnavailable) != 0) return; + try { _RefreshCrashLoggerModules(); } + catch (Exception ex) + { + Interlocked.Exchange(ref _moduleRefreshUnavailable, 1); + RynthLog.Compat($"SehTrampoline: crash-logger module refresh unavailable - {ex.GetType().Name}: {ex.Message}"); + } } // ── Tag-parser guard (native detour) ─────────────────────────────────── @@ -104,6 +165,10 @@ internal static class SehTrampoline CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_RefreshCrashLoggerModules", + CallingConvention = CallingConvention.Cdecl)] + private static extern void _RefreshCrashLoggerModules(); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _GetTagParserGuardAddress(); diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index 85fe442..51f5db9 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -16,6 +16,8 @@ internal static class SmartBoxHooks private const uint PlayerPositionUpdateOpcode = 0x0000F74B; private const uint VectorUpdateOpcode = 0x0000F74E; private const uint UpdateObjectOpcode = 0x0000F7DB; + private const uint ServerObjectDeleteOpcode = 0x0000F747; + private const uint PlayerTeleportOpcode = 0x0000F751; // ACSmartBox::DispatchSmartBoxEvent // 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08 @@ -136,6 +138,17 @@ internal static class SmartBoxHooks TryQueueHealthUpdate(blob, info); TryQueueDamageEvent(blob, info); + // Always on (no server-message capture needed), after AC handled the message: + // 0xF747 ObjectDelete [opcode][objectId]: the SERVER deleted it (AutoId re-arms it + // and its kept identify data goes), unlike the client's own view releases; + // 0xF751 PlayerTeleport: a teleport starts, so queued game actions hold for the + // settle window from this moment (WorldTransitionState), whatever the per-tick + // teleport_in_progress sample catches. + if (info.Opcode == ServerObjectDeleteOpcode && info.RawObjectId != 0) + AutoIdService.OnServerDelete(info.RawObjectId); + else if (info.Opcode == PlayerTeleportOpcode) + PlayerLifecycleLog.OnTeleportMessage(); + if (info.RawObjectId != 0 && (info.Opcode == PositionUpdateOpcode || info.Opcode == PlayerPositionUpdateOpcode || diff --git a/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs new file mode 100644 index 0000000..058ac8b --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs @@ -0,0 +1,146 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/WorldTransitionState.cs +// +// Is the player in a world transition: dead, in portal space (teleporting), or +// within SettleMs after either, or after a landblock JUMP (a teleport, not walking +// into the next landblock)? AC is then tearing objects down and loading new ones, +// and nothing the engine queued for the main thread may run against it. +// +// Seen in a real crash: a client died right after a death recall's landblock +// jump (0x00AE -> 0xA9B4), under GameTickHooks.UseTimeDetour, which runs queued casts +// before AC's tick; a queued SetAutoRun(off) had run 1047 ms late a moment before. +// The engine's own queued work runs inside those ticks, so it is the first +// suspect. +// +// Gate rule for queued game-mutating work (AcMainThreadQueue, at its drains): +// - while in transition, everything is HELD: nothing queued runs; +// - once it ends, work queued at or before the last moment a drain saw the +// transition is DROPPED (casts, selects, uses, moves, appraisals: the plugins +// re-send what they still want), EXCEPT teardown work: stops and cancels (autorun +// off, a motion off, StopMovement, StopCompletely, CancelAttack, a container close), +// which still run, in queue order, as one group. A dropped stop can leave the +// character running or turning, and AcMainThreadQueue never drops stops. +// +// Walking across a landblock boundary is not a transition: it happens constantly in a +// fight, AC streams the neighbour in without tearing the player's world down, and a 5 s +// hold there would stall every border fight. +// +// Pure: AC main thread only (single writer and reader: the UseTime sample and both +// main-thread drains). Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class WorldTransitionState +{ + public const long SettleMs = 5_000; + + [Flags] + public enum Edge + { + None = 0, + Died = 1, + Revived = 2, + PortalEntered = 4, + PortalExited = 8, + LandblockJump = 16, + } + + private bool _init; + public bool Dead { get; private set; } + public bool Portaling { get; private set; } + public uint Landblock { get; private set; } + public uint PreviousLandblock { get; private set; } + /// The settle window runs until this TickCount64. + public long SettleUntilMs { get; private set; } + /// Last time a gate check saw the transition (0 = never). + public long LastBlockedMs { get; private set; } + + /// One game-tick sample. Returns the edges crossed (for the lifecycle log). + public Edge Sample(long nowMs, bool dead, bool portaling, uint landblock) + { + if (!_init) + { + _init = true; + Dead = dead; + Portaling = portaling; + Landblock = landblock; + if (dead || portaling) SettleUntilMs = nowMs + SettleMs; + return Edge.None; + } + + Edge edges = Edge.None; + if (dead || portaling || Dead || Portaling) + SettleUntilMs = nowMs + SettleMs; + if (dead != Dead) { edges |= dead ? Edge.Died : Edge.Revived; Dead = dead; } + if (portaling != Portaling) { edges |= portaling ? Edge.PortalEntered : Edge.PortalExited; Portaling = portaling; } + + if (landblock != 0 && Landblock != 0 && landblock != Landblock) + { + if (IsJump(Landblock, landblock)) + { + edges |= Edge.LandblockJump; + SettleUntilMs = Math.Max(SettleUntilMs, nowMs + SettleMs); + } + } + if (landblock != 0 && landblock != Landblock) + { + PreviousLandblock = Landblock; + Landblock = landblock; + } + return edges; + } + + /// + /// The server's PlayerTeleport message (0xF751) arrived: a teleport begins now, whether or not + /// a tick sample ever sees teleport_in_progress or a landblock jump (a recall into the next + /// landblock shows neither). Starts (or extends) the settle window. Returns false when the + /// window was already running past it. + /// + public bool OnTeleportMessage(long nowMs) + { + long until = nowMs + SettleMs; + if (until <= SettleUntilMs) return false; + SettleUntilMs = until; + return true; + } + + /// Two landblocks more than one apart on either axis: a teleport, not a walk. + public static bool IsJump(uint from, uint to) + { + int dx = (int)((to >> 8) & 0xFF) - (int)((from >> 8) & 0xFF); + int dy = (int)(to & 0xFF) - (int)(from & 0xFF); + return Math.Abs(dx) > 1 || Math.Abs(dy) > 1; + } + + /// Dead, portaling, or inside the settle window. + public bool InTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs; + + public enum Verdict { Run, Hold, Drop } + + /// + /// A drain's check for the head of a queue: true = hold everything queued now. Records the + /// moment, so work queued up to here is judged by once it ends. + /// + public bool CheckHolding(long nowMs) + { + if (!InTransition(nowMs)) return false; + LastBlockedMs = nowMs; + return true; + } + + /// + /// What a drain does with one queued item: Hold while in transition; afterwards Drop it + /// if it was queued during the transition (at or before the last held drain) unless it is + /// work, which Runs; anything queued after the transition Runs. + /// + public Verdict Decide(long nowMs, long queuedAtMs, bool teardown) + { + if (CheckHolding(nowMs)) return Verdict.Hold; + if (LastBlockedMs != 0 && queuedAtMs <= LastBlockedMs) + return teardown ? Verdict.Run : Verdict.Drop; + return Verdict.Run; + } +} \ No newline at end of file diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index ab5f143..0507e2a 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -6,6 +6,12 @@ // always-on procdump (which also dumped on every clean exit and every handled // first-chance AV, so a .dmp's existence never meant a real crash). // +// Also writes ONE full-memory dump when AC shows its OUT OF MEMORY box +// (MessageBoxHooks): that box is modal, so the process never crashes and Windows +// never writes a dump; the launcher later kills the client as wedged +// (AutoRestartWedgedClients, kept as it is). The hang dump is a small type and +// holds no heap, which is what an out-of-memory needs. +// // Safe to call from a background thread: MiniDumpWriteDump suspends all other // threads internally while it snapshots them, which is exactly what we want for // a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire). @@ -14,6 +20,7 @@ using System; using System.IO; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine; @@ -46,6 +53,14 @@ internal static class CrashDump private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported) + // MiniDumpWithFullMemory (0x2) is as old as MiniDumpNormal, so dbghelp 6.1 takes it. + private const uint DumpTypeFull = 0x00000002 | 0x00000004; // FullMemory + WithHandleData + private const uint DumpTypeFullFallback = 0x00000002; // FullMemory only + + // dbghelp is single-threaded: every MiniDumpWriteDump in this process goes through this + // lock, so the hang watchdog's small dump can never run alongside the OOM full dump. + private static readonly object DumpLock = new(); + /// /// Write a minidump of the current process to Logs\dumps\. Best-effort; /// never throws. Returns true on success and sets . @@ -60,40 +75,7 @@ internal static class CrashDump string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp"); - - using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None); - bool ok = MiniDumpWriteDump( - GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle, - DumpTypePreferred, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); - int err = ok ? 0 : Marshal.GetLastWin32Error(); - - // ERROR_INVALID_PARAMETER (87) ⇒ AC's ancient dbghelp 6.1 rejected a flag. - // Retry with bare MiniDumpNormal (universally supported, still has every - // thread stack — what we need to read the deadlock's lock holder). - if (!ok && err == 87) - { - fs.SetLength(0); - ok = MiniDumpWriteDump( - GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle, - DumpTypeFallback, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); - err = ok ? 0 : Marshal.GetLastWin32Error(); - if (ok) RynthLog.Error($"CrashDump: rich flags rejected by AC's old dbghelp 6.1 — wrote bare Normal dump, reason={reason}"); - } - - if (!ok) - { - RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} reason={reason}"); - // Don't leave a 0-byte .dmp behind — it reads as a crash marker - // during triage (observed: hang_17692_20260611_114430.dmp, 0 - // bytes, main thread suspended mid-exception-dispatch). - try { fs.Close(); File.Delete(dumpPath); } catch { } - return false; - } - - long size = 0; - try { size = new FileInfo(dumpPath).Length; } catch { } - RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB) reason={reason}"); - return true; + return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason); } catch (Exception ex) { @@ -101,4 +83,215 @@ internal static class CrashDump return false; } } + + // Writes one dump to . On ERROR_INVALID_PARAMETER (87: AC's ancient + // dbghelp 6.1 rejected a flag) retries with . Never leaves a + // 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed: + // hang_17692_20260611_114430.dmp, 0 bytes, main thread suspended mid-exception-dispatch). + private static bool WriteDumpFile(string path, uint type, uint fallbackType, string reason) + { + lock (DumpLock) + { + bool ok; + int err; + using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) + { + ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle, + type, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + err = ok ? 0 : Marshal.GetLastWin32Error(); + if (!ok && err == 87 && fallbackType != type) + { + fs.SetLength(0); + ok = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle, + fallbackType, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + err = ok ? 0 : Marshal.GetLastWin32Error(); + if (ok) RynthLog.Error($"CrashDump: flags 0x{type:X} rejected by AC's old dbghelp 6.1 - wrote type 0x{fallbackType:X}, reason={reason}"); + } + } + + if (!ok) + { + RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} type=0x{type:X} reason={reason}"); + try { File.Delete(path); } catch { } + return false; + } + + long size = 0; + try { size = new FileInfo(path).Length; } catch { } + RynthLog.Error($"CrashDump: wrote {path} ({size / 1024}KB) reason={reason}"); + return true; + } + } + + // -- OUT OF MEMORY full-memory dump -------------------------------------- + + /// Full dumps kept in the Dumps folder (a full dump is about the size of the process). + internal const int OutOfMemoryDumpsKept = 3; + internal const string OutOfMemoryDumpPrefix = "acclient_oom_"; + + // Longest the showing thread waits for the dump writer before letting the box open anyway. + private const int FullDumpWaitMs = 300_000; + + private static int _oomDumpLatch; + private static volatile bool _fullDumpInProgress; + private static volatile string? _fullDumpWrittenPath; + + /// True while the OUT OF MEMORY full dump is being written (the watchdog holds off). + internal static bool FullDumpInProgress => _fullDumpInProgress; + + /// The OUT OF MEMORY full dump written this session, or null. + internal static string? FullDumpWrittenPath => _fullDumpWrittenPath; + + /// C:\Games\RynthCore\Dumps by default (beside Logs, under the install folder). + internal static string OutOfMemoryDumpDirectory => Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps"); + + /// + /// Once per process: write a full-memory dump to , log + /// its path, and keep only the newest of these dumps. + /// Called on the thread about to show AC's OUT OF MEMORY box, which waits here until the + /// dump is written (on its own thread, so the showing thread's stack is captured at rest). + /// Never throws. + /// + internal static void WriteOutOfMemoryDumpOnce(string? reason) + { + if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return; + string why = "AC OUT OF MEMORY box: " + (reason ?? "?"); + _fullDumpInProgress = true; + // The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every + // thread, so the log goes silent for the whole dump, which would otherwise read as a dead + // engine and get the client killed mid-dump. + try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); } + catch { } + Thread? writer = null; + try + { + writer = new Thread(() => + { + // The flag stays up until the writer itself is done, even past a timed-out Join. + try { WriteOutOfMemoryDumpCore(why); } + finally { FinishFullDump(); } + }) { IsBackground = true, Name = "RynthCore.OomDump" }; + writer.Start(); + } + catch (Exception ex) + { + // No thread to be had (out of memory, after all): write it from this one. + try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { } + writer = null; + } + try + { + if (writer == null) + { + try { WriteOutOfMemoryDumpCore(why); } + finally { FinishFullDump(); } + } + else if (!writer.Join(FullDumpWaitMs)) + { + RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going)."); + } + } + catch (Exception ex) + { + try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { } + } + } + + /// Log line written before the OUT OF MEMORY full dump starts (read by the launcher). + internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted; + /// Log line written once the writer has finished, whatever the outcome. + internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded; + + private static void FinishFullDump() + { + _fullDumpInProgress = false; + try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { } + } + + private static void WriteOutOfMemoryDumpCore(string reason) + { + try + { + string dir = OutOfMemoryDumpDirectory; + Directory.CreateDirectory(dir); + + string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp"); + if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason)) + { + _fullDumpWrittenPath = path; + RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump: {path}"); + // Only after the new dump succeeded: a failed write never costs an older one. + PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept); + } + else + { + RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead."); + WriteSelfDump(reason, out _, "oom-small"); + } + } + catch (Exception ex) + { + RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}"); + } + } + + /// + /// Deletes all but the newest *.dmp files in + /// . The folder is shared by every client: a dump whose name carries + /// the pid of ANOTHER process that is still running is never deleted (it may still be + /// writing it, or about to report it), and is not counted against . + /// Never throws. + /// + internal static int PruneDumps(string dir, string prefix, int keep) + { + int deleted = 0; + try + { + FileInfo[] files = new DirectoryInfo(dir).GetFiles(prefix + "*.dmp"); + Array.Sort(files, (a, b) => b.LastWriteTimeUtc.CompareTo(a.LastWriteTimeUtc)); + int kept = 0; + int self = Environment.ProcessId; + foreach (FileInfo f in files) + { + int pid = DumpPid(f.Name, prefix); + if (pid > 0 && pid != self && IsProcessAlive(pid)) + continue; // another live client's dump: not ours to delete + if (kept < Math.Max(0, keep)) { kept++; continue; } + string name = f.Name; + long length = 0; + try { length = f.Length; } catch { } + try + { + f.Delete(); + deleted++; + RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB)."); + } + catch { /* in use by a debugger, or already gone */ } + } + } + catch { } + return deleted; + } + + /// The pid in "prefix<pid>_...dmp", or 0. + internal static int DumpPid(string fileName, string prefix) + { + if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0; + int start = prefix.Length, end = start; + while (end < fileName.Length && char.IsDigit(fileName[end])) end++; + return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0; + } + + private static bool IsProcessAlive(int pid) + { + try + { + using var p = System.Diagnostics.Process.GetProcessById(pid); + return !p.HasExited; + } + catch + { + return false; + } + } } diff --git a/src/RynthCore.Engine/MainThreadFreeze.cs b/src/RynthCore.Engine/MainThreadFreeze.cs new file mode 100644 index 0000000..7256eee --- /dev/null +++ b/src/RynthCore.Engine/MainThreadFreeze.cs @@ -0,0 +1,87 @@ +// ============================================================================ +// RynthCore.Engine - MainThreadFreeze.cs +// The plugin pump's freeze gate (rule and reasons: MainThreadFreezeRule.cs). +// PluginManager.TickAll asks ShouldPausePluginTick once per pump tick; while it +// says yes, no plugin Tick runs (no decisions, no actions), while event delivery +// (ProcessPendingActions: observing) carries on. +// +// Plugins can read the state through GetEngineStatusJson (additive fields, no API +// version change): mainThreadFrozen, mainThreadStallMs, pluginTicksPausedMs (a running +// total, so a stall detector can subtract the paused time from what it measured). +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine; + +internal static class MainThreadFreeze +{ + private static readonly PumpPauseTracker Tracker = new(); // pump thread only + private static int _pausedFlag; // published copies, any thread + private static long _pausedTotalMs, _pausedSinceMs; + + /// Plugin ticks are paused right now. Any thread. + public static bool Paused => Volatile.Read(ref _pausedFlag) != 0; + + /// Total time plugin ticks have been paused, a pause in progress included. Any thread. + public static long PausedTotalMs + { + get + { + long total = Interlocked.Read(ref _pausedTotalMs); + long since = Interlocked.Read(ref _pausedSinceMs); + return Paused && since != 0 ? total + Math.Max(0, Environment.TickCount64 - since) : total; + } + } + + /// How long AC's main thread has gone without a beat (0 before the first one). Any thread. + public static long MainThreadStallMs => + MainThreadHangWatchdog.HasBeaten ? Math.Max(0, Environment.TickCount64 - MainThreadHangWatchdog.LastBeatTick) : 0; + + /// Frozen right now by the rule (main-thread message box, or a stale beat). Any thread. + public static bool IsFrozenNow(out int mainThreadBoxes, out long staleMs) + { + long now = Environment.TickCount64; + mainThreadBoxes = Compatibility.MessageBoxHooks.MainThreadOpenCount; + bool beaten = MainThreadHangWatchdog.HasBeaten; + long last = MainThreadHangWatchdog.LastBeatTick; + staleMs = beaten ? now - last : 0; + return MainThreadFreezeRule.IsFrozen(now, last, beaten, mainThreadBoxes, MainThreadHangWatchdog.HangThresholdMs); + } + + /// + /// Pump thread, once per TickAll. True = skip this tick's plugin Ticks. Logs the pause and + /// the resume. Never throws. + /// + public static bool ShouldPausePluginTick() + { + try + { + long now = Environment.TickCount64; + bool frozen = IsFrozenNow(out int boxes, out long staleMs); + PumpPauseTracker.Transition t = Tracker.Update(frozen, now); + if (t == PumpPauseTracker.Transition.Paused) + { + Interlocked.Exchange(ref _pausedSinceMs, now); + Volatile.Write(ref _pausedFlag, 1); + string why = boxes > 0 + ? $"a message box is open on its main thread ({Compatibility.MessageBoxHooks.Describe() ?? "?"})" + : $"no main-thread beat for {staleMs} ms"; + RynthLog.Warn($"PluginManager: AC's main thread is frozen ({why}) - plugin ticks PAUSED (events still delivered)."); + } + else if (t == PumpPauseTracker.Transition.Resumed) + { + Interlocked.Exchange(ref _pausedTotalMs, Tracker.FinishedPausedMs); + Volatile.Write(ref _pausedFlag, 0); + long lasted = now - Tracker.PausedSinceMs; + RynthLog.Info($"PluginManager: AC's main thread is back - plugin ticks resumed after {lasted} ms ({Tracker.TicksSkippedThisPause} tick(s) skipped, pause #{Tracker.Pauses})."); + } + return Tracker.Paused; + } + catch + { + return false; + } + } +} diff --git a/src/RynthCore.Engine/MainThreadFreezeRule.cs b/src/RynthCore.Engine/MainThreadFreezeRule.cs new file mode 100644 index 0000000..4af5b4a --- /dev/null +++ b/src/RynthCore.Engine/MainThreadFreezeRule.cs @@ -0,0 +1,96 @@ +// ============================================================================ +// RynthCore.Engine - MainThreadFreezeRule.cs +// +// When AC's main thread is frozen, plugin ticks (where plugins decide and act) are +// paused; event delivery (observing) goes on. In one real case AC's +// OUT OF MEMORY box held the main thread for 12 s while the plugin pump kept +// ticking; the bot jumped and asked for Peace mode to break a "stuck cast", and +// blamed the server, while nothing could reach the server at all. +// +// Frozen means either of: +// - a message box is open ON AC'S MAIN THREAD (MessageBoxHooks): modal, the main +// thread is inside it from the first instant; or +// - the main-thread heartbeat (EndScene / Client::UseTime beats) is at least the +// hang watchdog's threshold old: the same signal MainThreadHangWatchdog uses. +// Before the first beat nothing is frozen (the main thread is not known yet). +// +// PumpPauseTracker keeps the pause transitions and how long plugin ticks have been +// paused in total, which plugins can read (GetEngineStatusJson) to discount frozen +// time from their own stall detectors. +// +// Pure: no engine state. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +namespace RynthCore.Engine; + +internal static class MainThreadFreezeRule +{ + public static bool IsFrozen(long nowMs, long lastBeatMs, bool beatSeen, int mainThreadMessageBoxes, long thresholdMs) + { + if (mainThreadMessageBoxes > 0) + return true; + return beatSeen && nowMs - lastBeatMs >= thresholdMs; + } +} + +/// +/// Is a message box AC's OUT OF MEMORY box (the one that gets a full-memory dump)? Only on +/// AC's main thread, and only AC's own text, matched exactly at the start (ordinal): a plugin +/// box or a chat line that merely mentions memory must never cost a multi-gigabyte dump. +/// +internal static class OutOfMemoryBoxRule +{ + public const string Prefix = "OUT OF MEMORY: Failed to allocate"; + + public static bool IsOutOfMemoryBox(string? body, bool onMainThread) => + onMainThread && body != null && body.StartsWith(Prefix, System.StringComparison.Ordinal); +} + +/// Single-writer (the plugin pump). Not thread-safe; the engine glue publishes copies. +internal sealed class PumpPauseTracker +{ + public enum Transition { None, Paused, Resumed } + + public bool Paused { get; private set; } + public long PausedSinceMs { get; private set; } + /// Paused time of finished pauses (the current one is added by ). + public long FinishedPausedMs { get; private set; } + public int Pauses { get; private set; } + public long TicksSkippedThisPause { get; private set; } + public long TicksSkippedTotal { get; private set; } + + /// + /// Feed one pump tick. Returns the transition, if any. While paused the tick is to be + /// skipped (and is counted as skipped). + /// + public Transition Update(bool frozen, long nowMs) + { + if (frozen) + { + Transition t = Transition.None; + if (!Paused) + { + Paused = true; + PausedSinceMs = nowMs; + Pauses++; + TicksSkippedThisPause = 0; + t = Transition.Paused; + } + TicksSkippedThisPause++; + TicksSkippedTotal++; + return t; + } + if (Paused) + { + Paused = false; + long d = nowMs - PausedSinceMs; + if (d > 0) FinishedPausedMs += d; + return Transition.Resumed; + } + return Transition.None; + } + + /// Total time plugin ticks have been paused, including a pause in progress. + public long TotalPausedMs(long nowMs) => + FinishedPausedMs + (Paused && nowMs > PausedSinceMs ? nowMs - PausedSinceMs : 0); +} diff --git a/src/RynthCore.Engine/MainThreadHangWatchdog.cs b/src/RynthCore.Engine/MainThreadHangWatchdog.cs index 8f571ee..f3ec59b 100644 --- a/src/RynthCore.Engine/MainThreadHangWatchdog.cs +++ b/src/RynthCore.Engine/MainThreadHangWatchdog.cs @@ -63,7 +63,8 @@ internal static class MainThreadHangWatchdog internal static volatile string? CrashCause; // Stalls longer than this with no EndScene beat = main thread wedged. - private const long HangThresholdMs = 4000; + // Also the plugin pump's freeze gate (MainThreadFreeze): one signal for both. + internal const long HangThresholdMs = 4000; // Max stack samples to take during a single hang (1/sec). A permanent freeze // shows a stable eip across these = the true wedge; a transient stall logs // RECOVERED. Capped to keep the log readable. @@ -82,6 +83,12 @@ internal static class MainThreadHangWatchdog /// Monotonic EndScene frame count since engine init. internal static int FrameCount => _frameCount; + /// True once the main thread has beaten (its id is known). Any thread. + internal static bool HasBeaten => _mainThreadId != 0; + + /// Environment.TickCount64 of the last main-thread beat. Any thread. + internal static long LastBeatTick => Volatile.Read(ref _lastBeatTick); + /// /// Called from EndSceneDetour on AC's main thread, every frame. Must be /// cheap and never throw. @@ -155,6 +162,13 @@ internal static class MainThreadHangWatchdog uint tid = _mainThreadId; if (tid == 0) continue; // EndScene hasn't beaten yet + // The main thread is writing the OUT OF MEMORY full-memory dump (CrashDump, + // from MessageBoxHooks). Neither suspend it nor report the wedge yet: the + // launcher kills the client on "still hung after", which would cut the dump + // short. The hang is detected and reported as usual once the dump is done. + if (CrashDump.FullDumpInProgress) + continue; + long lastBeat = Volatile.Read(ref _lastBeatTick); long stale = Environment.TickCount64 - lastBeat; @@ -230,6 +244,11 @@ internal static class MainThreadHangWatchdog RynthLog.Info(" (hang minidump disabled via EngineSettings.EnableHangMinidump)"); return; } + if (CrashDump.FullDumpWrittenPath is { } full) + { + RynthLog.Info($" (hang minidump skipped: the full-memory dump {full} already covers this hang)"); + return; + } CrashDump.WriteSelfDump( $"main-thread hang tid={tid} stale={staleMs}ms build={EntryPoint.BuildStamp}", out _); } diff --git a/src/RynthCore.Engine/Net/ServerMessageStream.cs b/src/RynthCore.Engine/Net/ServerMessageStream.cs index 5125a9e..a40bc4c 100644 --- a/src/RynthCore.Engine/Net/ServerMessageStream.cs +++ b/src/RynthCore.Engine/Net/ServerMessageStream.cs @@ -218,6 +218,14 @@ internal static unsafe class ServerMessageStream { try { InventoryOrder.Observe(new ReadOnlySpan(message, length)); } catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: inventory order failed - {ex.GetType().Name}: {ex.Message}"); } + // The SERVER deleted an object (0xF747 ObjectDelete, its id after the opcode). AutoId + // tells this apart from the client's own releases: only this one makes a re-create + // under the same id due an appraisal again (AutoIdEligibility). + if (opcode == InventoryOrder.DeleteObjectOpcode && length >= 8) + { + try { Compatibility.AutoIdService.OnServerDelete(AcPacketWire.ReadU32(message + 4)); } + catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: server delete failed - {ex.GetType().Name}: {ex.Message}"); } + } } if (_pluginsWant) _dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4); diff --git a/src/RynthCore.Engine/Plugins/ManagedPlugins.cs b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs index 48fa4c3..7048f74 100644 --- a/src/RynthCore.Engine/Plugins/ManagedPlugins.cs +++ b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs @@ -146,10 +146,13 @@ internal static class ManagedPlugins if (retired.Contains(kv.Value)) Loaded.Remove(kv.Key); } #if ENGINE_CORECLR + string vaBefore = retired.Count > 0 ? Compatibility.AddressSpace.Describe() : ""; foreach (Entry e in retired) e.Context.Unload(); + // Context.Unload only starts the collection; "after" is right after the request, so the + // NEXT reload's "va before" is where a context that never collects shows up. if (retired.Count > 0) - RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))}."); + RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))} (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()})."); #endif } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 7d16441..625650b 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -1028,6 +1028,13 @@ internal static partial class PluginManager if (UiFlowHooks.ClientCleanupStarted) return; + // AC's main thread is frozen (a message box open on it, or no beat for the hang + // watchdog's threshold): no plugin Tick this pump tick, so plugins neither decide nor + // act against a client that cannot run anything (MainThreadFreezeRule.cs). Events keep + // flowing (ProcessPendingActions), and the Nav3D frame is left as it was. + if (MainThreadFreeze.ShouldPausePluginTick()) + return; + // Fire the delayed login self-identify once AC's vitals UI has settled // (armed in DispatchLoginCompleteToLoadedPlugins; deferred past the // early-init window where AC's gmVitalsUI::Update AV'd — 2026-06-09). @@ -2387,8 +2394,11 @@ internal static partial class PluginManager continue; } - RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}"); + // Address space before and after each load: a 32-bit client runs out on the largest + // free block, and a reload stacks copies (Compatibility/AddressSpace.cs). + RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath} (va before: {Compatibility.AddressSpace.Describe()})"); var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration); + RynthLog.Plugin($"PluginManager: loaded {Path.GetFileName(dllPath)}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); if (plugin != null) { plugin.Manifest = manifest; @@ -2552,7 +2562,9 @@ internal static partial class PluginManager // v71: its script windows close (their placement is kept). ScriptWindowRegistry.DropOwner(plugin); + string vaBefore = Compatibility.AddressSpace.Describe(); PluginLoader.Unload(plugin); + RynthLog.Plugin($"PluginManager: unloaded {plugin.DisplayName} (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()})"); } _plugins.Clear(); diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 0d1555d..3f05bfe 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -164,6 +164,7 @@ + diff --git a/src/Shared/DumpInProgressRule.cs b/src/Shared/DumpInProgressRule.cs new file mode 100644 index 0000000..ade35d0 --- /dev/null +++ b/src/Shared/DumpInProgressRule.cs @@ -0,0 +1,76 @@ +// ============================================================================ +// Shared - DumpInProgressRule.cs (compiled into the engine and the launcher) +// +// The engine's OUT OF MEMORY full-memory dump (CrashDump) suspends every thread in the +// client while dbghelp writes it, for minutes on a 3 GB process. The log goes silent +// meanwhile, which the launcher's wedge watch (AutoRestartWedgedClients) reads as a dead +// engine after 120 s and kills the client: mid-dump, leaving a truncated file. The engine +// writes MarkerStarted before the dump and MarkerEnded after it; the launcher holds off +// its kill while a dump is in progress by either sign: +// - the log tail's last MarkerStarted has no MarkerEnded after it, and the log was +// written less than MaxMarkerAge ago (a dump never takes that long; a client that +// died mid-dump is killed after it); or +// - the client's acclient_oom__*.dmp file is still being written (modified within +// FileQuietMs). +// The launcher's restart after the dump, for the OOM box that follows, is unchanged. +// A hold never lasts more than MaxHold per client (Decide, from the launcher's first hold +// of that pid): a log kept fresh by some other writer while a marker stays open must not +// shield a dead client forever. Past the cap the kills resume. +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Install; + +internal static class DumpInProgressRule +{ + public const string MarkerStarted = "CrashDump: FULL-MEMORY DUMP STARTED"; + public const string MarkerEnded = "CrashDump: FULL-MEMORY DUMP ENDED"; + public const string OomDumpPrefix = "acclient_oom_"; + + public static readonly TimeSpan MaxMarkerAge = TimeSpan.FromMinutes(10); + public static readonly TimeSpan FileQuietMs = TimeSpan.FromSeconds(30); + public static readonly TimeSpan MaxHold = TimeSpan.FromMinutes(15); + + public enum Hold + { + /// No dump in progress: the kill checks run. + None, + /// A dump is in progress: hold off the kills. + Holding, + /// Signs of a dump, but held for MaxHold already: the kill checks run. + Expired, + } + + /// + /// , capped: is when the launcher first + /// held this client (null = not held yet). The launcher keeps that time while the result is + /// Holding or Expired and forgets it on None, so an expired hold does not start again. + /// + public static Hold Decide(string? logTail, DateTime logLastWriteUtc, DateTime? newestOomDumpWriteUtc, + DateTime? holdSinceUtc, DateTime nowUtc) + { + if (!IsDumping(logTail, logLastWriteUtc, newestOomDumpWriteUtc, nowUtc)) return Hold.None; + if (holdSinceUtc is DateTime since && nowUtc - since >= MaxHold) return Hold.Expired; + return Hold.Holding; + } + + /// + /// True while the launcher must not kill the client for a silent log. + /// : the end of RynthCore.<pid>.log; + /// : its last write; : + /// the last write of the newest acclient_oom_<pid>_*.dmp, or null. + /// + public static bool IsDumping(string? logTail, DateTime logLastWriteUtc, DateTime? newestOomDumpWriteUtc, DateTime nowUtc) + { + if (newestOomDumpWriteUtc is DateTime dumpWrite && nowUtc - dumpWrite < FileQuietMs) + return true; + if (string.IsNullOrEmpty(logTail)) return false; + int started = logTail.LastIndexOf(MarkerStarted, StringComparison.Ordinal); + if (started < 0) return false; + if (logTail.IndexOf(MarkerEnded, started, StringComparison.Ordinal) >= 0) return false; + return nowUtc - logLastWriteUtc < MaxMarkerAge; + } +} diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj new file mode 100644 index 0000000..341bff5 --- /dev/null +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -0,0 +1,45 @@ + + + + + Exe + net10.0 + enable + enable + true + EngineRobustnessTests + + + + + + + + + + + + + + + + + + diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs new file mode 100644 index 0000000..2bead51 --- /dev/null +++ b/tools/EngineRobustnessTests/Program.cs @@ -0,0 +1,412 @@ +using RynthCore.Engine; +using RynthCore.Engine.Compatibility; + +namespace EngineRobustnessTests; + +/// +/// The pure decision parts of the engine-robustness pass. Every clock is a plain +/// number; nothing touches AC. +/// +internal static partial class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + QueueMergesSameObject(); + QueueDoesNotMergeAcrossLoginOrWhenStale(); + QueueFullStillMerges(); + + EligibilityCreateAndDuplicate(); + EligibilityWindowAfterClientRelease(); + EligibilityServerDeleteReArms(); + EligibilityUncachedIsAppraised(); + EligibilityReleaseBeforeSendRecordsNothing(); + EligibilityMapStaysBounded(); + PriorityFreshRule(); + + FreezeRule(); + PauseTracker(); + + TransitionHoldsWhileDead(); + TransitionLandblockJumpWithoutPortalHolds(); + TransitionAdjacentCrossingDoesNotHold(); + TransitionPortalHolds(); + TransitionShortTeleportToAdjacentLandblockHolds(); + TransitionDiagonalAndBorderWalksNeverHold(); + TransitionTwoLandblockJumpHolds(); + TransitionDrainHoldThenStopsSurvive(); + + AddressSpaceFold(); + + RunRingAndGateTests(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + // ---- fix 1: the RequestId slot merges --------------------------------------------- + + private const long MergeMax = 15_000; + + private static void QueueMergesSameObject() + { + _case = "queue merge"; + var q = new PendingIdQueue(8); + Check(q.Enqueue(0x80000001, 1000, 1, MergeMax) == PendingIdQueue.Result.Queued, "first request queued"); + Check(q.Enqueue(0x80000002, 1010, 1, MergeMax) == PendingIdQueue.Result.Queued, "other object queued"); + Check(q.Enqueue(0x80000001, 1100, 1, MergeMax) == PendingIdQueue.Result.Merged, "same object merged"); + Check(q.Enqueue(0x80000001, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged, "merged again"); + Check(q.Count == 2, $"two pending, got {q.Count}"); + Check(q.MergedTotal == 2, $"two merges counted, got {q.MergedTotal}"); + Check(q.TryDequeue(out var a) && a.Id == 0x80000001 && a.At == 1000, "FIFO head is the first request, original time"); + Check(q.TryDequeue(out var b) && b.Id == 0x80000002, "then the second object"); + Check(!q.TryDequeue(out _), "empty"); + // Once sent (dequeued), a new request for the same object queues again. + Check(q.Enqueue(0x80000001, 1300, 1, MergeMax) == PendingIdQueue.Result.Queued, "re-queued after the send"); + } + + private static void QueueDoesNotMergeAcrossLoginOrWhenStale() + { + _case = "queue no merge"; + var q = new PendingIdQueue(8); + q.Enqueue(7, 1000, 1, MergeMax); + Check(q.Enqueue(7, 1100, 2, MergeMax) == PendingIdQueue.Result.Queued, "a new login's request is not absorbed by the old one"); + Check(q.Enqueue(7, 1200, 1, MergeMax) == PendingIdQueue.Result.Merged, + "a later epoch-1 request still merges into the epoch-1 entry"); + Check(q.Enqueue(7, 1300, 2, MergeMax) == PendingIdQueue.Result.Merged, + "and an epoch-2 one into the epoch-2 entry"); + Check(q.Count == 2, $"one entry per login, got {q.Count}"); + var r = new PendingIdQueue(8); + r.Enqueue(9, 1000, 1, MergeMax); + Check(r.Enqueue(9, 1000 + MergeMax + 1, 1, MergeMax) == PendingIdQueue.Result.Queued, "a stale pending entry takes no merge"); + Check(r.Count == 2, "both kept"); + } + + private static void QueueFullStillMerges() + { + _case = "queue full"; + var q = new PendingIdQueue(3); + q.Enqueue(1, 0, 1, MergeMax); q.Enqueue(2, 0, 1, MergeMax); q.Enqueue(3, 0, 1, MergeMax); + Check(q.Enqueue(4, 1, 1, MergeMax) == PendingIdQueue.Result.Full, "a new object is refused when full"); + Check(q.Enqueue(2, 1, 1, MergeMax) == PendingIdQueue.Result.Merged, "a pending object still merges when full"); + // Wrap-around: dequeue one, add one, order holds. + q.TryDequeue(out _); + q.Enqueue(5, 2, 1, MergeMax); + var order = new List(); + while (q.TryDequeue(out var it)) order.Add(it.Id); + Check(string.Join(",", order) == "2,3,5", $"FIFO across the wrap, got {string.Join(",", order)}"); + } + + // ---- fix 3: re-eligibility --------------------------------------------------------- + + private const long Min = 60_000; + + private static void EligibilityCreateAndDuplicate() + { + _case = "eligibility create"; + var e = new AutoIdEligibility(); + Check(e.OnCreate(10, 1000, false) == AutoIdEligibility.CreateDecision.Appraise, "a new object is appraised"); + Check(e.OnCreate(10, 1001, false) == AutoIdEligibility.CreateDecision.SkipDuplicate, "a second create while live is a duplicate"); + Check(e.IsLive(10), "live"); + e.OnClientRelease(10); + Check(!e.IsLive(10), "released"); + Check(e.IsLive(999), "an untracked id counts as live (the drain sends it)"); + } + + private static void EligibilityWindowAfterClientRelease() + { + _case = "eligibility window"; + var e = new AutoIdEligibility(); + e.OnCreate(10, 0, false); + e.OnSent(10, 1000); + e.OnClientRelease(10); + Check(e.OnCreate(10, 1000 + 1 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "re-created 1 min later, cached: skipped"); + e.OnClientRelease(10); + Check(e.OnCreate(10, 1000 + 9 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "9 min later: still skipped"); + e.OnClientRelease(10); + Check(e.OnCreate(10, 1000 + 10 * Min, true) == AutoIdEligibility.CreateDecision.Appraise, "10 min later: appraised again"); + } + + private static void EligibilityServerDeleteReArms() + { + _case = "eligibility server delete"; + var e = new AutoIdEligibility(); + e.OnCreate(20, 0, false); + e.OnSent(20, 1000); + e.OnServerDelete(20); + e.OnClientRelease(20); + Check(e.OnCreate(20, 2000, true) == AutoIdEligibility.CreateDecision.Appraise, "server delete then re-create inside the window: appraised"); + // Client release first, server delete after: same result. + e.OnSent(20, 3000); + e.OnClientRelease(20); + e.OnServerDelete(20); + Check(e.OnCreate(20, 4000, true) == AutoIdEligibility.CreateDecision.Appraise, "release then server delete: appraised"); + } + + private static void EligibilityUncachedIsAppraised() + { + _case = "eligibility uncached"; + var e = new AutoIdEligibility(); + e.OnCreate(30, 0, false); + e.OnSent(30, 1000); + e.OnClientRelease(30); + Check(e.OnCreate(30, 2000, false) == AutoIdEligibility.CreateDecision.Appraise, "nothing cached any more: appraised even inside the window"); + } + + private static void EligibilityReleaseBeforeSendRecordsNothing() + { + _case = "eligibility unsent"; + var e = new AutoIdEligibility(); + e.OnCreate(40, 0, false); + e.OnClientRelease(40); // released before the drain sent its appraisal + Check(e.OnCreate(40, 500, true) == AutoIdEligibility.CreateDecision.Appraise, "never sent: the next create is appraised"); + } + + private static void EligibilityMapStaysBounded() + { + _case = "eligibility bound"; + var e = new AutoIdEligibility(10 * Min, 100); + for (uint i = 1; i <= 100; i++) e.OnCreate(i, 0, false); + Check(e.Count == 100, $"100 tracked, got {e.Count}"); + Check(e.OnCreate(101, 0, false) == AutoIdEligibility.CreateDecision.Appraise, "past the bound a create is still appraised"); + Check(e.Count == 100 && e.UntrackedAdmits == 1, $"but not tracked (count {e.Count}, untracked {e.UntrackedAdmits})"); + Check(e.Prune(1000) == 0, "all live: nothing pruned"); + + // 80 of them appraised (sent at different times) and released, all inside the window. + for (uint i = 1; i <= 80; i++) { e.OnSent(i, 1000 + i); e.OnClientRelease(i); } + int removed = e.Prune(2 * Min); + Check(e.Count <= 75, $"pruned to three quarters of the bound, count {e.Count} (removed {removed})"); + bool liveKept = true; + for (uint i = 81; i <= 100; i++) liveKept &= e.IsLive(i) && e.OnCreate(i, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipDuplicate; + Check(liveKept, "the 20 live entries are never pruned"); + // The newest-sent released entries survive the age passes before the oldest. + Check(e.OnCreate(80, 2 * Min, true) == AutoIdEligibility.CreateDecision.SkipRecent, "the most recently sent released entry survived"); + + // Outside the window everything released goes. + var f = new AutoIdEligibility(10 * Min, 100); + for (uint i = 1; i <= 50; i++) { f.OnCreate(i, 0, false); f.OnSent(i, 1); f.OnClientRelease(i); } + f.Prune(11 * Min); + Check(f.Count == 0, $"expired released entries are pruned, count {f.Count}"); + } + + private static void PriorityFreshRule() + { + _case = "priority fresh"; + long now = 1_800_000_000; + Check(AutoIdEligibility.IsAppraisalFresh(true, now - 60, now, 10 * Min), "cached, 1 min old: fresh (skip)"); + Check(!AutoIdEligibility.IsAppraisalFresh(true, now - 601, now, 10 * Min), "cached, 10 min+ old: stale (appraise)"); + Check(!AutoIdEligibility.IsAppraisalFresh(false, now - 60, now, 10 * Min), "not cached: appraise"); + Check(!AutoIdEligibility.IsAppraisalFresh(true, 0, now, 10 * Min), "no receive time: appraise"); + } + + // ---- fix 4: the plugin pump pauses while AC is frozen -------------------------------- + + private static void FreezeRule() + { + _case = "freeze rule"; + const long T = 4000; + Check(!MainThreadFreezeRule.IsFrozen(100_000, 0, false, 0, T), "no beat yet: not frozen"); + Check(!MainThreadFreezeRule.IsFrozen(100_000, 99_000, true, 0, T), "beat 1 s ago: running"); + Check(MainThreadFreezeRule.IsFrozen(100_000, 96_000, true, 0, T), "beat 4 s ago: frozen (the hang watchdog's threshold)"); + Check(MainThreadFreezeRule.IsFrozen(100_000, 99_900, true, 1, T), "a main-thread message box: frozen at once"); + Check(MainThreadFreezeRule.IsFrozen(100_000, 0, false, 1, T), "a message box before the first beat: frozen"); + } + + private static void PauseTracker() + { + _case = "pause tracker"; + var t = new PumpPauseTracker(); + Check(t.Update(false, 1000) == PumpPauseTracker.Transition.None && !t.Paused, "running"); + Check(t.Update(true, 2000) == PumpPauseTracker.Transition.Paused && t.Paused, "pauses"); + Check(t.Update(true, 2016) == PumpPauseTracker.Transition.None, "stays paused"); + Check(t.TicksSkippedThisPause == 2, $"2 ticks skipped, got {t.TicksSkippedThisPause}"); + Check(t.TotalPausedMs(5000) == 3000, $"3000 ms paused in progress, got {t.TotalPausedMs(5000)}"); + Check(t.Update(false, 14000) == PumpPauseTracker.Transition.Resumed && !t.Paused, "resumes"); + Check(t.FinishedPausedMs == 12000 && t.TotalPausedMs(20000) == 12000, $"12 s in total, got {t.FinishedPausedMs}"); + t.Update(true, 30000); t.Update(false, 30500); + Check(t.Pauses == 2 && t.FinishedPausedMs == 12500 && t.TicksSkippedTotal == 3, "second pause adds up"); + } + + // ---- the world-transition gate (coordinator items c and g) -------------------------- + + private static WorldTransitionState Started(uint landblock = 0x00AE) + { + var s = new WorldTransitionState(); + s.Sample(1000, false, false, landblock); + return s; + } + + private static void TransitionHoldsWhileDead() + { + _case = "transition dead"; + var s = Started(); + Check(!s.InTransition(1100), "alive and still: no transition"); + Check(s.Decide(1100, 1050, false) == WorldTransitionState.Verdict.Run, "work runs normally"); + var edges = s.Sample(2000, true, false, 0x00AE); + Check((edges & WorldTransitionState.Edge.Died) != 0, "death edge"); + Check(s.Decide(2000, 1900, false) == WorldTransitionState.Verdict.Hold, "a cast queued before the death is held"); + Check(s.Decide(2000, 1900, true) == WorldTransitionState.Verdict.Hold, "a stop is held too (never run into the death)"); + s.Sample(9000, false, false, 0x00AE); // revived + Check(s.InTransition(9000 + WorldTransitionState.SettleMs - 1), "settle window after revival"); + Check(!s.InTransition(9000 + WorldTransitionState.SettleMs), "window ends"); + } + + private static void TransitionLandblockJumpWithoutPortalHolds() + { + _case = "transition jump"; + // A real case: a death recall jumped 0x00AE -> 0xA9B4 with no portal-space edge. + var s = Started(0x00AE); + var edges = s.Sample(5000, false, false, 0xA9B4); + Check((edges & WorldTransitionState.Edge.LandblockJump) != 0, "jump edge"); + Check(s.InTransition(5000) && s.InTransition(5000 + WorldTransitionState.SettleMs - 1), "the jump alone starts the settle window"); + Check(s.Decide(6000, 4900, false) == WorldTransitionState.Verdict.Hold, "queued work is held after the jump"); + Check(WorldTransitionState.IsJump(0x00AE, 0xA9B4) && !WorldTransitionState.IsJump(0xA9B4, 0xA9B5) && !WorldTransitionState.IsJump(0xA9B4, 0xAAB5), + "adjacent (including diagonal) is not a jump"); + } + + private static void TransitionAdjacentCrossingDoesNotHold() + { + _case = "transition adjacent"; + var s = Started(0xA9B4); + var edges = s.Sample(5000, false, false, 0xA9B5); + Check(edges == WorldTransitionState.Edge.None, "walking into the next landblock: no edge"); + Check(!s.InTransition(5000) && s.Decide(5000, 4990, false) == WorldTransitionState.Verdict.Run, "and no hold"); + } + + private static void TransitionPortalHolds() + { + _case = "transition portal"; + var s = Started(); + s.Sample(2000, false, true, 0x00AE); + Check(s.Decide(2500, 1990, false) == WorldTransitionState.Verdict.Hold, "held in portal space"); + s.Sample(4000, false, false, 0x00AE); + Check(s.InTransition(4000 + WorldTransitionState.SettleMs - 1), "settle window after portal exit"); + } + + /// + /// A recall or portal into the NEXT landblock (a lifestone just over the border): no + /// non-adjacent jump, but teleport_in_progress (the portaling flag) is the signal, and the + /// full settle follows it. + /// + private static void TransitionShortTeleportToAdjacentLandblockHolds() + { + _case = "transition short teleport"; + var s = Started(0xA9B4); + s.Sample(2000, false, true, 0xA9B4); // teleport_in_progress set + s.Sample(2500, false, true, 0xA9B5); // lands one landblock over + var edges = s.Sample(3000, false, false, 0xA9B5); + Check((edges & WorldTransitionState.Edge.PortalExited) != 0, "portal exit edge"); + Check(s.Decide(3000 + WorldTransitionState.SettleMs - 1, 2900, false) == WorldTransitionState.Verdict.Hold, + "full 5 s settle after a teleport to an adjacent landblock"); + Check(s.Decide(3000 + WorldTransitionState.SettleMs, 2900, false) == WorldTransitionState.Verdict.Drop, + "then the stale action is dropped"); + } + + /// Walking across a border never gates, not even for a tick. + private static void TransitionDiagonalAndBorderWalksNeverHold() + { + _case = "transition walk"; + var s = Started(0xA9B4); + long now = 2000; + foreach (uint lb in new uint[] { 0xA9B5, 0xAAB6, 0xA9B5, 0xA8B4, 0xA9B4, 0xAAB3 }) + { + var edges = s.Sample(now, false, false, lb); + Check(edges == WorldTransitionState.Edge.None, $"walk into 0x{lb:X4}: no edge"); + Check(!s.InTransition(now) && s.Decide(now, now - 1, false) == WorldTransitionState.Verdict.Run, $"walk into 0x{lb:X4}: runs at once"); + now += 16; + } + // A cell read of 0 (pose not available for a tick) is not a jump to 0x0000 and back. + s.Sample(now, false, false, 0); + var back = s.Sample(now + 16, false, false, 0xAAB3); + Check(back == WorldTransitionState.Edge.None && !s.InTransition(now + 16), "an unknown pose for one tick is not a jump"); + } + + private static void TransitionTwoLandblockJumpHolds() + { + _case = "transition two-block jump"; + var sx = Started(0xA9B4); + Check((sx.Sample(2000, false, false, 0xABB4) & WorldTransitionState.Edge.LandblockJump) != 0 && sx.InTransition(2000), "2 apart in x: a teleport"); + var sy = Started(0xA9B4); + Check((sy.Sample(2000, false, false, 0xA9B2) & WorldTransitionState.Edge.LandblockJump) != 0 && sy.InTransition(2000), "2 apart in y: a teleport"); + } + + /// + /// The drain the gate sits in (AcMainThreadQueue.Drain): a FIFO walked head to tail, each + /// entry's verdict asked of the gate. While held, nothing runs and nothing is lost; once + /// the transition ends the stale cast and use are dropped, and both stops run, in order. + /// + private static void TransitionDrainHoldThenStopsSurvive() + { + _case = "transition drain"; + var s = Started(); + var fifo = new List<(string What, long At, bool Teardown)> + { + ("cast", 1500, false), + ("autorun-off", 1600, true), + ("use", 1700, false), + ("cancel-attack", 1800, true), + }; + s.Sample(2000, true, false, 0x00AE); // dies + + var ran = new List(); var dropped = new List(); + long revivedAt = 0; + bool queuedNew = false; + for (long now = 2000; now < 20_000; now += 16) + { + // Game tick sample: dead until 9 s, alive after. + s.Sample(now, now < 9000, false, 0x00AE); + if (now >= 9000 && revivedAt == 0) revivedAt = now; + if (!queuedNew && revivedAt != 0 && now >= revivedAt + WorldTransitionState.SettleMs + 500) + { + fifo.Add(("cast-new", now, false)); // queued after the window + queuedNew = true; + } + Drain(s, now, fifo, ran, dropped); + if (revivedAt == 0 || now < revivedAt + WorldTransitionState.SettleMs) + Check(ran.Count == 0 && dropped.Count == 0 && fifo.Count == 4, $"held: nothing runs or drops (t={now})"); + } + Check(dropped.SequenceEqual(new[] { "cast", "use" }), $"stale cast and use dropped, got [{string.Join(",", dropped)}]"); + Check(ran.SequenceEqual(new[] { "autorun-off", "cancel-attack", "cast-new" }), + $"stops run in queue order as a group, then new work, got [{string.Join(",", ran)}]"); + Check(fifo.Count == 0, "queue empty"); + } + + private static void Drain(WorldTransitionState s, long now, List<(string What, long At, bool Teardown)> fifo, + List ran, List dropped) + { + while (fifo.Count > 0) + { + var e = fifo[0]; + var v = s.Decide(now, e.At, e.Teardown); + if (v == WorldTransitionState.Verdict.Hold) return; + fifo.RemoveAt(0); + if (v == WorldTransitionState.Verdict.Drop) dropped.Add(e.What); + else ran.Add(e.What); + } + } + + // ---- fix 7: largest free block ------------------------------------------------------- + + private static void AddressSpaceFold() + { + _case = "address space"; + ulong free = 0, largest = 0; + AddressSpace.Accumulate(true, 10, ref free, ref largest); + AddressSpace.Accumulate(false, 500, ref free, ref largest); + AddressSpace.Accumulate(true, 40, ref free, ref largest); + AddressSpace.Accumulate(true, 30, ref free, ref largest); + Check(free == 80 && largest == 40, $"free 80 largest 40, got {free}/{largest}"); + var (f, l) = AddressSpace.FreeAndLargestMb(); + Check(f > 0 && l > 0 && l <= f, $"live walk of this process: free {f} MB, largest {l} MB"); + } +} diff --git a/tools/EngineRobustnessTests/RingAndGateTests.cs b/tools/EngineRobustnessTests/RingAndGateTests.cs new file mode 100644 index 0000000..e685a0c --- /dev/null +++ b/tools/EngineRobustnessTests/RingAndGateTests.cs @@ -0,0 +1,468 @@ +using System.Text.RegularExpressions; +using RynthCore.Engine; +using RynthCore.Engine.Compatibility; +using RynthCore.Install; + +namespace EngineRobustnessTests; + +/// Checks for the action ring, the mutator gate, appraisal retention, the dump rules and the cast slot. +internal static partial class Program +{ + private static void RunRingAndGateTests() + { + RingTakesAStopWhenFullOfStarts(); + RingRefusesStartsDuringATransition(); + RingStopRunsFirstAfterTheWindow(); + CastStopFindsAnOutOfOrderStop(); + + GateTruthTable(); + GateCallSitesAllUseTheSameShape(); + + RequestIdNeverMergesIntoAHeldEntry(); + + ReleasedDataKeptSoRecreateSkips(); + ReleasedDataExpiresAndServerDeleteEvicts(); + + TeleportMessageStartsTheWindow(); + + OutOfMemoryBoxMatchesOnlyAcsBox(); + LauncherHoldsTheKillDuringADump(); + + // The cast slot, the dump hold cap and the crash exits + CastRefusedDuringATransition(); + RingPeekAtWalksWithoutRemoving(); + EnqueueCastPassesTheTransitionState(); + LauncherDumpHoldIsCapped(); + CrashExitExcludesExitMinusOne(); + CrashExitPathsFlushTheCrashLog(); + } + + // ---- the action ring (the real ActionRing, the one AcMainThreadQueue uses) -------- + + private readonly record struct Act(string What, long At, bool Teardown); + + private static void RingTakesAStopWhenFullOfStarts() + { + _case = "ring reserve"; + var ring = new ActionRing(256, 32); + int queued = 0, full = 0; + for (int i = 0; i < 300; i++) + { + var r = ring.TryEnqueue(new Act("start", 1000, false), teardown: false, inTransition: false); + if (r == ActionRing.Admit.Queued) queued++; + else if (r == ActionRing.Admit.Full) full++; + } + Check(queued == 224 && full == 76, $"300 starts: 224 taken, the rest refused at the reserve (got {queued}/{full})"); + Check(ring.TryEnqueue(new Act("stop", 1001, true), teardown: true, inTransition: false) == ActionRing.Admit.Queued, + "a stop is still taken"); + for (int i = 0; i < 31; i++) + ring.TryEnqueue(new Act("cancel", 1002, true), teardown: true, inTransition: false); + Check(ring.Count == 256, $"the reserve fills only with teardown (count {ring.Count})"); + Check(ring.TryEnqueue(new Act("stop", 1003, true), teardown: true, inTransition: false) == ActionRing.Admit.Full, + "a completely full ring refuses even a stop"); + } + + private static void RingRefusesStartsDuringATransition() + { + _case = "ring transition"; + var ring = new ActionRing(256, 32); + int rejected = 0; + for (int i = 0; i < 300; i++) + if (ring.TryEnqueue(new Act("start", 2000, false), teardown: false, inTransition: true) == ActionRing.Admit.RejectedTransition) + rejected++; + Check(rejected == 300 && ring.Count == 0, $"300 starts during a hold are refused, none stored (rejected {rejected}, count {ring.Count})"); + Check(ring.TryEnqueue(new Act("stop", 2001, true), teardown: true, inTransition: true) == ActionRing.Admit.Queued, + "a stop during the hold is taken"); + } + + /// + /// The flood scenario against the real ring: a bot floods starts before the transition is + /// seen (the ring fills to the reserve), the player dies, 300 more starts arrive during the + /// hold, then a stop. Nothing runs during the hold; after it the stale starts are dropped and + /// the stops are the first things to run. + /// + private static void RingStopRunsFirstAfterTheWindow() + { + _case = "ring drain"; + var ring = new ActionRing(256, 32); + var s = new WorldTransitionState(); + s.Sample(900, false, false, 0x00AE); + for (int i = 0; i < 300; i++) + ring.TryEnqueue(new Act("start", 1000, false), false, s.InTransition(1000)); + s.Sample(1500, true, false, 0x00AE); // dies + for (int i = 0; i < 300; i++) + ring.TryEnqueue(new Act("start-held", 2000, false), false, s.InTransition(2000)); + var stopAdmit = ring.TryEnqueue(new Act("stop", 2500, true), true, s.InTransition(2500)); + Check(stopAdmit == ActionRing.Admit.Queued, $"the stop is accepted ({stopAdmit})"); + + var ran = new List(); + int dropped = 0; + bool heldClean = true; + for (long now = 1500; now < 20_000; now += 16) + { + s.Sample(now, now < 9000, false, 0x00AE); + int before = ring.Count; + if (s.CheckHolding(now)) { heldClean &= ring.Count == before; continue; } // Drain's early return + while (ring.TryDequeue(out Act e)) + { + var v = s.Decide(now, e.At, e.Teardown); + if (v == WorldTransitionState.Verdict.Drop) dropped++; + else ran.Add(e.What); + } + } + Check(heldClean, "nothing leaves the ring while held"); + Check(ran.Count > 0 && ran[0] == "stop", $"the stop runs first after the window (ran [{string.Join(",", ran.Take(3))}])"); + Check(ran.Count == 1 && dropped == 224, $"the 224 stale starts are dropped, nothing else runs (ran {ran.Count}, dropped {dropped})"); + } + + // ---- the cast drain's stop check (the real CastStopRules over the real ActionRing) ------ + + /// + /// A stop queued at or before the cast is found wherever it sits in the ring, including + /// behind an entry stamped after the cast (two producers can land out of time order). + /// + private static void CastStopFindsAnOutOfOrderStop() + { + _case = "cast stop check"; + static bool Any(ActionRing r, long at) => + CastStopRules.AnyStopAtOrBefore(r, at, static e => e.At, static e => e.Teardown); + + var empty = new ActionRing(8, 2); + Check(!Any(empty, 1000), "an empty ring has no stop"); + + var outOfOrder = new ActionRing(8, 2); + outOfOrder.TryEnqueue(new Act("start", 1200, false), false, false); // newer than the cast + outOfOrder.TryEnqueue(new Act("stop", 900, true), true, false); // older, queued behind it + Check(Any(outOfOrder, 1000), "a stop older than the cast, behind a newer entry, is found"); + + var onlyNewer = new ActionRing(8, 2); + onlyNewer.TryEnqueue(new Act("start", 500, false), false, false); + onlyNewer.TryEnqueue(new Act("stop", 1500, true), true, false); + Check(!Any(onlyNewer, 1000), "a stop queued after the cast does not count"); + + var sameTime = new ActionRing(8, 2); + sameTime.TryEnqueue(new Act("stop", 1000, true), true, false); + Check(Any(sameTime, 1000), "a stop queued at the cast's own time counts"); + + var noStop = new ActionRing(8, 2); + noStop.TryEnqueue(new Act("start", 100, false), false, false); + noStop.TryEnqueue(new Act("start", 200, false), false, false); + Check(!Any(noStop, 1000), "older entries that are not stops do not count"); + Check(noStop.Count == 2 && outOfOrder.Count == 2, "the check removes nothing"); + } + + // ---- the mutator gate -------------------------------------------------------- + + private static void GateTruthTable() + { + _case = "mutator gate"; + int asked = 0; + Func holding = () => { asked++; return true; }; + Func clear = () => { asked++; return false; }; + Check(MutatorGate.MustQueue(false, false, false, clear), "off the main thread: queue"); + Check(MutatorGate.MustQueue(false, true, true, clear), "off the main thread, even teardown in a drain: queue"); + Check(!MutatorGate.MustQueue(true, false, false, clear), "main thread, no transition: call now"); + Check(MutatorGate.MustQueue(true, false, false, holding), "main thread in a transition (render-thread host action): queue"); + Check(!MutatorGate.MustQueue(true, true, false, holding), "main thread in a transition, a stop: call now"); + asked = 0; + Check(!MutatorGate.MustQueue(true, false, true, holding) && asked == 0, "called by a drain: call now, without asking the transition state"); + asked = 0; + MutatorGate.MustQueue(false, false, false, holding); + Check(asked == 0, "off the main thread the (main-thread-only) transition state is never asked"); + } + + /// + /// Every AC-mutating helper opens with the same gate: no helper may still decide with the old + /// bare IsOnMainThread() check before an AcMainThreadQueue.Enqueue*, and each stop/cancel + /// passes teardown: true while every other passes false (or !enabled for the two toggles). + /// + private static void GateCallSitesAllUseTheSameShape() + { + _case = "gate call sites"; + string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility")); + Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up"); + if (compat == null) return; + string[] files = { "ClientCombatHooks.cs", "CommandInterpreterHooks.cs", "ClientHelperHooks.cs", "CombatActionHooks.cs", + "MovementActionHooks.cs", "PlayerPhysicsHooks.cs", "PlayerTrade.cs", "PlayerTraining.cs" }; + var enqueue = new Regex(@"AcMainThreadQueue\.(Enqueue\w+)\("); + var gate = new Regex(@"AcMainThreadQueue\.MustQueue\(teardown: (true|false|!enabled)\)"); + string[] teardownTrue = { "EnqueueStopCompletely", "EnqueueStopMovement", "EnqueueCancelAttack", "EnqueueCloseContainer" }; + string[] toggles = { "EnqueueSetAutoRun", "EnqueueSetMotion" }; + int sites = 0, bad = 0; + foreach (string f in files) + { + string[] lines = File.ReadAllLines(Path.Combine(compat, f)); + for (int i = 0; i < lines.Length; i++) + { + Match m = enqueue.Match(lines[i]); + if (!m.Success) continue; + string name = m.Groups[1].Value; + if (name is "EnqueueWriteToChat" or "EnqueueChatCommand") continue; + sites++; + // The gate line is the nearest "if (" line above the enqueue (within 3 lines). + string? gateLine = null; + for (int j = i; j >= Math.Max(0, i - 3); j--) + if (lines[j].TrimStart().StartsWith("if (", StringComparison.Ordinal)) { gateLine = lines[j]; break; } + Match g = gateLine == null ? Match.Empty : gate.Match(gateLine); + string want = teardownTrue.Contains(name) ? "true" : toggles.Contains(name) ? "!enabled" : "false"; + if (!g.Success || g.Groups[1].Value != want || gateLine!.Contains("IsOnMainThread")) + { + bad++; + Console.WriteLine($"[gate] {f}:{i + 1} {name}: gate line '{gateLine?.Trim()}' (want teardown: {want})"); + } + } + } + Check(sites == 45, $"45 gated mutator call sites found (got {sites})"); + Check(bad == 0, $"every one opens with AcMainThreadQueue.MustQueue(teardown: ...) and the right teardown value ({bad} wrong)"); + } + + private static string? FindRepoDir(string relative) + { + string? dir = AppContext.BaseDirectory; + while (dir != null) + { + string candidate = Path.Combine(dir, relative); + if (Directory.Exists(candidate)) return candidate; + dir = Path.GetDirectoryName(dir); + } + return null; + } + + // ---- no merge into an entry a transition will drop ------------------------------- + + private static void RequestIdNeverMergesIntoAHeldEntry() + { + _case = "requestid merge floor"; + var q = new PendingIdQueue(8); + q.Enqueue(42, 1000, 1, 7_500); + // A transition held the drains up to 1500: the entry from 1000 will be dropped. + Check(q.Enqueue(42, 2000, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Queued, + "a request after the window does not merge into the doomed entry"); + Check(q.Count == 2, "so it survives the drop"); + Check(q.Enqueue(42, 2100, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Merged, + "it merges into the new one"); + var r = new PendingIdQueue(8); + r.Enqueue(43, 1000, 1, 7_500); + Check(r.Enqueue(43, 2000, 1, 7_500, mergeOnlyAfterMs: 0) == PendingIdQueue.Result.Merged, "no transition: merges as before"); + } + + // ---- identify data kept across a client release --------------------------------- + + /// + /// Wired as the engine wires them: AppraisalHooks' cache (here a set) keeps an object while + /// ReleasedObjectRetention says so; AutoIdEligibility decides the re-create. + /// + private static void ReleasedDataKeptSoRecreateSkips() + { + _case = "release keeps data"; + var cache = new HashSet(); + var keep = new ReleasedObjectRetention(); + var elig = new AutoIdEligibility(); + long t = 1000; + Check(elig.OnCreate(50, t, cache.Contains(50)) == AutoIdEligibility.CreateDecision.Appraise, "first create: appraised"); + elig.OnSent(50, t + 100); + cache.Add(50); // the identify arrived + // Client release (BeingDeleted): AppraisalHooks.OnClientRelease + if (!keep.OnRelease(50, t + 60_000)) cache.Remove(50); + elig.OnClientRelease(50); + // Re-created 5 minutes later: AutoIdService.Enqueue (MarkLive, then the decision) + keep.Forget(50); + var d = elig.OnCreate(50, t + 5 * 60_000, cache.Contains(50)); + Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created within 10 min with the data kept: skipped ({d})"); + Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})"); + } + + private static void ReleasedDataExpiresAndServerDeleteEvicts() + { + _case = "release expiry"; + var keep = new ReleasedObjectRetention(10 * 60_000, 4); + var expired = new List(); + keep.OnRelease(1, 1000); + keep.OnRelease(2, 2000); + Check(keep.Expire(1000 + 10 * 60_000 - 1, expired) == 0, "kept inside the 10 minutes"); + Check(keep.Expire(2000 + 10 * 60_000, expired) == 2 && expired.SequenceEqual(new uint[] { 1, 2 }), "both dropped once past it"); + Check(keep.Count == 0, "and no longer tracked"); + for (uint i = 10; i < 14; i++) keep.OnRelease(i, 5000); + Check(!keep.OnRelease(99, 5000), "at the bound a release is not kept (the caller evicts it at once)"); + keep.Forget(10); + Check(keep.OnRelease(99, 5000), "room again once one is forgotten (re-created or server-deleted)"); + } + + // ---- 0xF751: the teleport message as its own signal ---------------------------------- + + private static void TeleportMessageStartsTheWindow() + { + _case = "teleport message"; + var s = new WorldTransitionState(); + s.Sample(1000, false, false, 0xA9B4); + Check(!s.InTransition(2000), "no transition before the message"); + Check(s.OnTeleportMessage(2000), "PlayerTeleport received: the window starts"); + // No portal flag, no landblock change, alive: only the message. + s.Sample(2016, false, false, 0xA9B4); + Check(s.InTransition(2000 + WorldTransitionState.SettleMs - 1), "held for the full settle on the message alone"); + Check(s.Decide(3000, 2500, false) == WorldTransitionState.Verdict.Hold, "queued work held"); + Check(!s.InTransition(2000 + WorldTransitionState.SettleMs), "window ends 5 s after it"); + Check(s.Decide(2000 + WorldTransitionState.SettleMs, 2500, false) == WorldTransitionState.Verdict.Drop, "then stale work is dropped"); + Check(!s.OnTeleportMessage(1500), "an older message never shortens a running window"); + } + + // ---- the OOM dump trigger ------------------------------------------------------ + + private static void OutOfMemoryBoxMatchesOnlyAcsBox() + { + _case = "oom box rule"; + // The real text, from a real log line. + const string real = "OUT OF MEMORY: Failed to allocate -778718788 bytes."; + Check(OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: true), "AC's box on its main thread: dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: false), "the same text off the main thread: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("Plugin X: OUT OF MEMORY: Failed to allocate 4 bytes.", true), "prefix not at the start: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("out of memory: failed to allocate 4 bytes.", true), "other case: no dump (ordinal)"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("OUT OF MEMORY", true), "the bare words: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(null, true), "no text: no dump"); + } + + // ---- the launcher holds its kill while a dump is written --------------------------- + + private static void LauncherHoldsTheKillDuringADump() + { + _case = "dump in progress"; + var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc); + string started = $"[18:18:16] {DumpInProgressRule.MarkerStarted} pid=123 - ...\n"; + string ended = $"[18:20:01] {DumpInProgressRule.MarkerEnded} pid=123.\n"; + Check(DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-3), null, now), "marker 3 min old, no end: hold the kill"); + Check(!DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-11), null, now), "marker over 10 min old: a client that died mid-dump is killed"); + Check(!DumpInProgressRule.IsDumping(started + ended, now.AddMinutes(-3), null, now), "dump ended: no hold"); + Check(DumpInProgressRule.IsDumping(started + ended + started, now.AddMinutes(-1), null, now), "the LAST marker decides"); + Check(DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddSeconds(-10), now), "no marker, but the dump file was written 10 s ago: hold"); + Check(!DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddMinutes(-2), now), "a dump file quiet for 2 min: no hold"); + Check(!DumpInProgressRule.IsDumping(null, now, null, now), "nothing at all: no hold"); + } + + // ---- the cast slot refuses during a transition (the real CastSlot) ------------- + + private static void CastRefusedDuringATransition() + { + _case = "cast slot transition"; + var slot = new CastSlot(); + Check(slot.TryEnqueue(0x50000001, 1234, 1000, inTransition: true) == CastSlot.Admit.RejectedTransition, + "an empty slot refuses a cast during a transition"); + Check(slot.Pending == 0 && slot.TargetId == 0 && slot.SpellId == 0 && slot.QueuedAt == 0, + "and stays untouched"); + + Check(slot.TryEnqueue(0x50000002, 99, 2000, inTransition: false) == CastSlot.Admit.Queued, "outside one, a cast is queued"); + Check(slot.TryEnqueue(0x50000003, 77, 2500, inTransition: true) == CastSlot.Admit.RejectedTransition, + "a transition refuses even with a cast pending (counted as a transition refusal, not busy)"); + Check(slot.Pending == 1 && slot.TargetId == 0x50000002 && slot.SpellId == 99 && slot.QueuedAt == 2000, + "the pending cast is unchanged"); + Check(slot.TryEnqueue(0x50000004, 55, 2600, inTransition: false) == CastSlot.Admit.Busy, "busy outside a transition"); + slot.Pending = 0; + Check(slot.TryEnqueue(0x50000005, 66, 9000, inTransition: false) == CastSlot.Admit.Queued + && slot.SpellId == 66 && slot.QueuedAt == 9000, "after the transition, casts queue again"); + + // The drain's once-per-cast stop-wait note belongs to the cast: a new cast clears it, a + // refused one leaves the pending cast's note alone. + slot.StopWaitNoted = true; + Check(slot.TryEnqueue(0x50000006, 67, 9100, inTransition: false) == CastSlot.Admit.Busy && slot.StopWaitNoted, + "a busy refusal keeps the pending cast's stop-wait note"); + slot.Pending = 0; + Check(slot.TryEnqueue(0x50000007, 68, 9200, inTransition: false) == CastSlot.Admit.Queued && !slot.StopWaitNoted, + "a newly queued cast starts with no stop-wait note"); + } + + // ---- The cast drain's walk of the ring (ActionRing.TryPeekAt) -------------------------- + + private static void RingPeekAtWalksWithoutRemoving() + { + _case = "ring peek-at"; + var ring = new ActionRing(8, 2); + Check(!ring.TryPeekAt(0, out _), "an empty ring has nothing at 0"); + // Wrap the ring once so the walk crosses the end of the storage. + for (int i = 0; i < 5; i++) ring.TryEnqueue(new Act("old" + i, i, false), false, false); + for (int i = 0; i < 5; i++) ring.TryDequeue(out _); + for (int i = 0; i < 6; i++) ring.TryEnqueue(new Act("e" + i, 100 + i, i == 4), i == 4, false); + var seen = new List(); + for (int i = 0; ring.TryPeekAt(i, out Act e); i++) seen.Add(e.What); + Check(string.Join(",", seen) == "e0,e1,e2,e3,e4,e5", $"oldest first across the wrap, got [{string.Join(",", seen)}]"); + Check(ring.Count == 6, $"nothing removed (count {ring.Count})"); + Check(!ring.TryPeekAt(6, out _) && !ring.TryPeekAt(-1, out _), "out of range is false"); + Check(ring.TryDequeue(out Act head) && head.What == "e0" && ring.TryPeekAt(0, out Act next) && next.What == "e1", + "after a dequeue, offset 0 is the new oldest"); + } + + private static void EnqueueCastPassesTheTransitionState() + { + _case = "EnqueueCast wiring"; + string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility")); + Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up"); + if (compat == null) return; + string src = File.ReadAllText(Path.Combine(compat, "AcMainThreadQueue.cs")); + int start = src.IndexOf("public static bool EnqueueCast(", StringComparison.Ordinal); + int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal); + string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start); + Check(body.Contains("_cast.TryEnqueue(targetId, spellId, NowMs, PlayerLifecycleLog.InWorldTransition)", StringComparison.Ordinal), + "EnqueueCast hands CastSlot the live transition state"); + Check(Regex.IsMatch(body, @"RejectedTransition\)\s*Interlocked\.Increment\(ref _transitionRejected\)"), + "and counts a refusal in TransitionRejectedCount (the heartbeat's qrej)"); + Check(!Regex.IsMatch(src, @"_cast\.(TargetId|SpellId|QueuedAt)\s*=[^=]"), + "nothing else writes the slot's cast fields"); + } + + // ---- the launcher's dump hold is capped per client -------------------------------- + + private static void LauncherDumpHoldIsCapped() + { + _case = "dump hold cap"; + var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc); + string open = $"hb #1\n[18:00:00] {DumpInProgressRule.MarkerStarted} pid=123 - ...\nhb #2\n"; + DateTime freshLog = now.AddSeconds(-5); + Check(DumpInProgressRule.Decide(open, freshLog, null, null, now) == DumpInProgressRule.Hold.Holding, + "an open marker, first seen now: hold"); + Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-5), now) == DumpInProgressRule.Hold.Holding, + "held 5 min: still holding"); + Check(DumpInProgressRule.Decide(open, freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired, + "fresh log, marker held over 15 min: the kill checks run"); + Check(DumpInProgressRule.Decide("hb #1\n", freshLog, now.AddSeconds(-3), now.AddMinutes(-16), now) == DumpInProgressRule.Hold.Expired, + "a dump file still being written does not extend the cap either"); + Check(DumpInProgressRule.Decide(open, freshLog, null, DateTime.MinValue, now) == DumpInProgressRule.Hold.Expired, + "the launcher's 'expired, logged' mark stays expired"); + Check(DumpInProgressRule.Decide("hb #1\n", freshLog, null, now.AddMinutes(-16), now) == DumpInProgressRule.Hold.None, + "no sign of a dump: None (the launcher forgets the pid)"); + } + + // ---- which exit codes are crash exits --------------------------------------------- + + private static void CrashExitExcludesExitMinusOne() + { + _case = "crash exit rule"; + Check(CrashExitRule.IsCrashExit(0xC0000005u), "0xC0000005 access violation: crash"); + Check(CrashExitRule.IsCrashExit(0xC0000409u), "0xC0000409 stack buffer overrun: crash"); + Check(CrashExitRule.IsCrashExit(0xC0000374u), "0xC0000374 heap corruption: crash"); + Check(CrashExitRule.IsCrashExit(0xC00000FDu), "0xC00000FD stack overflow: crash"); + Check(CrashExitRule.IsCrashExit(0xE0434352u), "0xE0434352 CLR unhandled exception: crash (as before)"); + Check(!CrashExitRule.IsCrashExit(0xFFFFFFFFu), "ExitProcess(-1): not a crash"); + Check(!CrashExitRule.IsCrashExit(0u), "0: not a crash"); + Check(!CrashExitRule.IsCrashExit(1u), "1: not a crash"); + Check(!CrashExitRule.IsCrashExit(0x80000003u), "0x80000003 (warning severity): not a crash"); + Check(!CrashExitRule.IsCrashExit(0x40010004u), "0x40010004 (informational): not a crash"); + } + + private static void CrashExitPathsFlushTheCrashLog() + { + _case = "crash exit flush"; + string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility")); + Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up"); + if (compat == null) return; + string src = File.ReadAllText(Path.Combine(compat, "ProcessExitHooks.cs")); + Check(src.Contains("private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code);", StringComparison.Ordinal), + "ProcessExitHooks uses CrashExitRule"); + foreach (string detour in new[] { "ExitProcessDetour", "TerminateProcessDetour", "RtlExitUserProcessDetour", "NtTerminateProcessDetour" }) + { + int start = src.IndexOf($"private static {(detour.Contains("Terminate") ? (detour.StartsWith("Nt") ? "uint" : "bool") : "void")} {detour}(", StringComparison.Ordinal); + int end = start < 0 ? -1 : src.IndexOf("\n }", start, StringComparison.Ordinal); + string body = start < 0 || end < 0 ? "" : src.Substring(start, end - start); + int flush = body.IndexOf("SehTrampoline.FlushCrashLog(", StringComparison.Ordinal); + int orig = body.IndexOf("Original!(", StringComparison.Ordinal); + Check(flush >= 0 && orig > flush, $"{detour}: a crash exit flushes the crash log before the original"); + } + } +} diff --git a/tools/UsageStatsTests/Program.cs b/tools/UsageStatsTests/Program.cs index aae647b..c0a02ad 100644 --- a/tools/UsageStatsTests/Program.cs +++ b/tools/UsageStatsTests/Program.cs @@ -106,6 +106,18 @@ internal static class Program Make("hang_4_new.dmp", now.AddMinutes(-5)); Check(UsageStats.CountCrashDumps(dumps, now.AddDays(-1), now) == 2, "only crash_*.dmp newer than the last report count (hangs don't)"); Check(UsageStats.CountCrashDumps(Path.Combine(root, "nope"), now.AddDays(-1), now) == 0, "missing dump folder = 0"); + + // CoreCLR fatal-error dumps (the loader's clr__