windows-boot: capture private minidumps and stacks on abnormal exit

This commit is contained in:
sodove
2026-11-25 13:22:52 +05:00
parent 3f81d46ac0
commit 1b9e4969a5
6 changed files with 427 additions and 2 deletions

View File

@ -206,6 +206,8 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
set_source_files_properties(shims/dstorage.cpp src/thread_stacks.cpp
PROPERTIES COMPILE_OPTIONS "$<$<CXX_COMPILER_ID:Clang>:/EHa>")
add_dependencies(gta6rt gta6rt_tls_host bcpack_history_train)
add_executable(gta6rt_crash_monitor ../scripts/windows-boot/crash_monitor.cpp)
target_link_libraries(gta6rt_crash_monitor PRIVATE dbghelp)
target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8)
# Static shim tables register themselves at startup; keep the linker from dropping their objects.
@ -709,6 +711,13 @@ include(CTest)
# LEONIDA_TRANSLATOR_DEPS: what the rules that run test/shaders/build.py depend on besides their .asm files.
include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/translator_deps.cmake")
if(BUILD_TESTING)
if(TARGET gta6rt_crash_monitor AND NOT CMAKE_CROSSCOMPILING)
add_executable(windows_crash_fixture test/windows_crash_fixture.cpp)
target_compile_options(windows_crash_fixture PRIVATE /Od /EHa)
add_test(NAME windows_crash_monitor COMMAND "${Python3_EXECUTABLE}" -I
"${CMAKE_CURRENT_SOURCE_DIR}/../scripts/windows-boot/test_crash_monitor.py"
$<TARGET_FILE:gta6rt_crash_monitor> $<TARGET_FILE:windows_crash_fixture>)
endif()
add_executable(gfx10_tiling_test test/gfx10_tiling_test.cpp)
add_test(NAME gfx10_tiling COMMAND gfx10_tiling_test)

View File

@ -0,0 +1,38 @@
#include <windows.h>
#include <cstdio>
#include <cwchar>
constexpr DWORD test_exception = 0xe0421234;
__declspec(noinline) DWORD WINAPI crash_worker(void*) {
RaiseException(test_exception, 0, 0, nullptr);
return 0;
}
int wmain(int argc, wchar_t** argv) {
wchar_t mode[32]{};
GetEnvironmentVariableW(L"LEONIDA_TEST_CRASH_MODE", mode, 32);
std::puts("fixture stdout");
std::fputs("fixture stderr\n", stderr);
std::fflush(stdout);
if (wcscmp(mode, L"worker") == 0) {
HANDLE worker = CreateThread(nullptr, 0, crash_worker, nullptr, 0, nullptr);
if (!worker) return 4;
WaitForSingleObject(worker, INFINITE);
CloseHandle(worker);
} else if (wcscmp(mode, L"handled") == 0) {
__try { RaiseException(test_exception, 0, 0, nullptr); }
__except (GetExceptionCode() == test_exception ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {}
} else if (wcscmp(mode, L"break") == 0) {
DebugBreak();
} else if (wcscmp(mode, L"exit") == 0) {
ExitProcess(23);
} else if (wcscmp(mode, L"numeric") == 0) {
ExitProcess(EXCEPTION_ACCESS_VIOLATION);
} else if (wcscmp(mode, L"timer") == 0) {
Sleep(30000);
} else if (wcscmp(mode, L"argv") == 0) {
return argc == 3 && wcscmp(argv[1], L"a b\\") == 0 && wcscmp(argv[2], L"a\"b") == 0 ? 0 : 5;
}
return 0;
}

View File

@ -26,6 +26,18 @@ profile and the parameters can be left out. Defaults: `gta6rt` from `runtime\bui
checkout, the executable from the game folder (`-Exe` or `LEONIDA_EXE` when it lives elsewhere), outputs in `$HOME\leonida-runs`.
The script refuses an output folder inside the repository.
### Private crash diagnostics
Build the `gta6rt_crash_monitor` target in the same x64 Windows build as the runtime, then add
`-CrashDump` to your usual boot command. Each invocation reserves a fresh directory under `-OutDir`.
An unhandled exception writes `crash.dmp` and `stack.txt` for the faulting thread. An explicit nonzero
exit captures the last thread at process exit, which may already be in shutdown. Handled exceptions,
successful exits and the boot time limit produce no crash report.
Keep matching PDBs beside the runtime for local symbol names. Frames without symbols can appear as
addresses, and unwinding can stop at manually mapped code. Dumps can contain process memory and stacks
can identify private inputs. Keep both on your machine. Share only the outcome, error class and counts.
## What it sets
Only when your shell has not set them already (`-DryRun` prints the final list):

View File

@ -87,6 +87,9 @@
.PARAMETER DryRun
Print the environment and the command line, check the paths, launch nothing.
.PARAMETER CrashDump
Run under the native Windows crash monitor. A crash dump and stack go into a fresh private folder under -OutDir.
.PARAMETER DigestOnly
Launch nothing; write the summary and digest again from an earlier run's files (-Name, -OutDir).
@ -116,6 +119,7 @@ param(
[string]$Stacks = "",
[hashtable]$SetEnv = @{},
[switch]$NoCapture,
[switch]$CrashDump,
[switch]$NoInput,
[string[]]$ExtraArgs = @(),
[string]$Python = "",
@ -209,6 +213,12 @@ if (-not (Test-Path -LiteralPath $Runtime -PathType Leaf)) { $problems.Add("no g
elseif (-not (Test-Path -LiteralPath (Join-Path $RuntimeDir "gta6rt_tls_host.dll") -PathType Leaf)) {
$problems.Add("gta6rt_tls_host.dll is missing beside $Runtime (build the gta6rt target; without it the title exits at once)")
}
if ($CrashDump) {
$monitor = Join-Path $RuntimeDir "gta6rt_crash_monitor.exe"
if (-not (Test-Path -LiteralPath $monitor -PathType Leaf)) {
$problems.Add("-CrashDump needs the gta6rt_crash_monitor build target beside the runtime")
}
}
if (-not $GameDir) { $problems.Add("no game folder: pass -GameDir or set LEONIDA_GAME_DIR") }
elseif (-not (Test-Path -LiteralPath (Join-Path $GameDir "MicrosoftGame.Config") -PathType Leaf)) {
$problems.Add("$GameDir has no MicrosoftGame.Config: -GameDir is the folder with it and the .rpf archives")
@ -336,11 +346,30 @@ if (-not $DigestOnly) {
# ------------------------------------------------------------------------------------------- the boot
$started = Get-Date
$proc = Start-Process -FilePath $Runtime -ArgumentList $argLine -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
$launchFile = $Runtime
$launchArgs = $argLine
if ($CrashDump) {
$crashDir = Join-Path $OutDir ("{0}-crash-{1}" -f $Name, [guid]::NewGuid().ToString("N"))
$runtimePath = (Get-Item -LiteralPath $Runtime).FullName
$childCommand = "$(ConvertTo-ProcessArgument $runtimePath) $argLine"
$launchFile = $monitor
$launchArgs = (@($RepoRoot, $crashDir, $Seconds, $runtimePath, $childCommand) |
ForEach-Object { ConvertTo-ProcessArgument ([string]$_) }) -join " "
}
$proc = Start-Process -FilePath $launchFile -ArgumentList $launchArgs -WorkingDirectory $RepoRoot -NoNewWindow -PassThru `
-RedirectStandardError $LogFile -RedirectStandardOutput $StdoutFile
$handle = $proc.Handle # keeps the exit code readable after the process ends
$stopped = $false
if (-not $proc.WaitForExit($Seconds * 1000)) {
if ($CrashDump) {
# The monitor owns the deadline so a dump already in progress can finish.
$proc.WaitForExit()
$stopped = Test-Path -LiteralPath (Join-Path $crashDir "timed-out")
if (Test-Path -LiteralPath (Join-Path $crashDir "crash.dmp")) {
Write-Output "[boot] private crash diagnostics: $crashDir"
} elseif ($proc.ExitCode -ne 0) {
Write-Warning "No crash dump was saved. See the monitor diagnostics in $LogFile"
}
} elseif (-not $proc.WaitForExit($Seconds * 1000)) {
$stopped = $true
try { Stop-Process -Id $proc.Id -Force -Confirm:$false } catch { }
[void]$proc.WaitForExit(20000)

View File

@ -0,0 +1,204 @@
// Optional out-of-process observer used by boot.ps1 on x64 Windows.
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <dbghelp.h>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cwchar>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <string>
namespace fs = std::filesystem;
namespace {
struct Handle {
HANDLE value;
~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
Handle(const Handle&) = delete;
Handle& operator=(const Handle&) = delete;
explicit Handle(HANDLE handle) : value(handle) {}
};
void report_error(const char* operation, DWORD error = GetLastError()) {
std::fprintf(stderr, "[crash-monitor] %s failed (%lu)\n", operation, error);
}
bool write_dump(const fs::path& dir, HANDLE process, DWORD pid, MINIDUMP_EXCEPTION_INFORMATION* info) {
const auto partial = dir / L"crash.dmp.partial";
{
Handle file(CreateFileW(partial.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr));
if (file.value == INVALID_HANDLE_VALUE) { report_error("create dump"); return false; }
if (!MiniDumpWriteDump(process, pid, file.value, MiniDumpWithThreadInfo, info, nullptr, nullptr)) {
report_error("MiniDumpWriteDump");
return false;
}
}
if (!MoveFileExW(partial.c_str(), (dir / L"crash.dmp").c_str(), MOVEFILE_WRITE_THROUGH)) {
report_error("publish dump");
return false;
}
return true;
}
void write_stack(std::ostream& out, HANDLE process, HANDLE thread, CONTEXT ctx, const fs::path& symbols) {
// Only look beside the runtime. Ignore debugger environment paths and embedded build-machine paths.
SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS |
SYMOPT_IGNORE_NT_SYMPATH | SYMOPT_IGNORE_CVREC | SYMOPT_DISABLE_SYMSRV_AUTODETECT);
const bool loaded = SymInitializeW(process, symbols.c_str(), TRUE) != FALSE;
STACKFRAME64 frame{};
frame.AddrPC = {ctx.Rip, 0, AddrModeFlat};
frame.AddrStack = {ctx.Rsp, 0, AddrModeFlat};
frame.AddrFrame = {ctx.Rbp, 0, AddrModeFlat};
for (unsigned n = 0; n < 64 && frame.AddrPC.Offset; ++n) {
const auto pc = frame.AddrPC.Offset;
const auto sp = frame.AddrStack.Offset;
out << '#' << std::dec << n << " 0x" << std::hex << pc;
IMAGEHLP_MODULE64 module{};
module.SizeOfStruct = sizeof(module);
if (loaded && SymGetModuleInfo64(process, pc, &module))
out << ' ' << module.ModuleName << "+0x" << pc - module.BaseOfImage;
alignas(SYMBOL_INFO) char storage[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]{};
auto* symbol = reinterpret_cast<SYMBOL_INFO*>(storage);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
DWORD64 displacement = 0;
if (loaded && SymFromAddr(process, pc, &displacement, symbol))
out << " (" << symbol->Name << "+0x" << displacement << ')';
out << '\n';
if (!loaded || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
SymFunctionTableAccess64, SymGetModuleBase64, nullptr))
break;
if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) {
// The first StackWalk64 call can describe the initial frame again.
if (n != 0 || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break;
if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) break;
}
}
if (loaded) SymCleanup(process);
}
void capture(const fs::path& dir, const fs::path& symbols, HANDLE process, const DEBUG_EVENT& event) {
const bool exception = event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT;
const DWORD code = exception ? event.u.Exception.ExceptionRecord.ExceptionCode : event.u.ExitProcess.dwExitCode;
Handle thread(OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, event.dwThreadId));
CONTEXT ctx{};
ctx.ContextFlags = CONTEXT_ALL;
const bool got_context = thread.value && GetThreadContext(thread.value, &ctx);
EXCEPTION_RECORD record{};
if (exception) {
record = event.u.Exception.ExceptionRecord;
record.ExceptionRecord = nullptr; // Nested records belong to the child address space.
}
EXCEPTION_POINTERS pointers{&record, &ctx};
MINIDUMP_EXCEPTION_INFORMATION info{event.dwThreadId, &pointers, FALSE};
if (!write_dump(dir, process, event.dwProcessId, exception && got_context ? &info : nullptr))
DeleteFileW((dir / L"crash.dmp.partial").c_str());
std::ofstream stack(dir / L"stack.txt");
stack << "kind=" << (exception ? "unhandled_exception" : "abnormal_exit")
<< "\ncode=0x" << std::hex << std::setw(8) << std::setfill('0') << code
<< "\nthread=" << std::dec << event.dwThreadId << '\n';
if (got_context) write_stack(stack, process, thread.value, ctx, symbols);
else stack << "thread context unavailable at this debug event\n";
stack.close();
if (!stack) report_error("write stack.txt", ERROR_WRITE_FAULT);
}
DWORD monitor(HANDLE process, const fs::path& dir, const fs::path& symbols, ULONGLONG deadline) {
bool initial_break = true;
bool captured = false;
bool stopped = false;
for (;;) {
DEBUG_EVENT event{};
if (!WaitForDebugEventEx(&event, 100)) {
if (GetLastError() != ERROR_SEM_TIMEOUT) { report_error("WaitForDebugEventEx"); return 1; }
} else {
DWORD disposition = DBG_CONTINUE;
const bool exiting = event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT;
if (event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT && event.u.CreateProcessInfo.hFile)
CloseHandle(event.u.CreateProcessInfo.hFile);
if (event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT && event.u.LoadDll.hFile)
CloseHandle(event.u.LoadDll.hFile);
if (event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
const auto& ex = event.u.Exception;
if (initial_break && ex.dwFirstChance && ex.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
initial_break = false; // The loader breakpoint belongs to the debugger.
else {
disposition = DBG_EXCEPTION_NOT_HANDLED;
if (!ex.dwFirstChance && !stopped && !captured) {
capture(dir, symbols, process, event);
captured = true;
}
}
} else if (exiting && event.u.ExitProcess.dwExitCode && !stopped && !captured) {
capture(dir, symbols, process, event);
}
if (!ContinueDebugEvent(event.dwProcessId, event.dwThreadId, disposition)) {
report_error("ContinueDebugEvent");
return 1;
}
if (exiting) {
if (!stopped) return event.u.ExitProcess.dwExitCode;
std::ofstream marker(dir / L"timed-out");
marker.close();
return marker ? 0 : 1;
}
}
if (!captured && !stopped && GetTickCount64() >= deadline) {
if (TerminateProcess(process, ERROR_TIMEOUT)) stopped = true;
else if (GetLastError() != ERROR_ACCESS_DENIED) { report_error("TerminateProcess"); return 1; }
}
}
}
} // namespace
int wmain(int argc, wchar_t** argv) {
if (argc != 6) {
std::fputs("usage: gta6rt_crash_monitor REPO NEW_REPORT_DIR SECONDS RUNTIME CHILD_COMMAND_LINE\n", stderr);
return 2;
}
wchar_t* end = nullptr;
const long seconds = std::wcstol(argv[3], &end, 10);
if (end == argv[3] || *end || errno == ERANGE || seconds < 0) return 2;
try {
const fs::path repo = fs::canonical(argv[1]);
const fs::path dir = fs::weakly_canonical(fs::absolute(argv[2]));
const fs::path runtime = fs::canonical(argv[4]);
// Resolve junctions and compare file identity (Windows path case can differ).
for (auto p = dir.parent_path();; p = p.parent_path()) {
if (fs::equivalent(p, repo)) {
std::fputs("[crash-monitor] private output must be outside the checkout\n", stderr);
return 2;
}
if (p == p.root_path()) break;
}
if (!fs::create_directory(dir)) {
std::fputs("[crash-monitor] report directory already exists\n", stderr);
return 2;
}
STARTUPINFOW startup{};
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESTDHANDLES;
startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
PROCESS_INFORMATION pi{};
std::wstring command(argv[5]);
if (!CreateProcessW(runtime.c_str(), command.data(), nullptr, nullptr, TRUE, DEBUG_ONLY_THIS_PROCESS,
nullptr, nullptr, &startup, &pi)) {
report_error("CreateProcessW");
return 2;
}
Handle process(pi.hProcess);
Handle thread(pi.hThread);
return static_cast<int>(monitor(process.value, dir, runtime.parent_path(), GetTickCount64() + seconds * 1000ULL));
} catch (const fs::filesystem_error& e) {
report_error("resolve private output or runtime", e.code().value());
return 2;
}
}

View File

@ -0,0 +1,133 @@
"""Exercise the native Windows crash monitor with an entirely synthetic child."""
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
import unittest
REPO = Path(__file__).resolve().parents[2]
@unittest.skipUnless(__name__ == "__main__", "run through the windows_crash_monitor CTest target")
class CrashMonitorTest(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix="leonida crash test ")
self.addCleanup(tmp.cleanup)
self.report = Path(tmp.name) / "private run"
def run_fixture(self, mode, *args, seconds=10):
env = dict(os.environ, LEONIDA_TEST_CRASH_MODE=mode)
result = subprocess.run(
[MONITOR, REPO, self.report, str(seconds), FIXTURE,
subprocess.list2cmdline([str(FIXTURE), *args])],
env=env, capture_output=True, timeout=30,
)
return result.returncode & 0xffffffff
def check_artifacts(self, code, exception):
data = (self.report / "crash.dmp").read_bytes()
self.assertEqual(data[:4], b"MDMP")
count, offset = struct.unpack_from("<II", data, 8)
streams = dict((kind, pos) for kind, size, pos in
(struct.unpack_from("<III", data, offset + 12*i) for i in range(count)))
self.assertIn(3, streams) # ThreadListStream
trace = (self.report / "stack.txt").read_text()
self.assertIn(f"code=0x{code:08x}", trace)
if exception:
pos = streams[6] # ExceptionStream: thread ID, padding, exception record
thread_id, _, actual_code = struct.unpack_from("<III", data, pos)
self.assertEqual(actual_code, code)
self.assertIn(f"thread={thread_id}\n", trace)
self.assertIn("kind=unhandled_exception", trace)
self.assertIn("#0 ", trace)
else:
self.assertNotIn(6, streams)
self.assertIn("kind=abnormal_exit", trace)
self.assertFalse((self.report / "crash.dmp.partial").exists())
return trace
def test_worker(self):
code = 0xe0421234
self.assertEqual(self.run_fixture("worker"), code)
trace = self.check_artifacts(code, True)
if FIXTURE.with_suffix(".pdb").exists():
self.assertIn("crash_worker", trace)
def test_breakpoint(self):
self.assertEqual(self.run_fixture("break"), 0x80000003)
self.check_artifacts(0x80000003, True)
def test_explicit_exit(self):
self.assertEqual(self.run_fixture("exit"), 23)
trace = self.check_artifacts(23, False)
self.assertIn("#0 ", trace)
def test_exit_with_exception_number(self):
self.assertEqual(self.run_fixture("numeric"), 0xc0000005)
self.check_artifacts(0xc0000005, False)
def test_handled(self):
self.assertEqual(self.run_fixture("handled"), 0)
self.assertFalse(any(self.report.iterdir()))
def test_arguments_and_clean_exit(self):
self.assertEqual(self.run_fixture("argv", "a b\\", 'a"b'), 0)
self.assertFalse(any(self.report.iterdir()))
def test_timeout(self):
self.assertEqual(self.run_fixture("timer", seconds=1), 0)
self.assertEqual([p.name for p in self.report.iterdir()], ["timed-out"])
def test_existing_directory(self):
self.report.mkdir()
sentinel = self.report / "keep"
sentinel.write_bytes(b"original")
self.assertNotEqual(self.run_fixture("worker"), 0)
self.assertEqual(list(self.report.iterdir()), [sentinel])
self.assertEqual(sentinel.read_text(), "original")
def test_repo_rejected(self):
self.report = REPO / (self.report.parent.name + "-forbidden")
self.assertNotEqual(self.run_fixture("worker"), 0)
self.assertFalse(self.report.exists())
def test_boot_entry_point(self):
root = self.report.parent
(root / "MicrosoftGame.Config").touch()
(root / "index.json").write_bytes(b"{}")
(root / "exe").mkdir()
(root / "exe" / "index.json").write_bytes(b"{}")
(root / "gta6rt_tls_host.dll").touch()
fixture = shutil.copy2(FIXTURE, root)
shutil.copy2(MONITOR, root)
out = root / "output"
script = REPO / "scripts" / "windows-boot" / "boot.ps1"
# Isolate the fixture from a developer's normal boot settings and paths.
env = {k: v for k, v in os.environ.items() if not k.upper().startswith("LEONIDA_")}
for mode, expected in (("exit", 23), ("timer", 0)):
with self.subTest(mode=mode):
result = subprocess.run(
["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script,
"-CrashDump", "-Name", mode, "-Runtime", fixture, "-Exe", fixture, "-GameDir", root,
"-Shaders", root, "-OutDir", out, "-Python", sys.executable, "-Seconds",
"1" if mode == "timer" else "10", "-LockWaitSeconds", "1", "-NoInput", "-NoCapture"],
env=dict(env, LEONIDA_TEST_CRASH_MODE=mode), capture_output=True, timeout=30,
)
self.assertEqual(result.returncode, expected, (result.stdout, result.stderr))
self.assertTrue((out / f"{mode}.digest.txt").is_file())
self.assertIn(b"fixture stdout", (out / f"{mode}.stdout.log").read_bytes())
self.assertIn(b"fixture stderr", (out / f"{mode}.log").read_bytes())
report, = out.glob(f"{mode}-crash-*")
if mode == "exit":
self.assertTrue((report / "crash.dmp").is_file())
else:
self.assertTrue((report / "timed-out").is_file())
self.assertFalse((report / "crash.dmp").exists())
if __name__ == "__main__":
MONITOR, FIXTURE = map(Path, sys.argv[1:3])
unittest.main(argv=sys.argv[:1], verbosity=2)