diff --git a/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md new file mode 100644 index 0000000..1f5444a --- /dev/null +++ b/Changelog/2026-10-04-create-seeds-and-fatal-only-crash-logger.md @@ -0,0 +1,70 @@ +# Engine: object identity seeded at create, native crash logger made fatal-only + +**Date:** 2026-10-04 +**Branch:** `SK-local` +**Ships in:** next installer (2026.10.4.10; previous 2026.10.4.9) + +## 1. Names and types readable from the moment an object is created + +### Problem +Off-thread plugin reads (`TryGetObjectName` / `TryGetItemType`) are served only from the +main-thread identity snapshot, rebuilt every 500 ms. For about 10 s after login that snapshot +resolves almost no names (`[SnapshotDiag] ... names=1`) because qualities aren't populated yet. +The plugin's quick classify retries finish in about 10 ms, so every login-burst object without a +position (pack contents) gave up: about 200 `CLASSIFY-GIVEUP` lines per login, and items stayed +unclassified until a slow retry caught them. + +### Fix +- `CreateObjectHooks` now passes the server's `PublicWeenieDesc` to the new + `ClientObjectHooks.SeedIdentityFromCreate`. It runs on AC's main thread before the plugin is + told about the object. + - It reads `_name` (PWD +4) and `_type` (PWD +56). These are the same offsets the existing + PWD-direct fallbacks use on the embedded copy. + - Every read is validated: the descriptor must start with an acclient.exe vtable, and the + string read is page-checked and length-capped. +- Off-thread lookups use these create seeds when the snapshot has no entry. For types, the seed + is also used when the snapshot says `0` (qualities not loaded yet). The snapshot still wins + whenever it has a real value. +- Seeds are removed in `DeleteObjectHooks`. A 16,384-entry cap clears them if a delete is ever + missed. +- Diagnostics: `[CreateSeed] #1..5` sample lines, plus one + `create-descriptor identity seeds active` summary, so the first in-game log confirms the + offsets. +- Position is unchanged: the position snapshot is taken every 100 ms and already worked at login. + +## 2. Native crash logger: fatal crashes only (`RynthCore.SehTrampoline.dll` v2) + +### Problem +`CrashVeh` logged **every** first-chance access violation, including ones AC or our own `SEH_*` +wrappers catch. Its stack sweep then read 4,096 slots past ESP regardless of where the stack +ended, faulted off the top of the stack, and logged that fault too +(`SehTrampoline.dll+0x13E8`, dataAddr on a page boundary). Every run began with 3–4 noise +entries, and with the 24-entry cap a real fatal crash could find the log already full. + +### Fix (`native/SehTrampoline/SehTrampoline.c`) +- **Stack sweep bounded** to `[Esp, NtCurrentTeb()->NtTib.StackBase)`, and skipped when ESP + isn't inside the thread's stack. +- **Per-thread guards:** + - `t_inLogger`: faults raised while the logger runs are never logged. + - `t_sehDepth`: every `SEH_*` wrapper brackets its call, so AVs those wrappers catch are + ignored. +- **Fatal-only routing:** + - **Unhandled-exception filter** (`SetUnhandledExceptionFilter`, chained to the previous + filter, with a re-entry guard): an unhandled exception is written immediately as FATAL. + - **AVs inside NativeAOT code** (engine/plugins, detected via the `DotNetRuntimeDebugHeader` + export) are written immediately. The runtime fail-fasts on these through + `RaiseFailFastException`, which bypasses every filter. 0xC0000602 / 0xC0000409 are also + written immediately. + - **Every other first-chance AV** (acclient.exe, drivers, DINPUT8…) is formatted into an + 8-slot in-memory ring. It is written only if the process then dies: through the filter, or + at `ExitProcess` (DllMain detach) if it happened within the last 30 s. That keeps + crashes AC's own handler swallows. AVs AC handles and survives never reach the file. +- Separate caps: 16 immediate records and 8 fatal records per run. Formatting is now + bounds-checked (8 KB per record). +- New export `RC_SehTrampolineVersion()` returns 2. The engine logs + `native crash logger installed (v2, fatal-only)` at startup. + +## Build +- `Build-SehTrampoline.ps1`: compiles clean (MSVC 14.50, x86, /W3). +- `RynthCore.Engine` Release build succeeds (no new warnings). +- Not yet verified in game. diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index a458eeb..1cec570 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -26,12 +26,36 @@ #define WIN32_LEAN_AND_MEAN #include +/* File version of this native module (bump with every behavioural change). */ +#define RC_SEH_TRAMPOLINE_VERSION 2 /* v2: fatal-only crash logger, bounded stack sweep */ + +/* Crash-logger state that the SEH_* wrappers and DllMain also touch (defined below). */ +static __declspec(thread) int t_sehDepth; /* >0 while inside an SEH_* wrapper call */ +static void CrashLoggerFlushOnExit(void); + +/* Every SEH_* wrapper brackets its guarded call with these so the crash logger knows an + * access violation on this thread is about to be caught by our own __except. */ +#define RC_SEH_ENTER() (++t_sehDepth) +#define RC_SEH_LEAVE() (--t_sehDepth) + BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) { - (void)hModule; (void)ul_reason; (void)lpReserved; + (void)hModule; + /* lpReserved != NULL on DLL_PROCESS_DETACH means the process is exiting (ExitProcess), + * which is how AC's own crash handling ends the process: write out any recent + * first-chance AVs so a crash AC swallowed still leaves a trace. */ + if (ul_reason == DLL_PROCESS_DETACH && lpReserved != NULL) { + CrashLoggerFlushOnExit(); + } return TRUE; } +/* Diagnostic: native module version so the engine log can confirm which build is loaded. */ +__declspec(dllexport) unsigned int __cdecl RC_SehTrampolineVersion(void) +{ + return RC_SEH_TRAMPOLINE_VERSION; +} + /* ── Cdecl helpers ─────────────────────────────────────────────────────── */ /* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */ @@ -40,14 +64,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -57,14 +84,17 @@ __declspec(dllexport) int __cdecl SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result) { *out_result = NULL; + RC_SEH_ENTER(); __try { *out_result = fn(); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = NULL; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -73,13 +103,16 @@ typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char); __declspec(dllexport) int __cdecl SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2) { + RC_SEH_ENTER(); __try { fn(arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -95,13 +128,16 @@ typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int s __declspec(dllexport) int __cdecl SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId) { + RC_SEH_ENTER(); __try { ((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); return 0; } + RC_SEH_LEAVE(); return 1; } @@ -152,14 +188,17 @@ SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg, unsigned char* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -171,14 +210,17 @@ __declspec(dllexport) int __cdecl SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_uint_noarg(fn, this_ptr); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } @@ -209,179 +251,436 @@ SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, int* out_result) { *out_result = 0; + RC_SEH_ENTER(); __try { *out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2); } __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + RC_SEH_LEAVE(); *out_result = 0; return 0; } + RC_SEH_LEAVE(); return 1; } -/* ── Process-wide native crash logger (VEH) ─────────────────────────────── - * Logs the faulting 32-bit context + a module-resolved stack sweep to a - * dedicated file BEFORE the process dies, for the fatal exceptions that bypass - * NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and - * 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled - * managed exception or a stack-walk fail-fast in the plugin/engine). +/* ── Process-wide native crash logger (fatal-only, v2) ──────────────────── + * Goal: native-crash.log holds FATAL crashes only. v1 logged every first-chance AV + * (including ones AC or our own SEH_* wrappers handle) plus its own stack-sweep faults, + * so its 24-entry cap filled with noise before a real crash could be recorded. * - * This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so - * unlike the removed managed CrashLogger VEH it cannot itself re-trigger a - * NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns - * EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly - * as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio / - * user32) so the build link line stays unchanged. Hardened: stack sweep in - * __try/__except, capped log count, dedicated file (no contention with the - * managed log). x86 (32-bit) context fields only — matches the WOW64 target. + * All paths are PURE NATIVE (no managed callback / reverse-P/Invoke — that could itself + * trigger a NativeAOT fail-fast on an AC-owned thread) and observe-only: they always + * return EXCEPTION_CONTINUE_SEARCH or chain, so AC's SEH and the runtime proceed exactly + * as before. Only kernel32 APIs + hand-rolled, bounds-checked formatting (no CRT stdio). + * + * 1. Unhandled-exception filter (SetUnhandledExceptionFilter, chained to the previous + * filter): an exception nobody handled is written immediately as FATAL. + * 2. First-chance VEH, immediate: AVs whose faulting address is inside a NativeAOT + * module (engine / plugins). The runtime fail-fasts on those via + * RaiseFailFastException, which bypasses every handler including the filter in (1), + * so first chance is the only chance to record them. 0xC0000602 / 0xC0000409 too. + * 3. First-chance VEH, deferred: every other AV (acclient.exe, drivers, DINPUT8, …) is + * formatted into an in-memory ring and written ONLY if the process then dies — via + * the filter in (1), or at ExitProcess (DllMain detach) when it happened within the + * last CL_EXIT_FLUSH_WINDOW_MS (AC's own crash handling ends with ExitProcess). + * AVs that AC handles and survives never reach the file. + * + * Skipped entirely: AVs raised inside our own SEH_* wrappers (t_sehDepth > 0 — our + * __except catches them) and any fault raised while the logger itself is running on + * that thread (t_inLogger — v1 logged its own sweep faults as SehTrampoline.dll+0x13E8). + * + * The stack sweep is bounded to [Esp, NtCurrentTeb()->NtTib.StackBase); v1 read 4096 + * slots past ESP unconditionally and ran off the top of the stack. + * x86 (32-bit) context fields only — matches the WOW64 target. */ +#define CL_SLOT_BYTES 8192 /* one formatted record */ +#define CL_RING_SLOTS 8 /* deferred first-chance records kept in memory */ +#define CL_MAX_IMMEDIATE 16 /* NativeAOT-module / fail-fast records per run */ +#define CL_MAX_FATAL 8 /* unhandled-exception records per run */ +#define CL_MAX_SWEEP_SLOTS 4096 /* stack slots scanned (also capped by StackBase) */ +#define CL_MAX_SWEEP_LINES 96 /* code pointers emitted per record */ +#define CL_EXIT_FLUSH_WINDOW_MS 30000 /* deferred AVs this recent are flushed at exit */ + +#define CL_SLOT_EMPTY 0 +#define CL_SLOT_WRITING 1 +#define CL_SLOT_PENDING 2 /* deferred first-chance AV, not in the file (yet) */ +#define CL_SLOT_DONE 3 /* written to the file, or discarded */ + +typedef struct { + volatile LONG state; + DWORD tid; + DWORD tick; + unsigned int exAddr; + int len; + char text[CL_SLOT_BYTES]; +} CL_SLOT; + static wchar_t g_crashLogPath[MAX_PATH]; -static volatile LONG g_crashCount = 0; -static PVOID g_vehHandle = NULL; +static PVOID g_vehHandle = NULL; +static CL_SLOT g_ring[CL_RING_SLOTS]; +static volatile LONG g_ringNext = 0; +static volatile LONG g_immediateCount = 0; +static volatile LONG g_fatalCount = 0; +static LPTOP_LEVEL_EXCEPTION_FILTER g_prevFilter = NULL; +static __declspec(thread) int t_inLogger; /* logger running on this thread */ +static __declspec(thread) int t_inUef; /* filter running (guards chain cycles) */ -static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; } +/* ── Bounds-checked text writer ── */ +typedef struct { char* p; char* end; } CL_W; -static char* cl_hex(char* p, unsigned int v) +static void cl_str(CL_W* w, const char* s) +{ + while (*s && w->p < w->end) { *w->p++ = *s++; } +} + +static void cl_hex(CL_W* w, unsigned int v) { const char* H = "0123456789ABCDEF"; int i; - *p++ = '0'; *p++ = 'x'; - for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; } - return p; + cl_str(w, "0x"); + for (i = 28; i >= 0 && w->p < w->end; i -= 4) { *w->p++ = H[(v >> i) & 0xF]; } } -static char* cl_u(char* p, unsigned int v) +static void cl_u(CL_W* w, unsigned int v) { char tmp[12]; int n = 0; - if (v == 0) { *p++ = '0'; return p; } + if (v == 0) { cl_str(w, "0"); return; } while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; } - while (n) { *p++ = tmp[--n]; } - return p; + while (n && w->p < w->end) { *w->p++ = tmp[--n]; } +} + +/* Leaf file name of a loaded module, as narrow ASCII (lower-cased when lower != 0). */ +static int cl_module_leaf(HMODULE hm, char* out, int cap, int lower) +{ + wchar_t wpath[MAX_PATH]; + DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); + DWORD i, leaf = 0; + int k = 0; + for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') { leaf = i + 1; } } + for (i = leaf; i < n && k < cap - 1; i++) { + char ch = (char)wpath[i]; + if (lower && ch >= 'A' && ch <= 'Z') { ch = (char)(ch - 'A' + 'a'); } + out[k++] = ch; + } + out[k] = 0; + return k; } /* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ -static char* cl_sym(char* p, unsigned int addr) +static void cl_sym(CL_W* w, unsigned int addr) { HMODULE hm = NULL; /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) { - wchar_t wpath[MAX_PATH]; - DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); - DWORD i, leaf = 0; - for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; } - for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; } - p = cl_str(p, "+"); - p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 0); + cl_str(w, leaf); + cl_str(w, "+"); + cl_hex(w, addr - (unsigned int)(UINT_PTR)hm); } else { - p = cl_hex(p, addr); + cl_hex(w, addr); } - return p; } -static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +static int cl_starts_with(const char* s, const char* prefix) { + while (*prefix) { if (*s++ != *prefix++) { return 0; } } + return 1; +} + +/* ── NativeAOT module detection (cached per module base) ── */ +#define CL_MOD_CACHE 16 +static volatile UINT_PTR g_modBase[CL_MOD_CACHE]; +static volatile LONG g_modManaged[CL_MOD_CACHE]; +static volatile LONG g_modNext = 0; + +/* True when addr lies in a NativeAOT image (engine / plugin). NativeAOT images export + * DotNetRuntimeDebugHeader; RynthCore.* names are a fallback (minus our native DLLs). */ +static int cl_is_nativeaot_address(unsigned int addr) +{ + HMODULE hm = NULL; + int i, managed; + if (!GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) || !hm) { return 0; } + + for (i = 0; i < CL_MOD_CACHE; i++) { + if (g_modBase[i] == (UINT_PTR)hm) { return (int)g_modManaged[i]; } + } + + managed = GetProcAddress(hm, "DotNetRuntimeDebugHeader") != NULL; + if (!managed) { + char leaf[MAX_PATH]; + cl_module_leaf(hm, leaf, MAX_PATH, 1); + managed = cl_starts_with(leaf, "rynthcore.") + && !cl_starts_with(leaf, "rynthcore.sehtrampoline") + && !cl_starts_with(leaf, "rynthcore.cimgui"); + } + + /* Benign race: base is cleared first and published last, so a concurrent reader + * either misses the entry (and recomputes) or sees a matching flag. */ + i = (int)((unsigned int)InterlockedIncrement(&g_modNext) % CL_MOD_CACHE); + g_modBase[i] = 0; + g_modManaged[i] = managed; + g_modBase[i] = (UINT_PTR)hm; + return managed; +} + +/* ── Record formatting ── */ + +/* Formats one crash record (header, registers, bounded stack sweep) into buf. + * Returns the byte count. Reads of stack memory are guarded by __try. */ +static int cl_format(char* buf, int cap, PEXCEPTION_POINTERS ep, const char* banner) +{ + CL_W w; + CONTEXT* c = ep->ContextRecord; DWORD code = ep->ExceptionRecord->ExceptionCode; - if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { - return EXCEPTION_CONTINUE_SEARCH; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + + w.p = buf; + w.end = buf + cap - 64; /* reserve room for the END line */ + + cl_str(&w, "\r\n==== NATIVE CRASH LOGGER: "); + cl_str(&w, banner); + cl_str(&w, " ====\r\n code="); + cl_hex(&w, code); + cl_str(&w, " exAddr="); + cl_sym(&w, exAddr); + cl_str(&w, " tid="); + cl_u(&w, GetCurrentThreadId()); + { + SYSTEMTIME st; GetLocalTime(&st); + cl_str(&w, " time="); + cl_u(&w, st.wHour); cl_str(&w, ":"); + if (st.wMinute < 10) { cl_str(&w, "0"); } cl_u(&w, st.wMinute); cl_str(&w, ":"); + if (st.wSecond < 10) { cl_str(&w, "0"); } cl_u(&w, st.wSecond); } - if (InterlockedIncrement(&g_crashCount) > 24) { - return EXCEPTION_CONTINUE_SEARCH; + 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]; + cl_str(&w, " access="); + cl_str(&w, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); + cl_str(&w, " dataAddr="); + cl_hex(&w, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ } + cl_str(&w, "\r\n eip="); cl_sym(&w, c->Eip); + cl_str(&w, " esp="); cl_hex(&w, c->Esp); + cl_str(&w, " ebp="); cl_hex(&w, c->Ebp); + cl_str(&w, "\r\n eax="); cl_hex(&w, c->Eax); + cl_str(&w, " ebx="); cl_hex(&w, c->Ebx); + cl_str(&w, " ecx="); cl_hex(&w, c->Ecx); + cl_str(&w, " edx="); cl_hex(&w, c->Edx); + cl_str(&w, " esi="); cl_hex(&w, c->Esi); + cl_str(&w, " edi="); cl_hex(&w, c->Edi); + cl_str(&w, "\r\n stack code pointers (esp -> StackBase):\r\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 EXCEPTION_CONTINUE_SEARCH; } - SetFilePointer(h, 0, NULL, FILE_END); - - { - char buf[4096]; - char* p = buf; - CONTEXT* c = ep->ContextRecord; - unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; - DWORD wr; - - p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code="); - p = cl_hex(p, code); - p = cl_str(p, " exAddr="); - p = cl_sym(p, exAddr); - p = cl_str(p, " tid="); - p = cl_u(p, GetCurrentThreadId()); - { - SYSTEMTIME st; GetLocalTime(&st); - p = cl_str(p, " time="); - p = cl_u(p, st.wHour); p = cl_str(p, ":"); - if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":"); - if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond); - } - if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { - unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; - unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; - p = cl_str(p, " access="); - p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); - p = cl_str(p, " dataAddr="); - p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ - } - p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip); - p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); - p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); - p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax); - p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx); - p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx); - p = cl_str(p, " edx="); p = cl_hex(p, c->Edx); - p = cl_str(p, " esi="); p = cl_hex(p, c->Esi); - p = cl_str(p, " edi="); p = cl_hex(p, c->Edi); - p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n"); - WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL); + /* The handler runs on the faulting thread, so this TEB's stack bounds apply to + * the faulting ESP. Never read at or past StackBase (top of the stack). */ + NT_TIB* tib = (NT_TIB*)NtCurrentTeb(); + UINT_PTR base = (UINT_PTR)tib->StackBase; + UINT_PTR limit = (UINT_PTR)tib->StackLimit; + UINT_PTR esp = (UINT_PTR)c->Esp; + if (esp < limit || esp >= base) { + cl_str(&w, " \r\n"); + } else { + unsigned int slots = (unsigned int)((base - esp) / sizeof(unsigned int)); + if (slots > CL_MAX_SWEEP_SLOTS) { slots = CL_MAX_SWEEP_SLOTS; } __try { - unsigned int* sp = (unsigned int*)c->Esp; - int i, emitted = 0; - for (i = 0; i < 4096 && emitted < 96; i++) { + const unsigned int* sp = (const unsigned int*)esp; + unsigned int i; + int emitted = 0; + /* 320 bytes of headroom = one full "+0xOFF module+0xRVA" line. */ + for (i = 0; i < slots && emitted < CL_MAX_SWEEP_LINES && (w.end - w.p) > 320; i++) { unsigned int v = sp[i]; if (v > 0x00401000u && v < 0x7FFF0000u) { HMODULE hm = NULL; if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { - char* q = buf; - q = cl_str(q, " +"); - q = cl_hex(q, (unsigned int)(i * 4)); - q = cl_str(q, " "); - q = cl_sym(q, v); - q = cl_str(q, "\r\n"); - WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL); + cl_str(&w, " +"); + cl_hex(&w, i * 4u); + cl_str(&w, " "); + cl_sym(&w, v); + cl_str(&w, "\r\n"); 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); + cl_str(&w, " \r\n"); } } - CloseHandle(h); } + + w.end = buf + cap; + cl_str(&w, "==== END NATIVE CRASH ====\r\n"); + return (int)(w.p - buf); +} + +/* ── Output ── */ + +static void cl_append_file(const char* data, int len) +{ + HANDLE h; + DWORD wr; + if (len <= 0 || g_crashLogPath[0] == 0) { return; } + 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); + WriteFile(h, data, (DWORD)len, &wr, NULL); + CloseHandle(h); +} + +/* Claims a ring slot for writing. Rotates through the ring, overwriting the oldest + * PENDING/DONE record; never steals a slot another thread is mid-write on. */ +static CL_SLOT* cl_claim_slot(void) +{ + int tries; + for (tries = 0; tries < CL_RING_SLOTS * 2; tries++) { + CL_SLOT* s = &g_ring[(unsigned int)InterlockedIncrement(&g_ringNext) % CL_RING_SLOTS]; + LONG st = s->state; + if (st != CL_SLOT_WRITING && + InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, st) == st) { + return s; + } + } + return NULL; +} + +/* Writes PENDING deferred records to the file. Skips the record matching skipTid/skipAddr + * (the same fault the caller is about to log) and, when maxAgeMs != 0, records older + * than maxAgeMs (handled AVs from long before the exit). */ +static void cl_flush_pending(DWORD skipTid, unsigned int skipAddr, DWORD maxAgeMs) +{ + DWORD now = GetTickCount(); + int i; + for (i = 0; i < CL_RING_SLOTS; i++) { + CL_SLOT* s = &g_ring[i]; + if (InterlockedCompareExchange(&s->state, CL_SLOT_WRITING, CL_SLOT_PENDING) != CL_SLOT_PENDING) { + continue; + } + if ((skipTid != 0 && s->tid == skipTid && s->exAddr == skipAddr) || + (maxAgeMs != 0 && now - s->tick > maxAgeMs)) { + InterlockedExchange(&s->state, CL_SLOT_DONE); + continue; + } + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } +} + +/* ── Handlers ── */ + +static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +{ + DWORD code = ep->ExceptionRecord->ExceptionCode; + unsigned int exAddr; + int immediate; + CL_SLOT* s; + + if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { + return EXCEPTION_CONTINUE_SEARCH; + } + if (t_inLogger) { + return EXCEPTION_CONTINUE_SEARCH; /* our own fault — the logger's __try handles it */ + } + if (code == 0xC0000005 && t_sehDepth > 0) { + return EXCEPTION_CONTINUE_SEARCH; /* an SEH_* wrapper's __except will catch it */ + } + + t_inLogger = 1; + exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + immediate = (code != 0xC0000005) || cl_is_nativeaot_address(exAddr); + + if (!immediate || InterlockedIncrement(&g_immediateCount) <= CL_MAX_IMMEDIATE) { + s = cl_claim_slot(); + if (s) { + s->tid = GetCurrentThreadId(); + s->tick = GetTickCount(); + s->exAddr = exAddr; + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, + code != 0xC0000005 + ? "FAIL-FAST / STACK CHECK (always fatal)" + : (immediate + ? "AV IN NATIVEAOT CODE (runtime fail-fasts unless it is a null-ref)" + : "FIRST-CHANCE AV (deferred; written because the process died or exited soon after)")); + if (immediate) { + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } else { + InterlockedExchange(&s->state, CL_SLOT_PENDING); + } + } + } + + t_inLogger = 0; return EXCEPTION_CONTINUE_SEARCH; } -/* Install the VEH once. logPath = wide path to the dedicated crash log. */ +/* Unhandled-exception filter: nobody caught this exception, so it is fatal. */ +static LONG WINAPI CrashUef(PEXCEPTION_POINTERS ep) +{ + LONG verdict = EXCEPTION_CONTINUE_SEARCH; + + /* A replaced-then-reasserted filter chain can loop back here; bail out of the cycle. */ + if (t_inUef) { + return EXCEPTION_CONTINUE_SEARCH; + } + t_inUef = 1; + + if (!t_inLogger && InterlockedIncrement(&g_fatalCount) <= CL_MAX_FATAL) { + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + CL_SLOT* s; + t_inLogger = 1; + /* Earlier first-chance AVs (other threads, earlier faults) are context for this + * crash; the first-chance record of THIS fault is skipped as a duplicate. Flushed + * before claiming a slot so the claim can't overwrite one of them. */ + cl_flush_pending(GetCurrentThreadId(), exAddr, 0); + s = cl_claim_slot(); + if (s) { + s->len = cl_format(s->text, CL_SLOT_BYTES, ep, "UNHANDLED EXCEPTION (fatal)"); + cl_append_file(s->text, s->len); + InterlockedExchange(&s->state, CL_SLOT_DONE); + } + t_inLogger = 0; + } + + if (g_prevFilter) { + verdict = g_prevFilter(ep); + } + t_inUef = 0; + return verdict; +} + +/* DllMain (process exit): write deferred AVs from the last CL_EXIT_FLUSH_WINDOW_MS. */ +static void CrashLoggerFlushOnExit(void) +{ + if (g_crashLogPath[0] == 0) { return; } + cl_flush_pending(0, 0, CL_EXIT_FLUSH_WINDOW_MS); +} + +/* Installs the VEH once and (re-)asserts the unhandled-exception filter. + * logPath = wide path to the dedicated crash log. Safe to call more than once: + * a later call re-installs the filter if AC or a runtime replaced it. */ __declspec(dllexport) void __cdecl RC_InstallCrashLogger(const wchar_t* logPath) { - if (g_vehHandle) { return; } + LPTOP_LEVEL_EXCEPTION_FILTER prev; if (logPath) { int i = 0; for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } g_crashLogPath[i] = 0; } - g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + if (!g_vehHandle) { + g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); + } + prev = SetUnhandledExceptionFilter(CrashUef); + if (prev != CrashUef) { + g_prevFilter = prev; + } } /* ── Tagged-text parser guard (native MinHook detour body) ──────────────── diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 4ef0fb2..53a8048 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -216,6 +216,24 @@ internal static class ClientObjectHooks private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static bool _loggedObjectIdentityServe; private const int ObjectIdentityPrefetchThrottleMs = 500; + + // Create-time identity seeds. ACCObjectMaint::CreateObject receives the server's + // PublicWeenieDesc, which already carries the object's name and ITEM_TYPE before + // qualities/appraisal exist. The main-thread snapshot above can't resolve names for + // ~10 s after login (qualities not populated yet), so off-thread readers fall back to + // these seeds when the snapshot has no entry (or reports type 0). Entries live from + // create until delete; the cap only guards against a missed delete hook. + private static readonly object _createSeedLock = new(); + private static readonly Dictionary _createSeedNames = new(1024); + private static readonly Dictionary _createSeedTypes = new(1024); + private const int CreateSeedCap = 16384; + // PublicWeenieDesc field offsets (Chorizite Weenie.cs; same layout the PWD-direct + // fallbacks in TryGetObjectName / TryGetItemType read from the embedded copy). + private const int PwdNameOffset = 4; + private const int PwdTypeOffset = 56; + private static int _createSeedCount; + private static bool _loggedCreateSeedServe; + // Every id the same walk visited, swapped whole (readers never see a half-built array). private static volatile uint[] _liveObjectIds = Array.Empty(); @@ -1767,6 +1785,19 @@ internal static class ClientObjectHooks // Off-thread: serve from the main-thread snapshot populated by PrefetchObjectIdentity(). if (!MainThreadGuard.IsOnMainThread()) { + lock (_objectIdentityCacheLock) + { + // A zero snapshot value means qualities weren't populated when the walk + // ran; prefer the create-time descriptor type in that case. + if (_objectTypeCache.TryGetValue(objectId, out typeFlags) && typeFlags != 0) + return true; + } + if (TryGetCreateSeedType(objectId, out uint seeded)) + { + typeFlags = seeded; + return true; + } + // Snapshot hit with flags=0 is still an answer (static scenery often has no type). lock (_objectIdentityCacheLock) { if (_objectTypeCache.TryGetValue(objectId, out typeFlags)) @@ -2542,6 +2573,101 @@ internal static class ClientObjectHooks } } + /// + /// Records an object's name and ITEM_TYPE straight from the PublicWeenieDesc passed + /// to ACCObjectMaint::CreateObject. Called from the create hook on AC's main thread, + /// after the original returns. The descriptor is server data that exists before the + /// object's qualities do, so this makes names/types readable off-thread immediately + /// instead of after the first successful identity snapshot (~10 s at login). + /// Every read is pointer-validated; a bad descriptor simply records nothing. + /// + internal static void SeedIdentityFromCreate(uint objectId, IntPtr weenieDesc) + { + if (objectId == 0 || weenieDesc == IntPtr.Zero) + return; + + try + { + // PublicWeenieDesc derives from PackObj, so a real descriptor starts with an + // acclient.exe vtable; reject anything else before reading fields. + if (!LooksLikeAcHeapObject(weenieDesc)) + return; + + bool gotName = TryReadPwdString(weenieDesc, PwdNameOffset, out string name); + + uint typeFlags = 0; + IntPtr typeAddr = weenieDesc + PwdTypeOffset; + bool gotType = IsReadablePointer(typeAddr); + if (gotType) + typeFlags = unchecked((uint)Marshal.ReadInt32(typeAddr)); + + if (!gotName && (!gotType || typeFlags == 0)) + return; + + lock (_createSeedLock) + { + // Safety valve for a missed delete: drop everything rather than grow forever. + // The live snapshot covers anything still in the world. + if (_createSeedNames.Count >= CreateSeedCap || _createSeedTypes.Count >= CreateSeedCap) + { + _createSeedNames.Clear(); + _createSeedTypes.Clear(); + } + if (gotName) + _createSeedNames[objectId] = name; + if (gotType && typeFlags != 0) + _createSeedTypes[objectId] = typeFlags; + } + + int seedNo = System.Threading.Interlocked.Increment(ref _createSeedCount); + // First few samples let a log reader confirm the descriptor offsets resolve + // to sensible names/types on this client build. + if (seedNo <= 5) + RynthLog.Compat($"[CreateSeed] #{seedNo} 0x{objectId:X8} name='{(gotName ? name : "")}' type=0x{typeFlags:X8}"); + if (!_loggedCreateSeedServe && seedNo >= 50) + { + _loggedCreateSeedServe = true; + int names, types; + lock (_createSeedLock) { names = _createSeedNames.Count; types = _createSeedTypes.Count; } + RynthLog.Compat($"ClientObjectHooks: create-descriptor identity seeds active — {names} names, {types} types captured at CreateObject."); + } + } + catch + { + // Descriptor read failures are non-fatal; the periodic snapshot still runs. + } + } + + /// Drops create-time seeds for a deleted object (called from the delete hook). + internal static void ForgetCreateSeed(uint objectId) + { + lock (_createSeedLock) + { + _createSeedNames.Remove(objectId); + _createSeedTypes.Remove(objectId); + } + } + + private static bool TryGetCreateSeedName(uint objectId, out string name) + { + lock (_createSeedLock) + { + if (_createSeedNames.TryGetValue(objectId, out string? seeded) && seeded.Length > 0) + { + name = seeded; + return true; + } + } + name = string.Empty; + return false; + } + + private static bool TryGetCreateSeedType(uint objectId, out uint typeFlags) + { + lock (_createSeedLock) + return _createSeedTypes.TryGetValue(objectId, out typeFlags); + } + public static bool TryGetObjectName(uint objectId, out string name) { name = string.Empty; @@ -2557,6 +2683,10 @@ internal static class ClientObjectHooks return true; } } + // Snapshot miss (login burst / object newer than the last walk): serve the + // name captured from the create descriptor. + if (TryGetCreateSeedName(objectId, out name)) + return true; name = string.Empty; return false; } diff --git a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs index 9377b39..558a192 100644 --- a/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CreateObjectHooks.cs @@ -81,6 +81,9 @@ internal static class CreateObjectHooks if (count <= 0) RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}"); + // Capture name/type from the create descriptor BEFORE the plugin is told about the + // object, so its off-thread classifier can read them on the very first attempt. + ClientObjectHooks.SeedIdentityFromCreate(objectId, weenieDesc); PluginManager.QueueCreateObject(objectId); AutoIdService.Enqueue(objectId); return result; diff --git a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs index 3f8df11..151dffd 100644 --- a/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/DeleteObjectHooks.cs @@ -71,6 +71,7 @@ internal static class DeleteObjectHooks if (objectId != 0) { PaletteCache.Remove(objectId); + ClientObjectHooks.ForgetCreateSeed(objectId); PluginManager.QueueDeleteObject(objectId); AutoIdService.Evict(objectId); } diff --git a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs index b731a79..573da2e 100644 --- a/src/RynthCore.Engine/Compatibility/SehTrampoline.cs +++ b/src/RynthCore.Engine/Compatibility/SehTrampoline.cs @@ -43,12 +43,24 @@ internal static class SehTrampoline /// no managed callback / reverse-P/Invoke transition — so unlike the removed /// managed CrashLogger VEH it cannot itself re-trigger a NativeAOT fail-fast on an /// AC-owned thread. Writes the faulting 32-bit context + a module-resolved stack - /// sweep to for the 0xC0000005 (AV/CSE) and 0xC0000602 - /// (RaiseFailFast) classes that bypass managed handlers. Observes only. + /// sweep (bounded by the thread's StackBase) to for FATAL + /// crashes only: unhandled exceptions (chained unhandled-exception filter), AVs in + /// NativeAOT code (which the runtime fail-fasts past every filter), and other + /// first-chance AVs only if the process dies shortly after. AVs caught by the SEH_* + /// wrappers and the logger's own faults are never written. Observes only. /// public static void InstallCrashLogger(string logPath) { - try { _InstallCrashLogger(logPath); } + try + { + _InstallCrashLogger(logPath); + // v2+ logs fatal crashes only (unhandled-exception filter + NativeAOT-module AVs); + // v1 (no version export) logged every first-chance AV. + uint version = 1; + try { version = _SehTrampolineVersion(); } + catch (EntryPointNotFoundException) { } + RynthLog.Compat($"SehTrampoline: native crash logger installed (v{version}{(version >= 2 ? ", fatal-only" : ", logs every first-chance AV")}) -> {logPath}"); + } catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); } } @@ -104,6 +116,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_SehTrampolineVersion", + CallingConvention = CallingConvention.Cdecl)] + private static extern uint _SehTrampolineVersion(); + [DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _GetTagParserGuardAddress();