Rise
The Vieneo Province
Loading...
Searching...
No Matches
CrashHandler.cpp
Go to the documentation of this file.
1#include "CrashShared.h"
2#include "CrashUpload.h"
3#include <DbgHelp.h>
4#include <shellapi.h>
5#include <filesystem>
6#include <fstream>
7#include <thread>
8#include <cstdio>
9
10namespace fs = std::filesystem;
11using namespace CrashReporting;
12
13namespace
14{
15 DWORD WriteDump(HANDLE process, Shared& request)
16 {
17 if (!HasCaptureSpace(request.directory)) return ERROR_DISK_FULL;
18 auto base = fs::path(request.directory) / request.id;
19 auto temporary = base.wstring() + L".part";
20 HANDLE file = CreateFileW(temporary.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);
21 if (file == INVALID_HANDLE_VALUE) return GetLastError();
22 // Always load Microsoft's system copy, not a DLL found in the game folder.
23 HMODULE dbghelp = LoadLibraryExW(L"dbghelp.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
24 auto write = dbghelp ? reinterpret_cast<decltype(&MiniDumpWriteDump)>(GetProcAddress(dbghelp, "MiniDumpWriteDump")) : nullptr;
25 DWORD error = ERROR_PROC_NOT_FOUND;
26 if (write) {
27 EXCEPTION_POINTERS pointers = { &request.exception, &request.context };
28 MINIDUMP_EXCEPTION_INFORMATION exception = { request.threadId, &pointers, FALSE };
29 wchar_t comment[2048];
30 swprintf_s(comment, L"Rise crash %s\nTrace: %s\nContext: %s\nReason: %hs\n", request.id, request.trace,
31 request.syntheticContext ? L"fatal reporting site (original C++ throw stack is not available)" : L"original Windows exception", request.reason);
32 MINIDUMP_USER_STREAM stream = { CommentStreamW, static_cast<ULONG>((wcslen(comment) + 1) * sizeof(wchar_t)), comment };
33 MINIDUMP_USER_STREAM_INFORMATION streams = { 1, &stream };
34 // Includes all thread stacks, loaded modules and matching PDB identities.
35 // FullMemoryInfo describes address regions; it does not copy the heap.
36 auto flags = static_cast<MINIDUMP_TYPE>(MiniDumpNormal | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithFullMemoryInfo);
37 error = write(process, request.processId, file, flags, &exception, &streams, nullptr) ? ERROR_SUCCESS : GetLastError();
38 }
39 LARGE_INTEGER bytes = {};
40 if (!error && (!GetFileSizeEx(file, &bytes) || bytes.QuadPart < 32 || bytes.QuadPart > MaxDumpBytes)) error = ERROR_FILE_TOO_LARGE;
41 if (!error && !FlushFileBuffers(file)) error = GetLastError();
42 CloseHandle(file);
43 if (dbghelp) FreeLibrary(dbghelp);
44 if (!error) {
45 // Metadata is complete before .dmp makes this record visible to uploaders.
46 std::ofstream metadata(base.wstring() + L".meta", std::ios::trunc);
47 metadata << fs::path(request.trace).filename().string() << '\n'
48 << "Process: " << request.processId << " Thread: " << request.threadId << '\n'
49 << "Exception: 0x" << std::hex << request.exception.ExceptionCode << '\n'
50 << "Context: " << (request.syntheticContext ? "fatal reporting site" : "original Windows exception") << '\n'
51 << "Reason: " << request.reason << '\n';
52 metadata.close();
53 if (!metadata) error = ERROR_WRITE_FAULT;
54 else if (!MoveFileExW(temporary.c_str(), (base.wstring() + L".dmp").c_str(), MOVEFILE_WRITE_THROUGH)) error = GetLastError();
55 }
56 if (error) DeleteFileW(temporary.c_str());
57 return error;
58 }
59
60 void CopyTrace(const Shared& request)
61 {
62 // Read only the last 8 MiB; traces can be huge. The normal trace uploader
63 // remains responsible for the complete text and existing email report.
64 std::ifstream input(fs::path(request.trace), std::ios::binary | std::ios::ate);
65 if (!input) return;
66 auto size = input.tellg();
67 input.seekg(size > 8 * 1024 * 1024 ? size - std::streamoff(8 * 1024 * 1024) : std::streamoff(0));
68 std::ofstream output((fs::path(request.directory) / request.id).wstring() + L".trace.txt", std::ios::binary);
69 output << input.rdbuf();
70 }
71}
72
73int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
74{
75 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
76 int count = 0;
77 wchar_t** args = CommandLineToArgvW(GetCommandLineW(), &count);
78 if (!args) return ERROR_INVALID_PARAMETER;
79 // Explicit CLI for isolated transport tests/manual retry. Not a game session.
80 if (count == 4 && (wcscmp(args[1], L"--upload") == 0 || wcscmp(args[1], L"--retry") == 0)) {
81 int result = 0;
82 try { UploadPending(args[2], args[3], wcscmp(args[1], L"--upload") == 0); } catch (...) { result = ERROR_UNHANDLED_EXCEPTION; }
83 LocalFree(args); return result;
84 }
85 if (count != 8 || wcscmp(args[1], L"--watch") != 0) { LocalFree(args); return ERROR_INVALID_PARAMETER; }
86 HANDLE handles[6];
87 for (unsigned i = 0; i < 6; ++i) handles[i] = reinterpret_cast<HANDLE>(static_cast<uintptr_t>(_wcstoui64(args[i + 2], nullptr, 10)));
88 LocalFree(args);
89 auto shared = static_cast<Shared*>(MapViewOfFile(handles[0], FILE_MAP_ALL_ACCESS, 0, 0, sizeof(Shared)));
90 if (!shared) return GetLastError();
91 if (shared->version != Protocol || shared->bytes != sizeof(Shared) || shared->processId != GetProcessId(handles[5])
92 || !wmemchr(shared->directory, 0, 1024) || !wmemchr(shared->trace, 0, 1024) || !wmemchr(shared->id, 0, 40)) return ERROR_INVALID_DATA;
93 // Snapshot healthy startup configuration before the game can damage it.
94 std::wstring directory(shared->directory), endpoint;
95 Shared request = *shared;
96 try { endpoint = UploadEndpoint(); } catch (...) { /* Capture remains available. */ }
97 SetEvent(handles[2]);
98 std::thread retry;
99 try {
100 retry = std::thread([directory, endpoint] {
101 try { MaintainQueue(directory); UploadPending(directory, endpoint); } catch (...) { /* Retain local files. */ }
102 });
103 } catch (...) { /* No worker resources: prioritize capture. */ }
104 HANDLE waiting[] = { handles[1], handles[4], handles[5] };
105 DWORD event = WaitForMultipleObjects(3, waiting, FALSE, INFINITE);
106 if (event == WAIT_OBJECT_0) {
107 // Paths, UUID and PID came from healthy startup; only fault data crosses
108 // the boundary now. Never trust a damaged process to choose output paths.
109 request.threadId = shared->threadId;
110 request.syntheticContext = shared->syntheticContext;
111 request.exception = shared->exception;
112 request.exception.ExceptionRecord = nullptr;
113 request.context = shared->context;
114 memcpy(request.reason, shared->reason, sizeof request.reason);
115 request.reason[sizeof request.reason - 1] = 0;
116 DWORD result = ERROR_UNHANDLED_EXCEPTION;
117 try { result = WriteDump(handles[5], request); } catch (...) { /* Always release the client. */ }
118 shared->result = result;
119 MemoryBarrier();
120 SetEvent(handles[3]); // Client may terminate now; upload does not delay it.
121 WaitForSingleObject(handles[5], 2000);
122 if (!result) { try { CopyTrace(request); } catch (...) {} }
123 }
124 if (retry.joinable()) retry.join();
125 if (event == WAIT_OBJECT_0) {
126 try { UploadPending(directory, endpoint); } catch (...) {}
127 }
128 UnmapViewOfFile(shared);
129 for (HANDLE handle : handles) CloseHandle(handle);
130 return 0;
131}
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int)
std::wstring UploadEndpoint()
constexpr DWORD Protocol
Definition CrashShared.h:6
constexpr unsigned long long MaxDumpBytes
Definition CrashShared.h:8
void UploadPending(const std::wstring &directory, const std::wstring &endpoint, bool forceRetry)
void MaintainQueue(const std::wstring &directory)
bool HasCaptureSpace(const std::wstring &directory)
wchar_t directory[1024]
Definition CrashShared.h:18
wchar_t trace[1024]
Definition CrashShared.h:19
EXCEPTION_RECORD exception
Definition CrashShared.h:22