aboutsummaryrefslogtreecommitdiff
path: root/NorthstarDLL/crashhandler.cpp
blob: 2532afd0519d30408d0ff55d2d6f7592ec9fa1fc (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#include "pch.h"
#include "crashhandler.h"
#include "dedicated.h"
#include "nsprefix.h"
#include "version.h"
#include "modmanager.h"

#include <minidumpapiset.h>

HANDLE hExceptionFilter;

std::shared_ptr<ExceptionLog> storedException {};

#define RUNTIME_EXCEPTION 3765269347
// clang format did this :/
std::map<int, std::string> ExceptionNames = {
	{EXCEPTION_ACCESS_VIOLATION, "Access Violation"},			{EXCEPTION_IN_PAGE_ERROR, "Access Violation"},
	{EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array bounds exceeded"}, {EXCEPTION_DATATYPE_MISALIGNMENT, "Datatype misalignment"},
	{EXCEPTION_FLT_DENORMAL_OPERAND, "Denormal operand"},		{EXCEPTION_FLT_DIVIDE_BY_ZERO, "Divide by zero (float)"},
	{EXCEPTION_FLT_INEXACT_RESULT, "Inexact float result"},		{EXCEPTION_FLT_INVALID_OPERATION, "Invalid operation"},
	{EXCEPTION_FLT_OVERFLOW, "Numeric overflow (float)"},		{EXCEPTION_FLT_STACK_CHECK, "Stack check"},
	{EXCEPTION_FLT_UNDERFLOW, "Numeric underflow (float)"},		{EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal instruction"},
	{EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero (int)"},		{EXCEPTION_INT_OVERFLOW, "Numeric overfloat (int)"},
	{EXCEPTION_INVALID_DISPOSITION, "Invalid disposition"},		{EXCEPTION_NONCONTINUABLE_EXCEPTION, "Non-continuable exception"},
	{EXCEPTION_PRIV_INSTRUCTION, "Priviledged instruction"},	{EXCEPTION_STACK_OVERFLOW, "Stack overflow"},
	{RUNTIME_EXCEPTION, "Uncaught runtime exception:"},
};

void PrintExceptionLog(ExceptionLog& exc)
{
	// General crash message
	spdlog::error("Northstar version: {}", version);
	spdlog::error("Northstar has crashed! a minidump has been written and exception info is available below:");
	spdlog::error("Loaded mods: ");
	for (const auto& mod : g_pModManager->m_LoadedMods)
	{
		if (mod.m_bEnabled)
		{
			spdlog::error("{} {}", mod.Name, mod.Version);
		}
	}
	spdlog::error(exc.cause);
	// If this was a runtime error, print the message
	if (exc.runtimeInfo.length() != 0)
		spdlog::error("\"{}\"", exc.runtimeInfo);
	spdlog::error("At: {} + {}", exc.trace[0].name, exc.trace[0].relativeAddress);
	spdlog::error("");
	spdlog::error("Stack trace:");

	// Generate format string for stack trace
	std::stringstream formatString;
	formatString << "    {:<" << exc.longestModuleNameLength + 2 << "} {:<" << exc.longestRelativeAddressLength << "} {}";
	std::string guide = fmt::format(formatString.str(), "Module Name", "Offset", "Full Address");
	std::string line(guide.length() + 2, '-');
	spdlog::error(guide);
	spdlog::error(line);

	for (const auto& module : exc.trace)
		spdlog::error(formatString.str(), module.name, module.relativeAddress, module.address);

	// Print dump of most CPU registers
	spdlog::error("");
	for (const auto& reg : exc.registerDump)
		spdlog::error(reg);

	if (!IsDedicatedServer())
		MessageBoxA(
			0,
			"Northstar has crashed! Crash info can be found in R2Northstar/logs",
			"Northstar has crashed!",
			MB_ICONERROR | MB_OK | MB_SYSTEMMODAL);
}

std::string GetExceptionName(ExceptionLog& exc)
{
	const DWORD exceptionCode = exc.exceptionRecord->ExceptionCode;
	auto name = ExceptionNames[exceptionCode];
	if (exceptionCode == EXCEPTION_ACCESS_VIOLATION || exceptionCode == EXCEPTION_IN_PAGE_ERROR)
	{
		std::stringstream returnString;
		returnString << name << ": ";

		auto exceptionInfo0 = exc.exceptionRecord->ExceptionInformation[0];
		auto exceptionInfo1 = exc.exceptionRecord->ExceptionInformation[1];

		if (!exceptionInfo0)
			returnString << "Attempted to read from: 0x" << (void*)exceptionInfo1;
		else if (exceptionInfo0 == 1)
			returnString << "Attempted to write to: 0x" << (void*)exceptionInfo1;
		else if (exceptionInfo0 == 8)
			returnString << "Data Execution Prevention (DEP) at: 0x" << (void*)std::hex << exceptionInfo1;
		else
			returnString << "Unknown access violation at: 0x" << (void*)exceptionInfo1;
		return returnString.str();
	}
	return name;
}

// Custom formatter for the Xmm registers
template <> struct fmt::formatter<M128A> : fmt::formatter<string_view>
{
	template <typename FormatContext> auto format(const M128A& obj, FormatContext& ctx)
	{
		// Masking the top and bottom half of the long long
		int v1 = obj.Low & INT_MAX;
		int v2 = obj.Low >> 32;
		int v3 = obj.High & INT_MAX;
		int v4 = obj.High >> 32;
		return fmt::format_to(
			ctx.out(),
			"[ {:G}, {:G}, {:G}, {:G}], [ 0x{:x}, 0x{:x}, 0x{:x}, 0x{:x} ]",
			*reinterpret_cast<float*>(&v1),
			*reinterpret_cast<float*>(&v2),
			*reinterpret_cast<float*>(&v3),
			*reinterpret_cast<float*>(&v4),
			v1,
			v2,
			v3,
			v4);
	}
};

void GenerateTrace(ExceptionLog& exc, bool skipErrorHandlingFrames = true, int numSkipFrames = 0)
{

	MODULEINFO crashedModuleInfo;
	GetModuleInformation(GetCurrentProcess(), exc.crashedModule, &crashedModuleInfo, sizeof(crashedModuleInfo));

	char crashedModuleFullName[MAX_PATH];
	GetModuleFileNameExA(GetCurrentProcess(), exc.crashedModule, crashedModuleFullName, MAX_PATH);
	char* crashedModuleName = strrchr(crashedModuleFullName, '\\') + 1;

	DWORD64 crashedModuleOffset = ((DWORD64)exc.exceptionRecord->ExceptionAddress) - ((DWORD64)crashedModuleInfo.lpBaseOfDll);

	PVOID framesToCapture[62];
	int frames = RtlCaptureStackBackTrace(0, 62, framesToCapture, NULL);
	bool haveSkippedErrorHandlingFrames = false;

	for (int i = 0; i < frames; i++)
	{

		HMODULE backtraceModuleHandle;
		GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPCSTR>(framesToCapture[i]), &backtraceModuleHandle);

		char backtraceModuleFullName[MAX_PATH];
		GetModuleFileNameExA(GetCurrentProcess(), backtraceModuleHandle, backtraceModuleFullName, MAX_PATH);
		char* backtraceModuleName = strrchr(backtraceModuleFullName, '\\') + 1;

		if (!haveSkippedErrorHandlingFrames)
		{
			if (!strncmp(backtraceModuleFullName, crashedModuleFullName, MAX_PATH) &&
				!strncmp(backtraceModuleName, crashedModuleName, MAX_PATH))
			{
				haveSkippedErrorHandlingFrames = true;
			}
			else
			{
				continue;
			}
		}

		if (numSkipFrames > 0)
		{
			numSkipFrames--;
			continue;
		}

		void* actualAddress = (void*)framesToCapture[i];
		void* relativeAddress = (void*)(uintptr_t(actualAddress) - uintptr_t(backtraceModuleHandle));
		std::string s_moduleName {backtraceModuleName};
		std::string s_relativeAddress {fmt::format("{}", relativeAddress)};
		// These are used for formatting later on
		if (s_moduleName.length() > exc.longestModuleNameLength)
		{
			exc.longestModuleNameLength = s_moduleName.length();
		}
		if (s_relativeAddress.length() > exc.longestRelativeAddressLength)
		{
			exc.longestRelativeAddressLength = s_relativeAddress.length();
		}

		exc.trace.push_back(BacktraceModule {s_moduleName, s_relativeAddress, fmt::format("{}", actualAddress)});
	}

	CONTEXT* exceptionContext = exc.contextRecord;

	exc.registerDump.push_back(fmt::format("Flags: 0b{0:b}", exceptionContext->ContextFlags));
	exc.registerDump.push_back(fmt::format("RIP: 0x{0:x}", exceptionContext->Rip));
	exc.registerDump.push_back(fmt::format("CS : 0x{0:x}", exceptionContext->SegCs));
	exc.registerDump.push_back(fmt::format("DS : 0x{0:x}", exceptionContext->SegDs));
	exc.registerDump.push_back(fmt::format("ES : 0x{0:x}", exceptionContext->SegEs));
	exc.registerDump.push_back(fmt::format("SS : 0x{0:x}", exceptionContext->SegSs));
	exc.registerDump.push_back(fmt::format("FS : 0x{0:x}", exceptionContext->SegFs));
	exc.registerDump.push_back(fmt::format("GS : 0x{0:x}", exceptionContext->SegGs));

	exc.registerDump.push_back(fmt::format("RAX: 0x{0:x}", exceptionContext->Rax));
	exc.registerDump.push_back(fmt::format("RBX: 0x{0:x}", exceptionContext->Rbx));
	exc.registerDump.push_back(fmt::format("RCX: 0x{0:x}", exceptionContext->Rcx));
	exc.registerDump.push_back(fmt::format("RDX: 0x{0:x}", exceptionContext->Rdx));
	exc.registerDump.push_back(fmt::format("RSI: 0x{0:x}", exceptionContext->Rsi));
	exc.registerDump.push_back(fmt::format("RDI: 0x{0:x}", exceptionContext->Rdi));
	exc.registerDump.push_back(fmt::format("RBP: 0x{0:x}", exceptionContext->Rbp));
	exc.registerDump.push_back(fmt::format("RSP: 0x{0:x}", exceptionContext->Rsp));
	exc.registerDump.push_back(fmt::format("R8 : 0x{0:x}", exceptionContext->R8));
	exc.registerDump.push_back(fmt::format("R9 : 0x{0:x}", exceptionContext->R9));
	exc.registerDump.push_back(fmt::format("R10: 0x{0:x}", exceptionContext->R10));
	exc.registerDump.push_back(fmt::format("R11: 0x{0:x}", exceptionContext->R11));
	exc.registerDump.push_back(fmt::format("R12: 0x{0:x}", exceptionContext->R12));
	exc.registerDump.push_back(fmt::format("R13: 0x{0:x}", exceptionContext->R13));
	exc.registerDump.push_back(fmt::format("R14: 0x{0:x}", exceptionContext->R14));
	exc.registerDump.push_back(fmt::format("R15: 0x{0:x}", exceptionContext->R15));

	exc.registerDump.push_back(fmt::format("Xmm0 : {}", exceptionContext->Xmm0));
	exc.registerDump.push_back(fmt::format("Xmm1 : {}", exceptionContext->Xmm1));
	exc.registerDump.push_back(fmt::format("Xmm2 : {}", exceptionContext->Xmm2));
	exc.registerDump.push_back(fmt::format("Xmm3 : {}", exceptionContext->Xmm3));
	exc.registerDump.push_back(fmt::format("Xmm4 : {}", exceptionContext->Xmm4));
	exc.registerDump.push_back(fmt::format("Xmm5 : {}", exceptionContext->Xmm5));
	exc.registerDump.push_back(fmt::format("Xmm6 : {}", exceptionContext->Xmm6));
	exc.registerDump.push_back(fmt::format("Xmm7 : {}", exceptionContext->Xmm7));
	exc.registerDump.push_back(fmt::format("Xmm8 : {}", exceptionContext->Xmm8));
	exc.registerDump.push_back(fmt::format("Xmm9 : {}", exceptionContext->Xmm9));
	exc.registerDump.push_back(fmt::format("Xmm10: {}", exceptionContext->Xmm10));
	exc.registerDump.push_back(fmt::format("Xmm11: {}", exceptionContext->Xmm11));
	exc.registerDump.push_back(fmt::format("Xmm12: {}", exceptionContext->Xmm12));
	exc.registerDump.push_back(fmt::format("Xmm13: {}", exceptionContext->Xmm13));
	exc.registerDump.push_back(fmt::format("Xmm14: {}", exceptionContext->Xmm14));
	exc.registerDump.push_back(fmt::format("Xmm15: {}", exceptionContext->Xmm15));
}

void CreateMiniDump(EXCEPTION_POINTERS* exceptionInfo)
{
	time_t time = std::time(nullptr);
	tm currentTime = *std::localtime(&time);
	std::stringstream stream;
	stream << std::put_time(&currentTime, (GetNorthstarPrefix() + "/logs/nsdump%Y-%m-%d %H-%M-%S.dmp").c_str());

	auto hMinidumpFile = CreateFileA(stream.str().c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
	if (hMinidumpFile)
	{
		MINIDUMP_EXCEPTION_INFORMATION dumpExceptionInfo;
		dumpExceptionInfo.ThreadId = GetCurrentThreadId();
		dumpExceptionInfo.ExceptionPointers = exceptionInfo;
		dumpExceptionInfo.ClientPointers = false;

		MiniDumpWriteDump(
			GetCurrentProcess(),
			GetCurrentProcessId(),
			hMinidumpFile,
			MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory),
			&dumpExceptionInfo,
			nullptr,
			nullptr);
		CloseHandle(hMinidumpFile);
	}
	else
		spdlog::error("Failed to write minidump file {}!", stream.str());
}

long GenerateExceptionLog(EXCEPTION_POINTERS* exceptionInfo)
{
	const DWORD exceptionCode = exceptionInfo->ExceptionRecord->ExceptionCode;

	void* exceptionAddress = exceptionInfo->ExceptionRecord->ExceptionAddress;

	auto exc = std::make_shared<ExceptionLog>();
	exc->exceptionRecord = exceptionInfo->ExceptionRecord;
	exc->contextRecord = exceptionInfo->ContextRecord;
	exc->cause = GetExceptionName(*exc);

	HMODULE crashedModuleHandle;
	GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast<LPCSTR>(exceptionAddress), &crashedModuleHandle);

	exc->crashedModule = crashedModuleHandle;

	// When encountering a runtime exception, we store the exception to be displayed later
	// We then have to return EXCEPTION_CONTINUE_SEARCH so that our runtime handler may be called
	// This might possibly cause some issues if client and server are crashing at the same time, but honestly i don't care
	if (exceptionCode == RUNTIME_EXCEPTION)
	{
		GenerateTrace(*exc, false, 2);
		storedException = exc;
		return EXCEPTION_CONTINUE_SEARCH;
	}

	GenerateTrace(*exc, true, 0);
	CreateMiniDump(exceptionInfo);
	PrintExceptionLog(*exc);
	return EXCEPTION_EXECUTE_HANDLER;
}

long __stdcall ExceptionFilter(EXCEPTION_POINTERS* exceptionInfo)
{
	if (!IsDebuggerPresent())
	{
		// Check if we are capable of handling this type of exception
		if (ExceptionNames.find(exceptionInfo->ExceptionRecord->ExceptionCode) == ExceptionNames.end())
			return EXCEPTION_CONTINUE_SEARCH;
		CreateMiniDump(exceptionInfo);
		return GenerateExceptionLog(exceptionInfo);
	}

	return EXCEPTION_EXECUTE_HANDLER;
}

void RuntimeExceptionHandler()
{
	auto ptr = std::current_exception();
	if (ptr)
	{
		try
		{
			// This is to generate an actual std::exception object that we can then inspect
			std::rethrow_exception(ptr);
		}
		catch (std::exception& e)
		{
			storedException->runtimeInfo = e.what();
		}
		catch (...)
		{
			storedException->runtimeInfo = "Unknown runtime exception type";
		}
		PrintExceptionLog(*storedException);
		exit(-1);
	}
	else
	{
		spdlog::error(
			"std::current_exception() returned nullptr while being handled by RuntimeExceptionHandler. This should never happen!");
		std::abort();
	}
}

BOOL WINAPI ConsoleHandlerRoutine(DWORD eventCode)
{
	switch (eventCode)
	{
	case CTRL_CLOSE_EVENT:
		// User closed console, shut everything down
		spdlog::info("Exiting due to console close...");
		RemoveCrashHandler();
		exit(EXIT_SUCCESS);
		return FALSE;
	}

	return TRUE;
}

void InitialiseCrashHandler()
{
	hExceptionFilter = AddVectoredExceptionHandler(TRUE, ExceptionFilter);
	SetConsoleCtrlHandler(ConsoleHandlerRoutine, true);
	std::set_terminate(RuntimeExceptionHandler);
}

void RemoveCrashHandler()
{
	RemoveVectoredExceptionHandler(hExceptionFilter);
}