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..d6a93b1 --- /dev/null +++ b/native/SehTrampoline/CrashLogFilter.h @@ -0,0 +1,143 @@ +/* + * 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. + * - A first-chance AV raised by the .NET Framework (faulting module clr.dll, mscorwks.dll + * or mscorlib, OR in no module with the nearest code pointer on the stack in one of + * those: JIT code) is logged once per address and never charged to the cap. + * - Every other first-chance exception is logged once per address too (an AC fault that + * SEH unwind re-raises costs one entry, not five). The limit is per address, not per + * entry: CLF_MAX_COUNTED distinct addresses, a flood guard only (a repeating fault + * never spends it). + * - Stack overflow and heap corruption are never treated as .NET Framework noise. + * - The last-chance (unhandled) entry is never charged to the limit and has its own small + * one (it happens once in a dying process; the limit only stops a loop). + * - When the address table is full: a new .NET Framework address is not written (counted + * as a repeat); a new other address is still written while under CLF_MAX_COUNTED, + * just no longer de-duplicated, so the logger never goes silent on AC's own faults. + */ +#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_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 + +typedef enum { + CLF_SKIP_CODE = 0, /* not a code the logger writes */ + CLF_LOG_COUNTED, /* write it; charged to the cap */ + CLF_LOG_NETFX, /* write it; .NET Framework first sighting, not charged */ + CLF_LOG_LAST_CHANCE, /* write it; unhandled */ + CLF_SKIP_REPEAT, /* address already written */ + CLF_SKIP_CAP, /* cap reached */ +} clf_decision; + +typedef struct { + unsigned int addrs[CLF_ADDR_SLOTS]; /* first-chance addresses already written */ + unsigned int addrCount; + unsigned int counted; /* entries charged to the cap */ + unsigned int lastChance; + unsigned int netfxRepeats; /* .NET Framework AVs not written (repeats) */ + unsigned int otherRepeats; /* other repeats not written */ + unsigned int overCap; /* not written: cap reached */ +} 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; + } +} + +/* Leaf file name of a module: the .NET Framework runtime or its core library. */ +static int clf_is_netfx_module(const wchar_t* leaf) +{ + return 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"); +} + +/* + * Is this first-chance exception .NET Framework noise? faultModuleNetfx: the faulting + * address is in a .NET Framework module. faultInNoModule: it is in no module (JIT code). + * firstFrameNetfx: the nearest module-resolved code pointer on the stack is in one. + */ +static int clf_is_netfx_fault(unsigned int code, int faultModuleNetfx, int faultInNoModule, int firstFrameNetfx) +{ + if (code != CLF_CODE_ACCESS_VIOLATION) return 0; + return faultModuleNetfx || (faultInNoModule && firstFrameNetfx); +} + +static int clf_seen(const clf_state* s, unsigned int addr) +{ + unsigned int i; + for (i = 0; i < s->addrCount; i++) + if (s->addrs[i] == addr) return 1; + return 0; +} + +static int clf_remember(clf_state* s, unsigned int addr) +{ + if (s->addrCount >= CLF_ADDR_SLOTS) return 0; + s->addrs[s->addrCount++] = addr; + return 1; +} + +/* A first-chance exception (vectored handler). */ +static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned int exAddr, int netfx) +{ + if (!clf_is_logged_code(code)) return CLF_SKIP_CODE; + if (clf_seen(s, exAddr)) { + if (netfx) s->netfxRepeats++; else s->otherRepeats++; + return CLF_SKIP_REPEAT; + } + if (netfx) { + if (!clf_remember(s, exAddr)) { s->netfxRepeats++; return CLF_SKIP_REPEAT; } + return CLF_LOG_NETFX; + } + if (s->counted >= CLF_MAX_COUNTED) { s->overCap++; return CLF_SKIP_CAP; } + s->counted++; + clf_remember(s, exAddr); /* full table: still logged, just not de-duplicated */ + return CLF_LOG_COUNTED; +} + +/* 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..176752d 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -220,25 +220,55 @@ 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; the + * .NET Framework's handled null references not charged to the cap; a last-chance + * entry always). Each entry carries the process 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" + static wchar_t g_crashLogPath[MAX_PATH]; -static volatile LONG g_crashCount = 0; 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 char g_buf[4096]; /* under g_logOwner */ +static wchar_t g_wpath[MAX_PATH]; /* under g_logOwner */ + +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,17 +290,31 @@ static char* cl_u(char* p, unsigned int v) return p; } +static char* cl_u2(char* p, unsigned int v) { if (v < 10) { *p++ = '0'; } return cl_u(p, v); } + +/* Module containing addr, or NULL. Under the lock: fills g_wpath and returns its leaf. */ +static const wchar_t* cl_module(unsigned int addr, HMODULE* out) +{ + HMODULE hm = NULL; + DWORD n, i, leaf = 0; + *out = NULL; + /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ + 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; } + *out = hm; + return g_wpath + leaf; +} + /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ static char* cl_sym(char* p, unsigned int addr) { - HMODULE hm = 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]; } + HMODULE hm; + const wchar_t* leaf = cl_module(addr, &hm); + if (leaf) { + while (*leaf) { *p++ = (char)*leaf++; } p = cl_str(p, "+"); p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); } else { @@ -279,99 +323,164 @@ static char* cl_sym(char* p, unsigned int addr) return p; } -static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +/* Nearest module-resolved code pointer on the stack is in the .NET Framework? */ +static int cl_first_frame_netfx(unsigned int esp) { - DWORD code = ep->ExceptionRecord->ExceptionCode; - if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { - return EXCEPTION_CONTINUE_SEARCH; - } - if (InterlockedIncrement(&g_crashCount) > 24) { - return EXCEPTION_CONTINUE_SEARCH; + int result = 0; + __try { + unsigned int* sp = (unsigned int*)(UINT_PTR)esp; + int i; + for (i = 0; i < 512; i++) { + unsigned int v = sp[i]; + if (v > 0x00401000u && v < 0x7FFF0000u) { + HMODULE hm; + const wchar_t* leaf = cl_module(v, &hm); + if (leaf) { result = clf_is_netfx_module(leaf); break; } + } + } } + __except (EXCEPTION_EXECUTE_HANDLER) { result = 0; } + return result; +} + +static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind) +{ + 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; } + SetFilePointer(h, 0, NULL, FILE_END); { - HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL); - if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } - SetFilePointer(h, 0, NULL, FILE_END); + char* p = g_buf; + CONTEXT* c = ep->ContextRecord; + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + DWORD wr; + SYSTEMTIME st; - { - char buf[4096]; - char* p = buf; - CONTEXT* c = ep->ContextRecord; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; - DWORD wr; + p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER ("); + 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); + 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); + 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, " netfxRepeats="); + p = cl_u(p, g_filter.netfxRepeats); + 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); + 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, g_buf, (DWORD)(p - g_buf), &wr, NULL); - 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++; - } + __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) { + HMODULE hm = NULL; + if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { + 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); + q = cl_str(q, "\r\n"); + WriteFile(h, g_buf, (DWORD)(q - g_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); - } } - CloseHandle(h); + __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); + } + } + CloseHandle(h); +} + +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; + HMODULE hm; + const wchar_t* leaf = cl_module(exAddr, &hm); + int netfx = clf_is_netfx_fault(code, + leaf != NULL && clf_is_netfx_module(leaf), + leaf == NULL, + leaf == NULL && code == 0xC0000005 ? cl_first_frame_netfx(ep->ContextRecord->Esp) : 0); + clf_decision d = clf_first_chance(&g_filter, code, exAddr, netfx); + if (d == CLF_LOG_COUNTED) + cl_write_entry(ep, "first-chance"); + else if (d == CLF_LOG_NETFX) + cl_write_entry(ep, "first-chance, .NET Framework, once per address, not counted"); + } + 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()) { + if (clf_last_chance(&g_filter) == CLF_LOG_LAST_CHANCE) + cl_write_entry(ep, "LAST-CHANCE, unhandled"); + 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. */ +/* Install the VEH and the last-chance filter once. logPath = wide path to the dedicated crash log. */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { @@ -382,6 +491,7 @@ RC_InstallCrashLogger(const wchar_t* logPath) g_crashLogPath[i] = 0; } 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..2abb8f5 --- /dev/null +++ b/native/SehTrampoline/tests/CrashLogFilterTests.c @@ -0,0 +1,118 @@ +/* + * CrashLogFilterTests.c - offline checks for CrashLogFilter.h (the native crash logger's + * filter). Build and run (x86 or x64 cl, from a VS developer prompt): + * cl /nologo /W4 /Fe:\clf_tests.exe CrashLogFilterTests.c + * \clf_tests.exe (exit 0 = pass, 1 = fail) + */ +#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); +} + +/* Seen in a real log: 24 handled .NET Framework AVs at ONE address spent the cap, + * and the fatal AC fault later was never written. */ +static void netfx_noise_never_spends_the_cap(void) +{ + clf_state s = {0}; + int i, logged = 0; + for (i = 0; i < 500; i++) { + clf_decision d = clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x433620C8u, 1); + if (d == CLF_LOG_NETFX) logged++; + } + check(logged == 1, "the repeating JIT-code AV is written once"); + check(s.counted == 0, "and never charged to the limit"); + check(s.netfxRepeats == 499, "repeats are counted"); + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x0055FA24u, 0) == CLF_LOG_COUNTED, + "a later AC fault is still written"); +} + +static void other_faults_dedupe_per_address(void) +{ + clf_state s = {0}; + unsigned int a; + int i; + for (i = 0; i < 50; i++) + clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00416C86u, 0); + check(s.counted == 1 && s.otherRepeats == 49, "a repeating AC fault costs one entry"); + for (a = 1; a < CLF_MAX_COUNTED; a++) + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00500000u + a * 16, 0) == CLF_LOG_COUNTED, + "distinct addresses written up to the limit"); + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00600000u, 0) == CLF_SKIP_CAP, + "past the limit: skipped"); + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00416C86u, 0) == CLF_SKIP_REPEAT, + "a known address is a repeat, not a cap hit"); +} + +static void codes(void) +{ + clf_state s = {0}; + check(clf_first_chance(&s, 0xC00000FDu, 0x1000u, 0) == CLF_LOG_COUNTED, "stack overflow is logged"); + check(clf_first_chance(&s, 0xC0000374u, 0x2000u, 0) == CLF_LOG_COUNTED, "heap corruption is logged"); + check(clf_first_chance(&s, 0xC0000409u, 0x3000u, 0) == CLF_LOG_COUNTED, "stack buffer overrun is logged"); + check(clf_first_chance(&s, 0xC0000602u, 0x4000u, 0) == CLF_LOG_COUNTED, "fail-fast is logged"); + check(clf_first_chance(&s, 0xE06D7363u, 0x5000u, 0) == CLF_SKIP_CODE, "a C++ exception is not"); + check(clf_first_chance(&s, 0x80000003u, 0x6000u, 0) == CLF_SKIP_CODE, "a breakpoint is not"); +} + +static void netfx_classification(void) +{ + check(clf_is_netfx_module(L"clr.dll") && clf_is_netfx_module(L"MSCORLIB.NI.DLL") + && clf_is_netfx_module(L"mscorwks.dll") && clf_is_netfx_module(L"mscorlib.dll"), + "the .NET Framework modules match, any case"); + check(!clf_is_netfx_module(L"coreclr.dll") && !clf_is_netfx_module(L"acclient.exe") + && !clf_is_netfx_module(L"clr.dllx") && !clf_is_netfx_module(0), + "CoreCLR, AC and near-misses do not"); + check(clf_is_netfx_fault(CLF_CODE_ACCESS_VIOLATION, 1, 0, 0), "an AV in clr.dll is noise"); + check(clf_is_netfx_fault(CLF_CODE_ACCESS_VIOLATION, 0, 1, 1), "an AV in JIT code under clr frames is noise"); + check(!clf_is_netfx_fault(CLF_CODE_ACCESS_VIOLATION, 0, 1, 0), "an AV in no module under AC frames is not"); + check(!clf_is_netfx_fault(CLF_CODE_STACK_OVERFLOW, 1, 0, 0), "a stack overflow is never noise"); + check(!clf_is_netfx_fault(CLF_CODE_HEAP_CORRUPTION, 1, 0, 0), "heap corruption is never noise"); +} + +static void last_chance_is_separate(void) +{ + clf_state s = {0}; + unsigned int a; + int i, logged = 0; + for (a = 0; a < CLF_MAX_COUNTED + 5; a++) + clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00700000u + a * 16, 0); + 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_never_silences_ac_faults(void) +{ + clf_state s = {0}; + unsigned int a; + for (a = 0; a < CLF_ADDR_SLOTS; a++) + clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x40000000u + a * 16, 1); /* netfx fills it */ + check(s.addrCount == CLF_ADDR_SLOTS && s.counted == 0, "table full of .NET Framework addresses"); + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x41000000u, 1) == CLF_SKIP_REPEAT, + "a new .NET Framework address is no longer written"); + check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x0055FA24u, 0) == CLF_LOG_COUNTED, + "an AC fault still is"); +} + +int main(void) +{ + netfx_noise_never_spends_the_cap(); + other_faults_dedupe_per_address(); + codes(); + netfx_classification(); + last_chance_is_separate(); + full_table_never_silences_ac_faults(); + 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.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 1544ef3..f847ac0 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -246,6 +246,29 @@ 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) => e.Kind switch + { + ActionKind.SetAutoRun => e.A == 0, + ActionKind.SetMotion => e.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)", @@ -524,14 +547,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,6 +573,13 @@ 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): in a world transition the + // pending value is discarded, never applied late in the next world. + if (holding) + { + if (Interlocked.Exchange(ref _directHeadingPending, 0) != 0) NoteTransitionDrop("heading", 0); + if (Interlocked.Exchange(ref _overlaySelectPending, 0) != 0) NoteTransitionDrop("overlay select", 0); + } DrainDirectHeading(); // Overlay click-to-select (Radar dot / nameplate click): also before the @@ -550,6 +589,12 @@ internal static class AcMainThreadQueue 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) ───────────────────────────────────────────────── // Every ring action perturbs AC's action/motion state to some degree: @@ -582,6 +627,12 @@ internal static class AcMainThreadQueue 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); + tail = Volatile.Read(ref _tail); + continue; + } if (e.Epoch != epochNow || (age > StaleActionMs && DropsWhenStale(e))) { NoteStale(Describe(e) + (e.Epoch != epochNow ? " (queued before this login)" : ""), age, dropped: true); @@ -733,22 +784,34 @@ 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; lock (_requestIdLock) { - if (_requestIdQueue.Count >= MaxRequestIdQueue) + PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), RequestIdMergeMaxAgeMs); + if (r == PendingIdQueue.Result.Full) { Interlocked.Increment(ref _dropped); return false; } - _requestIdQueue.Enqueue((objectId, NowMs, Volatile.Read(ref _loginEpoch))); return true; } } @@ -760,22 +823,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 +897,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 +913,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 { } } } @@ -1026,7 +1110,8 @@ internal static class AcMainThreadQueue // 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() { if (_disarmed) return; // engine teardown in progress @@ -1049,7 +1134,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 _castQueuedAt); + 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 = _castSpellId; _castPending = 0; } + NoteTransitionDrop($"CastSpell({droppedSpell})", nowCast - queuedAt); + return; + } + + long castAge = nowCast - queuedAt; if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) { if (castAge <= CastDeferMaxMs) 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/AutoIdEligibility.cs b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs new file mode 100644 index 0000000..f098160 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs @@ -0,0 +1,183 @@ +// ============================================================================ +// 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; + + /// 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; + return recent && appraisalCached ? CreateDecision.SkipRecent : 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..56dbc10 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,14 @@ internal static class AutoIdService private static Timer? _drainTimer; private static bool _started; + private static long _skippedRecent, _skippedPriorityFresh; + + /// Re-creates not appraised because a recent appraisal is still cached. + public static long SkippedRecentCount => Interlocked.Read(ref _skippedRecent); + + /// 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 +76,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 +89,54 @@ internal static class AutoIdService if (playerId != 0 && objectId == playerId) return; - // Skip if already sent this session - if (!_sent.TryAdd(objectId, 0)) - return; + 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); + else if (decision == AutoIdEligibility.CreateDecision.SkipRecent) + Interlocked.Increment(ref _skippedRecent); } /// - /// 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); + } + + /// + /// 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) { @@ -93,19 +145,30 @@ internal static class AutoIdService if (!CombatActionHooks.HasRequestId) 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 +176,37 @@ 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)."); + } } catch { } } diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index 7755d56..e8cb7ec 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -507,21 +507,20 @@ internal static class CombatActionHooks if (!MainThreadGuard.IsOnMainThread()) 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/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..cdd1c21 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -155,8 +155,20 @@ 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 { } + // 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 diff --git a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs index 75464d9..e135f32 100644 --- a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs +++ b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs @@ -105,8 +105,13 @@ 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 { } diff --git a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs index cf264b6..55d7ad9 100644 --- a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs @@ -52,6 +52,15 @@ 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); + + /// The text AC's out-of-memory box carries ("OUT OF MEMORY: Failed to allocate N bytes."). + internal const string OutOfMemoryMarker = "OUT OF MEMORY"; public static void Initialize() { @@ -114,10 +123,18 @@ internal static class MessageBoxHooks { MessageBoxDelegate? original = wide ? _originalW : _originalA; string? description = null; + bool mainThread = false; long opened = Environment.TickCount64; try { - description = Opened(text, caption, type, wide); + description = Opened(text, caption, type, wide, out mainThread, out bool outOfMemory); + // 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. Write ONE + // full-memory dump now, before the box shows (blocking this thread until it is + // written: the box would hold it anyway, and the user's OK must not let AC run on + // and exit mid-dump). + if (outOfMemory) + CrashDump.WriteOutOfMemoryDumpOnce(description); } catch { /* observation only: never block the dialog */ } @@ -127,6 +144,8 @@ internal static class MessageBoxHooks { long secs = (Environment.TickCount64 - opened) / 1000; RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); + if (mainThread && Interlocked.Decrement(ref _mainThreadOpenCount) < 0) + Interlocked.Exchange(ref _mainThreadOpenCount, 0); if (Interlocked.Decrement(ref _openCount) <= 0) { Interlocked.Exchange(ref _openCount, 0); @@ -137,11 +156,14 @@ internal static class MessageBoxHooks return result; } - private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide) + private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide, out bool mainThread, out bool outOfMemory) { string body = Read(text, wide); string title = Read(caption, wide); - bool mainThread = MainThreadGuard.IsOnMainThread(); + mainThread = MainThreadGuard.IsOnMainThread(); + // Counted first: the freeze gate must see the box even if the rest of this throws. + if (mainThread) Interlocked.Increment(ref _mainThreadOpenCount); + outOfMemory = body.Contains(OutOfMemoryMarker, StringComparison.OrdinalIgnoreCase); // The first frame outside user32 and this file: who asked for the dialog. string caller = "?"; diff --git a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs new file mode 100644 index 0000000..9cf5e07 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs @@ -0,0 +1,108 @@ +// ============================================================================ +// 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 . + /// + public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs) + { + 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) + { + 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..5cf8b38 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,29 @@ 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) => _state.CheckHolding(nowMs); + + /// 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) => + _state.Decide(nowMs, queuedAtMs, teardown); /// AC main thread, once per game tick. public static void SampleOnGameThread(bool portaling) @@ -52,51 +67,31 @@ 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 (landblock != 0 && _landblock != 0 && landblock != _landblock) + 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) { - 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)" : "")}."); + _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 (landblock != 0) _landblock = landblock; + 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."); } private static string Ago(long since, long now) => diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index a537b87..5a35d48 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) @@ -283,38 +185,26 @@ 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\Clr.c). This + // replaces the managed crash dump written here before, which left nothing for real crashes. + private static bool IsCrashExit(uint code) => code >= 0xC0000000u; + 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) - { + if (selfKill && !IsCrashExit(exitCode)) LogTermination("TerminateProcess", hProcess, exitCode); - DumpCrashOnce("TerminateProcess", 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(); @@ -331,59 +221,12 @@ internal static class ProcessExitHooks private static uint NtTerminateProcessDetour(IntPtr processHandle, uint exitStatus) { bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle(); - if (selfKill) - { + if (selfKill && !IsCrashExit(exitStatus)) LogTermination("NtTerminateProcess", processHandle, exitStatus); - DumpCrashOnce("NtTerminateProcess", 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/WorldTransitionState.cs b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs new file mode 100644 index 0000000..7287fd8 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs @@ -0,0 +1,132 @@ +// ============================================================================ +// 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; + } + + /// 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..4578833 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,159 @@ 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; + try + { + RynthLog.Error("CrashDump: AC OUT OF MEMORY box opening - writing one full-memory dump before it shows."); + Thread? writer = null; + try + { + writer = new Thread(() => WriteOutOfMemoryDumpCore(why)) { 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. + RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); + writer = null; + } + if (writer == null) + WriteOutOfMemoryDumpCore(why); + else if (!writer.Join(FullDumpWaitMs)) + RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open."); + } + catch (Exception ex) + { + RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); + } + finally + { + _fullDumpInProgress = false; + } + } + + private static void WriteOutOfMemoryDumpCore(string reason) + { + try + { + string dir = OutOfMemoryDumpDirectory; + Directory.CreateDirectory(dir); + // Room for the new one first: keep the newest (Kept - 1), so the folder never holds + // more than Kept full dumps even while this one is written. + PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept - 1); + + 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}"); + } + else + { + RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead."); + WriteSelfDump(reason, out _, "oom-small"); + } + PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept); + } + catch (Exception ex) + { + RynthLog.Error($"CrashDump: OOM dump writer failed {ex.GetType().Name}: {ex.Message}"); + } + } + + /// Deletes all but the newest *.dmp files in . 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)); + for (int i = Math.Max(0, keep); i < files.Length; i++) + { + try + { + files[i].Delete(); + deleted++; + RynthLog.Info($"CrashDump: pruned old dump {files[i].Name} ({files[i].Length / (1024 * 1024)}MB)."); + } + catch { /* in use by a debugger, or already gone */ } + } + } + catch { } + return deleted; + } } 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..3705784 --- /dev/null +++ b/src/RynthCore.Engine/MainThreadFreezeRule.cs @@ -0,0 +1,83 @@ +// ============================================================================ +// 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; + } +} + +/// 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/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj new file mode 100644 index 0000000..0525534 --- /dev/null +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -0,0 +1,31 @@ + + + + + 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..7b22b51 --- /dev/null +++ b/tools/EngineRobustnessTests/Program.cs @@ -0,0 +1,410 @@ +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 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(); + + 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"); + } +}