98void Logger::RecordCrash(
const char* reason,
unsigned long code, EXCEPTION_POINTERS* exception)
noexcept
100 if (InterlockedCompareExchange(&
crash->recorded, 1, 0) != 0)
return;
103 const bool haveBreadcrumbs = TryAcquireSRWLockShared(&
crash->breadcrumbLock) != FALSE;
107 ReleaseSRWLockShared(&
crash->breadcrumbLock);
110 std::snprintf(
crash->pending.report.entry,
sizeof crash->pending.report.entry,
111 "%.140s (0x%08lx), trace %s", reason ? reason :
"Fatal error", code,
fileName);
112 if (haveBreadcrumbs)
crash->snapshot.FormatPacket(
crash->pending.report.stackTrace);
113 else strcpy_s(
crash->pending.report.stackTrace,
"Breadcrumb snapshot unavailable: recorder busy");
115 const size_t stackUsed = (std::min)(strlen(
crash->pending.report.stackTrace),
sizeof crash->pending.report.stackTrace - 72);
116 std::snprintf(
crash->pending.report.stackTrace + stackUsed,
117 sizeof crash->pending.report.stackTrace - stackUsed,
"\nNative dump ID: %ls",
crash->dump.Id());
121 std::snprintf(
crash->line,
sizeof crash->line,
122 "\r\n%02u:%02u:%02u.%03u FATAL: %.700s (0x%08lx), thread %lu\r\n",
123 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
124 reason ? reason :
"Fatal error", code, GetCurrentThreadId());
128 SetFilePointer(
crash->pendingFile, 0,
nullptr, FILE_BEGIN);
129 WriteFile(
crash->pendingFile, &
crash->pending,
sizeof crash->pending, &written,
nullptr);
130 FlushFileBuffers(
crash->pendingFile);
131 FlushFileBuffers(
crash->trace);
133 const DWORD dumpResult =
crash->dump.Record(reason, code, exception);
134 std::snprintf(
crash->line,
sizeof crash->line,
135 "Native dump ID: %ls; helper capture result: 0x%08lx (0=locally saved)\r\n",
crash->dump.Id(), dumpResult);
137 FlushFileBuffers(
crash->trace);
141 const EXCEPTION_RECORD& record = *exception->ExceptionRecord;
142 std::snprintf(
crash->line,
sizeof crash->line,
"Exception address: %p\r\n", record.ExceptionAddress);
144 if ((code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_IN_PAGE_ERROR) && record.NumberParameters >= 2)
146 std::snprintf(
crash->line,
sizeof crash->line,
"Memory operation: %llu (0=read, 1=write, 8=execute), address: %p\r\n",
147 static_cast<unsigned long long>(record.ExceptionInformation[0]),
148 reinterpret_cast<void*
>(record.ExceptionInformation[1]));
152 const CONTEXT& context = *exception->ContextRecord;
153 std::snprintf(
crash->line,
sizeof crash->line,
154 "Registers: EIP=%08lx ESP=%08lx EBP=%08lx EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx ESI=%08lx EDI=%08lx\r\n",
155 context.Eip, context.Esp, context.Ebp, context.Eax, context.Ebx, context.Ecx, context.Edx, context.Esi, context.Edi);
159 WriteText(
crash->trace,
"Simulated call stack (recent breadcrumbs, newest first; may span threads):\r\n");
160 if (!haveBreadcrumbs) WriteText(
crash->trace,
" --> unavailable: breadcrumb recorder busy\r\n");
161 for (std::size_t i = 0; i <
crash->snapshot.Count(); ++i)
163 std::snprintf(
crash->line,
sizeof crash->line,
" --> %s\r\n",
crash->snapshot.Recent(i));
166 WriteText(
crash->trace,
"Crash report saved locally; upload will be retried on the next connection.\r\n");
167 FlushFileBuffers(
crash->trace);
170 MEMORYSTATUSEX memory = {};
171 memory.dwLength =
sizeof memory;
172 if (GlobalMemoryStatusEx(&memory))
174 std::snprintf(
crash->line,
sizeof crash->line,
175 "Memory bytes: virtual total=%llu available=%llu; physical available=%llu; commit available=%llu\r\n",
176 memory.ullTotalVirtual, memory.ullAvailVirtual, memory.ullAvailPhys, memory.ullAvailPageFile);
179 PROCESS_MEMORY_COUNTERS_EX processMemory = {};
180 if (GetProcessMemoryInfo(GetCurrentProcess(),
reinterpret_cast<PROCESS_MEMORY_COUNTERS*
>(&processMemory),
sizeof processMemory))
182 std::snprintf(
crash->line,
sizeof crash->line,
183 "Process memory bytes: private=%llu workingSet=%llu peakWorkingSet=%llu\r\n",
184 static_cast<unsigned long long>(processMemory.PrivateUsage),
185 static_cast<unsigned long long>(processMemory.WorkingSetSize),
186 static_cast<unsigned long long>(processMemory.PeakWorkingSetSize));
189 FlushFileBuffers(
crash->trace);
193 HMODULE module =
nullptr;
194 if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
195 reinterpret_cast<LPCSTR
>(exception->ExceptionRecord->ExceptionAddress), &module))
197 char modulePath[MAX_PATH] = {};
198 GetModuleFileNameA(module, modulePath, MAX_PATH);
199 std::snprintf(
crash->line,
sizeof crash->line,
"Fault module: %s base=%p RVA=0x%llx\r\n", modulePath, module,
200 static_cast<unsigned long long>(
reinterpret_cast<uintptr_t
>(exception->ExceptionRecord->ExceptionAddress) -
reinterpret_cast<uintptr_t
>(module)));
202 FlushFileBuffers(
crash->trace);
225 std::lock_guard<std::mutex> lock(
crash->errorUploadMutex);
226 crash->errorUploadBudget.ResetConnection();
228 crash->uploads.clear();
229 WIN32_FIND_DATAA found;
230 HANDLE search = FindFirstFileA(
"trace_*.log.pending", &found);
231 if (search == INVALID_HANDLE_VALUE)
return;
234 if (strcmp(found.cFileName,
crash->pendingName) == 0 ||
235 found.nFileSizeHigh != 0 ||
236 (found.nFileSizeLow != 0 && found.nFileSizeLow !=
sizeof(PendingCrash)))
continue;
238 HANDLE marker = CreateFileA(found.cFileName, GENERIC_READ, 0,
nullptr, OPEN_EXISTING, 0,
nullptr);
239 if (marker == INVALID_HANDLE_VALUE)
continue;
242 const std::string traceName(found.cFileName, strlen(found.cFileName) - strlen(
".pending"));
244 const bool legacyUncleanExit = found.nFileSizeLow == 0;
245 if (legacyUncleanExit) DescribeUncleanExit(saved, traceName.c_str());
246 const bool valid = legacyUncleanExit || (ReadFile(marker, &saved,
sizeof saved, &bytes,
nullptr) &&
247 bytes ==
sizeof saved && saved.signature == pendingSignature && saved.report.
level ==
Fatal);
249 if (!valid)
continue;
250 saved.report.
entry[
sizeof saved.report.
entry - 1] = 0;
252 std::ifstream file(traceName, std::ios::binary);
254 const std::string contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
258 crash->uploads.push_back({ receipt, found.cFileName });
259 Log((
"Queued saved crash report: " + traceName).c_str());
261 }
while (
crash->uploads.size() < 8 && FindNextFileA(search, &found));
285 if (!msg) msg =
"(null log message)";
292 const char* prefix = level ==
Warn ?
"Warning: " : level ==
Debug ?
"DEBUG: " :
293 level ==
Error ?
"ERROR: " : level ==
Fatal ?
"FATAL: " :
"";
295 std::snprintf(heading,
sizeof heading,
"%02u:%02u:%02u.%03u %s",
296 st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, prefix);
297 std::string line = heading;
299 char suffix[128] = {};
307 auto* device = host ? host->Device().Device() :
nullptr;
309 strncpy_s(suffix, detail.c_str(), _TRUNCATE);
322 WriteText(
crash->trace, line.c_str());
325 std::unique_lock<std::mutex> uploadLock(
crash->errorUploadMutex, std::defer_lock);
330 if (!uploadLock.try_lock() || !
crash->errorUploadBudget.CanSend(GetTickCount64()))
return;
333 errorPacket.
level = level;
334 std::snprintf(errorPacket.
entry,
sizeof errorPacket.
entry,
"%.190s%.64s", msg, suffix);
335 AcquireSRWLockShared(&
crash->breadcrumbLock);
337 ReleaseSRWLockShared(&
crash->breadcrumbLock);
347 SetCursor(LoadCursor(
nullptr, IDC_ARROW));
351 exit(errorCode != 0 ? errorCode : EXIT_FAILURE);
367 HANDLE h = FindFirstFileW(searchkey, &fd);
368 if (h == INVALID_HANDLE_VALUE)
return;
370 GetSystemTimeAsFileTime(&ftNow);
371 ULARGE_INTEGER current;
372 current.HighPart = ftNow.dwHighDateTime;
373 current.LowPart = ftNow.dwLowDateTime;
377 const std::wstring marker = std::wstring(fd.cFileName) + L
".pending";
378 WIN32_FILE_ATTRIBUTE_DATA pending;
379 if (GetFileAttributesExW(marker.c_str(), GetFileExInfoStandard, &pending))
continue;
380 ULARGE_INTEGER created;
381 created.HighPart = fd.ftCreationTime.dwHighDateTime;
382 created.LowPart = fd.ftCreationTime.dwLowDateTime;
383 if (current.QuadPart > created.QuadPart &&
384 (current.QuadPart - created.QuadPart) / 864000000000ULL >
static_cast<ULONGLONG
>(maxDays))
386 if (DeleteFileW(fd.cFileName)) DeleteFileW(marker.c_str());
388 }
while (FindNextFileW(h, &fd));
397 std::snprintf(
fileName,
sizeof fileName,
"trace_%04u-%02u-%02u-%02u%02u%02u-%03u-%lu-%ld.log",
398 st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds,
399 GetCurrentProcessId(), InterlockedIncrement(&logSequence));
400 crash->trace = CreateFileA(
fileName, GENERIC_WRITE, FILE_SHARE_READ,
nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
nullptr);
401 if (
crash->trace == INVALID_HANDLE_VALUE)
403 MessageBoxA(
nullptr,
"Could not open logfile for writing!",
"Fatal Exception", MB_ICONERROR | MB_OK);
407 crash->pendingFile = CreateFileA(
crash->pendingName, GENERIC_WRITE, FILE_SHARE_READ,
nullptr,
408 CREATE_NEW, FILE_ATTRIBUTE_NORMAL,
nullptr);
413 const bool pendingSaved = WriteFile(
crash->pendingFile, &
crash->pending,
sizeof crash->pending,
414 &written,
nullptr) && written ==
sizeof crash->pending && FlushFileBuffers(
crash->pendingFile);
416 crash->previousFilter = SetUnhandledExceptionFilter(OnUnhandledException);
417 crash->previousTerminate = std::set_terminate(OnTerminate);
418 crash->previousInvalid = _set_invalid_parameter_handler(OnInvalidParameter);
419 crash->previousPureCall = _set_purecall_handler(OnPureCall);
420 crash->previousAbort = std::signal(SIGABRT, OnAbort);
422 ULONG stackGuarantee = 32768;
423 SetThreadStackGuarantee(&stackGuarantee);
425 Log((std::string(
"Logger::ctor Opened logfile \"") +
fileName +
"\"").c_str());
426 Log(
"Crash diagnostics enabled; build " __DATE__
" " __TIME__);
427 char dumpStatus[4096];
428 if (
crash->dump.UpdateError())
430 std::snprintf(dumpStatus,
sizeof dumpStatus,
431 "Native crash helper update deferred: 0x%08lx at InstallStagedHelper; installed helper=%ls; pending CrashHandler1.exe retained",
432 crash->dump.UpdateError(),
crash->dump.HelperPath());
435 std::snprintf(dumpStatus,
sizeof dumpStatus,
436 "Native crash helper startup: 0x%08lx; stage=%s; dump ID %ls; helper=%ls; local queue=%ls",
437 dumpStartup,
crash->dump.StartupStage(),
crash->dump.Id(),
crash->dump.HelperPath(),
crash->dump.Directory());
439 char executable[MAX_PATH] = {};
440 GetModuleFileNameA(
nullptr, executable, MAX_PATH);
442 if (
crash->pendingFile == INVALID_HANDLE_VALUE)
443 Log(
"Could not create crash retry marker; local trace remains available",
Warn);
444 else if (!pendingSaved)
445 Log(
"Could not persist startup crash retry record; local trace remains available",
Warn);