Rise
The Vieneo Province
Loading...
Searching...
No Matches
CrashCapture.cpp
Go to the documentation of this file.
1#include "CrashCapture.h"
2#include <objbase.h>
3#include <cstdio>
4#include <cwchar>
5#include <cstring>
6#include <initializer_list>
7#pragma comment(lib, "ole32.lib")
8
10{
11 namespace
12 {
13 DWORD InstallStagedHelper(const wchar_t* helperPath) noexcept
14 {
15 wchar_t staged[1024];
16 if (wcscpy_s(staged, helperPath)) return ERROR_BUFFER_OVERFLOW;
17 wchar_t* name = wcsrchr(staged, L'\\');
18 name = name ? name + 1 : staged;
19 // Test fixtures may supply a different executable as the helper.
20 if (_wcsicmp(name, L"CrashHandler.exe") != 0) return ERROR_SUCCESS;
21 if (wcscpy_s(name, _countof(staged) - (name - staged), L"CrashHandler1.exe"))
22 return ERROR_BUFFER_OVERFLOW;
23 DWORD attributes = GetFileAttributesW(staged);
24 if (attributes == INVALID_FILE_ATTRIBUTES) {
25 DWORD error = GetLastError();
26 return error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND ? ERROR_SUCCESS : error;
27 }
28 if (attributes & FILE_ATTRIBUTE_DIRECTORY) return ERROR_DIRECTORY;
29
30 // A previous session's helper may still be finishing uploads. Never
31 // delete the installed helper first: a failed move must retain both
32 // the working executable and the pending update for the next launch.
33 const ULONGLONG deadline = GetTickCount64() + 5000;
34 for (;;) {
35 if (MoveFileExW(staged, helperPath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
36 return ERROR_SUCCESS;
37 DWORD error = GetLastError();
38 if ((error != ERROR_ACCESS_DENIED && error != ERROR_SHARING_VIOLATION && error != ERROR_LOCK_VIOLATION)
39 || GetTickCount64() >= deadline) return error;
40 Sleep(100);
41 }
42 }
43 }
44
46 {
47 if (stop_) SetEvent(stop_);
48 if (shared_) UnmapViewOfFile(shared_);
49 for (HANDLE handle : { mapping_, request_, ready_, done_, stop_, helper_ })
50 if (handle) CloseHandle(handle);
51 }
52
53 DWORD Capture::Start(const char* trace, const wchar_t* helper, const wchar_t* directory) noexcept
54 {
55 SECURITY_ATTRIBUTES inherit = { sizeof inherit, nullptr, TRUE };
56 startupStage_ = "CreateFileMappingW";
57 mapping_ = CreateFileMappingW(INVALID_HANDLE_VALUE, &inherit, PAGE_READWRITE, 0, sizeof(Shared), nullptr);
58 if (!mapping_) return GetLastError();
59 startupStage_ = "MapViewOfFile";
60 shared_ = static_cast<Shared*>(MapViewOfFile(mapping_, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(Shared)));
61 if (!shared_) return GetLastError();
62 shared_->version = Protocol;
63 shared_->bytes = sizeof(Shared);
64 shared_->processId = GetCurrentProcessId();
65 shared_->result = ERROR_IO_PENDING;
66 GUID id;
67 startupStage_ = "CoCreateGuid";
68 if (FAILED(CoCreateGuid(&id))) return ERROR_GEN_FAILURE;
69 wchar_t guid[40];
70 StringFromGUID2(id, guid, 40);
71 // Canonical lowercase UUID, without braces; also the server idempotency key.
72 wcsncpy_s(shared_->id, guid + 1, 36);
73 CharLowerBuffW(shared_->id, 36);
74 startupStage_ = "resolve executable directory";
75 wchar_t executableDirectory[1024];
76 DWORD n = GetModuleFileNameW(nullptr, executableDirectory, _countof(executableDirectory));
77 if (!n) return GetLastError();
78 if (n >= _countof(executableDirectory)) return ERROR_BUFFER_OVERFLOW;
79 wchar_t* slash = wcsrchr(executableDirectory, L'\\');
80 if (!slash) return ERROR_PATH_NOT_FOUND;
81 slash[1] = 0;
82 startupStage_ = "resolve helper path";
83 if (helper) {
84 if (wcsncpy_s(helperPath_, helper, _TRUNCATE)) return ERROR_BUFFER_OVERFLOW;
85 } else {
86 if (wcscpy_s(helperPath_, executableDirectory) || wcscat_s(helperPath_, L"CrashHandler.exe"))
87 return ERROR_BUFFER_OVERFLOW;
88 }
89 startupStage_ = "resolve crash directory";
90 if (directory) {
91 if (wcsncpy_s(shared_->directory, directory, _TRUNCATE)) return ERROR_BUFFER_OVERFLOW;
92 } else {
93 // Keep diagnostics beside the installed game, independent of its CWD.
94 if (wcscpy_s(shared_->directory, executableDirectory) || wcscat_s(shared_->directory, L"Crashes"))
95 return ERROR_BUFFER_OVERFLOW;
96 }
97 startupStage_ = "CreateDirectoryW(crash queue)";
98 if (!CreateDirectoryW(shared_->directory, nullptr) && GetLastError() != ERROR_ALREADY_EXISTS)
99 return GetLastError();
100 DWORD directoryAttributes = GetFileAttributesW(shared_->directory);
101 if (directoryAttributes == INVALID_FILE_ATTRIBUTES) return GetLastError();
102 if (!(directoryAttributes & FILE_ATTRIBUTE_DIRECTORY)) return ERROR_DIRECTORY;
103 startupStage_ = "resolve trace path";
104 wchar_t relative[1024];
105 if (!MultiByteToWideChar(CP_ACP, 0, trace, -1, relative, 1024)) return GetLastError();
106 DWORD pathLength = GetFullPathNameW(relative, 1024, shared_->trace, nullptr);
107 if (!pathLength || pathLength >= 1024) return ERROR_BUFFER_OVERFLOW;
108
109 // Apply the autopatcher's staged update before this process locks the
110 // helper image. If replacement is blocked, preserve the pending update
111 // and start the installed helper; its protocol handshake still must pass.
112 updateError_ = InstallStagedHelper(helperPath_);
113 startupStage_ = "CreateEventW(request)";
114 request_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
115 if (!request_) return GetLastError();
116 startupStage_ = "CreateEventW(ready)";
117 ready_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
118 if (!ready_) return GetLastError();
119 startupStage_ = "CreateEventW(done)";
120 done_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
121 if (!done_) return GetLastError();
122 startupStage_ = "CreateEventW(stop)";
123 stop_ = CreateEventW(&inherit, TRUE, FALSE, nullptr);
124 if (!stop_) return GetLastError();
125 startupStage_ = "OpenProcess(client)";
126 HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE, TRUE, GetCurrentProcessId());
127 if (!process) return GetLastError();
128 HANDLE handles[] = { mapping_, request_, ready_, done_, stop_, process };
129 SIZE_T size = 0;
130 InitializeProcThreadAttributeList(nullptr, 1, 0, &size);
131 startupStage_ = "HeapAlloc(startup attributes)";
132 auto attributes = static_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(HeapAlloc(GetProcessHeap(), 0, size));
133 DWORD error = ERROR_NOT_ENOUGH_MEMORY;
134 if (attributes) {
135 startupStage_ = "InitializeProcThreadAttributeList";
136 if (InitializeProcThreadAttributeList(attributes, 1, 0, &size)) {
137 startupStage_ = "UpdateProcThreadAttribute(handle list)";
138 if (UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, sizeof handles, nullptr, nullptr)) {
139 wchar_t command[1600];
140 swprintf_s(command, L"\"%s\" --watch %llu %llu %llu %llu %llu %llu", helperPath_,
141 (unsigned long long)(uintptr_t)mapping_, (unsigned long long)(uintptr_t)request_,
142 (unsigned long long)(uintptr_t)ready_, (unsigned long long)(uintptr_t)done_,
143 (unsigned long long)(uintptr_t)stop_, (unsigned long long)(uintptr_t)process);
144 STARTUPINFOEXW startup = {};
145 startup.StartupInfo.cb = sizeof startup;
146 startup.StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
147 startup.StartupInfo.wShowWindow = SW_HIDE;
148 startup.lpAttributeList = attributes;
149 PROCESS_INFORMATION child = {};
150 startupStage_ = "CreateProcessW(helper)";
151 if (CreateProcessW(helperPath_, command, nullptr, nullptr, TRUE,
152 EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW, nullptr, nullptr, &startup.StartupInfo, &child)) {
153 helper_ = child.hProcess;
154 CloseHandle(child.hThread);
155 HANDLE waiting[] = { ready_, helper_ };
156 startupStage_ = "wait for helper readiness";
157 DWORD result = WaitForMultipleObjects(2, waiting, FALSE, 5000);
158 error = result == WAIT_OBJECT_0 ? ERROR_SUCCESS : (result == WAIT_TIMEOUT ? WAIT_TIMEOUT :
159 (result == WAIT_FAILED ? GetLastError() : ERROR_PROCESS_ABORTED));
160 } else error = GetLastError();
161 } else error = GetLastError();
162 DeleteProcThreadAttributeList(attributes);
163 } else error = GetLastError();
164 }
165 if (attributes) HeapFree(GetProcessHeap(), 0, attributes);
166 // Inheritable handles must not leak into subsequently launched children.
167 for (HANDLE handle : handles) SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0);
168 CloseHandle(process);
169 if (!error) startupStage_ = "ready";
170 return error;
171 }
172
173 DWORD Capture::Record(const char* reason, DWORD code, EXCEPTION_POINTERS* exception) noexcept
174 {
175 if (!helper_ || !shared_ || WaitForSingleObject(helper_, 0) != WAIT_TIMEOUT) return ERROR_PROCESS_ABORTED;
176 if (InterlockedCompareExchange(&requested_, 1, 0)) return ERROR_ALREADY_EXISTS;
177 shared_->threadId = GetCurrentThreadId();
178 if (exception && exception->ExceptionRecord && exception->ContextRecord) {
179 shared_->exception = *exception->ExceptionRecord;
180 shared_->context = *exception->ContextRecord;
181 } else {
182 // A caught C++ exception has already unwound. This captures the fatal
183 // reporting site, never claims to recover its original throw stack.
184 shared_->syntheticContext = 1;
185 RtlCaptureContext(&shared_->context);
186 shared_->exception.ExceptionCode = code ? code : 0xe0000001;
187#ifdef _M_IX86
188 shared_->exception.ExceptionAddress = reinterpret_cast<void*>(shared_->context.Eip);
189#else
190 shared_->exception.ExceptionAddress = reinterpret_cast<void*>(shared_->context.Rip);
191#endif
192 }
193 shared_->exception.ExceptionRecord = nullptr; // Nested pointers belong to the client.
194 // No allocation, locks, symbol lookup, or network calls on this path.
195 size_t n = 0;
196 if (reason) while (n + 1 < sizeof shared_->reason && reason[n]) { shared_->reason[n] = reason[n]; ++n; }
197 shared_->reason[n] = 0;
198 MemoryBarrier();
199 if (!SetEvent(request_)) return GetLastError();
200 HANDLE waiting[] = { done_, helper_ };
201 DWORD result = WaitForMultipleObjects(2, waiting, FALSE, CaptureTimeoutMs);
202 if (result == WAIT_OBJECT_0) return shared_->result;
203 return result == WAIT_TIMEOUT ? WAIT_TIMEOUT : ERROR_PROCESS_ABORTED;
204 }
205}
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
const char * startupStage_
DWORD Record(const char *reason, DWORD code, EXCEPTION_POINTERS *exception) noexcept
volatile LONG requested_
wchar_t helperPath_[1024]
DWORD Start(const char *trace, const wchar_t *helper=nullptr, const wchar_t *directory=nullptr) noexcept
constexpr DWORD Protocol
Definition CrashShared.h:6
constexpr DWORD CaptureTimeoutMs
Definition CrashShared.h:7