From 50fdd7dde20537b3363d9e3d634871a6f8c95d4c Mon Sep 17 00:00:00 2001 From: OldSalty <7090702+OldSalty@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:37:53 +1000 Subject: [PATCH 1/3] 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 f44eb2535a..40ce7b77dd 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -344,7 +344,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; @@ -364,9 +365,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 d87d91482d..346ecc5539 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -235,6 +235,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 ebe7aa935f..e28fa2ce3a 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"); @@ -170,6 +269,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 b3316b81ce9cc4b45db6d6fde68babd129645f40 Mon Sep 17 00:00:00 2001 From: OldSalty <7090702+OldSalty@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:38:15 +1000 Subject: [PATCH 2/3] runtime: say what a fatal fault's registers held The faults that end a run follow pointers to garbage, and a faulting address computed base+index says nothing about which pointer was wrong: only the registers still hold the operands. Print the faulting context's registers, then the bytes near each one that points at committed readable memory (the fault's own address first, 48 bytes each, ten lines at most), so the title's data next to the bad pointer can be read out of the log. --- runtime/src/thread_stacks.cpp | 76 +++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp index 346ecc5539..b2ad470a94 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -235,6 +235,57 @@ void print_thread_stacks_now(std::uint32_t tid, const char* why) noexcept { } } +// A faulting read followed a pointer to a bad place; the pointers still in the registers say which one, and the +// bytes near them say what the title was reading there. One line per register that points at committed readable +// memory (the fault's own address first when it is), bounded so the fatal report stays short. +void dump_fault_memory(const char* tag, uint64_t fault_at, const CONTEXT& context) { + struct { const char* name; uint64_t value; } const sites[] = { + {"fault", fault_at}, {"rax", context.Rax}, {"rbx", context.Rbx}, + {"rcx", context.Rcx}, {"rdx", context.Rdx}, {"rsi", context.Rsi}, + {"rdi", context.Rdi}, {"r8", context.R8}, {"r9", context.R9}, + {"r10", context.R10}, {"r11", context.R11}, {"r12", context.R12}, + {"r13", context.R13}, {"r14", context.R14}, {"r15", context.R15}, + {"rbp", context.Rbp}}; + MEMORY_BASIC_INFORMATION page{}; + unsigned printed = 0; + for (const auto& site : sites) { + if (printed >= 10) break; + if (site.value < 0x1000) continue; + if (!VirtualQuery(reinterpret_cast(site.value), &page, sizeof(page))) continue; + if (page.State != MEM_COMMIT) continue; + switch (page.Protect & 0xff) { + case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: case PAGE_EXECUTE_READ: + case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: break; + default: continue; + } + std::array bytes{}; + SIZE_T got = 0; + if (!ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(site.value), bytes.data(), + bytes.size(), &got) || + !got) + continue; + std::string out = "[rt] fault "; + out += tag; + out += " mem "; + out += site.name; + out += " 0x"; + char hex[17]; + const auto end = std::to_chars(hex, hex + 16, site.value, 16); + out.append(hex, static_cast(end.ptr - hex)); + out += ":"; + for (SIZE_T i = 0; i < got; ++i) { + out += ' '; + const unsigned char b = bytes[i]; + out += "0123456789abcdef"[b >> 4]; + out += "0123456789abcdef"[b & 0xf]; + } + out += "\n"; + std::fputs(out.c_str(), stderr); + ++printed; + } + std::fflush(stderr); +} + void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* why) noexcept { static std::mutex mutex; try { @@ -255,6 +306,31 @@ void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, std::fprintf(stderr, "[rt] fault %s: exception 0x%08lx at %s\n", tag, static_cast(record->ExceptionCode), at.c_str()); } + // The faulting instruction's operands live in the registers: a faulting address that was computed + // (base+index) can only be traced back by reading them. One line, all of them. + if (context && context->Rip) + std::fprintf(stderr, "[rt] fault %s regs: rip 0x%llx rsp 0x%llx rbp 0x%llx rax 0x%llx rbx 0x%llx " + "rcx 0x%llx rdx 0x%llx rsi 0x%llx rdi 0x%llx r8 0x%llx r9 0x%llx r10 0x%llx " + "r11 0x%llx r12 0x%llx r13 0x%llx r14 0x%llx r15 0x%llx\n", tag, + static_cast(context->Rip), + static_cast(context->Rsp), + static_cast(context->Rbp), + static_cast(context->Rax), + static_cast(context->Rbx), + static_cast(context->Rcx), + static_cast(context->Rdx), + static_cast(context->Rsi), + static_cast(context->Rdi), + static_cast(context->R8), + static_cast(context->R9), + static_cast(context->R10), + static_cast(context->R11), + static_cast(context->R12), + static_cast(context->R13), + static_cast(context->R14), + static_cast(context->R15)); + if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) + dump_fault_memory(tag, static_cast(record->ExceptionInformation[1]), *context); } // 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). From e480a5e7bba3ce5cf67158f58aa67c400e334baf Mon Sep 17 00:00:00 2001 From: OldSalty <7090702+OldSalty@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:39:49 +1000 Subject: [PATCH 3/3] runtime: name a fatal fault with no locks or heap print_fault_stacks asked the module registry for a name, which takes g_lookup_mutex and then Loader::find_address's shared ownership of ranges_mutex_: a thread that faults in the DLL load path, holding that mutex exclusively, waits on itself and never reaches the fault line, the cache save or the title's filter. It also allocated, and took a snapshot of every other thread, in the one place where the heap may be what broke. A fatal report now names an address only from a fixed table published as images are mapped, writes with a raw stderr write instead of stdio, and leaves the other threads to print_thread_stacks_now. The whole report runs under __try, so a fault of its own says so instead of re-entering the filter's call_once. --- runtime/src/main.cpp | 7 +- runtime/src/pe_loader.cpp | 7 + runtime/src/thread_stacks.cpp | 288 +++++++++++++++++++++------- runtime/src/thread_stacks.h | 23 ++- runtime/test/thread_stacks_test.cpp | 163 +++++++++++++++- 5 files changed, 407 insertions(+), 81 deletions(-) diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 40ce7b77dd..9bf356f98e 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -368,9 +368,12 @@ static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) { 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. + // Before the waits below, while the faulting thread's stack is still the one we are running on. The + // fatal report takes no lock, no heap and no other thread: the fault may be the heap's, or the loader + // lookup's (a thread that faults while it holds ranges_mutex_ would wait on itself), so an address here + // is named only from the ranges published at map time, and the other threads are left alone. rt::print_fault_stacks(info ? info->ExceptionRecord : nullptr, info ? info->ContextRecord : nullptr, - "fatal"); + "fatal", true); rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs); rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs); std::fflush(stderr); diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 49588b4245..95cc592066 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -24,6 +24,7 @@ #include "clzero_patch.h" #include "cpu_emulation.h" #include "isa_jit_patch.h" +#include "thread_stacks.h" namespace rt { @@ -1433,6 +1434,7 @@ Loader::~Loader() { shims::remove_xmem_allocation_hooks(this); shims::remove_bundled_loader(this); shims::remove_module_lookup(this); + clear_fault_ranges(this); // before the unmapping below: a fault after this names these addresses as numbers for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) { @@ -1773,6 +1775,9 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // lookup first. std::unique_lock lock(ranges_mutex_); ranges_.push_back({reinterpret_cast(m->base), m->size, m->name}); + // A second copy for the fatal report, which may not take ranges_mutex_ (a thread that faults in the load + // path below holds it) nor the heap. See rt::publish_fault_range. + publish_fault_range(reinterpret_cast(m->base), m->size, m->name.c_str(), this); } std::memcpy(m->base, file.data(), oh.SizeOfHeaders); @@ -2354,6 +2359,8 @@ void Loader::protect_sections(Module& m) { std::unique_lock lock(ranges_mutex_); ranges_.push_back({reinterpret_cast(isa.stubs), static_cast(isa.stub_bytes), m.name + "[isa-stubs]"}); + publish_fault_range(reinterpret_cast(isa.stubs), static_cast(isa.stub_bytes), + (m.name + "[isa-stubs]").c_str(), this); } if (isa.inplace_sites || isa.bmi_stubs || isa.avx2_stubs || isa.fma3_stubs) { std::fprintf(stderr, diff --git a/runtime/src/thread_stacks.cpp b/runtime/src/thread_stacks.cpp index b2ad470a94..0623ff84c2 100644 --- a/runtime/src/thread_stacks.cpp +++ b/runtime/src/thread_stacks.cpp @@ -2,13 +2,17 @@ #include #include +#include #include #include +#include #include #include #include #include +#include +#include #include #include #include @@ -23,6 +27,66 @@ using Clock = std::chrono::steady_clock; using GetDescription = HRESULT(WINAPI*)(HANDLE, PWSTR*); using QueryThread = LONG(NTAPI*)(HANDLE, int, void*, ULONG, ULONG*); +// What a fatal fault may name without a lock or the heap: one row per image published when it was mapped, read as it +// stands when the fault happens. A row is filled (size, name) and then its base is released, so a reader that +// acquires a non-zero base also sees its size and name; clearing stores the zero base, after which the row's other +// fields are not read. Ranges are never rewritten in place, so a fault can happen while another thread publishes. +constexpr std::size_t kMaxFaultRanges = 256; // the title image and the modules it imports; more report as numbers +struct FaultRange { + std::atomic base{0}; // 0: the row holds nothing + std::uint32_t size = 0; + void* owner = nullptr; // revoked by clear_fault_ranges(owner) + char name[64] = {}; +}; +FaultRange g_fault_ranges[kMaxFaultRanges]; +std::atomic g_fault_range_next{0}; // rows go out one at a time; clear_fault_ranges resets it + +// "name+0x1234" for an address inside a published image, else "0x…". Straight into the caller's buffer: the fatal +// report's only address formatter, so it neither takes a lock nor touches the heap nor the module registry. +void format_fault_address(std::uint64_t address, char* out, std::size_t cap) { + for (const auto& row : g_fault_ranges) { + const std::uint64_t base = row.base.load(std::memory_order_acquire); + if (!base || address < base || address - base >= row.size) continue; + std::snprintf(out, cap, "%s+0x%llx", row.name, + static_cast(address - base)); + return; + } + std::snprintf(out, cap, "0x%llx", static_cast(address)); +} + +// Unbuffered, no lock, no allocation: the fatal report's only way out. stderr's FILE* carries a lock a thread that +// faulted inside stdio already holds, and flushing it can allocate; writing the descriptor goes straight through, +// and the tests' _dup2 redirection of descriptor 2 still captures it. +void write_stderr(const char* text, std::size_t bytes) { + if (bytes) (void)_write(_fileno(stderr), text, static_cast(bytes)); +} + +// The runtime's own image (the test binary's, in a test), published at start-up so a fault in this program's code is +// named without the report having to ask the OS for a name. The basename is ASCII for every module here; a wider one +// becomes UTF-8 the way the registry's own fallback does. +bool publish_process_image() { + const HMODULE host = GetModuleHandleW(nullptr); + if (!host) return false; + const auto* dos = reinterpret_cast(host); + const auto* nt = reinterpret_cast(reinterpret_cast(host) + + dos->e_lfanew); + wchar_t path[MAX_PATH] = {}; + const DWORD len = GetModuleFileNameW(host, path, MAX_PATH); + if (!len || len >= MAX_PATH) return false; + const wchar_t* slash = std::wcsrchr(path, L'\\'); + const wchar_t* file = slash ? slash + 1 : path; + if (!*file) return false; + char utf8[2 * MAX_PATH]; + const int bytes = WideCharToMultiByte(CP_UTF8, 0, file, -1, utf8, static_cast(sizeof utf8) - 1, nullptr, + nullptr); + if (bytes <= 0) return false; + utf8[bytes > 63 ? 63 : bytes] = '\0'; // publish_fault_range copies at most 63 characters + publish_fault_range(reinterpret_cast(host), nt->OptionalHeader.SizeOfImage, utf8, + nullptr); // mapped for the life of the process: nothing revokes it + return true; +} +[[maybe_unused]] const bool g_process_image_published = publish_process_image(); + struct CopiedStack { DWORD64 copy = 0; // Where the bytes are now. DWORD64 original = 0; // Where they were in the thread: [original, original + size). @@ -187,6 +251,34 @@ void snapshot_threads(const std::string& tag, StackSampler& sampler, GetDescript } // namespace +void publish_fault_range(std::uint64_t base, std::uint32_t size, const char* name, void* owner) { + if (!base || !size || !name) return; + const std::uint32_t slot = g_fault_range_next.fetch_add(1, std::memory_order_relaxed); + if (slot >= kMaxFaultRanges) return; // the image reports as a bare number + FaultRange& row = g_fault_ranges[slot]; + row.size = size; + row.owner = owner; + std::size_t i = 0; + for (; i + 1 < sizeof row.name && name[i]; ++i) row.name[i] = name[i]; + row.name[i] = '\0'; + row.base.store(base, std::memory_order_release); // publishes the row: a reader that sees this base sees the rest +} + +void clear_fault_ranges(void* owner) { + // The rows an owner revokes are the last ones it published, so walking back to the last live row frees them; + // publishing while another owner revokes (two loaders at once, which the runtime does not do) would need more + // than this count. + std::uint32_t live = 0; // free rows stay at the end: the count walks back to the last one still in use + const std::uint32_t published = g_fault_range_next.load(std::memory_order_relaxed); + for (std::uint32_t i = 0; i < published && i < kMaxFaultRanges; ++i) { + FaultRange& row = g_fault_ranges[i]; + if (row.owner == owner && row.base.load(std::memory_order_relaxed)) + row.base.store(0, std::memory_order_release); + if (row.base.load(std::memory_order_relaxed)) live = i + 1; + } + g_fault_range_next.store(live, std::memory_order_relaxed); +} + StackSampler::StackSampler() : stack_(std::make_unique_for_overwrite(kMaxStackBytes)) {} std::size_t StackSampler::sample(void* thread, std::uint64_t* frames) { @@ -264,73 +356,99 @@ void dump_fault_memory(const char* tag, uint64_t fault_at, const CONTEXT& contex bytes.size(), &got) || !got) continue; - std::string out = "[rt] fault "; - out += tag; - out += " mem "; - out += site.name; - out += " 0x"; - char hex[17]; - const auto end = std::to_chars(hex, hex + 16, site.value, 16); - out.append(hex, static_cast(end.ptr - hex)); - out += ":"; + // One fixed buffer per line: this runs inside the fatal report, where the heap may be what broke. + char hex[3 * 48 + 1]; + std::size_t at = 0; for (SIZE_T i = 0; i < got; ++i) { - out += ' '; - const unsigned char b = bytes[i]; - out += "0123456789abcdef"[b >> 4]; - out += "0123456789abcdef"[b & 0xf]; + hex[at++] = ' '; + hex[at++] = "0123456789abcdef"[bytes[i] >> 4]; + hex[at++] = "0123456789abcdef"[bytes[i] & 0xf]; } - out += "\n"; - std::fputs(out.c_str(), stderr); + hex[at] = '\0'; + char line[256]; + if (std::snprintf(line, sizeof line, "[rt] fault %s mem %s 0x%llx:%s\n", tag, site.name, + static_cast(site.value), hex) > 0) + write_stderr(line, std::strlen(line)); ++printed; } - std::fflush(stderr); } -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"; +// The registry's name for an address, copied into a fixed buffer. Its own function so that the report below holds no +// object that would need unwinding, which is what lets a fault of the report's own be caught where it happens. +void copy_registry_name(char* out, std::size_t cap, std::uint64_t address) { + const std::string named = shims::module_offset(address); + std::snprintf(out, cap, "%s", named.c_str()); +} + +// The other threads' call chains. It allocates (the thread list, one label per thread) and suspends every thread, and +// builds its 8 MB copy buffer on first use, so the fatal report leaves it out. +void take_thread_snapshot(const char* tag) { + 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); +} + +// One fault's report: the fault, the faulting context's registers, the bytes those registers point at, and the chain +// of the thread the fault happened on. POD locals only, and MSVC requires that: `report_fault` puts the whole thing +// under __try. Nothing it does on the fatal path takes a lock, allocates, or asks the module registry for a name; +// output goes through write_stderr, which leaves stdio's lock alone. `fatal` differs from the other callers only in +// where an address's name comes from (the published ranges, which cannot wait for the loader) and in leaving out the +// other threads' snapshot. +void report_fault(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* tag, bool fatal) { + __try { 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 at[128] = "unknown"; + if (record->ExceptionAddress) { + if (fatal) + format_fault_address(reinterpret_cast(record->ExceptionAddress), at, sizeof at); + else + copy_registry_name(at, sizeof at, reinterpret_cast(record->ExceptionAddress)); + } + char line[384]; 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()); + if (std::snprintf(line, sizeof line, "[rt] fault %s: %s of 0x%llx at %s\n", tag, access, + static_cast(record->ExceptionInformation[1]), at) > 0) + write_stderr(line, std::strlen(line)); + } else if (std::snprintf(line, sizeof line, "[rt] fault %s: exception 0x%08lx at %s\n", tag, + static_cast(record->ExceptionCode), at) > 0) { + write_stderr(line, std::strlen(line)); } // The faulting instruction's operands live in the registers: a faulting address that was computed // (base+index) can only be traced back by reading them. One line, all of them. - if (context && context->Rip) - std::fprintf(stderr, "[rt] fault %s regs: rip 0x%llx rsp 0x%llx rbp 0x%llx rax 0x%llx rbx 0x%llx " - "rcx 0x%llx rdx 0x%llx rsi 0x%llx rdi 0x%llx r8 0x%llx r9 0x%llx r10 0x%llx " - "r11 0x%llx r12 0x%llx r13 0x%llx r14 0x%llx r15 0x%llx\n", tag, - static_cast(context->Rip), - static_cast(context->Rsp), - static_cast(context->Rbp), - static_cast(context->Rax), - static_cast(context->Rbx), - static_cast(context->Rcx), - static_cast(context->Rdx), - static_cast(context->Rsi), - static_cast(context->Rdi), - static_cast(context->R8), - static_cast(context->R9), - static_cast(context->R10), - static_cast(context->R11), - static_cast(context->R12), - static_cast(context->R13), - static_cast(context->R14), - static_cast(context->R15)); - if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) - dump_fault_memory(tag, static_cast(record->ExceptionInformation[1]), *context); + if (context && context->Rip) { + char regs[512]; + if (std::snprintf(regs, sizeof regs, + "[rt] fault %s regs: rip 0x%llx rsp 0x%llx rbp 0x%llx rax 0x%llx rbx 0x%llx " + "rcx 0x%llx rdx 0x%llx rsi 0x%llx rdi 0x%llx r8 0x%llx r9 0x%llx r10 0x%llx " + "r11 0x%llx r12 0x%llx r13 0x%llx r14 0x%llx r15 0x%llx\n", tag, + static_cast(context->Rip), + static_cast(context->Rsp), + static_cast(context->Rbp), + static_cast(context->Rax), + static_cast(context->Rbx), + static_cast(context->Rcx), + static_cast(context->Rdx), + static_cast(context->Rsi), + static_cast(context->Rdi), + static_cast(context->R8), + static_cast(context->R9), + static_cast(context->R10), + static_cast(context->R11), + static_cast(context->R12), + static_cast(context->R13), + static_cast(context->R14), + static_cast(context->R15)) > 0) + write_stderr(regs, std::strlen(regs)); + } + if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) + dump_fault_memory(tag, static_cast(record->ExceptionInformation[1]), *context); } // 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). @@ -342,21 +460,59 @@ void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, 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); + char block[5120]; // one write for the whole chain: 40 frames of a name and an RVA each + int used = std::snprintf(block, sizeof block, "[rt] stacks %s thread %lu (faulting thread):\n", tag, + static_cast(GetCurrentThreadId())); + if (used < 0 || used >= static_cast(sizeof block)) used = 0; + if (!count) { + const int room = static_cast(sizeof block) - used; + const int w = std::snprintf(block + used, room, " stack unavailable\n"); + if (w > 0) used += (w < room) ? w : room - 1; + } else { + for (std::size_t i = 0; i < count; ++i) { + const int room = static_cast(sizeof block) - used; + if (room <= 1) break; + char where[128]; + if (fatal) + format_fault_address(frames[i], where, sizeof where); + else + copy_registry_name(where, sizeof where, frames[i]); + const int w = std::snprintf(block + used, room, " #%zu %s\n", i, where); + if (w < 0) break; + used += (w < room) ? w : room - 1; + } + } + write_stderr(block, static_cast(used)); } - 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); + if (fatal) { + // The other threads' chains are the part of this that allocates and suspends them. Left out of the fatal + // report; print_thread_stacks_now still gives them to anything that can afford it. + char line[128]; + if (std::snprintf(line, sizeof line, "[rt] stacks %s: other threads not sampled\n", tag) > 0) + write_stderr(line, std::strlen(line)); + } else { + take_thread_snapshot(tag); + } + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + // The report faulted on the thread that is already inside the filter's call_once, where re-entering the + // filter would wait for the report that is still running. Say so, and stop. + static const char note[] = "[rt] fault report: the report itself faulted\n"; + write_stderr(note, sizeof note - 1); + } +} + +void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* why, + bool fatal) noexcept { + static std::mutex mutex; + try { + // The fatal path takes no lock: std::call_once in the top-level filter already serialises the writers, and + // this mutex is not recursive, so a fault on a thread that already holds it would wait for itself before + // the fault line. The paths that run while the process carries on (an assert skip, device loss) can overlap + // each other, so those keep it. + std::unique_lock guard; + if (!fatal) guard = std::unique_lock(mutex); + report_fault(record, context, why ? why : "fatal", fatal); } catch (...) { } } diff --git a/runtime/src/thread_stacks.h b/runtime/src/thread_stacks.h index 42605c7afb..7bd95bac9f 100644 --- a/runtime/src/thread_stacks.h +++ b/runtime/src/thread_stacks.h @@ -41,9 +41,24 @@ 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; +// Records a mapped image so a fatal fault can name `module+0xRVA` without a lock or the heap: the report reads only +// rows published before it runs. `name` is copied (63 characters); the range must outlive the report, so publish a +// mapped image's range while it stays mapped and revoke it with the same `owner` when its owner unmaps. Rows past the +// last published one, and addresses in no published range, report as a bare number. +void publish_fault_range(std::uint64_t base, std::uint32_t size, const char* name, void* owner); + +// Revokes every range published under `owner`: call it when the images that published them are unmapped, so a later +// fault cannot name memory that is gone. A range that outlives the program (the process's own image) passes an owner +// nothing revokes. +void clear_fault_ranges(void* owner); + +// A fatal exception nothing handled: the fault (access and address for an access violation), the faulting context's +// registers, the bytes those registers point at, 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). From a top-level exception filter only. +// `fatal` says this is the process's last word: an address is then named only from the published ranges above, and +// the other-thread snapshot is left out, because taking it allocates (its thread list and labels) and suspends every +// thread. Without `fatal` the report is the same but uses the module registry for names and does the snapshot. +void print_fault_stacks(const EXCEPTION_RECORD* record, const CONTEXT* context, const char* why, + bool fatal = false) noexcept; } // namespace rt diff --git a/runtime/test/thread_stacks_test.cpp b/runtime/test/thread_stacks_test.cpp index e28fa2ce3a..a85dcf4425 100644 --- a/runtime/test/thread_stacks_test.cpp +++ b/runtime/test/thread_stacks_test.cpp @@ -162,8 +162,12 @@ __declspec(noinline) int fault_here() { return none[3]; // a read of 0xc } +// Which print_fault_stacks path the guarded fault below exercises: the fatal one (no registry names, no snapshot), +// or the one an assert skip uses (registry names, and the other threads snapshotted). +bool g_fatal_call = true; + LONG WINAPI fault_filter(EXCEPTION_POINTERS* info) { - rt::print_fault_stacks(info->ExceptionRecord, info->ContextRecord, "test"); + rt::print_fault_stacks(info->ExceptionRecord, info->ContextRecord, g_fatal_call ? "test" : "assert", g_fatal_call); return EXCEPTION_EXECUTE_HANDLER; } @@ -186,31 +190,38 @@ long long frame_rva(const std::string& line) { return std::stoll(line.substr(at + name.size()), nullptr, 16); } -void fault_stacks() { +// The capture around one guarded fault, as a function of its own so both report modes can be run through it. +std::string capture_fault(bool fatal) { 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"; + const std::string path = + std::string(dir) + "leonida_thread_stacks_fault_" + std::to_string(GetCurrentProcessId()) + + (fatal ? "_fatal" : "_named") + ".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; + 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 + g_fatal_call = fatal; + g_fault_caller_fn = here(); // the caller here: 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()); + return capture; +} + +void fault_stacks() { + // The fatal report: no lock, no heap, no other thread, and names only what was published before the fault. + const std::string capture = capture_fault(true); 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, @@ -243,7 +254,94 @@ 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 fatal path is the process's last word: it names no thread but the one that faulted, and says so, because + // the other-thread snapshot allocates (its thread list and labels) and suspends every thread in the process. + check(capture.find("other threads not sampled") != std::string::npos, + "the fatal report says it left the other threads alone"); + size_t chain_heads = 0; + for (size_t p = capture.find("[rt] stacks test thread "); p != std::string::npos; + p = capture.find("[rt] stacks test thread ", p + 1)) + ++chain_heads; + check(chain_heads == 1, "and names only the faulting thread's chain"); + + // The path an assert skip uses is the same report with the registry's names and the other threads snapshotted: + // the process carries on afterwards, so the heap and the other threads are not in question. + const std::string named = capture_fault(false); + check(named.find("[rt] fault assert: read of 0xc at ") != std::string::npos, + "the non-fatal report names the fault the same way"); + check(named.find("(faulting thread):\n") != std::string::npos, + "and holds the same chain"); + check(named.find("[rt] stacks assert: ") != std::string::npos && named.find(" threads") != std::string::npos, + "and snapshots the other threads, which the fatal report leaves out"); + check(named.find("other threads not sampled") == std::string::npos, + "and says nothing about leaving them out"); +} + +// The other-thread snapshot, on the path that still takes it (rt::print_thread_stacks_now). A helper parked in a +// known function is what makes this a check and not a shape match: "0 threads" and "thread list failed" both satisfy +// a search for the tag, and neither names a thread id or a frame that thread is really in. +void snapshot_helper() { + g_ready = CreateEventW(nullptr, TRUE, FALSE, nullptr); + g_release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + const HANDLE thread = CreateThread(nullptr, 0, blocked_main, nullptr, 0, nullptr); + check(thread && WaitForSingleObject(g_ready, 5000) == WAIT_OBJECT_0, "the snapshot helper reached its wait"); + if (!thread) return; + const DWORD tid = GetThreadId(thread); + + char dir[MAX_PATH] = {}; + const DWORD len = GetTempPathA(sizeof dir, dir); + check(len > 0 && len < sizeof dir, "the temp path resolves for the snapshot capture"); + const std::string path = + std::string(dir) + "leonida_thread_stacks_snap_" + std::to_string(GetCurrentProcessId()) + ".log"; + HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + const bool opened = file != INVALID_HANDLE_VALUE; + check(opened, "the snapshot capture's file opens"); + std::string capture; + if (opened) { + const int saved = _dup(_fileno(stderr)); + const int fd = _open_osfhandle(reinterpret_cast(file), _O_BINARY); + _dup2(fd, _fileno(stderr)); + rt::print_thread_stacks_now(0, "snap"); + _dup2(saved, _fileno(stderr)); + _close(saved); + _close(fd); // the last CRT reference to `file`, so this closes the handle + std::ifstream in(path, std::ios::binary); + capture = std::string{std::istreambuf_iterator(in), std::istreambuf_iterator()}; + in.close(); + std::remove(path.c_str()); + } + + const std::string needle = "[rt] stacks snap thread " + std::to_string(tid) + " ("; + const size_t at = capture.find(needle); + check(at != std::string::npos, "the snapshot names the helper thread by its id"); + if (at == std::string::npos) { + std::printf(" capture (%zu bytes):\n%s\n", capture.size(), capture.c_str()); + } else { + const size_t next = capture.find("[rt] stacks snap thread ", at + needle.size()); + const std::string block = capture.substr(at, next == std::string::npos ? std::string::npos : next - at); + const DWORD64 base = reinterpret_cast(GetModuleHandleW(nullptr)); + int parked = -1, frame = 0; + size_t pos = 0; + while ((pos = block.find(" #", pos)) != std::string::npos) { + const size_t end = block.find('\n', pos); + if (const long long rva = frame_rva(block.substr(pos, end - pos)); rva >= 0) { + const DWORD64 function = function_of(base + static_cast(rva)); + if (function == g_blocked_fn || function == g_blocked_main_fn) { + parked = frame; + break; + } + ++frame; + } + pos = end == std::string::npos ? block.size() : end; + } + check(parked >= 0, "and a frame of the function that helper is parked in"); + } + SetEvent(g_release); + WaitForSingleObject(thread, 5000); + CloseHandle(thread); + CloseHandle(g_ready); + CloseHandle(g_release); } void parse() { @@ -263,6 +361,51 @@ void parse() { check(sampler.sample(GetCurrentThread(), nullptr) == 0, "null frames buffer returns zero frames"); } +// The published ranges are what the fatal report names an address from: nothing in that path asks the module +// registry, so a fault on a thread holding the loader's lookup lock cannot wait for itself. No Loader here, and no +// game data: an address nothing is mapped at, published by the test, stands in for a mapped image. +void published_ranges() { + struct Owner {} owner; // just an address to publish under and revoke by + char dir[MAX_PATH] = {}; + const DWORD len = GetTempPathA(sizeof dir, dir); + check(len > 0 && len < sizeof dir, "the temp path resolves for the ranges capture"); + const std::string path = + std::string(dir) + "leonida_thread_stacks_ranges_" + std::to_string(GetCurrentProcessId()) + ".log"; + HANDLE file = CreateFileA(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + const bool opened = file != INVALID_HANDLE_VALUE; + check(opened, "the ranges capture's file opens"); + if (!opened) return; + + EXCEPTION_RECORD record{}; + record.ExceptionCode = EXCEPTION_ACCESS_VIOLATION; + record.NumberParameters = 2; + record.ExceptionInformation[0] = 0; // a read + record.ExceptionInformation[1] = 0xc; + record.ExceptionAddress = reinterpret_cast(0x10000002a); // inside the range published below + + const int saved = _dup(_fileno(stderr)); + const int fd = _open_osfhandle(reinterpret_cast(file), _O_BINARY); + _dup2(fd, _fileno(stderr)); + rt::publish_fault_range(0x100000000, 0x1000, "guest.dll", &owner); + rt::print_fault_stacks(&record, nullptr, "range", true); + rt::clear_fault_ranges(&owner); + rt::print_fault_stacks(&record, nullptr, "range", true); + _dup2(saved, _fileno(stderr)); + _close(saved); + _close(fd); + + 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()); + check(capture.find("[rt] fault range: read of 0xc at guest.dll+0x2a") != std::string::npos, + "a published range names the fault's place"); + check(capture.find("[rt] fault range: read of 0xc at 0x10000002a") != std::string::npos, + "and once the owner revokes it, the same address is a bare number"); + if (capture.find("guest.dll+0x2a") == std::string::npos) + std::printf(" capture (%zu bytes):\n%s\n", capture.size(), capture.c_str()); +} + } // namespace int main() { @@ -270,6 +413,8 @@ int main() { blocked_thread(); moving_thread(); fault_stacks(); + snapshot_helper(); + published_ranges(); std::printf("%d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; }