upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/windows-boot/crash_monitor.cpp
diff options
context:
space:
mode:
authorsodove <mixercraft@gmail.com>2026-11-25 13:22:52 +0500
committersodove <mixercraft@gmail.com>2026-11-25 13:22:52 +0500
commit1b9e4969a5dc1aefd9823167d52e4325f3f9b0ac (patch)
tree7b6b7d3bd8e40022527b56256317d56eaa556091 /scripts/windows-boot/crash_monitor.cpp
parent3f81d46ac01021bd7517f0cce153f4283bc8dd17 (diff)
windows-boot: capture private minidumps and stacks on abnormal exit
Diffstat (limited to 'scripts/windows-boot/crash_monitor.cpp')
-rw-r--r--scripts/windows-boot/crash_monitor.cpp204
1 files changed, 204 insertions, 0 deletions
diff --git a/scripts/windows-boot/crash_monitor.cpp b/scripts/windows-boot/crash_monitor.cpp
new file mode 100644
index 000000000..7cabf38ee
--- /dev/null
+++ b/scripts/windows-boot/crash_monitor.cpp
@@ -0,0 +1,204 @@
1// Optional out-of-process observer used by boot.ps1 on x64 Windows.
2#define WIN32_LEAN_AND_MEAN
3#define NOMINMAX
4#include <windows.h>
5#include <dbghelp.h>
6#include <cerrno>
7#include <cstdio>
8#include <cstdlib>
9#include <cwchar>
10#include <filesystem>
11#include <fstream>
12#include <iomanip>
13#include <string>
14
15namespace fs = std::filesystem;
16
17namespace {
18struct Handle {
19 HANDLE value;
20 ~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
21 Handle(const Handle&) = delete;
22 Handle& operator=(const Handle&) = delete;
23 explicit Handle(HANDLE handle) : value(handle) {}
24};
25
26void report_error(const char* operation, DWORD error = GetLastError()) {
27 std::fprintf(stderr, "[crash-monitor] %s failed (%lu)\n", operation, error);
28}
29
30bool write_dump(const fs::path& dir, HANDLE process, DWORD pid, MINIDUMP_EXCEPTION_INFORMATION* info) {
31 const auto partial = dir / L"crash.dmp.partial";
32 {
33 Handle file(CreateFileW(partial.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr));
34 if (file.value == INVALID_HANDLE_VALUE) { report_error("create dump"); return false; }
35 if (!MiniDumpWriteDump(process, pid, file.value, MiniDumpWithThreadInfo, info, nullptr, nullptr)) {
36 report_error("MiniDumpWriteDump");
37 return false;
38 }
39 }
40 if (!MoveFileExW(partial.c_str(), (dir / L"crash.dmp").c_str(), MOVEFILE_WRITE_THROUGH)) {
41 report_error("publish dump");
42 return false;
43 }
44 return true;
45}
46
47void write_stack(std::ostream& out, HANDLE process, HANDLE thread, CONTEXT ctx, const fs::path& symbols) {
48 // Only look beside the runtime. Ignore debugger environment paths and embedded build-machine paths.
49 SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS |
50 SYMOPT_IGNORE_NT_SYMPATH | SYMOPT_IGNORE_CVREC | SYMOPT_DISABLE_SYMSRV_AUTODETECT);
51 const bool loaded = SymInitializeW(process, symbols.c_str(), TRUE) != FALSE;
52 STACKFRAME64 frame{};
53 frame.AddrPC = {ctx.Rip, 0, AddrModeFlat};
54 frame.AddrStack = {ctx.Rsp, 0, AddrModeFlat};
55 frame.AddrFrame = {ctx.Rbp, 0, AddrModeFlat};
56 for (unsigned n = 0; n < 64 && frame.AddrPC.Offset; ++n) {
57 const auto pc = frame.AddrPC.Offset;
58 const auto sp = frame.AddrStack.Offset;
59 out << '#' << std::dec << n << " 0x" << std::hex << pc;
60 IMAGEHLP_MODULE64 module{};
61 module.SizeOfStruct = sizeof(module);
62 if (loaded && SymGetModuleInfo64(process, pc, &module))
63 out << ' ' << module.ModuleName << "+0x" << pc - module.BaseOfImage;
64 alignas(SYMBOL_INFO) char storage[sizeof(SYMBOL_INFO) + MAX_SYM_NAME]{};
65 auto* symbol = reinterpret_cast<SYMBOL_INFO*>(storage);
66 symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
67 symbol->MaxNameLen = MAX_SYM_NAME;
68 DWORD64 displacement = 0;
69 if (loaded && SymFromAddr(process, pc, &displacement, symbol))
70 out << " (" << symbol->Name << "+0x" << displacement << ')';
71 out << '\n';
72 if (!loaded || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
73 SymFunctionTableAccess64, SymGetModuleBase64, nullptr))
74 break;
75 if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) {
76 // The first StackWalk64 call can describe the initial frame again.
77 if (n != 0 || !StackWalk64(IMAGE_FILE_MACHINE_AMD64, process, thread, &frame, &ctx, nullptr,
78 SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break;
79 if (frame.AddrPC.Offset == pc && frame.AddrStack.Offset == sp) break;
80 }
81 }
82 if (loaded) SymCleanup(process);
83}
84
85void capture(const fs::path& dir, const fs::path& symbols, HANDLE process, const DEBUG_EVENT& event) {
86 const bool exception = event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT;
87 const DWORD code = exception ? event.u.Exception.ExceptionRecord.ExceptionCode : event.u.ExitProcess.dwExitCode;
88 Handle thread(OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT, FALSE, event.dwThreadId));
89 CONTEXT ctx{};
90 ctx.ContextFlags = CONTEXT_ALL;
91 const bool got_context = thread.value && GetThreadContext(thread.value, &ctx);
92 EXCEPTION_RECORD record{};
93 if (exception) {
94 record = event.u.Exception.ExceptionRecord;
95 record.ExceptionRecord = nullptr; // Nested records belong to the child address space.
96 }
97 EXCEPTION_POINTERS pointers{&record, &ctx};
98 MINIDUMP_EXCEPTION_INFORMATION info{event.dwThreadId, &pointers, FALSE};
99 if (!write_dump(dir, process, event.dwProcessId, exception && got_context ? &info : nullptr))
100 DeleteFileW((dir / L"crash.dmp.partial").c_str());
101
102 std::ofstream stack(dir / L"stack.txt");
103 stack << "kind=" << (exception ? "unhandled_exception" : "abnormal_exit")
104 << "\ncode=0x" << std::hex << std::setw(8) << std::setfill('0') << code
105 << "\nthread=" << std::dec << event.dwThreadId << '\n';
106 if (got_context) write_stack(stack, process, thread.value, ctx, symbols);
107 else stack << "thread context unavailable at this debug event\n";
108 stack.close();
109 if (!stack) report_error("write stack.txt", ERROR_WRITE_FAULT);
110}
111
112DWORD monitor(HANDLE process, const fs::path& dir, const fs::path& symbols, ULONGLONG deadline) {
113 bool initial_break = true;
114 bool captured = false;
115 bool stopped = false;
116 for (;;) {
117 DEBUG_EVENT event{};
118 if (!WaitForDebugEventEx(&event, 100)) {
119 if (GetLastError() != ERROR_SEM_TIMEOUT) { report_error("WaitForDebugEventEx"); return 1; }
120 } else {
121 DWORD disposition = DBG_CONTINUE;
122 const bool exiting = event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT;
123 if (event.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT && event.u.CreateProcessInfo.hFile)
124 CloseHandle(event.u.CreateProcessInfo.hFile);
125 if (event.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT && event.u.LoadDll.hFile)
126 CloseHandle(event.u.LoadDll.hFile);
127 if (event.dwDebugEventCode == EXCEPTION_DEBUG_EVENT) {
128 const auto& ex = event.u.Exception;
129 if (initial_break && ex.dwFirstChance && ex.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT)
130 initial_break = false; // The loader breakpoint belongs to the debugger.
131 else {
132 disposition = DBG_EXCEPTION_NOT_HANDLED;
133 if (!ex.dwFirstChance && !stopped && !captured) {
134 capture(dir, symbols, process, event);
135 captured = true;
136 }
137 }
138 } else if (exiting && event.u.ExitProcess.dwExitCode && !stopped && !captured) {
139 capture(dir, symbols, process, event);
140 }
141 if (!ContinueDebugEvent(event.dwProcessId, event.dwThreadId, disposition)) {
142 report_error("ContinueDebugEvent");
143 return 1;
144 }
145 if (exiting) {
146 if (!stopped) return event.u.ExitProcess.dwExitCode;
147 std::ofstream marker(dir / L"timed-out");
148 marker.close();
149 return marker ? 0 : 1;
150 }
151 }
152 if (!captured && !stopped && GetTickCount64() >= deadline) {
153 if (TerminateProcess(process, ERROR_TIMEOUT)) stopped = true;
154 else if (GetLastError() != ERROR_ACCESS_DENIED) { report_error("TerminateProcess"); return 1; }
155 }
156 }
157}
158} // namespace
159
160int wmain(int argc, wchar_t** argv) {
161 if (argc != 6) {
162 std::fputs("usage: gta6rt_crash_monitor REPO NEW_REPORT_DIR SECONDS RUNTIME CHILD_COMMAND_LINE\n", stderr);
163 return 2;
164 }
165 wchar_t* end = nullptr;
166 const long seconds = std::wcstol(argv[3], &end, 10);
167 if (end == argv[3] || *end || errno == ERANGE || seconds < 0) return 2;
168 try {
169 const fs::path repo = fs::canonical(argv[1]);
170 const fs::path dir = fs::weakly_canonical(fs::absolute(argv[2]));
171 const fs::path runtime = fs::canonical(argv[4]);
172 // Resolve junctions and compare file identity (Windows path case can differ).
173 for (auto p = dir.parent_path();; p = p.parent_path()) {
174 if (fs::equivalent(p, repo)) {
175 std::fputs("[crash-monitor] private output must be outside the checkout\n", stderr);
176 return 2;
177 }
178 if (p == p.root_path()) break;
179 }
180 if (!fs::create_directory(dir)) {
181 std::fputs("[crash-monitor] report directory already exists\n", stderr);
182 return 2;
183 }
184 STARTUPINFOW startup{};
185 startup.cb = sizeof(startup);
186 startup.dwFlags = STARTF_USESTDHANDLES;
187 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
188 startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
189 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
190 PROCESS_INFORMATION pi{};
191 std::wstring command(argv[5]);
192 if (!CreateProcessW(runtime.c_str(), command.data(), nullptr, nullptr, TRUE, DEBUG_ONLY_THIS_PROCESS,
193 nullptr, nullptr, &startup, &pi)) {
194 report_error("CreateProcessW");
195 return 2;
196 }
197 Handle process(pi.hProcess);
198 Handle thread(pi.hThread);
199 return static_cast<int>(monitor(process.value, dir, runtime.parent_path(), GetTickCount64() + seconds * 1000ULL));
200 } catch (const fs::filesystem_error& e) {
201 report_error("resolve private output or runtime", e.code().value());
202 return 2;
203 }
204}