From 4469914649a0c6c1f4ba0924eb6befade61fff22 Mon Sep 17 00:00:00 2001 From: OldSalty <7090702+OldSalty@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:15:06 +1000 Subject: [PATCH 1/2] runtime: print the call chain of a fatal fault A run that ended in an unhandled exception saved the pipeline caches but said nothing about where the title faulted: the log had the exception code and no call chain. print_fault_stacks names the access and the address, walks the faulting thread's own chain from the exception context (the filter runs on that thread, so its stack is live), and snapshots the other threads as LEONIDA_STACKS does. On the retail package this unwound a faulting chain of six title frames out of the title's worker pool and named the read that faulted, which no earlier log did. thread_stacks_test covers it with a guarded null read captured to a file. --- runtime/src/main.cpp | 8 ++- runtime/src/thread_stacks.cpp | 50 ++++++++++++++ runtime/src/thread_stacks.h | 7 ++ runtime/test/thread_stacks_test.cpp | 102 +++++++++++++++++++++++++++- 4 files changed, 164 insertions(+), 3 deletions(-) diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 21551e9489..b9ccea556f 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -340,7 +340,8 @@ static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) { } // A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device -// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is +// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again: this prints +// the fault and the threads' call chains (rt::print_fault_stacks) and saves them. The device is // left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own // handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with. static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr; @@ -360,9 +361,12 @@ static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) { // Several title threads can fault at once (measured: eight within a second). The first writes; the others // wait here for it, so none of them reaches the title's filter, which may end the process, mid-write. static std::once_flag once; - std::call_once(once, [code] { + std::call_once(once, [info, code] { std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the " "process ends\n", static_cast(code)); + // Before the waits below, while the faulting thread's stack is still the one we are running on. + rt::print_fault_stacks(info ? info->ExceptionRecord : nullptr, info ? info->ContextRecord : nullptr, + "fatal"); rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs); std::fflush(stderr); diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp index 38d7cc2a44..4cbe6a76ff 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -223,6 +223,56 @@ void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept { } } +void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* why) noexcept { + static std::mutex mutex; + try { + const std::lock_guard lock(mutex); + const char* tag = why ? why : "fatal"; + if (record) { + // ExceptionAddress is where the faulting instruction is, which for a fault raised by an instruction in a + // leaf without unwind data can name nothing; the chain below says what called it either way. + const std::string at = record->ExceptionAddress + ? shims::module_offset(reinterpret_cast(record->ExceptionAddress)) + : std::string("unknown"); + if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { + const char* access = record->ExceptionInformation[0] == 0 ? "read" + : record->ExceptionInformation[0] == 1 ? "write" : "execute"; + std::fprintf(stderr, "[rt] fault %s: %s of 0x%llx at %s\n", tag, access, + static_cast(record->ExceptionInformation[1]), at.c_str()); + } else { + std::fprintf(stderr, "[rt] fault %s: exception 0x%08lx at %s\n", tag, + static_cast(record->ExceptionCode), at.c_str()); + } + } + // The filter runs on the faulting thread and its stack is live under us, so unlike a sampled thread this one + // unwinds directly, with no copy (the same frames the suspended thread's own unwinder would walk). + if (context && context->Rip) { + CONTEXT walk = *context; + std::array frames{}; + std::size_t count = 0; + while (walk.Rip && count < frames.size()) { + frames[count++] = walk.Rip; + if (!unwind_frame(walk)) break; + } + std::string out = "[rt] stacks " + std::string(tag) + " thread " + std::to_string(GetCurrentThreadId()) + + " (faulting thread):\n"; + if (!count) out += " stack unavailable\n"; + else + for (std::size_t i = 0; i < count; ++i) + out += " #" + std::to_string(i) + " " + shims::module_offset(frames[i]) + "\n"; + std::fputs(out.c_str(), stderr); + std::fflush(stderr); + } + static StackSampler sampler; + const auto describe = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); + const auto query = reinterpret_cast(reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); + snapshot_threads(tag, sampler, describe, query, 0); + } catch (...) { + } +} + std::jthread start_thread_stacks() { const auto start = Clock::now(); char spec[1024]; diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h index 1edc1b3501..42605c7afb 100644 --- a/runtime/src/thread_stacks.h +++ b/runtime/src/thread_stacks.h @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -39,4 +41,9 @@ std::jthread start_thread_stacks(); // the tag `why`. One call at a time; the device-loss diagnostics call it (vulkan_device_fault.h thread_stack_hook). void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept; +// A fatal exception nothing handled: the fault (access and address for an access violation) and the faulting thread's +// own call chain, walked directly from the exception's context (the filter runs on that thread, whose stack is +// live), then a LEONIDA_STACKS snapshot of the other threads. From a top-level exception filter only. +void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* why) noexcept; + } // namespace rt diff --git a/runtime/test/thread_stacks_test.cpp b/runtime/test/thread_stacks_test.cpp index 60b48870f3..8d19f43b24 100644 --- a/runtime/test/thread_stacks_test.cpp +++ b/runtime/test/thread_stacks_test.cpp @@ -1,11 +1,16 @@ // rt::StackSampler (runtime/src/thread_stacks.cpp, LEONIDA_STACKS): the call chain of a thread blocked in a known -// function, and of a thread whose stack keeps changing while it is sampled. No game data. +// function, of a thread whose stack keeps changing while it is sampled, and of the thread a fatal fault happens on +// (rt::print_fault_stacks). No game data. #include #include +#include +#include #include #include #include +#include +#include #include #include "../src/thread_stacks.h" @@ -147,6 +152,100 @@ void moving_thread() { check(reached + deep == sampled, "every chain of a moving stack unwinds to its thread function"); } +// rt::print_fault_stacks: the fault it was called for and the call chain of the thread it happened on. The function +// writes to stderr, so the capture points fd 2 at a file for the duration of the fault and the file is read back. +std::atomic g_fault_fn{0}, g_fault_caller_fn{0}; + +__declspec(noinline) int fault_here() { + g_fault_fn = here(); + volatile const int* none = nullptr; + return none[3]; // a read of 0xc +} + +LONG WINAPI fault_filter(EXCEPTION_POINTERS* info) { + rt::print_fault_stacks(info->ExceptionRecord, info->ContextRecord, "test"); + return EXCEPTION_EXECUTE_HANDLER; +} + +// The __try in a function of its own: MSVC refuses __try in a function whose own objects need unwinding. +__declspec(noinline) int run_fault() { + int value = 0; + __try { + value = fault_here(); + } __except (fault_filter(GetExceptionInformation())) { + value = -1; + } + return value; +} + +// "thread_stacks_test.exe+0x1a2b" -> 0x1a2b, or -1 for a line naming another module (a host DLL frame). +long long frame_rva(const std::string& line) { + const std::string name = "thread_stacks_test.exe+0x"; + const size_t at = line.find(name); + if (at == std::string::npos) return -1; + return std::stoll(line.substr(at + name.size()), nullptr, 16); +} + +void fault_stacks() { + char dir[MAX_PATH] = {}; + const DWORD len = GetTempPathA(sizeof dir, dir); + check(len > 0 && len < sizeof dir, "the temp path resolves"); + if (!len) return; + const std::string path = std::string(dir) + "leonida_thread_stacks_fault_" + std::to_string(GetCurrentProcessId()) + + ".log"; + HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + check(file != INVALID_HANDLE_VALUE, "the fault capture's file opens"); + if (file == INVALID_HANDLE_VALUE) return; + const int saved = _dup(_fileno(stderr)); + // Binary: the capture must hold the bytes the diagnostics wrote, with their own line endings. + const int fd = _open_osfhandle(reinterpret_cast(file), _O_BINARY); + _dup2(fd, _fileno(stderr)); + g_fault_caller_fn = here(); // fault_stacks itself: the chain must reach it above the fault + const int value = run_fault(); + _dup2(saved, _fileno(stderr)); + _close(saved); + _close(fd); // the last CRT reference to `file`, so this closes the handle + check(value == -1, "the guarded call ended in its handler"); + + std::ifstream in(path, std::ios::binary); + const std::string capture{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + in.close(); + std::remove(path.c_str()); + if (capture.size() < 40) std::printf(" capture: [%s]\n", capture.c_str()); + check(capture.find("[rt] fault test: read of 0xc at thread_stacks_test.exe+0x") != std::string::npos || + capture.find("[rt] fault test: read of 0xc at host:thread_stacks_test.exe+0x") != std::string::npos, + "the fault names the access and the instruction"); + + // The chain of the faulting thread starts at the faulting instruction itself and unwinds out to the caller. + const size_t chain = capture.find("(faulting thread):\n"); + check(chain != std::string::npos, "the capture holds the faulting thread's chain"); + if (chain == std::string::npos) std::printf(" capture (%zu bytes):\n%s\n", capture.size(), capture.c_str()); + if (chain == std::string::npos) return; + const size_t fault_line = capture.find("[rt] fault test:"); + const size_t at = fault_line != std::string::npos ? capture.find(" at ", fault_line) : std::string::npos; + const std::string where = + at != std::string::npos ? capture.substr(at + 4, capture.find('\n', at) - at - 4) : std::string(); + check(!where.empty() && capture.find("#0 " + where, chain) != std::string::npos, + "frame #0 is the faulting instruction the fault line names"); + + const DWORD64 base = reinterpret_cast(GetModuleHandleW(nullptr)); + int in_fault_here = -1, in_caller = -1, frame = 0; + size_t pos = chain; + while ((pos = capture.find(" #", pos)) != std::string::npos) { + const size_t end = capture.find('\n', pos); + if (const long long rva = frame_rva(capture.substr(pos, end - pos)); rva >= 0) { + const DWORD64 function = function_of(base + static_cast(rva)); + if (function == g_fault_fn && in_fault_here < 0) in_fault_here = frame; + if (function == g_fault_caller_fn && in_caller < 0) in_caller = frame; + ++frame; + } + pos = end == std::string::npos ? capture.size() : end; + } + check(in_fault_here >= 0, "the chain reaches the function the fault happened in"); + check(in_caller > in_fault_here, "and unwinds out of it to the function that called it"); + check(capture.find("[rt] stacks test: ") != std::string::npos, "the other threads are snapshotted too"); +} + void parse() { std::vector t; check(rt::parse_stack_times("90,180", t) && t == std::vector{90, 180}, "parse 90,180"); @@ -163,6 +262,7 @@ int main() { parse(); blocked_thread(); moving_thread(); + fault_stacks(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } From 4be68530268702cd6899a24725d96f7e06b99307 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:10:24 +0000 Subject: [PATCH 2/2] runtime: a fatal fault's report names its registers and host, and is kept in a crash log (RT-CRASH-LOG) On top of print_fault_stacks (#2276): - the faulting context's registers (rax..r15, rip, eflags) and a host line (Windows build from RtlGetVersion, CPU brand from CPUID), as [rt] fault lines; - for an exception other than an access violation, what its parameters say: a C++ throw's object, throw info and mangled type name (read under __try), an in-page error's status, or the raw parameters; - the whole report, after a dated header, is appended and flushed to %LOCALAPPDATA%\Leonida\crashes.log, or to LEONIDA_CRASH_LOG (0: no file), with Win32 calls only, so it outlives the console. The text is built in src/crash_report.h, pure and portable, and checked by crash_report_test on every platform. thread_stacks_test points the crash log at a temporary file and checks its content. Idea from Marvisak/VIctory (crates/victory-loader/src/crash.rs, GPL-3.0); no code of it is used. Changes made by Claude Code (AI-assisted). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01JPqXc6svM4pbBagTsVEYA3 --- runtime/CMakeLists.txt | 4 + runtime/README.md | 1 + runtime/src/crash_report.h | 150 ++++++++++++++++++++++++++ runtime/src/thread_stacks.cpp | 162 ++++++++++++++++++++++++++-- runtime/test/crash_report_test.cpp | 87 +++++++++++++++ runtime/test/thread_stacks_test.cpp | 20 ++++ 6 files changed, 415 insertions(+), 9 deletions(-) create mode 100644 runtime/src/crash_report.h create mode 100644 runtime/test/crash_report_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..f69f305721 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1892,6 +1892,10 @@ if(NOT TARGET Vulkan::Headers) FetchContent_MakeAvailable(VulkanHeaders) endif() endif() +# The text of a fatal-fault report and LEONIDA_CRASH_LOG's choice (src/crash_report.h): portable, no Windows. +add_executable(crash_report_test test/crash_report_test.cpp) +add_test(NAME crash_report COMMAND crash_report_test) + if(TARGET Vulkan::Headers) add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp) target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers) diff --git a/runtime/README.md b/runtime/README.md index 23a7811abe..60f643f969 100644 --- a/runtime/README.md +++ b/runtime/README.md @@ -316,6 +316,7 @@ document names. | `LEONIDA_PACKAGED` | `1` | `0`, or text that is not a number, makes `XPackageIsPackagedProcess` return false. Any other number keeps it true. | | `LEONIDA_TITLE_MEMORY_MB` | unset | Caps the title memory limit (in MiB, clamped to `2048..65536`) reported by both `XSystemGetAppMemoryUsageLimit` (`xgameruntime.cpp`) and `XMemGetWorkingSetStatistics` (`xmem.cpp`). Useful on 16 GB RAM / low-VRAM hosts to prevent oversized title pools; invalid or non-positive values are ignored and fall back to the host memory report. | | `LEONIDA_STACKS` | unset | Comma-separated whole seconds after the title's entry point is called (e.g. `90,180`). At each time `--run` suspends every other thread in turn just long enough to copy its context and stack, then unwinds the copy (title frames through the unwind tables the loader registers) and prints to stderr `[rt] stacks t= thread ():` and up to 40 `#i module+0xRVA` frames, innermost first; a chain identical to an earlier thread's prints `same as thread `. | +| `LEONIDA_CRASH_LOG` | unset | Where a fatal fault's report is appended (RT-CRASH-LOG). An exception nothing handles prints `[rt] fault fatal:` lines on stderr (the fault as `module+0xRVA`, what an exception other than an access violation carries, with a C++ throw's type, the registers and a host line with the Windows build and CPU), then the faulting thread's chain and a `LEONIDA_STACKS`-style snapshot of the other threads. The same report, after a dated header, is appended and flushed to `%LOCALAPPDATA%\Leonida\crashes.log` when the variable is unset or empty, to the named file otherwise, and to no file with `0`. A stack overflow prints nothing. | ### Switches of the D3D12 layer for a retail boot diff --git a/runtime/src/crash_report.h b/runtime/src/crash_report.h new file mode 100644 index 0000000000..5f52917ba2 --- /dev/null +++ b/runtime/src/crash_report.h @@ -0,0 +1,150 @@ +// The parts of a fatal-fault report (rt::print_fault_stacks, RT-CRASH-LOG) that are only text: the faulting thread's +// registers, what an exception's parameters say, the host line and the header of one report in the crash log. Pure +// and portable, so runtime/test/crash_report_test.cpp checks them on every platform; the Windows side +// (thread_stacks.cpp) fills them from the EXCEPTION_RECORD and CONTEXT and writes the result. +// +// The idea of keeping each report in a file that outlives the console, with the host's CPU and Windows build and the +// thread's registers, is from Marvisak/VIctory (crates/victory-loader/src/crash.rs, GPL-3.0); no code of it is used. +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace rt::crash_report { + +// The general registers of the faulting context, in CONTEXT's names. +struct Registers { + std::uint64_t rax = 0, rbx = 0, rcx = 0, rdx = 0, rsi = 0, rdi = 0, rbp = 0, rsp = 0; + std::uint64_t r8 = 0, r9 = 0, r10 = 0, r11 = 0, r12 = 0, r13 = 0, r14 = 0, r15 = 0; + std::uint64_t rip = 0; + std::uint32_t eflags = 0; +}; + +// Four lines, four registers each and then rip and eflags, every line starting with `prefix`. +inline std::string registers_lines(const Registers& r, std::string_view prefix) { + const struct { + const char* name; + std::uint64_t value; + } all[] = {{"rax", r.rax}, {"rbx", r.rbx}, {"rcx", r.rcx}, {"rdx", r.rdx}, {"rsi", r.rsi}, {"rdi", r.rdi}, + {"rbp", r.rbp}, {"rsp", r.rsp}, {"r8", r.r8}, {"r9", r.r9}, {"r10", r.r10}, {"r11", r.r11}, + {"r12", r.r12}, {"r13", r.r13}, {"r14", r.r14}, {"r15", r.r15}}; + std::string out; + char field[32]; + for (std::size_t i = 0; i < std::size(all); ++i) { + if (i % 4 == 0) out += prefix; + std::snprintf(field, sizeof field, "%-3s=%016" PRIx64, all[i].name, all[i].value); + out += field; + out += i % 4 == 3 ? "\n" : " "; + } + std::snprintf(field, sizeof field, "rip=%016" PRIx64, r.rip); + out += prefix; + out += field; + std::snprintf(field, sizeof field, " eflags=%08" PRIx32 "\n", r.eflags); + out += field; + return out; +} + +// Exception codes a report names (winnt.h / ntstatus.h values, and MSVC's C++ throw). +inline constexpr std::uint32_t kAccessViolation = 0xC0000005u; +inline constexpr std::uint32_t kInPageError = 0xC0000006u; +inline constexpr std::uint32_t kIllegalInstruction = 0xC000001Du; +inline constexpr std::uint32_t kIntDivideByZero = 0xC0000094u; +inline constexpr std::uint32_t kPrivilegedInstruction = 0xC0000096u; +inline constexpr std::uint32_t kStackOverflow = 0xC00000FDu; +inline constexpr std::uint32_t kHeapCorruption = 0xC0000374u; +inline constexpr std::uint32_t kBreakpoint = 0x80000003u; +inline constexpr std::uint32_t kCppException = 0xE06D7363u; // 'msc' | 0xE0000000: a C++ throw nothing caught + +inline const char* exception_name(std::uint32_t code) { + switch (code) { + case kAccessViolation: return "access violation"; + case kInPageError: return "in-page error"; + case kIllegalInstruction: return "illegal instruction"; + case kIntDivideByZero: return "integer divide by zero"; + case kPrivilegedInstruction: return "privileged instruction"; + case kStackOverflow: return "stack overflow"; + case kHeapCorruption: return "heap corruption"; + case kBreakpoint: return "breakpoint"; + case kCppException: return "C++ exception"; + default: return nullptr; + } +} + +// What an access to memory was: ExceptionInformation[0] of an access violation or an in-page error. +inline const char* access_kind(std::uint64_t kind) { + return kind == 0 ? "read" : kind == 1 ? "write" : kind == 8 ? "execute" : "access"; +} + +// One line (ending in '\n', starting with `prefix`) that says what the exception's parameters mean, or its raw +// parameters for a code it does not know. `type_name` is the mangled name of a C++ exception's thrown type when the +// caller could read it (".?AVruntime_error@std@@"), else empty. +inline std::string exception_detail(std::uint32_t code, std::uint32_t count, const std::uint64_t* params, + std::string_view type_name, std::string_view prefix) { + char line[256]; + const char* name = exception_name(code); + std::string out(prefix); + if ((code == kAccessViolation || code == kInPageError) && count >= 2) { + std::snprintf(line, sizeof line, "%s: %s of 0x%" PRIx64, name, access_kind(params[0]), params[1]); + out += line; + if (code == kInPageError && count >= 3) { + std::snprintf(line, sizeof line, ", status 0x%08" PRIx32, static_cast(params[2])); + out += line; + } + } else if (code == kCppException && count >= 3) { + std::snprintf(line, sizeof line, "%s: object 0x%" PRIx64 ", throw info 0x%" PRIx64, name, params[1], + params[2]); + out += line; + if (!type_name.empty()) { + out += ", type "; + out += type_name; + } + } else { + std::snprintf(line, sizeof line, "%s 0x%08" PRIx32 ", %" PRIu32 " parameter%s", name ? name : "exception", + code, count, count == 1 ? "" : "s"); + out += line; + for (std::uint32_t i = 0; i < count && i < 15; ++i) { + std::snprintf(line, sizeof line, " 0x%" PRIx64, params[i]); + out += line; + } + } + out += '\n'; + return out; +} + +// The host line: the CPU decides which of the console's Zen 2 instructions are emulated (cpu_emulation.h), and the +// Windows build which loader and driver stack the title runs on. +inline std::string host_line(std::string_view cpu, std::uint32_t major, std::uint32_t minor, std::uint32_t build, + std::string_view prefix) { + char line[96]; + std::snprintf(line, sizeof line, "host: Windows %" PRIu32 ".%" PRIu32 ".%" PRIu32 ", CPU ", major, minor, build); + std::string out(prefix); + out += line; + // CPUID's brand string is padded with spaces at either end. + while (!cpu.empty() && (cpu.front() == ' ' || cpu.front() == '\0')) cpu.remove_prefix(1); + while (!cpu.empty() && (cpu.back() == ' ' || cpu.back() == '\0')) cpu.remove_suffix(1); + out += cpu.empty() ? std::string_view("unknown") : cpu; + out += '\n'; + return out; +} + +// The first line of one report in the crash log, so reports appended one after another can be told apart. +inline std::string log_header(int year, int month, int day, int hour, int minute, int second, std::uint32_t pid) { + char line[96]; + std::snprintf(line, sizeof line, "==== %04d-%02d-%02d %02d:%02d:%02d UTC, process %" PRIu32 " ====\n", year, month, + day, hour, minute, second, pid); + return line; +} + +// How LEONIDA_CRASH_LOG reads: unset or empty for the default file, "0" for no file, anything else a path. +enum class LogChoice { default_file, off, path }; +inline LogChoice log_choice(std::string_view value) { + if (value.empty()) return LogChoice::default_file; + if (value == "0") return LogChoice::off; + return LogChoice::path; +} + +} // namespace rt::crash_report diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp index 4cbe6a76ff..f4a75a4a22 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -1,6 +1,7 @@ #include "thread_stacks.h" #include +#include #include #include @@ -8,10 +9,13 @@ #include #include #include +#include #include +#include #include #include +#include "crash_report.h" #include "../shims/shims.h" #include "../shims/startup_trace.h" @@ -121,7 +125,8 @@ struct ThreadTrace { size_t count = 0; }; -void print_traces(const std::string& tag, const std::vector& traces) { +// `also`, when given, receives the same text (the crash log's copy of a fatal report). +void print_traces(const std::string& tag, const std::vector& traces, std::string* also = nullptr) { std::string out = "[rt] stacks " + tag + ": " + std::to_string(traces.size()) + " threads\n"; for (auto it = traces.begin(); it != traces.end(); ++it) { out += "[rt] stacks " + tag + " thread " + std::to_string(it->tid) + " (" + it->label + "):\n"; @@ -140,10 +145,11 @@ void print_traces(const std::string& tag, const std::vector& traces } std::fputs(out.c_str(), stderr); std::fflush(stderr); + if (also) *also += out; } void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescription describe, QueryThread query, - DWORD only = 0) { + DWORD only = 0, std::string* also = nullptr) { const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (snapshot == INVALID_HANDLE_VALUE) { std::fprintf(stderr, "[rt] stacks %s: thread list failed (error %lu)\n", tag.c_str(), GetLastError()); @@ -171,7 +177,108 @@ void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescript CloseHandle(thread); } CloseHandle(snapshot); - print_traces(tag, traces); + print_traces(tag, traces, also); +} + +// ---- The crash log (RT-CRASH-LOG, src/crash_report.h) ---- + +// CPUID's 48-byte brand string, e.g. "AMD Ryzen 9 7900X 12-Core Processor"; empty if the CPU has none. +std::string cpu_brand() { + int regs[4]{}; + __cpuid(regs, 0x80000000); + if (static_cast(regs[0]) < 0x80000004u) return {}; + char brand[49]{}; + for (int i = 0; i < 3; ++i) { + __cpuid(regs, 0x80000002 + i); + std::memcpy(brand + 16 * i, regs, sizeof regs); + } + return brand; +} + +// The running Windows, from RtlGetVersion: GetVersionEx reports what the executable's manifest declares instead. +void windows_version(std::uint32_t& major, std::uint32_t& minor, std::uint32_t& build) { + major = minor = build = 0; + using GetVersion = LONG(WINAPI*)(OSVERSIONINFOW*); + const auto get = reinterpret_cast( + reinterpret_cast(GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "RtlGetVersion"))); + OSVERSIONINFOW info{sizeof info}; + if (get && get(&info) >= 0) { + major = info.dwMajorVersion; + minor = info.dwMinorVersion; + build = info.dwBuildNumber; + } +} + +// The mangled name of the type a C++ throw raised (".?AVruntime_error@std@@"), read through the throw info MSVC +// passes in the exception's parameters: ThrowInfo -> CatchableTypeArray -> its first CatchableType -> TypeDescriptor, +// every pointer an RVA from the image base in parameter 3. No C++ objects here: __try cannot unwind them. +bool read_thrown_type(const EXCEPTION_RECORD& record, char* name, std::size_t size) { + if (record.ExceptionCode != crash_report::kCppException || record.NumberParameters < 4 || size == 0) return false; + const auto base = static_cast(record.ExceptionInformation[3]); + const auto throw_info = static_cast(record.ExceptionInformation[2]); + if (!base || !throw_info) return false; + name[0] = '\0'; + __try { + // ThrowInfo: attributes, pmfnUnwind, pForwardCompat, pCatchableTypeArray (32-bit RVAs on x64). + const auto array = base + *reinterpret_cast(throw_info + 12); + // CatchableTypeArray: nCatchableTypes, then arrayOfCatchableTypes[] as RVAs. + if (*reinterpret_cast(array) < 1) return false; + const auto type = base + *reinterpret_cast(array + 4); + // CatchableType: properties, pType (an RVA to a TypeDescriptor: vftable, spare, then the name). + const auto descriptor = base + *reinterpret_cast(type + 4); + const char* text = reinterpret_cast(descriptor + 2 * sizeof(void*)); + std::size_t i = 0; + for (; i + 1 < size && text[i]; ++i) name[i] = text[i]; + name[i] = '\0'; + } __except (EXCEPTION_EXECUTE_HANDLER) { + name[0] = '\0'; + return false; + } + return name[0] != '\0'; +} + +std::string thrown_type(const EXCEPTION_RECORD& record) { + char name[128]; + return read_thrown_type(record, name, sizeof name) ? std::string(name) : std::string(); +} + +// Where reports are appended: LEONIDA_CRASH_LOG, else %LOCALAPPDATA%\Leonida\crashes.log; empty for none. +std::wstring crash_log_path() { + wchar_t buffer[MAX_PATH * 2]; + DWORD n = GetEnvironmentVariableW(L"LEONIDA_CRASH_LOG", buffer, static_cast(std::size(buffer))); + if (n >= std::size(buffer)) return {}; + std::string narrow; + for (DWORD i = 0; i < n; ++i) narrow += buffer[i] < 0x80 ? static_cast(buffer[i]) : '?'; + switch (crash_report::log_choice(narrow)) { + case crash_report::LogChoice::off: return {}; + case crash_report::LogChoice::path: return std::wstring(buffer, n); + case crash_report::LogChoice::default_file: break; + } + n = GetEnvironmentVariableW(L"LOCALAPPDATA", buffer, static_cast(std::size(buffer))); + if (!n || n >= std::size(buffer)) return {}; + std::wstring dir = std::wstring(buffer, n) + L"\\Leonida"; + CreateDirectoryW(dir.c_str(), nullptr); // already there is fine; a failure shows as the open below failing + return dir + L"\\crashes.log"; +} + +// Appends `text` to the crash log with Win32 calls only, flushed, so the report outlives the console and the +// process. Says on stderr where it went, or why it did not. +void append_crash_log(const std::string& text) { + const std::wstring path = crash_log_path(); + if (path.empty()) return; + const HANDLE file = CreateFileW(path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + std::fprintf(stderr, "[rt] crash log: could not open %ls (error %lu)\n", path.c_str(), GetLastError()); + return; + } + DWORD written = 0; + const bool ok = WriteFile(file, text.data(), static_cast(text.size()), &written, nullptr) && + written == text.size(); + FlushFileBuffers(file); + CloseHandle(file); + if (ok) std::fprintf(stderr, "[rt] crash log: report appended to %ls\n", path.c_str()); + else std::fprintf(stderr, "[rt] crash log: writing %ls failed (error %lu)\n", path.c_str(), GetLastError()); } } // namespace @@ -228,22 +335,58 @@ void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, try { const std::lock_guard lock(mutex); const char* tag = why ? why : "fatal"; + const std::string prefix = "[rt] fault " + std::string(tag) + ": "; + // Everything printed below, kept for the crash log as well (RT-CRASH-LOG). + std::string report; + const auto emit = [&report](const std::string& text) { + std::fputs(text.c_str(), stderr); + report += text; + }; + { + SYSTEMTIME now{}; + GetSystemTime(&now); + report += crash_report::log_header(now.wYear, now.wMonth, now.wDay, now.wHour, now.wMinute, now.wSecond, + GetCurrentProcessId()); + } if (record) { // ExceptionAddress is where the faulting instruction is, which for a fault raised by an instruction in a // leaf without unwind data can name nothing; the chain below says what called it either way. const std::string at = record->ExceptionAddress ? shims::module_offset(reinterpret_cast(record->ExceptionAddress)) : std::string("unknown"); + char line[512]; if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { const char* access = record->ExceptionInformation[0] == 0 ? "read" : record->ExceptionInformation[0] == 1 ? "write" : "execute"; - std::fprintf(stderr, "[rt] fault %s: %s of 0x%llx at %s\n", tag, access, - static_cast(record->ExceptionInformation[1]), at.c_str()); + std::snprintf(line, sizeof line, "%s%s of 0x%llx at %s\n", prefix.c_str(), access, + static_cast(record->ExceptionInformation[1]), at.c_str()); + emit(line); } else { - std::fprintf(stderr, "[rt] fault %s: exception 0x%08lx at %s\n", tag, - static_cast(record->ExceptionCode), at.c_str()); + std::snprintf(line, sizeof line, "%sexception 0x%08lx at %s\n", prefix.c_str(), + static_cast(record->ExceptionCode), at.c_str()); + emit(line); + // What its parameters say: a C++ throw's type, an in-page error's status, or the raw words. + std::uint64_t params[EXCEPTION_MAXIMUM_PARAMETERS]{}; + const DWORD n = (std::min)(record->NumberParameters, EXCEPTION_MAXIMUM_PARAMETERS); + for (DWORD i = 0; i < n; ++i) params[i] = record->ExceptionInformation[i]; + emit(crash_report::exception_detail(record->ExceptionCode, n, params, thrown_type(*record), prefix)); } } + if (context) { + crash_report::Registers r; + r.rax = context->Rax, r.rbx = context->Rbx, r.rcx = context->Rcx, r.rdx = context->Rdx; + r.rsi = context->Rsi, r.rdi = context->Rdi, r.rbp = context->Rbp, r.rsp = context->Rsp; + r.r8 = context->R8, r.r9 = context->R9, r.r10 = context->R10, r.r11 = context->R11; + r.r12 = context->R12, r.r13 = context->R13, r.r14 = context->R14, r.r15 = context->R15; + r.rip = context->Rip, r.eflags = context->EFlags; + emit(crash_report::registers_lines(r, prefix)); + } + { + std::uint32_t major, minor, build; + windows_version(major, minor, build); + emit(crash_report::host_line(cpu_brand(), major, minor, build, prefix)); + } + std::fflush(stderr); // The filter runs on the faulting thread and its stack is live under us, so unlike a sampled thread this one // unwinds directly, with no copy (the same frames the suspended thread's own unwinder would walk). if (context && context->Rip) { @@ -260,7 +403,7 @@ void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, else for (std::size_t i = 0; i < count; ++i) out += " #" + std::to_string(i) + " " + shims::module_offset(frames[i]) + "\n"; - std::fputs(out.c_str(), stderr); + emit(out); std::fflush(stderr); } static StackSampler sampler; @@ -268,7 +411,8 @@ void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetThreadDescription"))); const auto query = reinterpret_cast(reinterpret_cast( GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread"))); - snapshot_threads(tag, sampler, describe, query, 0); + snapshot_threads(tag, sampler, describe, query, 0, &report); + append_crash_log(report); } catch (...) { } } diff --git a/runtime/test/crash_report_test.cpp b/runtime/test/crash_report_test.cpp new file mode 100644 index 0000000000..6dc6d18f33 --- /dev/null +++ b/runtime/test/crash_report_test.cpp @@ -0,0 +1,87 @@ +// src/crash_report.h: the text of a fatal-fault report (registers, exception parameters, host line, log header and +// the LEONIDA_CRASH_LOG choice). Synthetic values only; no game data, no Windows. +#include "../src/crash_report.h" + +#include +#include + +namespace { + +int g_failures = 0; + +void check(bool condition, const char* what) { + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +bool has(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } + +using namespace rt::crash_report; + +void registers() { + Registers r; + r.rax = 0x1; + r.rsp = 0x000000a1b2c3d4e0; + r.r15 = 0xffffffffffffffff; + r.rip = 0x00007ff612340abc; + r.eflags = 0x10246; + const std::string text = registers_lines(r, "[rt] fault: "); + check(has(text, "[rt] fault: rax=0000000000000001 rbx=0000000000000000"), "rax and rbx lead the first line"); + check(has(text, "rsp=000000a1b2c3d4e0\n"), "rsp ends the second line"); + check(has(text, "r15=ffffffffffffffff\n"), "r15 ends the fourth line"); + check(has(text, "[rt] fault: rip=00007ff612340abc eflags=00010246\n"), "rip and eflags are the last line"); + std::size_t lines = 0; + for (char c : text) lines += c == '\n'; + check(lines == 5, "five lines, each with the prefix"); +} + +void exceptions() { + const std::uint64_t av[2] = {1, 0xc}; + check(exception_detail(kAccessViolation, 2, av, {}, "> ") == "> access violation: write of 0xc\n", + "an access violation names the access and the address"); + const std::uint64_t exec[2] = {8, 0x1234}; + check(has(exception_detail(kAccessViolation, 2, exec, {}, ""), "execute of 0x1234"), "a DEP fault is an execute"); + const std::uint64_t page[3] = {0, 0x5000, 0xC000009Cu}; + check(exception_detail(kInPageError, 3, page, {}, "") == "in-page error: read of 0x5000, status 0xc000009c\n", + "an in-page error adds the status that failed the read"); + const std::uint64_t cpp[4] = {0x19930520, 0x00000012345678a0, 0x00007ff6000f0000, 0x00007ff600000000}; + const std::string thrown = exception_detail(kCppException, 4, cpp, ".?AVruntime_error@std@@", ""); + check(has(thrown, "C++ exception: object 0x12345678a0, throw info 0x7ff6000f0000"), "a C++ throw names its object"); + check(has(thrown, ", type .?AVruntime_error@std@@\n"), "and its type when it could be read"); + check(!has(exception_detail(kCppException, 4, cpp, {}, ""), "type"), "no type when it could not"); + const std::uint64_t raw[3] = {0xa, 0xb, 0xc}; + check(exception_detail(0xC0000420u, 3, raw, {}, "") == "exception 0xc0000420, 3 parameters 0xa 0xb 0xc\n", + "an unknown code prints its raw parameters"); + check(exception_detail(kIllegalInstruction, 0, nullptr, {}, "") == "illegal instruction 0xc000001d, 0 parameters\n", + "a known code without parameters is named"); + check(exception_detail(kAccessViolation, 1, av, {}, "").starts_with("access violation 0xc0000005, 1 parameter "), + "an access violation short of its parameters falls back to the raw form"); +} + +void host() { + check(host_line(" AMD Ryzen 9 7900X 12-Core Processor ", 10, 0, 26100, "[rt] fault: ") == + "[rt] fault: host: Windows 10.0.26100, CPU AMD Ryzen 9 7900X 12-Core Processor\n", + "the host line trims CPUID's padding"); + check(has(host_line(std::string_view("\0\0", 2), 10, 0, 19045, ""), "CPU unknown"), "an empty brand is unknown"); +} + +void header_and_choice() { + check(log_header(2026, 11, 26, 9, 5, 3, 4242) == "==== 2026-11-26 09:05:03 UTC, process 4242 ====\n", + "the log header dates the report"); + check(log_choice("") == LogChoice::default_file, "LEONIDA_CRASH_LOG unset or empty: the default file"); + check(log_choice("0") == LogChoice::off, "LEONIDA_CRASH_LOG=0: no file"); + check(log_choice("D:\\logs\\crash.log") == LogChoice::path, "anything else is a path"); + check(log_choice("00") == LogChoice::path, "only a lone 0 turns it off"); +} + +} // namespace + +int main() { + registers(); + exceptions(); + host(); + header_and_choice(); + std::printf(g_failures ? "crash_report_test: %d failure(s)\n" : "crash_report_test: all checks passed\n", + g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/thread_stacks_test.cpp b/runtime/test/thread_stacks_test.cpp index 8d19f43b24..05d6b29fa1 100644 --- a/runtime/test/thread_stacks_test.cpp +++ b/runtime/test/thread_stacks_test.cpp @@ -200,8 +200,14 @@ void fault_stacks() { // Binary: the capture must hold the bytes the diagnostics wrote, with their own line endings. const int fd = _open_osfhandle(reinterpret_cast(file), _O_BINARY); _dup2(fd, _fileno(stderr)); + // The report also goes to the crash log (RT-CRASH-LOG): a temporary one here, never the user's. + const std::string crash_log = std::string(dir) + "leonida_thread_stacks_crash_" + + std::to_string(GetCurrentProcessId()) + ".log"; + std::remove(crash_log.c_str()); + SetEnvironmentVariableA("LEONIDA_CRASH_LOG", crash_log.c_str()); g_fault_caller_fn = here(); // fault_stacks itself: the chain must reach it above the fault const int value = run_fault(); + SetEnvironmentVariableA("LEONIDA_CRASH_LOG", nullptr); _dup2(saved, _fileno(stderr)); _close(saved); _close(fd); // the last CRT reference to `file`, so this closes the handle @@ -244,6 +250,20 @@ void fault_stacks() { check(in_fault_here >= 0, "the chain reaches the function the fault happened in"); check(in_caller > in_fault_here, "and unwinds out of it to the function that called it"); check(capture.find("[rt] stacks test: ") != std::string::npos, "the other threads are snapshotted too"); + + // The registers and the host line are printed, and the whole report is in the crash log, after a dated header. + check(capture.find("[rt] fault test: rip=") != std::string::npos, "the faulting context's registers are printed"); + check(capture.find("[rt] fault test: host: Windows ") != std::string::npos, "so is the host line"); + std::ifstream log_in(crash_log, std::ios::binary); + const std::string logged{std::istreambuf_iterator(log_in), std::istreambuf_iterator()}; + log_in.close(); + std::remove(crash_log.c_str()); + check(logged.rfind("==== ", 0) == 0 && logged.find(" UTC, process ") != std::string::npos, + "the crash log's report starts with its dated header"); + check(logged.find("[rt] fault test: read of 0xc at ") != std::string::npos && + logged.find("(faulting thread):\n") != std::string::npos && + logged.find("[rt] stacks test: ") != std::string::npos, + "and holds the fault, the faulting thread's chain and the other threads"); } void parse() {