diff --git a/native/SehTrampoline/CrashLogFilter.h b/native/SehTrampoline/CrashLogFilter.h index d6a93b1..a28e0d2 100644 --- a/native/SehTrampoline/CrashLogFilter.h +++ b/native/SehTrampoline/CrashLogFilter.h @@ -15,26 +15,34 @@ * 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. + * - Each faulting address has a slot with its hit count and the time it was last + * written. The first sighting is written. A repeat is written again (with its count) + * when the count is a power of two, when 30 s have passed since that address was + * last written, or when the code is not an AV. So a contained AV that later recurs + * as the fatal one is not swallowed as "seen before": a fatal fault is usually a + * terminate from some handler, and then no last-chance filter ever runs. + * - Noise is classified, written once per address like the rest, and never charged to + * the AC limit: + * .NET Framework (Decal plugins): faulting module clr.dll, mscorwks.dll, mscorlib; + * managed (the engine's CoreCLR): coreclr.dll, clrjit.dll, System.Private.CoreLib; + * or no module at all (JIT code) with the nearest module-resolved code pointer on the + * stack in one of those. Only AVs are ever noise. + * - A first sighting of anything else (AC's faults) is charged to CLF_MAX_COUNTED, a + * flood guard on DISTINCT addresses only. + * - The last-chance (unhandled) entry is never charged to that limit and has its own + * small one (it happens once in a dying process; the limit only stops a loop). + * - A full address table evicts its least recently written NOISE slot. With no noise + * slot to evict, an AC address is still written (under the limit), just not tracked. + * + * Times are GetTickCount milliseconds (32-bit; unsigned subtraction survives the wrap). */ #ifndef RYNTHCORE_CRASH_LOG_FILTER_H #define RYNTHCORE_CRASH_LOG_FILTER_H -#define CLF_MAX_COUNTED 96 -#define CLF_MAX_LAST_CHANCE 8 -#define CLF_ADDR_SLOTS 128 +#define CLF_MAX_COUNTED 96 +#define CLF_MAX_LAST_CHANCE 8 +#define CLF_ADDR_SLOTS 128 +#define CLF_RELOG_MS 30000u #define CLF_CODE_ACCESS_VIOLATION 0xC0000005u #define CLF_CODE_FAIL_FAST 0xC0000602u @@ -42,23 +50,39 @@ #define CLF_CODE_STACK_OVERFLOW 0xC00000FDu #define CLF_CODE_HEAP_CORRUPTION 0xC0000374u +/* What raised a fault. Anything but CLF_CLASS_AC is noise. */ +typedef enum { + CLF_CLASS_AC = 0, /* AC, Decal native code, the engine's native code: counted */ + CLF_CLASS_NETFX = 1, /* the .NET Framework (Decal's managed plugins) */ + CLF_CLASS_MANAGED = 2, /* the engine's CoreCLR runtime and its JIT code */ +} clf_class; + typedef enum { CLF_SKIP_CODE = 0, /* not a code the logger writes */ - CLF_LOG_COUNTED, /* write it; charged to the cap */ - CLF_LOG_NETFX, /* write it; .NET Framework first sighting, not charged */ + CLF_LOG_COUNTED, /* write it; first sighting, charged to the limit */ + CLF_LOG_NOISE, /* write it; first sighting of noise, not charged */ + CLF_LOG_REPEAT, /* write it again; a repeat (see hits) */ CLF_LOG_LAST_CHANCE, /* write it; unhandled */ - CLF_SKIP_REPEAT, /* address already written */ - CLF_SKIP_CAP, /* cap reached */ + CLF_SKIP_REPEAT, /* a repeat not due to be written */ + CLF_SKIP_CAP, /* limit 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 addr; + unsigned int hits; /* sightings, the first included */ + unsigned int lastWriteMs; + unsigned char cls; /* clf_class */ + unsigned char used; +} clf_slot; + +typedef struct { + clf_slot slots[CLF_ADDR_SLOTS]; + unsigned int counted; /* AC first sightings charged to the limit */ unsigned int lastChance; - unsigned int netfxRepeats; /* .NET Framework AVs not written (repeats) */ - unsigned int otherRepeats; /* other repeats not written */ - unsigned int overCap; /* not written: cap reached */ + unsigned int noiseRepeats; /* noise repeats not written */ + unsigned int otherRepeats; /* other repeats not written */ + unsigned int overCap; /* not written: limit reached */ + unsigned int untracked; /* AC addresses written but not tracked (table full of AC) */ } clf_state; static int clf_is_logged_code(unsigned int code) @@ -81,55 +105,102 @@ static int clf_wide_ieq(const wchar_t* a, const char* b) } } -/* Leaf file name of a module: the .NET Framework runtime or its core library. */ -static int clf_is_netfx_module(const wchar_t* leaf) +/* Class of a module, by its leaf file name. */ +static clf_class clf_module_class(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"); + if (clf_wide_ieq(leaf, "clr.dll") || clf_wide_ieq(leaf, "mscorwks.dll") + || clf_wide_ieq(leaf, "mscorlib.dll") || clf_wide_ieq(leaf, "mscorlib.ni.dll")) + return CLF_CLASS_NETFX; + if (clf_wide_ieq(leaf, "coreclr.dll") || clf_wide_ieq(leaf, "clrjit.dll") + || clf_wide_ieq(leaf, "System.Private.CoreLib.dll")) + return CLF_CLASS_MANAGED; + return CLF_CLASS_AC; } /* - * 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. + * Class of a first-chance exception. faultClass: class of the faulting module (AC when in + * no module). faultInNoModule: the faulting address is in no module (JIT code). + * firstFrameClass: class of the nearest module-resolved code pointer on the stack. */ -static int clf_is_netfx_fault(unsigned int code, int faultModuleNetfx, int faultInNoModule, int firstFrameNetfx) +static clf_class clf_classify(unsigned int code, clf_class faultClass, int faultInNoModule, clf_class firstFrameClass) { - if (code != CLF_CODE_ACCESS_VIOLATION) return 0; - return faultModuleNetfx || (faultInNoModule && firstFrameNetfx); + if (code != CLF_CODE_ACCESS_VIOLATION) return CLF_CLASS_AC; + if (faultClass != CLF_CLASS_AC) return faultClass; + if (faultInNoModule) return firstFrameClass; + return CLF_CLASS_AC; } -static int clf_seen(const clf_state* s, unsigned int addr) +static clf_slot* clf_find(clf_state* s, unsigned int addr) { - unsigned int i; - for (i = 0; i < s->addrCount; i++) - if (s->addrs[i] == addr) return 1; + int i; + for (i = 0; i < CLF_ADDR_SLOTS; i++) + if (s->slots[i].used && s->slots[i].addr == addr) return &s->slots[i]; return 0; } -static int clf_remember(clf_state* s, unsigned int addr) +static int clf_is_pow2(unsigned int v) { return v != 0 && (v & (v - 1)) == 0; } + +/* A repeat at a tracked address. *hits gets the sighting count. */ +static clf_decision clf_repeat(clf_state* s, clf_slot* slot, unsigned int code, unsigned int nowMs, unsigned int* hits) { - if (s->addrCount >= CLF_ADDR_SLOTS) return 0; - s->addrs[s->addrCount++] = addr; - return 1; + slot->hits++; + if (hits) *hits = slot->hits; + if (clf_is_pow2(slot->hits) || nowMs - slot->lastWriteMs >= CLF_RELOG_MS || code != CLF_CODE_ACCESS_VIOLATION) { + slot->lastWriteMs = nowMs; + return CLF_LOG_REPEAT; + } + if (slot->cls != CLF_CLASS_AC) s->noiseRepeats++; else s->otherRepeats++; + return CLF_SKIP_REPEAT; } -/* A first-chance exception (vectored handler). */ -static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned int exAddr, int netfx) +/* A free slot, else the least recently written noise slot, else none. */ +static clf_slot* clf_take_slot(clf_state* s) { + clf_slot* oldest = 0; + int i; + for (i = 0; i < CLF_ADDR_SLOTS; i++) + if (!s->slots[i].used) return &s->slots[i]; + for (i = 0; i < CLF_ADDR_SLOTS; i++) { + clf_slot* c = &s->slots[i]; + if (c->cls == CLF_CLASS_AC) continue; + if (!oldest || (int)(c->lastWriteMs - oldest->lastWriteMs) < 0) oldest = c; + } + return oldest; +} + +/* First sighting of an address (clf_find found nothing). */ +static clf_decision clf_new(clf_state* s, unsigned int code, unsigned int addr, clf_class cls, unsigned int nowMs) +{ + clf_slot* slot; + if (cls == CLF_CLASS_AC) { + if (s->counted >= CLF_MAX_COUNTED) { s->overCap++; return CLF_SKIP_CAP; } + s->counted++; + } + slot = clf_take_slot(s); + if (slot) { + slot->addr = addr; + slot->hits = 1; + slot->lastWriteMs = nowMs; + slot->cls = (unsigned char)cls; + slot->used = 1; + } else { + s->untracked++; + } + (void)code; + return cls == CLF_CLASS_AC ? CLF_LOG_COUNTED : CLF_LOG_NOISE; +} + +/* The whole first-chance decision in one call (the logger splits it to skip the module + * lookup for repeats). *hits gets the sighting count (1 for a first sighting). */ +static clf_decision clf_first_chance(clf_state* s, unsigned int code, unsigned int addr, clf_class cls, + unsigned int nowMs, unsigned int* hits) +{ + clf_slot* slot; + if (hits) *hits = 1; if (!clf_is_logged_code(code)) return CLF_SKIP_CODE; - 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; + slot = clf_find(s, addr); + if (slot) return clf_repeat(s, slot, code, nowMs, hits); + return clf_new(s, code, addr, cls, nowMs); } /* The last-chance (unhandled) filter. Any code: whatever reaches it is fatal. */ diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index 176752d..4bbc3da 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -230,9 +230,10 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, * 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. + * Which entries are written is CrashLogFilter.h's rule (once per address, a repeat + * again at a power-of-two count or after 30 s; .NET Framework and CoreCLR noise not + * charged to the limit; a last-chance entry always). Each entry carries the process id, + * thread id, date and time. * * This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so * unlike the removed managed CrashLogger VEH it cannot itself re-trigger a @@ -247,13 +248,46 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, */ #include "CrashLogFilter.h" +/* + * Exception time does as little as it can: the address dedupe runs first (most + * exceptions are repeats and stop there), module names come from a cache built + * outside exception time (install, then RC_RefreshCrashLoggerModules from the engine's + * heartbeat), and the log file is opened once at install, so writing an entry is + * formatting plus WriteFile. Only an address the cache does not cover (a module loaded + * since the last refresh) falls back to GetModuleHandleExW, for the faulting address + * and eip only. + */ + +#define CL_MOD_MAX 384 + +typedef struct { + unsigned int base, end; /* [base, end) */ + unsigned char cls; /* clf_class */ + char leaf[48]; /* ASCII leaf name, truncated */ +} cl_mod; + +typedef struct { + cl_mod mods[CL_MOD_MAX]; + int count; +} cl_mod_table; + static wchar_t g_crashLogPath[MAX_PATH]; +static HANDLE g_logHandle = INVALID_HANDLE_VALUE; static PVOID g_vehHandle = NULL; static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL; static volatile LONG g_logOwner = 0; /* thread id holding the logger, 0 = free */ static clf_state g_filter; /* under g_logOwner */ static char g_buf[4096]; /* under g_logOwner */ static wchar_t g_wpath[MAX_PATH]; /* under g_logOwner */ +static char g_fallbackLeaf[48]; /* under g_logOwner */ +static cl_mod_table g_modTables[2]; /* double buffer: refresh builds the inactive one */ +static volatile LONG g_modActive = -1; /* index of the published table, -1 = none */ +static volatile LONG g_modRefreshing = 0; + +typedef BOOL (WINAPI *PFN_EnumMods)(HANDLE, HMODULE*, DWORD, LPDWORD); +typedef BOOL (WINAPI *PFN_ModInfo)(HANDLE, HMODULE, void*, DWORD); +typedef DWORD (WINAPI *PFN_BaseName)(HANDLE, HMODULE, LPWSTR, DWORD); +typedef struct { LPVOID lpBaseOfDll; DWORD SizeOfImage; LPVOID EntryPoint; } cl_modinfo; static int cl_lock(void) { @@ -292,153 +326,223 @@ static char* cl_u(char* p, unsigned int v) 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) +/* + * Rebuild the module cache (NOT at exception time: it takes the loader lock). Builds the + * table no reader is using and publishes it with one interlocked store; refreshes are + * serialized and seconds apart, so a reader never sees its table rebuilt under it. + */ +__declspec(dllexport) void __cdecl +RC_RefreshCrashLoggerModules(void) { + static PFN_EnumMods pEnum; + static PFN_ModInfo pInfo; + static PFN_BaseName pName; + HMODULE mods[CL_MOD_MAX]; + DWORD needed = 0, n, i; + HANDLE self = GetCurrentProcess(); + LONG active, next; + cl_mod_table* t; + if (InterlockedCompareExchange(&g_modRefreshing, 1, 0) != 0) return; + if (!pEnum) { + HMODULE k32 = GetModuleHandleW(L"kernel32.dll"); + pEnum = (PFN_EnumMods)GetProcAddress(k32, "K32EnumProcessModules"); + pInfo = (PFN_ModInfo)GetProcAddress(k32, "K32GetModuleInformation"); + pName = (PFN_BaseName)GetProcAddress(k32, "K32GetModuleBaseNameW"); + } + if (!pEnum || !pInfo || !pName || !pEnum(self, mods, sizeof(mods), &needed)) { + InterlockedExchange(&g_modRefreshing, 0); + return; + } + n = needed / sizeof(HMODULE); + if (n > CL_MOD_MAX) n = CL_MOD_MAX; + active = g_modActive; + next = active == 0 ? 1 : 0; + t = &g_modTables[next]; + t->count = 0; + for (i = 0; i < n; i++) { + cl_modinfo mi; + wchar_t name[64]; + DWORD len, k; + cl_mod* m; + if (!pInfo(self, mods[i], &mi, sizeof(mi))) continue; + len = pName(self, mods[i], name, 63); + name[len < 63 ? len : 63] = 0; + m = &t->mods[t->count++]; + m->base = (unsigned int)(UINT_PTR)mi.lpBaseOfDll; + m->end = m->base + mi.SizeOfImage; + m->cls = (unsigned char)clf_module_class(name); + for (k = 0; k < sizeof(m->leaf) - 1 && name[k]; k++) + m->leaf[k] = name[k] < 128 ? (char)name[k] : '?'; + m->leaf[k] = 0; + } + InterlockedExchange(&g_modActive, next); + InterlockedExchange(&g_modRefreshing, 0); +} + +/* Cached module containing addr, or NULL. No API calls. */ +static const cl_mod* cl_mod_cached(unsigned int addr) +{ + LONG a = g_modActive; + const cl_mod_table* t; + int i; + if (a < 0) return NULL; + t = &g_modTables[a]; + for (i = 0; i < t->count; i++) + if (addr >= t->mods[i].base && addr < t->mods[i].end) return &t->mods[i]; + return NULL; +} + +/* + * Module of addr: the cache, then (allowFallback) the loader. Under the lock. Returns + * the leaf and sets *base and *cls, or NULL (no module: JIT code or garbage). + */ +static const char* cl_module(unsigned int addr, int allowFallback, unsigned int* base, clf_class* cls) +{ + const cl_mod* m = cl_mod_cached(addr); HMODULE hm = NULL; - DWORD n, i, leaf = 0; - *out = NULL; + DWORD n, i, leaf = 0, k; + if (m) { *base = m->base; *cls = (clf_class)m->cls; return m->leaf; } + if (!allowFallback) return NULL; /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) 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; + *base = (unsigned int)(UINT_PTR)hm; + *cls = clf_module_class(g_wpath + leaf); + for (k = 0; k < sizeof(g_fallbackLeaf) - 1 && g_wpath[leaf + k]; k++) + g_fallbackLeaf[k] = g_wpath[leaf + k] < 128 ? (char)g_wpath[leaf + k] : '?'; + g_fallbackLeaf[k] = 0; + return g_fallbackLeaf; } /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ -static char* cl_sym(char* p, unsigned int addr) +static char* cl_sym(char* p, unsigned int addr, int allowFallback) { - HMODULE hm; - const wchar_t* leaf = cl_module(addr, &hm); + unsigned int base; + clf_class cls; + const char* leaf = cl_module(addr, allowFallback, &base, &cls); if (leaf) { - while (*leaf) { *p++ = (char)*leaf++; } + p = cl_str(p, leaf); p = cl_str(p, "+"); - p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); + p = cl_hex(p, addr - base); } else { p = cl_hex(p, addr); } return p; } -/* Nearest module-resolved code pointer on the stack is in the .NET Framework? */ -static int cl_first_frame_netfx(unsigned int esp) +/* Class of the nearest cached-module code pointer on the stack (AC if none found). */ +static clf_class cl_first_frame_class(unsigned int esp) { - int result = 0; + clf_class result = CLF_CLASS_AC; __try { unsigned int* sp = (unsigned int*)(UINT_PTR)esp; int i; for (i = 0; i < 512; i++) { unsigned int v = sp[i]; - if (v > 0x00401000u && v < 0x7FFF0000u) { - HMODULE hm; - const wchar_t* leaf = cl_module(v, &hm); - if (leaf) { result = clf_is_netfx_module(leaf); break; } - } + const cl_mod* m; + if (v <= 0x00401000u || v >= 0x7FFF0000u) continue; + m = cl_mod_cached(v); + if (m) { result = (clf_class)m->cls; break; } } } - __except (EXCEPTION_EXECUTE_HANDLER) { result = 0; } + __except (EXCEPTION_EXECUTE_HANDLER) { result = CLF_CLASS_AC; } return result; } -static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind) +static void cl_write(const char* p, DWORD n) { - 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); + DWORD wr; + if (g_logHandle != INVALID_HANDLE_VALUE) WriteFile(g_logHandle, p, n, &wr, NULL); +} - { - 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; +static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits) +{ + char* p = g_buf; + CONTEXT* c = ep->ContextRecord; + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + SYSTEMTIME st; + if (g_logHandle == INVALID_HANDLE_VALUE) return; - p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER ("); - p = cl_str(p, kind); - p = cl_str(p, ") ====\r\n code="); - p = cl_hex(p, code); - p = cl_str(p, " exAddr="); - p = cl_sym(p, exAddr); - 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 ("); + p = cl_str(p, kind); + p = cl_str(p, ") ====\r\n code="); + p = cl_hex(p, code); + p = cl_str(p, " exAddr="); + p = cl_sym(p, exAddr, 1); + if (hits > 1) { p = cl_str(p, " repeat="); p = cl_u(p, hits); } + p = cl_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, " noiseRepeats="); + p = cl_u(p, g_filter.noiseRepeats); + p = cl_str(p, " otherRepeats="); + p = cl_u(p, g_filter.otherRepeats); + p = cl_str(p, " overCap="); + p = cl_u(p, g_filter.overCap); + p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip, 1); + p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); + p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); + p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax); + p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx); + p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx); + p = cl_str(p, " edx="); p = cl_hex(p, c->Edx); + p = cl_str(p, " esi="); p = cl_hex(p, c->Esi); + p = cl_str(p, " edi="); p = cl_hex(p, c->Edi); + p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n"); + cl_write(g_buf, (DWORD)(p - g_buf)); - __try { - unsigned int* sp = (unsigned int*)(UINT_PTR)c->Esp; - int i, emitted = 0; - for (i = 0; i < 4096 && emitted < 96; i++) { - unsigned int v = sp[i]; - if (v > 0x00401000u && v < 0x7FFF0000u) { - 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++; - } - } + __try { + unsigned int* sp = (unsigned int*)(UINT_PTR)c->Esp; + int i, emitted = 0; + for (i = 0; i < 4096 && emitted < 96; i++) { + unsigned int v = sp[i]; + if (v > 0x00401000u && v < 0x7FFF0000u && cl_mod_cached(v)) { + char* q = g_buf; + q = cl_str(q, " +"); + q = cl_hex(q, (unsigned int)(i * 4)); + q = cl_str(q, " "); + q = cl_sym(q, v, 0); + q = cl_str(q, "\r\n"); + cl_write(g_buf, (DWORD)(q - g_buf)); + emitted++; } } - __except (EXCEPTION_EXECUTE_HANDLER) { - const char* m = " \r\n"; - 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"; + cl_write(m, (DWORD)lstrlenA(m)); + } + + { + const char* e = "==== END NATIVE CRASH ====\r\n"; + cl_write(e, (DWORD)lstrlenA(e)); + } } static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) @@ -450,17 +554,27 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) 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"); + unsigned int now = GetTickCount(); + unsigned int hits = 1; + clf_slot* slot = clf_find(&g_filter, exAddr); + if (slot) { + /* A repeat: decided without touching any module. */ + if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) + cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits); + } else { + unsigned int base; + clf_class faultCls = CLF_CLASS_AC; + const char* leaf = cl_module(exAddr, 1, &base, &faultCls); + clf_class cls = clf_classify(code, leaf ? faultCls : CLF_CLASS_AC, leaf == NULL, + leaf == NULL && code == CLF_CODE_ACCESS_VIOLATION ? cl_first_frame_class(ep->ContextRecord->Esp) : CLF_CLASS_AC); + clf_decision d = clf_new(&g_filter, code, exAddr, cls, now); + if (d == CLF_LOG_COUNTED) + cl_write_entry(ep, "first-chance", 1); + else if (d == CLF_LOG_NOISE) + cl_write_entry(ep, cls == CLF_CLASS_NETFX + ? "first-chance, .NET Framework noise, not counted" + : "first-chance, managed (CoreCLR) noise, not counted", 1); + } } cl_unlock(); return EXCEPTION_CONTINUE_SEARCH; @@ -471,7 +585,7 @@ 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_write_entry(ep, "LAST-CHANCE, unhandled", 1); cl_unlock(); } if (g_prevFilter && g_prevFilter != CrashLastChance) { @@ -480,7 +594,11 @@ static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep) return EXCEPTION_CONTINUE_SEARCH; } -/* Install the VEH and the last-chance filter 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, opened here for the life of the process (append, shared for reading and + * deleting). Also builds the first module cache. + */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { @@ -489,7 +607,11 @@ RC_InstallCrashLogger(const wchar_t* logPath) int i = 0; for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } g_crashLogPath[i] = 0; + g_logHandle = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); } + RC_RefreshCrashLoggerModules(); g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); g_prevFilter = SetUnhandledExceptionFilter(CrashLastChance); } diff --git a/native/SehTrampoline/tests/CrashLogFilterTests.c b/native/SehTrampoline/tests/CrashLogFilterTests.c index 2abb8f5..65c5dde 100644 --- a/native/SehTrampoline/tests/CrashLogFilterTests.c +++ b/native/SehTrampoline/tests/CrashLogFilterTests.c @@ -1,8 +1,6 @@ /* * 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) + * filter). Build and run with Run-CrashLogFilterTests.ps1 (x86 MSVC). Exit 0 = pass. */ #include #include @@ -18,73 +16,128 @@ static void check(int ok, const char* what) 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) +#define AV CLF_CODE_ACCESS_VIOLATION +#define FC(s, code, addr, cls, now) clf_first_chance((s), (code), (addr), (cls), (now), &hits) + +static int is_write(clf_decision d) { - 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"); + return d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE || d == CLF_LOG_REPEAT; } -static void other_faults_dedupe_per_address(void) +/* Seen in a real log: handled .NET Framework AVs at ONE address spent the old cap, + * and the fatal AC fault later was never written. */ +static void netfx_noise_never_spends_the_limit(void) { - 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"); + static clf_state s; + unsigned int hits, i, written = 0; + for (i = 0; i < 500; i++) + if (is_write(FC(&s, AV, 0x433620C8u, CLF_CLASS_NETFX, 1000 + i * 10))) written++; + /* first + the power-of-two repeats 2,4,8,16,32,64,128,256 = 9 entries for 500 hits */ + check(written == 9, "500 hits of one JIT-code AV: 9 entries (first + powers of two)"); + check(s.counted == 0, "and never charged to the limit"); + check(s.noiseRepeats == 491, "skipped repeats are counted as noise"); + check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 7000) == CLF_LOG_COUNTED, "a later AC fault is still written"); +} + +/* A contained AV at a known address that later goes fatal. */ +static void known_address_going_fatal_is_written(void) +{ + static clf_state s; + unsigned int hits, i; + clf_decision d; + for (i = 0; i < 3; i++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000 + i); + d = FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1010); + check(d == CLF_LOG_REPEAT && hits == 4, "3 contained AVs, then a 4th (fatal) at the same address: written, repeat=4"); + + { + static clf_state t; + unsigned int now = 5000; + for (i = 0; i < 1000; i++) FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + i); /* within 1 s */ + d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31000); + check(d == CLF_LOG_REPEAT && hits == 1001, "1000 repeats, then the same address 31 s later: written"); + d = FC(&t, AV, 0x00416C86u, CLF_CLASS_AC, now + 1000 + 31001); + check(d == CLF_SKIP_REPEAT, "and the next one right after is not"); + } + { + static clf_state u; + FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 100); + FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 101); + FC(&u, AV, 0x00500000u, CLF_CLASS_AC, 102); /* hits 3: skipped */ + d = FC(&u, CLF_CODE_HEAP_CORRUPTION, 0x00500000u, CLF_CLASS_AC, 103); + check(d == CLF_LOG_REPEAT, "a non-AV code at a known address is always written"); + } + { + static clf_state w; /* the 32-bit tick wrap */ + FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF000u); + FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF001u); + FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0xFFFFF002u); + d = FC(&w, AV, 0x00600000u, CLF_CLASS_AC, 0x00007000u); /* ~32 s later, past the wrap */ + check(d == CLF_LOG_REPEAT, "the 30 s relog survives the GetTickCount wrap"); + } +} + +static void ac_faults_limited_per_distinct_address(void) +{ + static clf_state s; + unsigned int hits, a; + for (a = 0; a < 50; a++) FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000); + check(s.counted == 1, "a repeating AC fault is charged once"); for (a = 1; a < CLF_MAX_COUNTED; a++) - check(clf_first_chance(&s, CLF_CODE_ACCESS_VIOLATION, 0x00500000u + a * 16, 0) == CLF_LOG_COUNTED, + check(FC(&s, AV, 0x00500000u + a * 16, CLF_CLASS_AC, 1000) == 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"); + check(FC(&s, AV, 0x00700000u, CLF_CLASS_AC, 1000) == CLF_SKIP_CAP, "past the limit: skipped"); + check(FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, 1000) != CLF_SKIP_CAP, + "a known address is decided as a repeat, never by the limit"); } static void codes(void) { - 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 clf_state s; + unsigned int hits; + check(FC(&s, 0xC00000FDu, 0x1000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack overflow is logged"); + check(FC(&s, 0xC0000374u, 0x2000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "heap corruption is logged"); + check(FC(&s, 0xC0000409u, 0x3000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "stack buffer overrun is logged"); + check(FC(&s, 0xC0000602u, 0x4000u, CLF_CLASS_AC, 1) == CLF_LOG_COUNTED, "fail-fast is logged"); + check(FC(&s, 0xE06D7363u, 0x5000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a C++ exception is not"); + check(FC(&s, 0x80000003u, 0x6000u, CLF_CLASS_AC, 1) == CLF_SKIP_CODE, "a breakpoint is not"); } -static void netfx_classification(void) +static void 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"); + check(clf_module_class(L"clr.dll") == CLF_CLASS_NETFX && clf_module_class(L"MSCORLIB.NI.DLL") == CLF_CLASS_NETFX + && clf_module_class(L"mscorwks.dll") == CLF_CLASS_NETFX && clf_module_class(L"mscorlib.dll") == CLF_CLASS_NETFX, + "the .NET Framework modules, any case"); + check(clf_module_class(L"coreclr.dll") == CLF_CLASS_MANAGED && clf_module_class(L"clrjit.dll") == CLF_CLASS_MANAGED + && clf_module_class(L"System.Private.CoreLib.dll") == CLF_CLASS_MANAGED, + "the engine's CoreCLR modules are managed noise"); + check(clf_module_class(L"acclient.exe") == CLF_CLASS_AC && clf_module_class(L"clr.dllx") == CLF_CLASS_AC + && clf_module_class(0) == CLF_CLASS_AC, "AC and near-misses are not noise"); + check(clf_classify(AV, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_NETFX, "an AV in clr.dll is .NET Framework noise"); + check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_NETFX) == CLF_CLASS_NETFX, "JIT code under clr frames: .NET Framework noise"); + check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_MANAGED) == CLF_CLASS_MANAGED, "JIT code under CoreCLR frames: managed noise"); + check(clf_classify(AV, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_MANAGED, "an AV in coreclr.dll: managed noise"); + check(clf_classify(AV, CLF_CLASS_AC, 1, CLF_CLASS_AC) == CLF_CLASS_AC, "no module under AC frames: AC"); + check(clf_classify(AV, CLF_CLASS_AC, 0, CLF_CLASS_NETFX) == CLF_CLASS_AC, "an AV in an AC module is AC whatever is below it"); + check(clf_classify(CLF_CODE_STACK_OVERFLOW, CLF_CLASS_NETFX, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "a stack overflow is never noise"); + check(clf_classify(CLF_CODE_HEAP_CORRUPTION, CLF_CLASS_MANAGED, 0, CLF_CLASS_AC) == CLF_CLASS_AC, "heap corruption is never noise"); +} + +static void managed_noise_is_its_own_bucket(void) +{ + static clf_state s; + unsigned int hits, a; + for (a = 0; a < 40; a++) + check(FC(&s, AV, 0x70000000u + a * 16, CLF_CLASS_MANAGED, 1) == CLF_LOG_NOISE, "managed noise written once per address"); + check(s.counted == 0, "and never charged to the AC limit"); } static void last_chance_is_separate(void) { - clf_state s = {0}; - unsigned int a; + static clf_state s; + unsigned int hits, 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); + FC(&s, AV, 0x00700000u + a * 16, CLF_CLASS_AC, 1); check(s.counted == CLF_MAX_COUNTED, "first-chance limit reached"); check(clf_last_chance(&s) == CLF_LOG_LAST_CHANCE, "the unhandled one is still written"); for (i = 0; i < 20; i++) @@ -92,27 +145,35 @@ static void last_chance_is_separate(void) check(logged == CLF_MAX_LAST_CHANCE - 1, "last-chance has its own small limit"); } -static void full_table_never_silences_ac_faults(void) +static void full_table_evicts_oldest_noise(void) { - clf_state s = {0}; - unsigned int a; + static clf_state s; + unsigned int hits, a; + clf_decision d; 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"); + FC(&s, AV, 0x40000000u + a * 16, CLF_CLASS_NETFX, 1000 + a); /* noise fills it, 0x40000000 oldest */ + check(s.counted == 0, "table full of .NET Framework addresses"); + d = FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5000); + check(d == CLF_LOG_COUNTED, "an AC fault is written"); + check(clf_find(&s, 0x0055FA24u) != 0, "and tracked, in the evicted slot"); + check(clf_find(&s, 0x40000000u) == 0, "the least recently written noise slot was evicted"); + check(clf_find(&s, 0x40000010u) != 0, "the next one was not"); + check(FC(&s, AV, 0x0055FA24u, CLF_CLASS_AC, 5001) == CLF_LOG_REPEAT && hits == 2, "so its repeat is deduped"); + d = FC(&s, AV, 0x41000000u, CLF_CLASS_NETFX, 6000); + check(d == CLF_LOG_NOISE, "a new .NET Framework address is written, evicting an older one"); + check(clf_find(&s, 0x0055FA24u) != 0, "AC slots are never evicted"); } int main(void) { - netfx_noise_never_spends_the_cap(); - other_faults_dedupe_per_address(); + netfx_noise_never_spends_the_limit(); + known_address_going_fatal_is_written(); + ac_faults_limited_per_distinct_address(); codes(); - netfx_classification(); + classification(); + managed_noise_is_its_own_bucket(); last_chance_is_separate(); - full_table_never_silences_ac_faults(); + full_table_evicts_oldest_noise(); printf("%d check(s), %d failed.\n", g_checks, g_failed); return g_failed == 0 ? 0 : 1; } diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index cbcf9ed..9c6698e 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -3104,6 +3104,26 @@ internal partial class MainWindow : Window // thread not draining the marshalled-action queue), and a stale heartbeat // file. private readonly Dictionary _wedgeZeroFpsSinceUtc = new(); + // PIDs whose "dump in progress, kill held off" line was logged (once per dump). + private readonly HashSet _dumpHoldLoggedPids = new(); + + // Last write of the newest acclient_oom__*.dmp in the shared Dumps folder, or null. + private static DateTime? NewestOomDumpWriteUtc(int pid) + { + try + { + string dir = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "Dumps"); + if (!Directory.Exists(dir)) return null; + DateTime? newest = null; + foreach (string f in Directory.EnumerateFiles(dir, $"{RynthCore.Install.DumpInProgressRule.OomDumpPrefix}{pid}_*.dmp")) + { + DateTime w = File.GetLastWriteTimeUtc(f); + if (newest == null || w > newest) newest = w; + } + return newest; + } + catch { return null; } + } // fps (1), plug pump rate (2), login (3), qd = main-thread queue depth (4, optional on older engines). private static readonly System.Text.RegularExpressions.Regex WedgeHbRegex = new(@"hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?", System.Text.RegularExpressions.RegexOptions.Compiled); @@ -3184,6 +3204,18 @@ internal partial class MainWindow : Window int read = fs.Read(buf, 0, (int)want); tail = System.Text.Encoding.UTF8.GetString(buf, 0, read); + // The engine's OUT OF MEMORY full-memory dump suspends every thread for minutes: + // the log goes silent and the main thread looks hung, but killing now would cut + // the dump short. Hold off both kills below while it is being written + // (DumpInProgressRule); the restart for the box that follows is unchanged. + if (RynthCore.Install.DumpInProgressRule.IsDumping(tail, fi.LastWriteTimeUtc, NewestOomDumpWriteUtc(pid), DateTime.UtcNow)) + { + if (_dumpHoldLoggedPids.Add(pid)) + LauncherDiag.Info($"WEDGE: PID {pid} is writing a full-memory dump - kill held off until it ends."); + continue; + } + _dumpHoldLoggedPids.Remove(pid); + if (hbStale) { KillWedgedClient(process, pid, activeContexts, activeSessions, diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 0446f2a..dea6361 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -58,6 +58,7 @@ + diff --git a/src/RynthCore.App.Avalonia/UsageStats.cs b/src/RynthCore.App.Avalonia/UsageStats.cs index 456a3e3..84ee228 100644 --- a/src/RynthCore.App.Avalonia/UsageStats.cs +++ b/src/RynthCore.App.Avalonia/UsageStats.cs @@ -22,7 +22,8 @@ namespace RynthCore.App.Avalonia; /// - the RynthCore version; /// - the enabled plugins the update feed ships (RynthSuite), with their versions; other plugins /// only as a count, never by name (a private plugin's name could identify its author); -/// - how many crash_*.dmp files the engine wrote since the last report (a count only); +/// - how many crash dumps were written since the last report (a count only): the engine's +/// Logs\dumps\crash_*.dmp and CoreCLR's Logs\dumps\clr_*.dmp; /// - the Windows major version ("10" or "11"). /// Never: character, account or server names, file paths, or anything else identifying. /// @@ -221,18 +222,30 @@ internal sealed class UsageStats return "other"; } - /// crash_*.dmp files written after (hang dumps are not crashes). + /// + /// Crash dump names counted: the engine's crash_*.dmp and the CoreCLR fatal-error dumps the + /// loader asks for in the same folder (clr_*.dmp, Loader.c ConfigureCrashDumps). + /// + private static readonly string[] CrashDumpPatterns = { "crash_*.dmp", "clr_*.dmp" }; + + /// + /// Crash dumps (crash_*.dmp, clr_*.dmp) written after . Hang dumps + /// and the OUT OF MEMORY dumps are not crashes. + /// public static int CountCrashDumps(string dir, DateTime sinceUtc, DateTime utcNow) { try { if (!Directory.Exists(dir)) return 0; int n = 0; - foreach (string f in Directory.EnumerateFiles(dir, "crash_*.dmp")) + foreach (string pattern in CrashDumpPatterns) { - DateTime t = File.GetLastWriteTimeUtc(f); - if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++; - if (n >= MaxCrashes) break; + foreach (string f in Directory.EnumerateFiles(dir, pattern)) + { + DateTime t = File.GetLastWriteTimeUtc(f); + if (t > sinceUtc && t <= utcNow.AddMinutes(5)) n++; + if (n >= MaxCrashes) return n; + } } return n; } diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index f847ac0..6f4a225 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -250,10 +250,16 @@ internal static class AcMainThreadQueue /// 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 + private static bool IsTeardown(in Entry e) => IsTeardownKind(e.Kind, e.A, e.B); + + /// + /// The ONE teardown predicate: the enqueue side (ActionRing admission, the teardown reserve) + /// and the drain side (which entries survive a world transition) both ask it. + /// + internal static bool IsTeardownKind(ActionKind kind, uint a, uint b) => kind switch { - ActionKind.SetAutoRun => e.A == 0, - ActionKind.SetMotion => e.B == 0, + ActionKind.SetAutoRun => a == 0, + ActionKind.SetMotion => b == 0, ActionKind.StopMovement or ActionKind.StopCompletely or ActionKind.CancelAttack or ActionKind.CloseContainer => true, _ => false, @@ -279,38 +285,64 @@ internal static class AcMainThreadQueue _ => e.Kind.ToString(), }; + // The ring (ActionRing: storage, FIFO, admission). 256 entries, the top 32 for teardown + // only, so a ring a bot filled with starts still takes its stops and cancels. private const int Capacity = 256; // power of two - private const int Mask = Capacity - 1; - private static readonly Entry[] _slots = new Entry[Capacity]; - private static readonly object _producerLock = new(); - - // Monotonic counters. Producers advance _tail under _producerLock; the sole - // consumer (main thread) advances _head. - private static int _head; - private static int _tail; + private const int TeardownReserve = 32; + private static readonly ActionRing _ring = new(Capacity, TeardownReserve); private static long _dropped; + private static long _transitionRejected; + /// Entries refused because the ring was full (a running total; the heartbeat's qdrop). public static long DroppedCount => Interlocked.Read(ref _dropped); + /// Non-teardown entries refused while the player was in a world transition. + public static long TransitionRejectedCount => Interlocked.Read(ref _transitionRejected); + + // -- The mutator gate ---------------------------------------------------------- + // Every AC-mutating helper (ClientHelperHooks, CombatActionHooks, MovementActionHooks, + // CommandInterpreterHooks, ClientCombatHooks, PlayerPhysicsHooks, PlayerTrade, + // PlayerTraining) opens with the same line: + // if (AcMainThreadQueue.MustQueue(teardown: )) return Enqueue...; + // Off AC's main thread it queues (as always). ON the main thread it also queues while a + // world transition holds the drains, unless it is being called BY a drain (IsDraining) + // or is teardown: render-thread host actions (ImGui panels, the EndScene plugin calls) + // used to run straight into a world AC was tearing down, around the gate. The queue + // then refuses or holds it like any other queued work (WorldTransitionState). + private static int _drainDepth; // AC main thread only + + /// AC main thread only: a drain is dispatching queued work right now. + public static bool IsDraining => _drainDepth > 0; + + /// AC main thread only: a direct call now would run into a world transition. + public static bool ShouldDefer() => !IsDraining && PlayerLifecycleLog.HoldQueuedWork(NowMs); + + /// + /// The one gate every mutator opens with: true = queue instead of calling AC now. + /// : a stop or cancel (IsTeardownKind), which runs at once on + /// the main thread even in a transition. + /// + public static bool MustQueue(bool teardown) => + MutatorGate.MustQueue(MainThreadGuard.IsOnMainThread(), teardown, IsDraining, HoldNow); + + // Cached (no allocation per call): main thread only, asked only by MutatorGate on it. + private static readonly Func HoldNow = () => PlayerLifecycleLog.HoldQueuedWork(NowMs); + private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0) { - lock (_producerLock) - { - int tail = _tail; - int head = Volatile.Read(ref _head); - if (tail - head >= Capacity) - { - // Full. Drop rather than block or fall back to an off-thread AC - // mutation — a dropped movement/attack tick self-corrects on the - // next bot tick; an off-thread mutation can crash the client. - Interlocked.Increment(ref _dropped); - return false; - } - - _slots[tail & Mask] = new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)); - Volatile.Write(ref _tail, tail + 1); - return true; - } + bool teardown = IsTeardownKind(kind, a, b); + // Dead / portaling / settling: a start queued now would be dropped when the window + // ends anyway (WorldTransitionState), so it is refused here and never takes a slot a + // stop needs. Stops and cancels are always taken (the reserve keeps room for them). + var r = _ring.TryEnqueue(new Entry(kind, a, b, c, d, NowMs, Volatile.Read(ref _loginEpoch)), + teardown, PlayerLifecycleLog.InWorldTransition); + if (r == ActionRing.Admit.Queued) return true; + // Full: drop rather than block or fall back to an off-thread AC mutation - a dropped + // movement/attack tick self-corrects on the next bot tick; an off-thread mutation can + // crash the client. + if (r == ActionRing.Admit.Full) Interlocked.Increment(ref _dropped); + else Interlocked.Increment(ref _transitionRejected); + return false; } // ── Typed enqueue helpers (called by the public action methods when they @@ -359,19 +391,33 @@ internal static class AcMainThreadQueue // CommandInterpreter turn, which would change the steering behaviour. private static int _directHeadingPending; private static uint _directHeadingBits; + private static long _directHeadingAt; public static bool EnqueueDirectHeading(float headingDegrees) { Volatile.Write(ref _directHeadingBits, BitConverter.SingleToUInt32Bits(headingDegrees)); + Interlocked.Exchange(ref _directHeadingAt, NowMs); Volatile.Write(ref _directHeadingPending, 1); return true; } // Main thread only (from Drain). Same order as the pre-queue code: the direct // snap first, the CommandInterpreter turn only when there is no player. + // World transition: the pending heading is held; once the window ends a heading set + // during it is stale (the bot steers again from where it landed) and is dropped. private static void DrainDirectHeading() { + if (Volatile.Read(ref _directHeadingPending) == 0) return; + long now = NowMs; + long at = Interlocked.Read(ref _directHeadingAt); + WorldTransitionState.Verdict v = PlayerLifecycleLog.DecideQueued(now, at, teardown: false); + if (v == WorldTransitionState.Verdict.Hold) return; if (Interlocked.Exchange(ref _directHeadingPending, 0) == 0) return; + if (v == WorldTransitionState.Verdict.Drop) + { + NoteTransitionDrop("heading", now - at); + return; + } float heading = BitConverter.UInt32BitsToSingle(Volatile.Read(ref _directHeadingBits)); try { @@ -394,18 +440,25 @@ internal static class AcMainThreadQueue // selects mid-gesture too). Lock-free and allocation-free. private static int _overlaySelectPending; private static uint _overlaySelectId; + private static long _overlaySelectAt; public static bool EnqueueOverlaySelect(uint objectId) { if (objectId == 0) return false; Volatile.Write(ref _overlaySelectId, objectId); + Interlocked.Exchange(ref _overlaySelectAt, NowMs); Volatile.Write(ref _overlaySelectPending, 1); return true; } - // Main thread only (from Drain). + // Main thread only (from Drain). World transition: held, and kept when the window ends: + // it is the user's own click, and SelectFromOverlay re-checks the object still exists. private static void DrainOverlaySelect() { + if (Volatile.Read(ref _overlaySelectPending) == 0) return; + if (PlayerLifecycleLog.DecideQueued(NowMs, Interlocked.Read(ref _overlaySelectAt), teardown: true) + == WorldTransitionState.Verdict.Hold) + return; if (Interlocked.Exchange(ref _overlaySelectPending, 0) == 0) return; uint id = Volatile.Read(ref _overlaySelectId); try { ClientHelperHooks.SelectFromOverlay(id); } @@ -514,6 +567,14 @@ internal static class AcMainThreadQueue private static long _drainDeferSinceMs; public static void Drain() + { + // IsDraining: the helpers this dispatches run their AC call directly (MustQueue). + _drainDepth++; + try { DrainCore(); } + finally { _drainDepth--; } + } + + private static void DrainCore() { if (_disarmed) { @@ -573,22 +634,14 @@ 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); - } + // Both are latest-value slots (a heading, a select): held through a world transition, + // then decided by their own drains (a stale heading dropped, a user's select kept). DrainDirectHeading(); // Overlay click-to-select (Radar dot / nameplate click): also before the // gesture defer, so a click selects at once even while the bot swings. DrainOverlaySelect(); - int head = _head; // only the main thread writes _head - int tail = Volatile.Read(ref _tail); - // In a world transition the ring is held whole (FIFO kept): nothing runs, nothing is // dropped yet. Once it ends, the loop below drops what was queued during it, except // stops and cancels, which run in order as one teardown group. @@ -607,7 +660,7 @@ internal static class AcMainThreadQueue // drop: dropping arbitrary item/movement actions desyncs the bot far // worse than a late injection, and the pre-2026-06-12 behavior was // "always inject" anyway, so proceeding past the cap is never worse). - if (head != tail) + if (_ring.Count > 0) { // In milliseconds (was 250 Drain calls: 2 s to over 10 s depending on the frame rate). if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight) @@ -621,22 +674,20 @@ internal static class AcMainThreadQueue } long runAt = NowMs; int epochNow = Volatile.Read(ref _loginEpoch); - while (head != tail) + // Bounded to what is queued now plus a capacity's worth: an action that re-queues + // itself can never spin the main thread. + int budget = Capacity * 2; + while (budget-- > 0 && _ring.TryDequeue(out Entry e)) { - Entry e = _slots[head & Mask]; - Volatile.Write(ref _head, ++head); - long age = runAt - e.At; if (PlayerLifecycleLog.DecideQueued(runAt, e.At, IsTeardown(e)) == WorldTransitionState.Verdict.Drop) { NoteTransitionDrop(Describe(e), age); - 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); - tail = Volatile.Read(ref _tail); continue; } if (age > LateActionLogMs) @@ -770,8 +821,6 @@ internal static class AcMainThreadQueue // not managed exceptions and won't be caught here — but these // now run on the correct thread, which is the whole point.) } - - tail = Volatile.Read(ref _tail); } } @@ -804,9 +853,16 @@ internal static class AcMainThreadQueue public static bool EnqueueRequestId(uint objectId) { if (objectId == 0) return false; + // Dead / portaling / settling: an appraisal queued now is dropped when the window + // ends, so it is refused here (the caller sees false and may ask again later). Nor + // does a request merge into an entry from before the last held drain: that entry is + // dropped when the drain reaches it, and the merged request would go with it. + if (PlayerLifecycleLog.InWorldTransition) return false; + long mergeOnlyAfter = PlayerLifecycleLog.LastBlockedMs; lock (_requestIdLock) { - PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), RequestIdMergeMaxAgeMs); + PendingIdQueue.Result r = _requestIdQueue.Enqueue(objectId, NowMs, Volatile.Read(ref _loginEpoch), + RequestIdMergeMaxAgeMs, mergeOnlyAfter); if (r == PendingIdQueue.Result.Full) { Interlocked.Increment(ref _dropped); @@ -1067,9 +1123,12 @@ internal static class AcMainThreadQueue if (_castPending != 0) return false; _castTargetId = targetId; _castSpellId = spellId; - _castQueuedAt = NowMs; + // Volatile: DrainCasts reads both without the lock, and a plain 64-bit store can + // tear on x86. The time and the stop-wait reset first, then the flag that + // publishes them (a release store: the drain's Volatile.Read of the flag sees both). + Volatile.Write(ref _castQueuedAt, NowMs); _castStopWaitNoted = false; - _castPending = 1; + Volatile.Write(ref _castPending, 1); return true; } } @@ -1092,27 +1151,25 @@ internal static class AcMainThreadQueue /// /// True when the action ring holds a movement stop queued at or before . - /// Main thread only (the ring's sole consumer). Entries are stamped under the producer lock, so - /// their times rise from head to tail and the walk stops at the first newer one. + /// Main thread only (the ring's sole consumer). An entry's time is taken before ActionRing's + /// producer lock, so two producers can land slightly out of time order: the walk checks every + /// queued entry (at most Capacity) instead of stopping at the first newer one (CastStopRules). /// - private static bool StopQueuedAtOrBefore(long castQueuedAt) - { - int head = _head; - int tail = Volatile.Read(ref _tail); - for (int i = head; i != tail; i++) - { - ref readonly Entry e = ref _slots[i & Mask]; - if (e.At > castQueuedAt) return false; - if (IsMovementStop(e)) return true; - } - return false; - } + private static bool StopQueuedAtOrBefore(long castQueuedAt) => + CastStopRules.AnyStopAtOrBefore(_ring, castQueuedAt, static e => e.At, static e => IsMovementStop(e)); // Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick). // Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the // cast directly via the SEH trampoline (targeted: FreeHandsAndCastSpell with the target // passed explicitly, no SelectItem; self: ClientMagicSystem::CastSpell). public static void DrainCasts() + { + _drainDepth++; + try { DrainCastsCore(); } + finally { _drainDepth--; } + } + + private static void DrainCastsCore() { if (_disarmed) return; // engine teardown in progress if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path diff --git a/src/RynthCore.Engine/Compatibility/ActionRing.cs b/src/RynthCore.Engine/Compatibility/ActionRing.cs new file mode 100644 index 0000000..9a8a077 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ActionRing.cs @@ -0,0 +1,123 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ActionRing.cs +// +// The storage and admission policy of AcMainThreadQueue's action ring: a fixed ring of +// entries, many producers (under one lock), ONE consumer (AC's main thread), FIFO. +// +// Admission: during a world transition the drain holds the ring +// (WorldTransitionState), and a bot keeps queueing starts at ~60 Hz meanwhile, so the +// ring used to fill and then refuse the stops and cancels that matter most. Now: +// - while the caller says a transition is on, non-teardown entries are refused at +// once (they would be dropped when it ends anyway); +// - the top TeardownReserve slots only take teardown entries (stops and cancels), so a +// ring filled by starts before the transition was seen still takes a stop. +// What counts as teardown is the caller's (AcMainThreadQueue.IsTeardownKind, the same +// predicate its drain uses). +// +// Pure: no engine state. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class ActionRing where T : struct +{ + public enum Admit + { + Queued, + /// No room (for a non-teardown entry: none below the teardown reserve). + Full, + /// A world transition is on and the entry is not teardown. + RejectedTransition, + } + + private readonly T[] _slots; + private readonly int _mask; + private readonly int _reserve; + private readonly object _lock = new(); + // Monotonic counters. Producers advance _tail under _lock; the sole consumer advances _head. + private int _head; + private int _tail; + + public ActionRing(int capacityPowerOfTwo, int teardownReserve) + { + if (capacityPowerOfTwo <= 0 || (capacityPowerOfTwo & (capacityPowerOfTwo - 1)) != 0) + throw new System.ArgumentOutOfRangeException(nameof(capacityPowerOfTwo)); + if (teardownReserve < 0 || teardownReserve >= capacityPowerOfTwo) + throw new System.ArgumentOutOfRangeException(nameof(teardownReserve)); + _slots = new T[capacityPowerOfTwo]; + _mask = capacityPowerOfTwo - 1; + _reserve = teardownReserve; + } + + public int Capacity => _slots.Length; + public int TeardownReserve => _reserve; + + /// Entries waiting (any thread; a snapshot). + public int Count => Volatile.Read(ref _tail) - Volatile.Read(ref _head); + + /// Producer side, any thread. + public Admit TryEnqueue(in T entry, bool teardown, bool inTransition) + { + lock (_lock) + { + if (inTransition && !teardown) + return Admit.RejectedTransition; + int tail = _tail; + int used = tail - Volatile.Read(ref _head); + int limit = teardown ? _slots.Length : _slots.Length - _reserve; + if (used >= limit) + return Admit.Full; + _slots[tail & _mask] = entry; + Volatile.Write(ref _tail, tail + 1); + return Admit.Queued; + } + } + + /// Consumer only: the oldest entry, without removing it. + public bool TryPeek(out T entry) + { + int head = _head; + if (head == Volatile.Read(ref _tail)) + { + entry = default; + return false; + } + entry = _slots[head & _mask]; + return true; + } + + /// + /// Consumer only: the entry places behind the oldest (0 = the + /// oldest), without removing anything. False past the newest entry. + /// + public bool TryPeekAt(int offset, out T entry) + { + int head = _head; + if (offset < 0 || offset >= Volatile.Read(ref _tail) - head) + { + entry = default; + return false; + } + entry = _slots[(head + offset) & _mask]; + return true; + } + + /// Consumer only: removes the oldest entry (after a successful TryPeek). + public void Pop() + { + int head = _head; + if (head == Volatile.Read(ref _tail)) return; + _slots[head & _mask] = default; + Volatile.Write(ref _head, head + 1); + } + + /// Consumer only: removes and returns the oldest entry. + public bool TryDequeue(out T entry) + { + if (!TryPeek(out entry)) return false; + Pop(); + return true; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs index 2334a06..5afef9d 100644 --- a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -80,6 +80,9 @@ internal static class AppraisalHooks // Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray at +0x30) private static readonly Dictionary _spellIdCache = new(); private static readonly object _cacheLock = new(); + // Objects the CLIENT released, whose data is kept a while (ReleasedObjectRetention). + private static readonly ReleasedObjectRetention _released = new(); + private static readonly List _expiredScratch = new(); public static bool IsInstalled => _hookInstalled; public static string StatusMessage => _statusMessage; @@ -114,19 +117,64 @@ internal static class AppraisalHooks _bags.Clear(); _spellIdCache.Clear(); _failedRollLogged.Clear(); + _released.Clear(); } } - /// Drops everything cached for an object AC deleted (PropertyUpdateHooks' BeingDeleted hook). + /// + /// Drops everything cached for an object: the SERVER deleted it (0xF747, SmartBoxHooks / + /// ServerMessageStream), or its kept-after-release time ran out. Any thread. + /// public static void EvictObject(uint guid) + { + lock (_cacheLock) + EvictLocked(guid); + } + + // Caller holds _cacheLock. + private static void EvictLocked(uint guid) + { + _appraisedGuids.Remove(guid); + _lastIdTime.Remove(guid); + _bags.Remove(guid); + _spellIdCache.Remove(guid); + _failedRollLogged.Remove(guid); + _released.Forget(guid); + } + + /// + /// The CLIENT released an object (AC's BeingDeleted: it left the client's view). Its data is + /// kept for ReleasedObjectRetention.RetainMs, so a re-create inside that time still finds it + /// (AutoId then skips the re-appraisal). Main thread (the BeingDeleted detour). + /// + public static void OnClientRelease(uint guid, long nowMs) { lock (_cacheLock) { - _appraisedGuids.Remove(guid); - _lastIdTime.Remove(guid); - _bags.Remove(guid); - _spellIdCache.Remove(guid); - _failedRollLogged.Remove(guid); + if (!_appraisedGuids.Contains(guid) && !_bags.ContainsKey(guid)) return; + if (!_released.OnRelease(guid, nowMs)) + EvictLocked(guid); // the kept-released bound is full: drop it now + } + } + + /// The object was created again: its data is current, not merely kept. + public static void MarkLive(uint guid) + { + lock (_cacheLock) + _released.Forget(guid); + } + + /// Drops the data of objects released longer ago than the retention time. Timer thread. + public static int ExpireReleased(long nowMs) + { + lock (_cacheLock) + { + _expiredScratch.Clear(); + int n = _released.Expire(nowMs, _expiredScratch); + foreach (uint g in _expiredScratch) + EvictLocked(g); + _expiredScratch.Clear(); + return n; } } @@ -150,10 +198,7 @@ internal static class AppraisalHooks if (t < oldestTime) { oldestTime = t; oldest = g; } } if (oldest == 0) return; - _bags.Remove(oldest); - _appraisedGuids.Remove(oldest); - _lastIdTime.Remove(oldest); - _spellIdCache.Remove(oldest); + EvictLocked(oldest); } } diff --git a/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs index f098160..a51c979 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdEligibility.cs @@ -68,6 +68,9 @@ internal sealed class AutoIdEligibility public int MaxTracked => _maxTracked; public long WindowMs => _windowMs; + /// Re-creates skipped because the last appraisal is recent and still cached. + public long SkippedRecentTotal { get; private set; } + /// Creates admitted while the map was full (appraised, not tracked). public long UntrackedAdmits { get; private set; } @@ -84,7 +87,12 @@ internal sealed class AutoIdEligibility e.Live = true; bool recent = e.LastSentMs != 0 && nowMs - e.LastSentMs < _windowMs; _map[id] = e; - return recent && appraisalCached ? CreateDecision.SkipRecent : CreateDecision.Appraise; + if (recent && appraisalCached) + { + SkippedRecentTotal++; + return CreateDecision.SkipRecent; + } + return CreateDecision.Appraise; } if (_map.Count >= _maxTracked) diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index 56dbc10..5770cb4 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -44,10 +44,13 @@ internal static class AutoIdService private static Timer? _drainTimer; private static bool _started; - private static long _skippedRecent, _skippedPriorityFresh; + private static long _skippedPriorityFresh; /// Re-creates not appraised because a recent appraisal is still cached. - public static long SkippedRecentCount => Interlocked.Read(ref _skippedRecent); + public static long SkippedRecentCount + { + get { lock (_gate) return _eligibility.SkippedRecentTotal; } + } /// Selected-target priority appraisals skipped because the target's data is cached and fresh. public static long SkippedPriorityFreshCount => Interlocked.Read(ref _skippedPriorityFresh); @@ -89,6 +92,9 @@ internal static class AutoIdService if (playerId != 0 && objectId == playerId) return; + // Created again: data kept since a client release is current again (and still cached + // if the release was inside ReleasedObjectRetention's time). + AppraisalHooks.MarkLive(objectId); bool cached = AppraisalHooks.HasAppraisalData(objectId); AutoIdEligibility.CreateDecision decision; lock (_gate) @@ -96,8 +102,6 @@ internal static class AutoIdService if (decision == AutoIdEligibility.CreateDecision.Appraise) _queue.Enqueue(objectId); - else if (decision == AutoIdEligibility.CreateDecision.SkipRecent) - Interlocked.Increment(ref _skippedRecent); } /// @@ -121,6 +125,8 @@ internal static class AutoIdService if (objectId == 0) return; lock (_gate) _eligibility.OnServerDelete(objectId); + // It really went away: its kept identify data goes too. + AppraisalHooks.EvictObject(objectId); } /// @@ -144,6 +150,10 @@ internal static class AutoIdService { if (!CombatActionHooks.HasRequestId) return; + // Dead / portaling / settling: AcMainThreadQueue refuses appraisals now, so the + // backlog waits here instead of being dequeued into a refusal and lost. + if (PlayerLifecycleLog.InWorldTransition) + return; long now = Environment.TickCount64; int sent = 0; @@ -206,6 +216,10 @@ internal static class AutoIdService removed = _eligibility.Count > _eligibility.MaxTracked / 2 ? _eligibility.Prune(now) : 0; if (removed > 0) RynthLog.Verbose($"Compat: AutoIdService pruned {removed} appraisal record(s)."); + // Identify data kept after a client release: dropped once its time is up. + int expired = AppraisalHooks.ExpireReleased(now); + if (expired > 0) + RynthLog.Verbose($"Compat: AppraisalHooks dropped {expired} released object(s) past the retention time."); } } catch { } diff --git a/src/RynthCore.Engine/Compatibility/CastStopRules.cs b/src/RynthCore.Engine/Compatibility/CastStopRules.cs new file mode 100644 index 0000000..f021b59 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/CastStopRules.cs @@ -0,0 +1,38 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/CastStopRules.cs +// +// The cast drain's question about the action ring: is a movement stop queued at or +// before the pending cast? (AcMainThreadQueue.StopQueuedAtOrBefore: such a stop runs +// first, so the cast's own stop is not sent while AC's locomotion is still on.) +// +// Every queued entry is checked. An entry's time is taken before ActionRing's producer +// lock, so two producers can land slightly out of time order, and a walk that stopped +// at the first entry newer than the cast could miss an older stop queued behind it. +// +// Pure: no engine state. Consumer side of the ring only (AC's main thread). Compiled +// into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class CastStopRules +{ + /// + /// True when any entry in was queued at or before + /// (by ) and is a movement stop + /// (by ). Pass static lambdas: nothing is allocated per call. + /// + public static bool AnyStopAtOrBefore(ActionRing ring, long castQueuedAt, + Func queuedAt, Func isStop) where T : struct + { + int count = ring.Count; + for (int i = 0; i < count; i++) + { + if (!ring.TryPeekAt(i, out T e)) break; + if (queuedAt(e) <= castQueuedAt && isStop(e)) return true; + } + return false; + } +} diff --git a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs index a26f98e..a3b5166 100644 --- a/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientCombatHooks.cs @@ -177,7 +177,7 @@ internal static class ClientCombatHooks // MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal // as ONE queue entry (not split into four) so the sequence stays atomic // relative to the drain loop's other actions. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power); try diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index b706fb1..2d5bc81 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -371,7 +371,7 @@ internal static class ClientHelperHooks // (every UseObject/MoveItem/cast sibling already marshals). Drain re-invokes // this on the main thread, where the gate is satisfied and it runs directly. // SelectItem() funnels through here, so this one gate covers both. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSetSelectedObject(objectId); if (_setSelectedObject == null) @@ -400,7 +400,7 @@ internal static class ClientHelperHooks /// public static bool SelectFromOverlay(uint objectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueOverlaySelect(objectId); if (objectId == 0 || _setSelectedObject == null) @@ -433,7 +433,7 @@ internal static class ClientHelperHooks // main thread (via the OnEndScene drain), not off the pump thread. Off-thread // UseObject mutated AC's animation sequence (CSequence) and corrupted it -> // the CSequence::update_internal AV captured after looting was enabled. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseObject(objectId); if (_useObject == null || !IsValidObjectId(objectId)) @@ -466,7 +466,7 @@ internal static class ClientHelperHooks // Marshal onto AC's main thread (off-thread use-on-target mutates AC's // object/animation graph and corrupts it — see UseObject). Drain re-invokes // this on the main thread, where the gate is satisfied and it runs directly. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseObjectOn(sourceObjectId, targetObjectId); if (_useWithTargetEvent == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId)) @@ -492,7 +492,7 @@ internal static class ClientHelperHooks public static bool UseEquippedItem(uint sourceObjectId, uint targetObjectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueUseEquippedItem(sourceObjectId, targetObjectId); if (_useEquippedItem == null || !IsValidObjectId(sourceObjectId) || !IsValidObjectId(targetObjectId)) @@ -517,7 +517,7 @@ internal static class ClientHelperHooks { // Marshal onto AC's main thread — off-thread item moves race AC's per-tick // object/container bookkeeping (the looting null-deref AV class). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMoveItemExternal(objectId, targetContainerId, amount); if (_moveItemExternal == null || !IsValidObjectId(objectId) || !IsValidContainerId(targetContainerId) || amount < 0) @@ -547,7 +547,7 @@ internal static class ClientHelperHooks public static bool MoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMoveItemInternal(objectId, targetContainerId, slot, amount); if (_moveItemInternal == null) return false; @@ -604,7 +604,7 @@ internal static class ClientHelperHooks /// public static bool SplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSplitStackInternal(objectId, targetContainerId, slot, amount); if (_moveItemInternal == null) return false; @@ -656,7 +656,7 @@ internal static class ClientHelperHooks /// public static bool MergeStackInternal(uint sourceObjectId, uint targetObjectId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMergeStackInternal(sourceObjectId, targetObjectId); if (_eventStackableMerge == null) return false; @@ -714,7 +714,7 @@ internal static class ClientHelperHooks /// public static bool PutItemInContainerAt(uint objectId, uint containerId, int slot) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueuePutItemInContainer(objectId, containerId, slot); if (_eventPutItemInContainer == null) return false; @@ -749,7 +749,7 @@ internal static class ClientHelperHooks // Marshal onto AC's main thread — off-thread F7B1 inventory sends race AC's // per-tick object/container bookkeeping (the looting null-deref AV class), // exactly like MoveItemExternal / MergeStackInternal. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueGiveObjectTo(objectId, targetId, amount); if (_eventGiveObjectRequest == null) return false; @@ -795,7 +795,7 @@ internal static class ClientHelperHooks public static bool WieldItem(uint objectId, uint equipMask) { // Inventory sends run on AC's main thread, like MoveItemExternal / GiveObjectTo. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventGetAndWieldItem != null && IsValidObjectId(objectId) && equipMask != 0 && AcMainThreadQueue.EnqueueWieldItem(objectId, equipMask); @@ -825,7 +825,7 @@ internal static class ClientHelperHooks public static bool DropItem(uint objectId) { // Inventory sends run on AC's main thread, like WieldItem / GiveObjectTo. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventDropItem != null && IsValidObjectId(objectId) && AcMainThreadQueue.EnqueueDropItem(objectId); @@ -859,7 +859,7 @@ internal static class ClientHelperHooks public static bool CloseContainer(uint containerId) { // An inventory game-action send, like DropItem / WieldItem: main thread only. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return _eventNoLongerViewingContents != null && IsValidObjectId(containerId) && AcMainThreadQueue.EnqueueCloseContainer(containerId); @@ -1151,7 +1151,7 @@ internal static class ClientHelperHooks // same class as the SetSelectedObject 0x60D1D AV. The ring is FIFO with // one consumer, so open -> add -> execute keep their order. Drain calls // back into this method on the main thread, where the gate is satisfied. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageOpen(toolId); try @@ -1193,7 +1193,7 @@ internal static class ClientHelperHooks // queued entry carries only the item id: on the main thread this method // runs again and re-reads the instance, since the panel may have closed // or been rebuilt in between. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageAddItem(itemId); try @@ -1228,7 +1228,7 @@ internal static class ClientHelperHooks // Off-thread: same shape as SalvagePanelAddItem (instance re-read on the // main thread when the entry drains). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSalvageExecute(); try diff --git a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs index e8cb7ec..4ec9061 100644 --- a/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatActionHooks.cs @@ -332,7 +332,7 @@ internal static class CombatActionHooks public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel); if (_meleeAttack == null) @@ -350,7 +350,7 @@ internal static class CombatActionHooks public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel); if (_missileAttack == null) @@ -373,7 +373,7 @@ internal static class CombatActionHooks // (CSequence) state on the thread that updates it — eliminating the // off-thread-mutation corruption class (e.g. the CSequence::update_internal // AV). On the main thread (incl. the drain) this executes directly. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode); // Prefer the CLIENT-level entry point. _changeCombatMode is bound by @@ -412,7 +412,7 @@ internal static class CombatActionHooks // same gate. Queued in the action ring so it keeps FIFO order after an attack // that is already queued (it used to run at once and could overtake it). The // drain re-enters here on the main thread, where the gate passes. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueCancelAttack(); try @@ -435,7 +435,7 @@ internal static class CombatActionHooks // so off-thread calls go to the non-gesture QueryHealth queue and the drain // re-enters here on the main thread. Callers ignore the result and read the // async 0x01C0 reply, so "queued" is enough. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return targetId != 0 && AcMainThreadQueue.EnqueueQueryHealth(targetId); try @@ -461,7 +461,7 @@ internal static class CombatActionHooks // here on the main thread, where this gate passes and the packet is sent. // Fire-and-forget: the appraisal reply is async anyway, so "queued" keeps // the bool's meaning ("requested"). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueRequestId(objectId); try @@ -504,7 +504,7 @@ internal static class CombatActionHooks // which the drain-before order is intended to fix. On the main thread (the // UseTime drain, or any main-thread caller) this falls through to the direct // cast below. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId); // From here on we are ON AC's main thread: the Client::UseTime cast drain diff --git a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs index 80aa85e..036d104 100644 --- a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs @@ -163,7 +163,7 @@ internal static class CommandInterpreterHooks // motion graph the CSequence-AV corruption class kills. Off-thread // callers marshal through the action ring (drained post-tick, // gesture-gated) like every other mutator. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: !enabled)) return AcMainThreadQueue.EnqueueSetAutoRun(enabled); int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls); if (!TryBindDelegates()) @@ -269,7 +269,7 @@ internal static class CommandInterpreterHooks public static bool SetMotion(uint motion, bool enabled) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: !enabled)) return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun if (!TryBindDelegates() || _setMotion == null) return false; @@ -287,7 +287,7 @@ internal static class CommandInterpreterHooks public static bool StopCompletely() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun if (!TryBindDelegates() || _stopCompletely == null) return false; @@ -305,7 +305,7 @@ internal static class CommandInterpreterHooks public static bool TurnToHeading(float headingDegrees) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls); if (!TryBindDelegates() || _turnToHeading == null) @@ -398,7 +398,7 @@ internal static class CommandInterpreterHooks public static bool TapJump() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTapJump(); if (!TryBindDelegates()) return false; @@ -419,7 +419,7 @@ internal static class CommandInterpreterHooks public static bool CommenceJump() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueCommenceJump(); if (!TryBindDelegates()) return false; @@ -437,7 +437,7 @@ internal static class CommandInterpreterHooks public static bool DoJump(bool autonomous) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous); if (!TryBindDelegates()) return false; diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index cdd1c21..af86683 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -166,6 +166,14 @@ internal static class HeartbeatLogger if (largest >= 0) vaField += $" valargest={largest}MB"; } catch { } + // Crash logger module cache (native): rebuilt every 10 s here, so a fault + // never has to call the loader to name a module. + if (tick % 10 == 1) + { + try { SehTrampoline.RefreshCrashLoggerModules(); } catch { } + } + // Safety net for the main-thread message box count (MainThreadFreeze). + MessageBoxHooks.ReconcileStaleMainThreadCount(); // pump=paused = plugin ticks paused because AC's main thread is frozen // (MainThreadFreeze); omitted while running. try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; } diff --git a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs index e135f32..fab95f8 100644 --- a/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs +++ b/src/RynthCore.Engine/Compatibility/MainThreadSnapshots.cs @@ -117,10 +117,15 @@ internal static class MainThreadSnapshots try { PlayerProgressHooks.Prefetch(); } catch { } } - // Aelrynth skill mastery: the /mastery-data request after login, on panel open - // and after a raise (only on Aelrynth; a few compares when nothing is wanted). - try { MasteryFeed.MainThreadTick(playerLive); } catch { } - // Aelrynth account vault (the Inventory panel's Vault view): reads on request only. - try { VaultFeed.MainThreadTick(playerLive); } catch { } + // Both send server commands (a mastery raise, a vault withdraw), so like the + // Inventory panel they wait out a world transition; their requests stay pending. + if (!PlayerLifecycleLog.InWorldTransition) + { + // Aelrynth skill mastery: the /mastery-data request after login, on panel open + // and after a raise (only on Aelrynth; a few compares when nothing is wanted). + try { MasteryFeed.MainThreadTick(playerLive); } catch { } + // Aelrynth account vault (the Inventory panel's Vault view): reads on request only. + try { VaultFeed.MainThreadTick(playerLive); } catch { } + } } } diff --git a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs index 55d7ad9..5570429 100644 --- a/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MessageBoxHooks.cs @@ -59,8 +59,6 @@ internal static class MessageBoxHooks /// 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() { @@ -123,47 +121,58 @@ internal static class MessageBoxHooks { MessageBoxDelegate? original = wide ? _originalW : _originalA; string? description = null; - bool mainThread = false; + bool counted = false; long opened = Environment.TickCount64; + int result = 0; try { - 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 */ } - - int result = original != null ? original(hWnd, text, caption, type) : 0; - - try - { - long secs = (Environment.TickCount64 - opened) / 1000; - RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); - if (mainThread && Interlocked.Decrement(ref _mainThreadOpenCount) < 0) - Interlocked.Exchange(ref _mainThreadOpenCount, 0); - if (Interlocked.Decrement(ref _openCount) <= 0) + try { - Interlocked.Exchange(ref _openCount, 0); - _openDescription = null; + // Counted first: the freeze gate must see the box even if the rest throws. + bool mainThread = MainThreadGuard.IsOnMainThread(); + if (mainThread) + { + Interlocked.Increment(ref _mainThreadOpenCount); + counted = true; + } + string body = Read(text, wide); + // AC's OUT OF MEMORY box is modal: the process never crashes, so Windows never + // writes a dump, and the launcher later kills the client as wedged. Decide and + // write ONE full-memory dump now, before anything here allocates more (the stack + // walk and the description below), and before the box shows (this thread waits: + // the box would hold it anyway, and the user's OK must not let AC run on and + // exit mid-dump). + if (OutOfMemoryBoxRule.IsOutOfMemoryBox(body, mainThread)) + CrashDump.WriteOutOfMemoryDumpOnce(Flatten(body)); + description = Opened(body, caption, type, wide, mainThread); } + catch { /* observation only: never block the dialog */ } + + result = original != null ? original(hWnd, text, caption, type) : 0; + } + finally + { + // First, and whatever happened above: a leaked count would pause plugin ticks for good. + if (counted && Interlocked.Decrement(ref _mainThreadOpenCount) < 0) + Interlocked.Exchange(ref _mainThreadOpenCount, 0); + try + { + long secs = (Environment.TickCount64 - opened) / 1000; + if (Interlocked.Decrement(ref _openCount) <= 0) + { + Interlocked.Exchange(ref _openCount, 0); + _openDescription = null; + } + RynthLog.Info($"MessageBoxHooks: closed after {secs}s (result={result}): {description ?? "?"}"); + } + catch { } } - catch { } return result; } - private static string Opened(IntPtr text, IntPtr caption, uint type, bool wide, out bool mainThread, out bool outOfMemory) + private static string Opened(string body, IntPtr caption, uint type, bool wide, bool mainThread) { - string body = Read(text, wide); string title = Read(caption, wide); - 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 = "?"; @@ -187,6 +196,63 @@ internal static class MessageBoxHooks return description; } + // -- Stale main-thread count (safety net) ------------------------------------ + // The count is decremented in Show's finally, so it should never leak; if it ever reads + // non-zero while AC's main thread owns no dialog window for 30 s, it is reset (and + // logged), so a leak can never pause plugin ticks for good. Heartbeat thread, 1 Hz. + private const long StaleCountResetMs = 30_000; + private static long _countWithoutBoxSinceMs; + + private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lParam); + + [DllImport("user32.dll")] + private static extern bool EnumThreadWindows(uint threadId, EnumThreadWndProc callback, IntPtr lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetClassNameW(IntPtr hWnd, System.Text.StringBuilder name, int max); + + [DllImport("user32.dll")] + private static extern bool IsWindowVisible(IntPtr hWnd); + + private static bool MainThreadOwnsDialog() + { + uint tid = MainThreadGuard.MainThreadId; + if (tid == 0) return false; + bool found = false; + var name = new System.Text.StringBuilder(64); + EnumThreadWindows(tid, (h, _) => + { + name.Clear(); + if (GetClassNameW(h, name, name.Capacity) > 0 && name.ToString() == "#32770" && IsWindowVisible(h)) + { + found = true; + return false; + } + return true; + }, IntPtr.Zero); + return found; + } + + /// Heartbeat thread, about once a second. Never throws. + public static void ReconcileStaleMainThreadCount() + { + try + { + long now = Environment.TickCount64; + // The OOM dump runs before the box window exists: counted, no dialog yet, legitimately. + if (MainThreadOpenCount <= 0 || CrashDump.FullDumpInProgress || MainThreadOwnsDialog()) + { + _countWithoutBoxSinceMs = 0; + return; + } + if (_countWithoutBoxSinceMs == 0) { _countWithoutBoxSinceMs = now; return; } + if (now - _countWithoutBoxSinceMs < StaleCountResetMs) return; + int was = Interlocked.Exchange(ref _mainThreadOpenCount, 0); + _countWithoutBoxSinceMs = 0; + RynthLog.Warn($"MessageBoxHooks: main-thread box count was {was} with no dialog open on AC's main thread for {StaleCountResetMs / 1000}s - reset to 0."); + } + catch { } + } private static string Read(IntPtr p, bool wide) { if (p == IntPtr.Zero) return ""; diff --git a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs index 13617dd..00f404c 100644 --- a/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/MovementActionHooks.cs @@ -151,7 +151,7 @@ internal static class MovementActionHooks public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey); int n = System.Threading.Interlocked.Increment(ref _doMovementCalls); @@ -179,7 +179,7 @@ internal static class MovementActionHooks public static bool StopMovement(uint motion, int holdKey = HoldKeyRun) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: true)) return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey); int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls); @@ -207,7 +207,7 @@ internal static class MovementActionHooks public static bool JumpNonAutonomous(float extent) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueJump(extent); if (_jumpNonAutonomous == null) @@ -231,7 +231,7 @@ internal static class MovementActionHooks if (_autonomyLevel == null) return false; - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueSetAutonomyLevel(level); try diff --git a/src/RynthCore.Engine/Compatibility/MutatorGate.cs b/src/RynthCore.Engine/Compatibility/MutatorGate.cs new file mode 100644 index 0000000..e69f443 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/MutatorGate.cs @@ -0,0 +1,28 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/MutatorGate.cs +// +// The decision behind AcMainThreadQueue.MustQueue, the one line every AC-mutating helper +// opens with: call AC now, or queue the call? +// - off AC's main thread: queue (AC is single-threaded); +// - on it, called BY a queue drain: call now (the drain already applied the gate); +// - on it, a stop or cancel (teardown): call now, even in a world transition; +// - on it otherwise: queue while a world transition holds the drains (render-thread host +// actions used to run straight into a world AC was tearing down), else call now. +// holding is asked last and only when it matters (it is main-thread state). +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +internal static class MutatorGate +{ + public static bool MustQueue(bool onMainThread, bool teardown, bool draining, Func holding) + { + if (!onMainThread) return true; + if (draining || teardown) return false; + return holding(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs index 9cf5e07..63727b6 100644 --- a/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs +++ b/src/RynthCore.Engine/Compatibility/PendingIdQueue.cs @@ -65,14 +65,18 @@ internal sealed class PendingIdQueue /// /// Queue a request for , or merge it into a pending one for the /// same object from the same that is at most - /// old at . + /// old at and was queued AFTER + /// (the last moment a world transition held the + /// drains: an entry from before then is dropped when the drain reaches it, and a request + /// merged into it would be lost with it). /// - public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs) + public Result Enqueue(uint id, long nowMs, int epoch, long mergeMaxAgeMs, long mergeOnlyAfterMs = 0) { for (int i = 0; i < _count; i++) { ref readonly Item q = ref _ring[(_head + i) % _ring.Length]; - if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs) + if (q.Id == id && q.Epoch == epoch && nowMs - q.At <= mergeMaxAgeMs + && (mergeOnlyAfterMs <= 0 || q.At > mergeOnlyAfterMs)) // 0 = no transition: no floor { MergedTotal++; return Result.Merged; diff --git a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs index 5cf8b38..f997a5b 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs @@ -45,11 +45,28 @@ internal static class PlayerLifecycleLog /// 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); + public static bool HoldQueuedWork(long nowMs) + { + bool hold = _state.CheckHolding(nowMs); + if (hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs); + return hold; + } /// AC main thread only: what a drain does with one queued item (WorldTransitionState.Decide). - public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown) => - _state.Decide(nowMs, queuedAtMs, teardown); + public static WorldTransitionState.Verdict DecideQueued(long nowMs, long queuedAtMs, bool teardown) + { + WorldTransitionState.Verdict v = _state.Decide(nowMs, queuedAtMs, teardown); + if (v == WorldTransitionState.Verdict.Hold) Interlocked.Exchange(ref _lastBlockedPublished, nowMs); + return v; + } + + private static long _lastBlockedPublished; + + /// + /// The last moment a drain was held by a world transition (0 = never), for other threads: + /// queued work from at or before it is dropped when the drains reach it. + /// + public static long LastBlockedMs => Interlocked.Read(ref _lastBlockedPublished); /// AC main thread, once per game tick. public static void SampleOnGameThread(bool portaling) @@ -94,6 +111,19 @@ internal static class PlayerLifecycleLog 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."); } + /// + /// AC main thread (SmartBoxHooks, after AC handled 0xF751 PlayerTeleport): a teleport starts + /// now. The settle window runs from here, published at once for the enqueue side. + /// + public static void OnTeleportMessage() + { + long now = Environment.TickCount64; + bool started = _state.OnTeleportMessage(now); + Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs); + if (started) + RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s."); + } + private static string Ago(long since, long now) => since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s"; } diff --git a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs index 8f60197..f502798 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs @@ -385,7 +385,7 @@ internal static class PlayerPhysicsHooks // Park the heading in the coalesced slot instead; AcMainThreadQueue.Drain // calls back in here on the main thread (and falls back to the // CommandInterpreter turn there when there is no player, as before). - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueDirectHeading(decalHeadingDeg); int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls); @@ -457,7 +457,7 @@ internal static class PlayerPhysicsHooks // raw write racing AC's own motion-graph tick is a guaranteed torn // write, not just an AV risk. Reachable off-thread via Jumper.cs's // ReleaseJump on the Decal-coexistence pump thread. - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC); if (!TryGetCMotionInterp(out IntPtr cmi)) diff --git a/src/RynthCore.Engine/Compatibility/PlayerTrade.cs b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs index ac7f2e6..63966dc 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerTrade.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerTrade.cs @@ -141,7 +141,7 @@ internal static unsafe class PlayerTrade /// Ask to trade (0x01F6 OpenTradeNegotiations). public static bool Open(uint targetId) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventOpenTradeNegotiations != null && targetId != 0 && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Open, targetId, 0); if (_eventOpenTradeNegotiations == null || targetId == 0) return false; @@ -153,7 +153,7 @@ internal static unsafe class PlayerTrade /// Put one of your items in the trade window (0x01F8 AddToTrade). slot 0 = next free. public static bool Add(uint itemId, uint slot) { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventAddToTrade != null && itemId != 0 && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Add, itemId, slot); if (_eventAddToTrade == null || itemId == 0) return false; @@ -165,7 +165,7 @@ internal static unsafe class PlayerTrade /// Empty both sides of the window (0x0204 ResetTrade). public static bool Reset() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventResetTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Reset, 0, 0); if (_eventResetTrade == null) return false; byte rv = _eventResetTrade(); @@ -176,7 +176,7 @@ internal static unsafe class PlayerTrade /// Close the trade (0x01F7 CloseTradeNegotiations). public static bool Close() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _eventCloseTradeNegotiations != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Close, 0, 0); if (_eventCloseTradeNegotiations == null) return false; byte rv = _eventCloseTradeNegotiations(); @@ -187,7 +187,7 @@ internal static unsafe class PlayerTrade /// Accept the trade as it stands (the window's Accept button, 0x01FA AcceptTrade). public static bool Accept() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _tradeSystemAcceptTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Accept, 0, 0); if (_tradeSystemAcceptTrade == null) return false; IntPtr system = TradeSystemWithTrade(); @@ -200,7 +200,7 @@ internal static unsafe class PlayerTrade /// Withdraw your acceptance (the window's Decline button, 0x01FB DeclineTrade). public static bool Decline() { - if (!MainThreadGuard.IsOnMainThread()) + if (AcMainThreadQueue.MustQueue(teardown: false)) return _tradeSystemDeclineTrade != null && AcMainThreadQueue.EnqueueTrade((uint)TradeOp.Decline, 0, 0); if (_tradeSystemDeclineTrade == null) return false; IntPtr system = TradeSystemWithTrade(); diff --git a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs index bce841f..36c9705 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs @@ -121,7 +121,7 @@ internal static unsafe class PlayerTraining RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world"); return false; } - if (defer || !MainThreadGuard.IsOnMainThread()) + if (defer || AcMainThreadQueue.MustQueue(teardown: false)) return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp); byte rv = kind switch diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index 5a35d48..993f193 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -174,6 +174,14 @@ internal static class ProcessExitHooks private static void ExitProcessDetour(uint exitCode) { + // A crash exit goes straight to the original, before any managed work (IsCrashExit). + // The reverse-P/Invoke transition into this detour is the only managed step left; a + // native pass-through would remove that too; it is possible but not done here. + if (IsCrashExit(exitCode)) + { + _exitOriginal!(exitCode); + return; + } LogTermination("ExitProcess", IntPtr.Zero, exitCode); // Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this, // hooks stay installed, our threads (TickPump, Avalonia STA) keep @@ -191,7 +199,7 @@ internal static class ProcessExitHooks // 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 + // handler sees the fault first) and CoreCLR's own createdump (native\Loader\Loader.c, ConfigureCrashDumps). This // replaces the managed crash dump written here before, which left nothing for real crashes. private static bool IsCrashExit(uint code) => code >= 0xC0000000u; @@ -211,6 +219,11 @@ internal static class ProcessExitHooks private static void RtlExitUserProcessDetour(uint exitStatus) { + if (IsCrashExit(exitStatus)) // see ExitProcessDetour + { + _rtlExitOriginal!(exitStatus); + return; + } LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus); try { EngineLifecycle.Shutdown(); } catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); } diff --git a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs index 2407ccc..51824cb 100644 --- a/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PropertyUpdateHooks.cs @@ -456,7 +456,9 @@ internal static class PropertyUpdateHooks if (objectId != 0) { EvictObject(objectId); - AppraisalHooks.EvictObject(objectId); + // A client release keeps the identify data a while (a server delete, + // 0xF747, evicts it): see ReleasedObjectRetention. + AppraisalHooks.OnClientRelease(objectId, Environment.TickCount64); } } } diff --git a/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs new file mode 100644 index 0000000..1ffb902 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs @@ -0,0 +1,77 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ReleasedObjectRetention.cs +// +// How long AppraisalHooks keeps an object's identify data after the CLIENT released it +// (AC's BeingDeleted, which fires for every object leaving the client's view). +// +// Before: the data was evicted on every client release, so when the +// object came back into view AutoId found nothing cached and appraised it again: the +// 10-minute re-appraisal window (AutoIdEligibility) almost never applied. Now the data is +// kept for RetainMs after a client release and dropped: +// - when RetainMs has passed (Expire, from AutoIdService's timer); +// - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject); +// - at a session clear (logout), and under AppraisalHooks' object cap. +// A re-create (OnLive) makes the object current again. +// +// Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock). +// Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class ReleasedObjectRetention +{ + public const long DefaultRetainMs = 10L * 60 * 1000; + public const int DefaultMaxReleased = 4096; + + private readonly Dictionary _releasedAt; + private readonly long _retainMs; + private readonly int _max; + + public ReleasedObjectRetention(long retainMs = DefaultRetainMs, int maxReleased = DefaultMaxReleased) + { + _retainMs = retainMs; + _max = maxReleased; + _releasedAt = new Dictionary(maxReleased + 1); + } + + public int Count => _releasedAt.Count; + public long RetainMs => _retainMs; + + /// + /// The client released (which has cached data). Returns true when the + /// data is kept for now; false when it must be dropped at once (the bound is reached and + /// nothing has expired to make room). + /// + public bool OnRelease(uint id, long nowMs) + { + if (_releasedAt.ContainsKey(id)) { _releasedAt[id] = nowMs; return true; } + if (_releasedAt.Count >= _max) return false; + _releasedAt[id] = nowMs == 0 ? 1 : nowMs; + return true; + } + + /// The object is current again (re-created), or its data was dropped for another reason. + public void Forget(uint id) => _releasedAt.Remove(id); + + public bool IsReleased(uint id) => _releasedAt.ContainsKey(id); + + /// Released ids whose data has outlived RetainMs: removed here and added to . + public int Expire(long nowMs, List expired) + { + int n = 0; + foreach (KeyValuePair kv in _releasedAt) + { + if (nowMs - kv.Value < _retainMs) continue; + expired.Add(kv.Key); + n++; + } + for (int i = expired.Count - n; i < expired.Count; i++) + _releasedAt.Remove(expired[i]); + return n; + } + + public void Clear() => _releasedAt.Clear(); +} diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index b731a79..59604ed 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -28,6 +28,7 @@ using System; using System.Runtime.InteropServices; +using System.Threading; namespace RynthCore.Engine.Compatibility; @@ -52,6 +53,24 @@ internal static class SehTrampoline catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } } + private static int _moduleRefreshUnavailable; + + /// + /// Rebuilds the crash logger's module cache (module names at exception time come from it, + /// so the handler never calls the loader). Heartbeat thread, every few seconds. A DLL + /// older than the export is tolerated: the first failure stops the calls. + /// + public static void RefreshCrashLoggerModules() + { + if (!_available || Volatile.Read(ref _moduleRefreshUnavailable) != 0) return; + try { _RefreshCrashLoggerModules(); } + catch (Exception ex) + { + Interlocked.Exchange(ref _moduleRefreshUnavailable, 1); + RynthLog.Compat($"SehTrampoline: crash-logger module refresh unavailable - {ex.GetType().Name}: {ex.Message}"); + } + } + // ── Tag-parser guard (native detour) ─────────────────────────────────── /// Address of the native tag-parser null-guard detour (RC_TagParserGuard), /// for the engine to pass to MinHook as the detour target. @@ -104,6 +123,10 @@ internal static class SehTrampoline CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_RefreshCrashLoggerModules", + CallingConvention = CallingConvention.Cdecl)] + private static extern void _RefreshCrashLoggerModules(); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _GetTagParserGuardAddress(); diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index 85fe442..51f5db9 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -16,6 +16,8 @@ internal static class SmartBoxHooks private const uint PlayerPositionUpdateOpcode = 0x0000F74B; private const uint VectorUpdateOpcode = 0x0000F74E; private const uint UpdateObjectOpcode = 0x0000F7DB; + private const uint ServerObjectDeleteOpcode = 0x0000F747; + private const uint PlayerTeleportOpcode = 0x0000F751; // ACSmartBox::DispatchSmartBoxEvent // 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08 @@ -136,6 +138,17 @@ internal static class SmartBoxHooks TryQueueHealthUpdate(blob, info); TryQueueDamageEvent(blob, info); + // Always on (no server-message capture needed), after AC handled the message: + // 0xF747 ObjectDelete [opcode][objectId]: the SERVER deleted it (AutoId re-arms it + // and its kept identify data goes), unlike the client's own view releases; + // 0xF751 PlayerTeleport: a teleport starts, so queued game actions hold for the + // settle window from this moment (WorldTransitionState), whatever the per-tick + // teleport_in_progress sample catches. + if (info.Opcode == ServerObjectDeleteOpcode && info.RawObjectId != 0) + AutoIdService.OnServerDelete(info.RawObjectId); + else if (info.Opcode == PlayerTeleportOpcode) + PlayerLifecycleLog.OnTeleportMessage(); + if (info.RawObjectId != 0 && (info.Opcode == PositionUpdateOpcode || info.Opcode == PlayerPositionUpdateOpcode || diff --git a/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs index 7287fd8..058ac8b 100644 --- a/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs +++ b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs @@ -93,6 +93,20 @@ internal sealed class WorldTransitionState return edges; } + /// + /// The server's PlayerTeleport message (0xF751) arrived: a teleport begins now, whether or not + /// a tick sample ever sees teleport_in_progress or a landblock jump (a recall into the next + /// landblock shows neither). Starts (or extends) the settle window. Returns false when the + /// window was already running past it. + /// + public bool OnTeleportMessage(long nowMs) + { + long until = nowMs + SettleMs; + if (until <= SettleUntilMs) return false; + SettleUntilMs = until; + return true; + } + /// Two landblocks more than one apart on either axis: a teleport, not a walk. public static bool IsJump(uint from, uint to) { diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index 4578833..af6fb8a 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -123,7 +123,7 @@ internal static class CrashDump } } - // ── OUT OF MEMORY full-memory dump ────────────────────────────────────── + // -- 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; @@ -157,34 +157,55 @@ internal static class CrashDump if (Interlocked.Exchange(ref _oomDumpLatch, 1) != 0) return; string why = "AC OUT OF MEMORY box: " + (reason ?? "?"); _fullDumpInProgress = true; + // The launcher reads this marker (DumpInProgressRule): MiniDumpWriteDump suspends every + // thread, so the log goes silent for the whole dump, which would otherwise read as a dead + // engine and get the client killed mid-dump. + try { RynthLog.Error($"{DumpMarkerStarted} pid={Environment.ProcessId} - AC OUT OF MEMORY box; writing one full-memory dump before it shows."); } + catch { } + Thread? writer = null; try { - RynthLog.Error("CrashDump: AC OUT OF MEMORY box opening - writing one full-memory dump before it shows."); - Thread? writer = null; - try + writer = new Thread(() => { - 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."); + // The flag stays up until the writer itself is done, even past a timed-out Join. + try { WriteOutOfMemoryDumpCore(why); } + finally { FinishFullDump(); } + }) { IsBackground = true, Name = "RynthCore.OomDump" }; + writer.Start(); } catch (Exception ex) { - RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); + // No thread to be had (out of memory, after all): write it from this one. + try { RynthLog.Error($"CrashDump: dump thread failed to start ({ex.GetType().Name}) - writing on the calling thread."); } catch { } + writer = null; } - finally + try { - _fullDumpInProgress = false; + if (writer == null) + { + try { WriteOutOfMemoryDumpCore(why); } + finally { FinishFullDump(); } + } + else if (!writer.Join(FullDumpWaitMs)) + { + RynthLog.Error($"CrashDump: full dump still writing after {FullDumpWaitMs / 1000}s - letting the box open (the writer keeps going)."); + } } + catch (Exception ex) + { + try { RynthLog.Error($"CrashDump: OOM dump failed {ex.GetType().Name}: {ex.Message}"); } catch { } + } + } + + /// Log line written before the OUT OF MEMORY full dump starts (read by the launcher). + internal const string DumpMarkerStarted = RynthCore.Install.DumpInProgressRule.MarkerStarted; + /// Log line written once the writer has finished, whatever the outcome. + internal const string DumpMarkerEnded = RynthCore.Install.DumpInProgressRule.MarkerEnded; + + private static void FinishFullDump() + { + _fullDumpInProgress = false; + try { RynthLog.Error($"{DumpMarkerEnded} pid={Environment.ProcessId}."); } catch { } } private static void WriteOutOfMemoryDumpCore(string reason) @@ -193,22 +214,20 @@ internal static class CrashDump { 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}"); + // Only after the new dump succeeded: a failed write never costs an older one. + PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept); } else { RynthLog.Error("CrashDump: OUT OF MEMORY full-memory dump FAILED; writing the small hang-type dump instead."); WriteSelfDump(reason, out _, "oom-small"); } - PruneDumps(dir, OutOfMemoryDumpPrefix, OutOfMemoryDumpsKept); } catch (Exception ex) { @@ -216,7 +235,13 @@ internal static class CrashDump } } - /// Deletes all but the newest *.dmp files in . Never throws. + /// + /// Deletes all but the newest *.dmp files in + /// . The folder is shared by every client: a dump whose name carries + /// the pid of ANOTHER process that is still running is never deleted (it may still be + /// writing it, or about to report it), and is not counted against . + /// Never throws. + /// internal static int PruneDumps(string dir, string prefix, int keep) { int deleted = 0; @@ -224,13 +249,22 @@ internal static class CrashDump { 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++) + int kept = 0; + int self = Environment.ProcessId; + foreach (FileInfo f in files) { + int pid = DumpPid(f.Name, prefix); + if (pid > 0 && pid != self && IsProcessAlive(pid)) + continue; // another live client's dump: not ours to delete + if (kept < Math.Max(0, keep)) { kept++; continue; } + string name = f.Name; + long length = 0; + try { length = f.Length; } catch { } try { - files[i].Delete(); + f.Delete(); deleted++; - RynthLog.Info($"CrashDump: pruned old dump {files[i].Name} ({files[i].Length / (1024 * 1024)}MB)."); + RynthLog.Info($"CrashDump: pruned old dump {name} ({length / (1024 * 1024)}MB)."); } catch { /* in use by a debugger, or already gone */ } } @@ -238,4 +272,25 @@ internal static class CrashDump catch { } return deleted; } -} + + /// The pid in "prefix<pid>_...dmp", or 0. + internal static int DumpPid(string fileName, string prefix) + { + if (!fileName.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return 0; + int start = prefix.Length, end = start; + while (end < fileName.Length && char.IsDigit(fileName[end])) end++; + return end > start && int.TryParse(fileName.AsSpan(start, end - start), out int pid) ? pid : 0; + } + + private static bool IsProcessAlive(int pid) + { + try + { + using var p = System.Diagnostics.Process.GetProcessById(pid); + return !p.HasExited; + } + catch + { + return false; + } + }} diff --git a/src/RynthCore.Engine/MainThreadFreezeRule.cs b/src/RynthCore.Engine/MainThreadFreezeRule.cs index 3705784..4af5b4a 100644 --- a/src/RynthCore.Engine/MainThreadFreezeRule.cs +++ b/src/RynthCore.Engine/MainThreadFreezeRule.cs @@ -33,6 +33,19 @@ internal static class MainThreadFreezeRule } } +/// +/// Is a message box AC's OUT OF MEMORY box (the one that gets a full-memory dump)? Only on +/// AC's main thread, and only AC's own text, matched exactly at the start (ordinal): a plugin +/// box or a chat line that merely mentions memory must never cost a multi-gigabyte dump. +/// +internal static class OutOfMemoryBoxRule +{ + public const string Prefix = "OUT OF MEMORY: Failed to allocate"; + + public static bool IsOutOfMemoryBox(string? body, bool onMainThread) => + onMainThread && body != null && body.StartsWith(Prefix, System.StringComparison.Ordinal); +} + /// Single-writer (the plugin pump). Not thread-safe; the engine glue publishes copies. internal sealed class PumpPauseTracker { diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 0d1555d..3f05bfe 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -164,6 +164,7 @@ + diff --git a/src/Shared/DumpInProgressRule.cs b/src/Shared/DumpInProgressRule.cs new file mode 100644 index 0000000..41c5c68 --- /dev/null +++ b/src/Shared/DumpInProgressRule.cs @@ -0,0 +1,49 @@ +// ============================================================================ +// Shared - DumpInProgressRule.cs (compiled into the engine and the launcher) +// +// The engine's OUT OF MEMORY full-memory dump (CrashDump) suspends every thread in the +// client while dbghelp writes it, for minutes on a 3 GB process. The log goes silent +// meanwhile, which the launcher's wedge watch (AutoRestartWedgedClients) reads as a dead +// engine after 120 s and kills the client: mid-dump, leaving a truncated file. The engine +// writes MarkerStarted before the dump and MarkerEnded after it; the launcher holds off +// its kill while a dump is in progress by either sign: +// - the log tail's last MarkerStarted has no MarkerEnded after it, and the log was +// written less than MaxMarkerAge ago (a dump never takes that long; a client that +// died mid-dump is killed after it); or +// - the client's acclient_oom__*.dmp file is still being written (modified within +// FileQuietMs). +// The launcher's restart after the dump, for the OOM box that follows, is unchanged. +// +// Pure. Compiled into tools\EngineRobustnessTests. +// ============================================================================ + +using System; + +namespace RynthCore.Install; + +internal static class DumpInProgressRule +{ + public const string MarkerStarted = "CrashDump: FULL-MEMORY DUMP STARTED"; + public const string MarkerEnded = "CrashDump: FULL-MEMORY DUMP ENDED"; + public const string OomDumpPrefix = "acclient_oom_"; + + public static readonly TimeSpan MaxMarkerAge = TimeSpan.FromMinutes(10); + public static readonly TimeSpan FileQuietMs = TimeSpan.FromSeconds(30); + + /// + /// True while the launcher must not kill the client for a silent log. + /// : the end of RynthCore.<pid>.log; + /// : its last write; : + /// the last write of the newest acclient_oom_<pid>_*.dmp, or null. + /// + public static bool IsDumping(string? logTail, DateTime logLastWriteUtc, DateTime? newestOomDumpWriteUtc, DateTime nowUtc) + { + if (newestOomDumpWriteUtc is DateTime dumpWrite && nowUtc - dumpWrite < FileQuietMs) + return true; + if (string.IsNullOrEmpty(logTail)) return false; + int started = logTail.LastIndexOf(MarkerStarted, StringComparison.Ordinal); + if (started < 0) return false; + if (logTail.IndexOf(MarkerEnded, started, StringComparison.Ordinal) >= 0) return false; + return nowUtc - logLastWriteUtc < MaxMarkerAge; + } +} diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index 0525534..29122af 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -9,6 +9,11 @@ WorldTransitionState.cs queued game actions are held through a death / portal / landblock jump, then stale ones dropped while stops and cancels still run AddressSpace.cs the largest-free-block fold (and one live walk of this process) + ActionRing.cs the action ring itself: teardown reserve, refusal in a transition + CastStopRules.cs a cast waits for a movement stop queued at or before it + MutatorGate.cs queue-or-call for every mutator (plus a source scan of the call sites) + ReleasedObjectRetention identify data kept 10 min after a client release + DumpInProgressRule.cs the launcher holds its wedge kill while an OOM dump is written Run: dotnet run -c Release (exit 0 = pass, 1 = fail) --> @@ -26,6 +31,11 @@ + + + + + diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs index 7b22b51..2bead51 100644 --- a/tools/EngineRobustnessTests/Program.cs +++ b/tools/EngineRobustnessTests/Program.cs @@ -7,7 +7,7 @@ namespace EngineRobustnessTests; /// The pure decision parts of the engine-robustness pass. Every clock is a plain /// number; nothing touches AC. /// -internal static class Program +internal static partial class Program { private static int _checks, _failed; private static string _case = ""; @@ -40,6 +40,8 @@ internal static class Program AddressSpaceFold(); + RunRingAndGateTests(); + Console.WriteLine($"{_checks} check(s), {_failed} failed."); return _failed == 0 ? 0 : 1; } diff --git a/tools/EngineRobustnessTests/RingAndGateTests.cs b/tools/EngineRobustnessTests/RingAndGateTests.cs new file mode 100644 index 0000000..b1676f8 --- /dev/null +++ b/tools/EngineRobustnessTests/RingAndGateTests.cs @@ -0,0 +1,332 @@ +using System.Text.RegularExpressions; +using RynthCore.Engine; +using RynthCore.Engine.Compatibility; +using RynthCore.Install; + +namespace EngineRobustnessTests; + +/// Checks for the action ring, the mutator gate, appraisal retention, the dump rules and the cast slot. +internal static partial class Program +{ + private static void RunRingAndGateTests() + { + RingTakesAStopWhenFullOfStarts(); + RingRefusesStartsDuringATransition(); + RingStopRunsFirstAfterTheWindow(); + CastStopFindsAnOutOfOrderStop(); + + GateTruthTable(); + GateCallSitesAllUseTheSameShape(); + + RequestIdNeverMergesIntoAHeldEntry(); + + ReleasedDataKeptSoRecreateSkips(); + ReleasedDataExpiresAndServerDeleteEvicts(); + + TeleportMessageStartsTheWindow(); + + OutOfMemoryBoxMatchesOnlyAcsBox(); + LauncherHoldsTheKillDuringADump(); + } + + // ---- the action ring (the real ActionRing, the one AcMainThreadQueue uses) -------- + + private readonly record struct Act(string What, long At, bool Teardown); + + private static void RingTakesAStopWhenFullOfStarts() + { + _case = "ring reserve"; + var ring = new ActionRing(256, 32); + int queued = 0, full = 0; + for (int i = 0; i < 300; i++) + { + var r = ring.TryEnqueue(new Act("start", 1000, false), teardown: false, inTransition: false); + if (r == ActionRing.Admit.Queued) queued++; + else if (r == ActionRing.Admit.Full) full++; + } + Check(queued == 224 && full == 76, $"300 starts: 224 taken, the rest refused at the reserve (got {queued}/{full})"); + Check(ring.TryEnqueue(new Act("stop", 1001, true), teardown: true, inTransition: false) == ActionRing.Admit.Queued, + "a stop is still taken"); + for (int i = 0; i < 31; i++) + ring.TryEnqueue(new Act("cancel", 1002, true), teardown: true, inTransition: false); + Check(ring.Count == 256, $"the reserve fills only with teardown (count {ring.Count})"); + Check(ring.TryEnqueue(new Act("stop", 1003, true), teardown: true, inTransition: false) == ActionRing.Admit.Full, + "a completely full ring refuses even a stop"); + } + + private static void RingRefusesStartsDuringATransition() + { + _case = "ring transition"; + var ring = new ActionRing(256, 32); + int rejected = 0; + for (int i = 0; i < 300; i++) + if (ring.TryEnqueue(new Act("start", 2000, false), teardown: false, inTransition: true) == ActionRing.Admit.RejectedTransition) + rejected++; + Check(rejected == 300 && ring.Count == 0, $"300 starts during a hold are refused, none stored (rejected {rejected}, count {ring.Count})"); + Check(ring.TryEnqueue(new Act("stop", 2001, true), teardown: true, inTransition: true) == ActionRing.Admit.Queued, + "a stop during the hold is taken"); + } + + /// + /// The flood scenario against the real ring: a bot floods starts before the transition is + /// seen (the ring fills to the reserve), the player dies, 300 more starts arrive during the + /// hold, then a stop. Nothing runs during the hold; after it the stale starts are dropped and + /// the stops are the first things to run. + /// + private static void RingStopRunsFirstAfterTheWindow() + { + _case = "ring drain"; + var ring = new ActionRing(256, 32); + var s = new WorldTransitionState(); + s.Sample(900, false, false, 0x00AE); + for (int i = 0; i < 300; i++) + ring.TryEnqueue(new Act("start", 1000, false), false, s.InTransition(1000)); + s.Sample(1500, true, false, 0x00AE); // dies + for (int i = 0; i < 300; i++) + ring.TryEnqueue(new Act("start-held", 2000, false), false, s.InTransition(2000)); + var stopAdmit = ring.TryEnqueue(new Act("stop", 2500, true), true, s.InTransition(2500)); + Check(stopAdmit == ActionRing.Admit.Queued, $"the stop is accepted ({stopAdmit})"); + + var ran = new List(); + int dropped = 0; + bool heldClean = true; + for (long now = 1500; now < 20_000; now += 16) + { + s.Sample(now, now < 9000, false, 0x00AE); + int before = ring.Count; + if (s.CheckHolding(now)) { heldClean &= ring.Count == before; continue; } // Drain's early return + while (ring.TryDequeue(out Act e)) + { + var v = s.Decide(now, e.At, e.Teardown); + if (v == WorldTransitionState.Verdict.Drop) dropped++; + else ran.Add(e.What); + } + } + Check(heldClean, "nothing leaves the ring while held"); + Check(ran.Count > 0 && ran[0] == "stop", $"the stop runs first after the window (ran [{string.Join(",", ran.Take(3))}])"); + Check(ran.Count == 1 && dropped == 224, $"the 224 stale starts are dropped, nothing else runs (ran {ran.Count}, dropped {dropped})"); + } + + // ---- the cast drain's stop check (the real CastStopRules over the real ActionRing) ------ + + /// + /// A stop queued at or before the cast is found wherever it sits in the ring, including + /// behind an entry stamped after the cast (two producers can land out of time order). + /// + private static void CastStopFindsAnOutOfOrderStop() + { + _case = "cast stop check"; + static bool Any(ActionRing r, long at) => + CastStopRules.AnyStopAtOrBefore(r, at, static e => e.At, static e => e.Teardown); + + var empty = new ActionRing(8, 2); + Check(!Any(empty, 1000), "an empty ring has no stop"); + + var outOfOrder = new ActionRing(8, 2); + outOfOrder.TryEnqueue(new Act("start", 1200, false), false, false); // newer than the cast + outOfOrder.TryEnqueue(new Act("stop", 900, true), true, false); // older, queued behind it + Check(Any(outOfOrder, 1000), "a stop older than the cast, behind a newer entry, is found"); + + var onlyNewer = new ActionRing(8, 2); + onlyNewer.TryEnqueue(new Act("start", 500, false), false, false); + onlyNewer.TryEnqueue(new Act("stop", 1500, true), true, false); + Check(!Any(onlyNewer, 1000), "a stop queued after the cast does not count"); + + var sameTime = new ActionRing(8, 2); + sameTime.TryEnqueue(new Act("stop", 1000, true), true, false); + Check(Any(sameTime, 1000), "a stop queued at the cast's own time counts"); + + var noStop = new ActionRing(8, 2); + noStop.TryEnqueue(new Act("start", 100, false), false, false); + noStop.TryEnqueue(new Act("start", 200, false), false, false); + Check(!Any(noStop, 1000), "older entries that are not stops do not count"); + Check(noStop.Count == 2 && outOfOrder.Count == 2, "the check removes nothing"); + } + + // ---- the mutator gate -------------------------------------------------------- + + private static void GateTruthTable() + { + _case = "mutator gate"; + int asked = 0; + Func holding = () => { asked++; return true; }; + Func clear = () => { asked++; return false; }; + Check(MutatorGate.MustQueue(false, false, false, clear), "off the main thread: queue"); + Check(MutatorGate.MustQueue(false, true, true, clear), "off the main thread, even teardown in a drain: queue"); + Check(!MutatorGate.MustQueue(true, false, false, clear), "main thread, no transition: call now"); + Check(MutatorGate.MustQueue(true, false, false, holding), "main thread in a transition (render-thread host action): queue"); + Check(!MutatorGate.MustQueue(true, true, false, holding), "main thread in a transition, a stop: call now"); + asked = 0; + Check(!MutatorGate.MustQueue(true, false, true, holding) && asked == 0, "called by a drain: call now, without asking the transition state"); + asked = 0; + MutatorGate.MustQueue(false, false, false, holding); + Check(asked == 0, "off the main thread the (main-thread-only) transition state is never asked"); + } + + /// + /// Every AC-mutating helper opens with the same gate: no helper may still decide with the old + /// bare IsOnMainThread() check before an AcMainThreadQueue.Enqueue*, and each stop/cancel + /// passes teardown: true while every other passes false (or !enabled for the two toggles). + /// + private static void GateCallSitesAllUseTheSameShape() + { + _case = "gate call sites"; + string? compat = FindRepoDir(Path.Combine("src", "RynthCore.Engine", "Compatibility")); + Check(compat != null, "found src\\RynthCore.Engine\\Compatibility by walking up"); + if (compat == null) return; + string[] files = { "ClientCombatHooks.cs", "CommandInterpreterHooks.cs", "ClientHelperHooks.cs", "CombatActionHooks.cs", + "MovementActionHooks.cs", "PlayerPhysicsHooks.cs", "PlayerTrade.cs", "PlayerTraining.cs" }; + var enqueue = new Regex(@"AcMainThreadQueue\.(Enqueue\w+)\("); + var gate = new Regex(@"AcMainThreadQueue\.MustQueue\(teardown: (true|false|!enabled)\)"); + string[] teardownTrue = { "EnqueueStopCompletely", "EnqueueStopMovement", "EnqueueCancelAttack", "EnqueueCloseContainer" }; + string[] toggles = { "EnqueueSetAutoRun", "EnqueueSetMotion" }; + int sites = 0, bad = 0; + foreach (string f in files) + { + string[] lines = File.ReadAllLines(Path.Combine(compat, f)); + for (int i = 0; i < lines.Length; i++) + { + Match m = enqueue.Match(lines[i]); + if (!m.Success) continue; + string name = m.Groups[1].Value; + if (name is "EnqueueWriteToChat" or "EnqueueChatCommand") continue; + sites++; + // The gate line is the nearest "if (" line above the enqueue (within 3 lines). + string? gateLine = null; + for (int j = i; j >= Math.Max(0, i - 3); j--) + if (lines[j].TrimStart().StartsWith("if (", StringComparison.Ordinal)) { gateLine = lines[j]; break; } + Match g = gateLine == null ? Match.Empty : gate.Match(gateLine); + string want = teardownTrue.Contains(name) ? "true" : toggles.Contains(name) ? "!enabled" : "false"; + if (!g.Success || g.Groups[1].Value != want || gateLine!.Contains("IsOnMainThread")) + { + bad++; + Console.WriteLine($"[gate] {f}:{i + 1} {name}: gate line '{gateLine?.Trim()}' (want teardown: {want})"); + } + } + } + Check(sites == 45, $"45 gated mutator call sites found (got {sites})"); + Check(bad == 0, $"every one opens with AcMainThreadQueue.MustQueue(teardown: ...) and the right teardown value ({bad} wrong)"); + } + + private static string? FindRepoDir(string relative) + { + string? dir = AppContext.BaseDirectory; + while (dir != null) + { + string candidate = Path.Combine(dir, relative); + if (Directory.Exists(candidate)) return candidate; + dir = Path.GetDirectoryName(dir); + } + return null; + } + + // ---- no merge into an entry a transition will drop ------------------------------- + + private static void RequestIdNeverMergesIntoAHeldEntry() + { + _case = "requestid merge floor"; + var q = new PendingIdQueue(8); + q.Enqueue(42, 1000, 1, 7_500); + // A transition held the drains up to 1500: the entry from 1000 will be dropped. + Check(q.Enqueue(42, 2000, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Queued, + "a request after the window does not merge into the doomed entry"); + Check(q.Count == 2, "so it survives the drop"); + Check(q.Enqueue(42, 2100, 1, 7_500, mergeOnlyAfterMs: 1500) == PendingIdQueue.Result.Merged, + "it merges into the new one"); + var r = new PendingIdQueue(8); + r.Enqueue(43, 1000, 1, 7_500); + Check(r.Enqueue(43, 2000, 1, 7_500, mergeOnlyAfterMs: 0) == PendingIdQueue.Result.Merged, "no transition: merges as before"); + } + + // ---- identify data kept across a client release --------------------------------- + + /// + /// Wired as the engine wires them: AppraisalHooks' cache (here a set) keeps an object while + /// ReleasedObjectRetention says so; AutoIdEligibility decides the re-create. + /// + private static void ReleasedDataKeptSoRecreateSkips() + { + _case = "release keeps data"; + var cache = new HashSet(); + var keep = new ReleasedObjectRetention(); + var elig = new AutoIdEligibility(); + long t = 1000; + Check(elig.OnCreate(50, t, cache.Contains(50)) == AutoIdEligibility.CreateDecision.Appraise, "first create: appraised"); + elig.OnSent(50, t + 100); + cache.Add(50); // the identify arrived + // Client release (BeingDeleted): AppraisalHooks.OnClientRelease + if (!keep.OnRelease(50, t + 60_000)) cache.Remove(50); + elig.OnClientRelease(50); + // Re-created 5 minutes later: AutoIdService.Enqueue (MarkLive, then the decision) + keep.Forget(50); + var d = elig.OnCreate(50, t + 5 * 60_000, cache.Contains(50)); + Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created within 10 min with the data kept: skipped ({d})"); + Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})"); + } + + private static void ReleasedDataExpiresAndServerDeleteEvicts() + { + _case = "release expiry"; + var keep = new ReleasedObjectRetention(10 * 60_000, 4); + var expired = new List(); + keep.OnRelease(1, 1000); + keep.OnRelease(2, 2000); + Check(keep.Expire(1000 + 10 * 60_000 - 1, expired) == 0, "kept inside the 10 minutes"); + Check(keep.Expire(2000 + 10 * 60_000, expired) == 2 && expired.SequenceEqual(new uint[] { 1, 2 }), "both dropped once past it"); + Check(keep.Count == 0, "and no longer tracked"); + for (uint i = 10; i < 14; i++) keep.OnRelease(i, 5000); + Check(!keep.OnRelease(99, 5000), "at the bound a release is not kept (the caller evicts it at once)"); + keep.Forget(10); + Check(keep.OnRelease(99, 5000), "room again once one is forgotten (re-created or server-deleted)"); + } + + // ---- 0xF751: the teleport message as its own signal ---------------------------------- + + private static void TeleportMessageStartsTheWindow() + { + _case = "teleport message"; + var s = new WorldTransitionState(); + s.Sample(1000, false, false, 0xA9B4); + Check(!s.InTransition(2000), "no transition before the message"); + Check(s.OnTeleportMessage(2000), "PlayerTeleport received: the window starts"); + // No portal flag, no landblock change, alive: only the message. + s.Sample(2016, false, false, 0xA9B4); + Check(s.InTransition(2000 + WorldTransitionState.SettleMs - 1), "held for the full settle on the message alone"); + Check(s.Decide(3000, 2500, false) == WorldTransitionState.Verdict.Hold, "queued work held"); + Check(!s.InTransition(2000 + WorldTransitionState.SettleMs), "window ends 5 s after it"); + Check(s.Decide(2000 + WorldTransitionState.SettleMs, 2500, false) == WorldTransitionState.Verdict.Drop, "then stale work is dropped"); + Check(!s.OnTeleportMessage(1500), "an older message never shortens a running window"); + } + + // ---- the OOM dump trigger ------------------------------------------------------ + + private static void OutOfMemoryBoxMatchesOnlyAcsBox() + { + _case = "oom box rule"; + // The real text, from a real log line. + const string real = "OUT OF MEMORY: Failed to allocate -778718788 bytes."; + Check(OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: true), "AC's box on its main thread: dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(real, onMainThread: false), "the same text off the main thread: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("Plugin X: OUT OF MEMORY: Failed to allocate 4 bytes.", true), "prefix not at the start: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("out of memory: failed to allocate 4 bytes.", true), "other case: no dump (ordinal)"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox("OUT OF MEMORY", true), "the bare words: no dump"); + Check(!OutOfMemoryBoxRule.IsOutOfMemoryBox(null, true), "no text: no dump"); + } + + // ---- the launcher holds its kill while a dump is written --------------------------- + + private static void LauncherHoldsTheKillDuringADump() + { + _case = "dump in progress"; + var now = new DateTime(2026, 10, 10, 22, 18, 30, DateTimeKind.Utc); + string started = $"[18:18:16] {DumpInProgressRule.MarkerStarted} pid=123 - ...\n"; + string ended = $"[18:20:01] {DumpInProgressRule.MarkerEnded} pid=123.\n"; + Check(DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-3), null, now), "marker 3 min old, no end: hold the kill"); + Check(!DumpInProgressRule.IsDumping("hb #1\n" + started, now.AddMinutes(-11), null, now), "marker over 10 min old: a client that died mid-dump is killed"); + Check(!DumpInProgressRule.IsDumping(started + ended, now.AddMinutes(-3), null, now), "dump ended: no hold"); + Check(DumpInProgressRule.IsDumping(started + ended + started, now.AddMinutes(-1), null, now), "the LAST marker decides"); + Check(DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddSeconds(-10), now), "no marker, but the dump file was written 10 s ago: hold"); + Check(!DumpInProgressRule.IsDumping("hb #1\n", now.AddMinutes(-5), now.AddMinutes(-2), now), "a dump file quiet for 2 min: no hold"); + Check(!DumpInProgressRule.IsDumping(null, now, null, now), "nothing at all: no hold"); + } +} diff --git a/tools/UsageStatsTests/Program.cs b/tools/UsageStatsTests/Program.cs index aae647b..c0a02ad 100644 --- a/tools/UsageStatsTests/Program.cs +++ b/tools/UsageStatsTests/Program.cs @@ -106,6 +106,18 @@ internal static class Program Make("hang_4_new.dmp", now.AddMinutes(-5)); Check(UsageStats.CountCrashDumps(dumps, now.AddDays(-1), now) == 2, "only crash_*.dmp newer than the last report count (hangs don't)"); Check(UsageStats.CountCrashDumps(Path.Combine(root, "nope"), now.AddDays(-1), now) == 0, "missing dump folder = 0"); + + // CoreCLR fatal-error dumps (the loader's clr__