forked from tiltedphoques/TiltedEvolution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCrashHandler.cpp
90 lines (72 loc) · 2.92 KB
/
CrashHandler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "CrashHandler.h"
#include <DbgHelp.h>
#include <Windows.h>
#include <chrono>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <strsafe.h>
using time_point = std::chrono::system_clock::time_point;
std::string SerializeTimePoint(const time_point& time, const std::string& format)
{
std::time_t tt = std::chrono::system_clock::to_time_t(time);
std::tm tm = *std::gmtime(&tt); // GMT (UTC)
// std::tm tm = *std::localtime(&tt); //Locale time-zone, usually UTC by default.
std::stringstream ss;
ss << std::put_time(&tm, format.c_str());
return ss.str();
}
LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo)
{
if (pExceptionInfo->ExceptionRecord->ExceptionCode == 0xC0000005)
{
spdlog::error("Crash occurred!");
MINIDUMP_EXCEPTION_INFORMATION M;
char dumpPath[MAX_PATH];
M.ThreadId = GetCurrentThreadId();
M.ExceptionPointers = pExceptionInfo;
M.ClientPointers = 0;
std::ostringstream oss;
oss << "crash_" << SerializeTimePoint(std::chrono::system_clock::now(), "UTC_%Y-%m-%d_%H-%M-%S") << ".dmp";
GetModuleFileNameA(NULL, dumpPath, sizeof(dumpPath));
std::filesystem::path modulePath(dumpPath);
auto subPath = modulePath.parent_path();
CrashHandler::RemovePreviousDump(subPath);
subPath /= oss.str();
auto hDumpFile = CreateFileA(subPath.string().c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
// baseline settings from https://stackoverflow.com/a/63123214/5273909
auto dumpSettings = MiniDumpWithDataSegs | MiniDumpWithProcessThreadData | MiniDumpWithHandleData | MiniDumpWithThreadInfo |
/*
//MiniDumpWithPrivateReadWriteMemory | // this one gens bad dump
MiniDumpWithUnloadedModules |
MiniDumpWithFullMemoryInfo |
MiniDumpWithTokenInformation |
MiniDumpWithPrivateWriteCopyMemory |
*/
0;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, (MINIDUMP_TYPE)dumpSettings, (pExceptionInfo) ? &M : NULL, NULL, NULL);
CloseHandle(hDumpFile);
spdlog::error("Coredump created -> flush logs.");
spdlog::default_logger()->flush();
return EXCEPTION_EXECUTE_HANDLER;
}
return EXCEPTION_CONTINUE_SEARCH;
}
CrashHandler::CrashHandler()
{
AddVectoredExceptionHandler(1, &VectoredExceptionHandler);
}
CrashHandler::~CrashHandler()
{
}
void CrashHandler::RemovePreviousDump(std::filesystem::path path)
{
for (auto& entry : std::filesystem::directory_iterator(path))
{
if (entry.path().string().find("crash") != std::string::npos)
{
DeleteFileA(entry.path().string().c_str());
}
}
}