Rise
The Vieneo Province
Loading...
Searching...
No Matches
Tests/CrashCaptureTests.cpp

Source at documentation-generation time. See Test catalog for fixture associations.

1#include "../CrashReporting/CrashCapture.h"
2#include <DbgHelp.h>
3#include <filesystem>
4#include <fstream>
5#include <iostream>
6#include <vector>
7#include <string>
8#include <memory>
9#include <thread>
10#pragma comment(lib, "dbghelp.lib")
11namespace fs = std::filesystem;
13Capture* capture = nullptr;
14std::wstring expectedPath;
15int failures = 0;
16void* dumpData = nullptr;
17BOOL CALLBACK ReadDumpMemory(HANDLE, DWORD64 address, PVOID buffer, DWORD bytes, LPDWORD read)
18{
19 PMINIDUMP_DIRECTORY directory = nullptr; void* stream = nullptr; ULONG size = 0;
20 *read = 0;
21 if (!MiniDumpReadDumpStream(dumpData, MemoryListStream, &directory, &stream, &size)) return FALSE;
22 auto list = static_cast<MINIDUMP_MEMORY_LIST*>(stream);
23 for (ULONG i = 0; i < list->NumberOfMemoryRanges; ++i) {
24 const auto& region = list->MemoryRanges[i];
25 if (address >= region.StartOfMemoryRange && address - region.StartOfMemoryRange + bytes <= region.Memory.DataSize) {
26 memcpy(buffer, static_cast<char*>(dumpData) + region.Memory.Rva + address - region.StartOfMemoryRange, bytes);
27 *read = bytes; return TRUE;
28 }
29 }
30 return FALSE;
31}
32void Check(bool ok, const char* label) { std::cout << (ok ? "PASS " : "FAIL ") << label << '\n'; if (!ok) ++failures; }
33LONG Filter(EXCEPTION_POINTERS* exception)
34{
35 std::ofstream expected(expectedPath);
36 expected << GetCurrentThreadId() << ' ' << reinterpret_cast<uintptr_t>(exception->ExceptionRecord->ExceptionAddress);
37 expected.close();
38 DWORD result = capture->Record("isolated access violation test", exception->ExceptionRecord->ExceptionCode, exception);
39 TerminateProcess(GetCurrentProcess(), result ? 2 : 77);
40 return EXCEPTION_EXECUTE_HANDLER;
41}
42__declspec(noinline) void Fault() { *reinterpret_cast<volatile int*>(1) = 123; }
43DWORD WINAPI CrashThread(void*) { __try { Fault(); } __except(Filter(GetExceptionInformation())) {} return 0; }
44
45void CheckHelperUpdates(const fs::path& root, const fs::path& source)
46{
47 for (const auto* mode : { L"replace", L"install", L"temporary-lock", L"running-helper" }) {
48 fs::path scenario = root / L"updates" / mode;
49 fs::create_directories(scenario);
50 fs::path helper = scenario / L"CrashHandler.exe", staged = scenario / L"CrashHandler1.exe";
51 std::ofstream(scenario / L"CrashHandler.ini") << "[CrashReporting]\nUploadUrl=\n";
52 std::string trace = (scenario / L"trace_update.log").string();
53 std::ofstream(trace) << "Isolated helper update test; no game connection\n";
54 const bool running = wcscmp(mode, L"running-helper") == 0;
55 const bool temporary = wcscmp(mode, L"temporary-lock") == 0;
56 std::unique_ptr<Capture> previous;
57 if (running) {
58 fs::copy_file(source, helper);
59 previous = std::make_unique<Capture>();
60 Check(previous->Start(trace.c_str(), helper.c_str(), scenario.c_str()) == 0,
61 "start previous helper to reproduce executable lock");
62 } else if (wcscmp(mode, L"install") != 0) {
63 // Startup can only succeed if this invalid old image is replaced first.
64 std::ofstream(helper) << "old helper placeholder";
65 }
66 fs::copy_file(source, staged);
67 HANDLE lock = INVALID_HANDLE_VALUE;
68 std::thread release;
69 if (temporary) {
70 lock = CreateFileW(helper.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
71 Check(lock != INVALID_HANDLE_VALUE, "hold temporary helper replacement lock");
72 if (lock != INVALID_HANDLE_VALUE) release = std::thread([lock] { Sleep(300); CloseHandle(lock); });
73 }
74 {
75 Capture updated;
76 ULONGLONG start = GetTickCount64();
77 DWORD result = updated.Start(trace.c_str(), helper.c_str(), scenario.c_str());
78 const ULONGLONG elapsed = GetTickCount64() - start;
79 if (release.joinable()) release.join();
80 if (running) {
81 Check(result == ERROR_SUCCESS && strcmp(updated.StartupStage(), "ready") == 0,
82 "blocked update still starts the installed helper");
83 Check(updated.UpdateError() == ERROR_ACCESS_DENIED || updated.UpdateError() == ERROR_SHARING_VIOLATION
84 || updated.UpdateError() == ERROR_LOCK_VIOLATION, "deferred update preserves the replacement error");
85 Check(elapsed >= 4900 && elapsed < 8000, "helper replacement retries are bounded");
86 Check(fs::exists(staged) && fs::file_size(staged) == fs::file_size(source)
87 && fs::exists(helper) && fs::file_size(helper) == fs::file_size(source),
88 "failed replacement preserves installed helper and staged update");
89 Check(updated.Record("capture with deferred update", 0xe0000001, nullptr) == ERROR_SUCCESS,
90 "native dump capture works while installed helper replacement is blocked");
91 Check(fs::exists(scenario / (std::wstring(updated.Id()) + L".dmp")),
92 "deferred update fallback saves a complete dump");
93 } else {
94 Check(result == ERROR_SUCCESS, "install staged helper before invoking it");
95 Check(!fs::exists(staged) && fs::file_size(helper) == fs::file_size(source),
96 "successful update consumes staged file and installs complete executable");
97 if (temporary) Check(elapsed >= 250 && elapsed < 8000, "retry succeeds after temporary lock releases");
98 }
99 }
100 if (running) {
101 previous.reset();
102 Capture retried;
103 Check(retried.Start(trace.c_str(), helper.c_str(), scenario.c_str()) == ERROR_SUCCESS,
104 "next startup installs pending update after previous helper exits");
105 Check(!fs::exists(staged), "retried update consumes staged file");
106 }
107 }
108}
109
110int wmain(int argc, wchar_t** argv)
111{
112 if (argc == 8 && wcscmp(argv[1], L"--watch") == 0) {
113 // Stand-in helper that acknowledges startup but never completes capture.
114 HANDLE ready = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(_wcstoui64(argv[4], nullptr, 10)));
115 HANDLE waiting[] = {
116 reinterpret_cast<HANDLE>(static_cast<uintptr_t>(_wcstoui64(argv[6], nullptr, 10))),
117 reinterpret_cast<HANDLE>(static_cast<uintptr_t>(_wcstoui64(argv[7], nullptr, 10))) };
118 SetEvent(ready); WaitForMultipleObjects(2, waiting, FALSE, 40000); return 0;
119 }
120 if (argc == 5 && wcscmp(argv[1], L"--child") == 0) {
121 fs::path root(argv[3]); fs::create_directories(root);
122 std::string trace = (root / L"trace_test.log").string();
123 std::ofstream(trace) << "Isolated crash test; no game connection\n";
124 Capture reporting; capture = &reporting; expectedPath = (root / L"expected.txt").wstring();
125 const bool adjacent = wcscmp(argv[2], L"adjacent") == 0;
126 DWORD started = adjacent ? reporting.Start(trace.c_str()) : reporting.Start(trace.c_str(), argv[4], root.c_str());
127 if (started) return 3;
128 if (wcscmp(argv[2], L"clean") == 0) return 0;
129 if (wcscmp(argv[2], L"fatal") == 0) return reporting.Record("caught C++ reporting site test", 0xe0000001, nullptr) ? 4 : 77;
130 if (wcscmp(argv[2], L"worker") == 0) {
131 HANDLE thread = CreateThread(nullptr, 0, CrashThread, nullptr, 0, nullptr);
132 if (!thread) return 5;
133 WaitForSingleObject(thread, 30000); return 6;
134 }
135 CrashThread(nullptr); return 7;
136 }
137 if (argc != 3) { std::cerr << "Usage: CrashCaptureTests helper.exe test-directory\n"; return 1; }
138 fs::path root = fs::absolute(argv[2]); fs::create_directories(root / L"bin");
139 fs::path helper = root / L"bin" / L"CrashHandler.exe";
140 fs::copy_file(argv[1], helper, fs::copy_options::overwrite_existing);
141 std::ofstream(root / L"bin" / L"CrashHandler.ini") << "[CrashReporting]\nUploadUrl=\n";
142 CheckHelperUpdates(root, fs::absolute(argv[1]));
143 wchar_t self[1024]; GetModuleFileNameW(nullptr, self, 1024);
144 for (auto mode : { L"main", L"worker", L"fatal", L"clean", L"adjacent" }) {
145 fs::path scenario = root / mode;
146 fs::path childExecutable = self, queue = scenario;
147 if (wcscmp(mode, L"adjacent") == 0) {
148 const auto game = scenario / L"game folder";
149 fs::create_directories(game);
150 childExecutable = game / L"CrashCaptureTests.exe";
151 fs::copy_file(self, childExecutable);
152 fs::copy_file(helper, game / L"CrashHandler.exe");
153 fs::copy_file(root / L"bin" / L"CrashHandler.ini", game / L"CrashHandler.ini");
154 queue = game / L"Crashes";
155 }
156 std::wstring command = L"\"" + childExecutable.wstring() + L"\" --child " + mode + L" \"" + scenario.wstring() + L"\" \"" + helper.wstring() + L"\"";
157 STARTUPINFOW startup = {}; startup.cb = sizeof startup; PROCESS_INFORMATION process = {};
158 bool created = CreateProcessW(childExecutable.c_str(), command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, root.c_str(), &startup, &process) != FALSE;
159 Check(created, "create isolated child"); if (!created) continue;
160 DWORD wait = WaitForSingleObject(process.hProcess, 35000), code = 0;
161 if (wait == WAIT_TIMEOUT) TerminateProcess(process.hProcess, 99);
162 GetExitCodeProcess(process.hProcess, &code); CloseHandle(process.hThread); CloseHandle(process.hProcess);
163 bool clean = wcscmp(mode, L"clean") == 0, synthetic = wcscmp(mode, L"fatal") == 0;
164 Check(wait == WAIT_OBJECT_0 && code == (clean ? 0ul : 77ul), "capture completed before child exit");
165 std::vector<fs::path> dumps;
166 if (fs::exists(queue))
167 for (const auto& file : fs::directory_iterator(queue)) if (file.path().extension() == L".dmp") dumps.push_back(file.path());
168 Check(dumps.size() == (clean ? 0u : 1u), "exactly one dump for fault, none for normal exit");
169 if (dumps.empty()) continue;
170 std::ifstream input(dumps[0], std::ios::binary | std::ios::ate);
171 std::vector<char> data(static_cast<size_t>(input.tellg())); input.seekg(0); input.read(data.data(), data.size());
172 Check(data.size() < CrashReporting::MaxDumpBytes, "bounded dump size");
173 PMINIDUMP_DIRECTORY directory = nullptr; void* stream = nullptr; ULONG bytes = 0;
174 bool present = MiniDumpReadDumpStream(data.data(), ExceptionStream, &directory, &stream, &bytes) != FALSE;
175 Check(present && bytes >= sizeof(MINIDUMP_EXCEPTION_STREAM), "exception stream present");
176 if (present) {
177 auto exception = static_cast<MINIDUMP_EXCEPTION_STREAM*>(stream);
178 Check(exception->ExceptionRecord.ExceptionCode == (synthetic ? 0xe0000001ul : EXCEPTION_ACCESS_VIOLATION), "exception code preserved");
179 if (!synthetic) {
180 DWORD tid = 0; uintptr_t address = 0; std::ifstream(scenario / L"expected.txt") >> tid >> address;
181 Check(exception->ThreadId == tid, "faulting thread identity preserved");
182 Check(exception->ExceptionRecord.ExceptionAddress == address, "original instruction address preserved");
183 Check(exception->ExceptionRecord.ExceptionInformation[0] == 1 && exception->ExceptionRecord.ExceptionInformation[1] == 1, "write violation target preserved");
184 auto context = reinterpret_cast<CONTEXT*>(data.data() + exception->ThreadContext.Rva);
185#ifdef _M_X64
186 Check(context->Rip == address, "original x64 register context preserved");
187#else
188 Check(context->Eip == address, "original x86 register context preserved");
189#endif
190 }
191 }
192 Check(MiniDumpReadDumpStream(data.data(), ThreadListStream, &directory, &stream, &bytes)
193 && static_cast<MINIDUMP_THREAD_LIST*>(stream)->NumberOfThreads >= (wcscmp(mode, L"worker") == 0 ? 2ul : 1ul), "thread stacks captured (including multiple threads for worker fault)");
194 bool modules = MiniDumpReadDumpStream(data.data(), ModuleListStream, &directory, &stream, &bytes) != FALSE;
195 Check(modules, "module stream present");
196 bool pdb = false;
197 if (modules) { auto list = static_cast<MINIDUMP_MODULE_LIST*>(stream);
198 for (ULONG i = 0; i < list->NumberOfModules; ++i) { auto cv = list->Modules[i].CvRecord;
199 if (cv.DataSize >= 24 && memcmp(data.data() + cv.Rva, "RSDS", 4) == 0) pdb = true;
200 }
201 }
202 Check(pdb, "PDB GUID and age captured for later symbol lookup");
203 if (!synthetic && modules) {
204 auto list = static_cast<MINIDUMP_MODULE_LIST*>(stream);
205 HANDLE symbols = GetCurrentProcess();
206 SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS);
207 SymInitialize(symbols, fs::path(self).parent_path().string().c_str(), FALSE);
208 for (ULONG i = 0; i < list->NumberOfModules; ++i) {
209 auto& module = list->Modules[i];
210 auto name = reinterpret_cast<MINIDUMP_STRING*>(data.data() + module.ModuleNameRva);
211 if (wcsstr(name->Buffer, L"CrashCaptureTests.exe"))
212 SymLoadModuleEx(symbols, nullptr, fs::path(self).string().c_str(), nullptr, module.BaseOfImage, module.SizeOfImage, nullptr, 0);
213 }
214 MiniDumpReadDumpStream(data.data(), ExceptionStream, &directory, &stream, &bytes);
215 auto exception = static_cast<MINIDUMP_EXCEPTION_STREAM*>(stream);
216 CONTEXT context = *reinterpret_cast<CONTEXT*>(data.data() + exception->ThreadContext.Rva);
217 STACKFRAME64 frame = {};
218#ifdef _M_X64
219 const DWORD machine = IMAGE_FILE_MACHINE_AMD64;
220 frame.AddrPC.Offset = context.Rip; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp;
221#else
222 const DWORD machine = IMAGE_FILE_MACHINE_I386;
223 frame.AddrPC.Offset = context.Eip; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp;
224#endif
225 frame.AddrPC.Mode = frame.AddrFrame.Mode = frame.AddrStack.Mode = AddrModeFlat;
226 dumpData = data.data(); bool faultName = false, callerName = false, sourceLine = false;
227 for (unsigned n = 0; n < 16; ++n) {
228 alignas(SYMBOL_INFO) char storage[sizeof(SYMBOL_INFO) + 256] = {};
229 auto symbol = reinterpret_cast<SYMBOL_INFO*>(storage); symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = 256;
230 DWORD64 displacement = 0;
231 if (SymFromAddr(symbols, frame.AddrPC.Offset, &displacement, symbol)) {
232 std::cout << " native frame: " << symbol->Name << '\n';
233 faultName |= strcmp(symbol->Name, "Fault") == 0;
234 callerName |= strcmp(symbol->Name, "CrashThread") == 0;
235 }
236 IMAGEHLP_LINE64 line = {}; line.SizeOfStruct = sizeof line; DWORD delta = 0;
237 if (SymGetLineFromAddr64(symbols, frame.AddrPC.Offset, &delta, &line)) sourceLine |= line.LineNumber > 0;
238 if (!StackWalk64(machine, symbols, nullptr, &frame, &context, ReadDumpMemory, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) break;
239 }
240 Check(faultName && callerName, "true saved stack unwinds to Fault and its caller using matching PDB");
241 Check(sourceLine, "saved stack resolves source line numbers");
242 SymCleanup(symbols); dumpData = nullptr;
243 }
244 Check(MiniDumpReadDumpStream(data.data(), CommentStreamW, &directory, &stream, &bytes)
245 && wcsstr(static_cast<wchar_t*>(stream), synthetic ? L"fatal reporting site" : L"original Windows exception"), "context provenance recorded honestly");
246 }
247 Capture missing;
248 auto absent = (root / L"does-not-exist.exe").wstring();
249 Check(missing.Start("trace_missing.log", absent.c_str(), root.c_str()) != 0, "missing helper detected without blocking launch");
250 Check(strcmp(missing.StartupStage(), "CreateProcessW(helper)") == 0 && missing.HelperPath() == absent,
251 "missing helper diagnostic identifies the failed operation and exact path");
252 ULONGLONG start = GetTickCount64();
253 Check(missing.Record("missing helper", 1, nullptr) != 0 && GetTickCount64() - start < 1000, "missing helper preserves quick fatal fallback");
254 const auto blockedQueue = root / L"not-a-directory";
255 std::ofstream(blockedQueue) << "queue path collision";
256 Capture invalidQueue;
257 Check(invalidQueue.Start("trace_bad_queue.log", helper.c_str(), blockedQueue.c_str()) == ERROR_DIRECTORY
258 && strcmp(invalidQueue.StartupStage(), "CreateDirectoryW(crash queue)") == 0
259 && fs::path(invalidQueue.Directory()) == blockedQueue,
260 "queue path failure is distinguished from helper launch failure");
261 Capture stalled;
262 Check(stalled.Start("trace_stalled.log", self, root.c_str()) == 0, "start stalled-helper fixture");
263 start = GetTickCount64();
264 Check(stalled.Record("stalled helper", 1, nullptr) == WAIT_TIMEOUT
265 && GetTickCount64() - start >= 19000 && GetTickCount64() - start < 30000, "stalled helper cannot block crash thread beyond capture timeout");
266 return failures ? 1 : 0;
267}
SCRIPT_CONTROL SCRIPT_STATE const void SCRIPT_CONTROL SCRIPT_STATE const int SCRIPT_TABDEF const BYTE SCRIPT_STRING_ANALYSIS BOOL
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
constexpr unsigned long long MaxDumpBytes
Definition CrashShared.h:8
double Capture(double horizontal, double vertical)
Definition FlightPath.h:13