BsWin32CrashHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. #include "BsPrerequisitesUtil.h"
  2. #include "BsDebug.h"
  3. #include "BsDynLib.h"
  4. #include "BsFileSystem.h"
  5. #include "windows.h"
  6. #include "DbgHelp.h"
  7. #include <psapi.h>
  8. namespace BansheeEngine
  9. {
  10. /**
  11. * @brief Returns the raw stack trace using the provided context. Raw stack trace contains only
  12. * function addresses.
  13. *
  14. * @param context Processor context from which to start the stack trace.
  15. * @param stackTrace Output parameter that will contain the function addresses. First address is the deepest
  16. * called function and following address is its caller and so on.
  17. *
  18. * @returns Number of functions in the call stack.
  19. */
  20. UINT32 win32_getRawStackTrace(CONTEXT context, UINT64 stackTrace[BS_MAX_STACKTRACE_DEPTH])
  21. {
  22. HANDLE hProcess = GetCurrentProcess();
  23. HANDLE hThread = GetCurrentThread();
  24. UINT32 machineType;
  25. STACKFRAME64 stackFrame;
  26. memset(&stackFrame, 0, sizeof(stackFrame));
  27. stackFrame.AddrPC.Mode = AddrModeFlat;
  28. stackFrame.AddrStack.Mode = AddrModeFlat;
  29. stackFrame.AddrFrame.Mode = AddrModeFlat;
  30. #if BS_ARCH_TYPE == BS_ARCHITECTURE_x86_64
  31. stackFrame.AddrPC.Offset = context.Rip;
  32. stackFrame.AddrStack.Offset = context.Rsp;
  33. stackFrame.AddrFrame.Offset = context.Rbp;
  34. machineType = IMAGE_FILE_MACHINE_AMD64;
  35. #else
  36. stackFrame.AddrPC.Offset = context.Eip;
  37. stackFrame.AddrStack.Offset = context.Esp;
  38. stackFrame.AddrFrame.Offset = context.Ebp;
  39. machineType = IMAGE_FILE_MACHINE_I386;
  40. #endif
  41. UINT32 numEntries = 0;
  42. while (true)
  43. {
  44. if (!StackWalk64(machineType, hProcess, hThread, &stackFrame, &context, nullptr,
  45. SymFunctionTableAccess64, SymGetModuleBase64, nullptr))
  46. {
  47. break;
  48. }
  49. if (numEntries < BS_MAX_STACKTRACE_DEPTH)
  50. stackTrace[numEntries] = stackFrame.AddrPC.Offset;
  51. numEntries++;
  52. if (stackFrame.AddrPC.Offset == 0 || stackFrame.AddrFrame.Offset == 0)
  53. break;
  54. }
  55. return numEntries;
  56. }
  57. /**
  58. * @brief Returns a string containing a stack trace using the provided context. If function can be found in the symbol
  59. * table its readable name will be present in the stack trace, otherwise just its address.
  60. *
  61. * @param context Processor context from which to start the stack trace.
  62. * @param skip Number of bottom-most call stack entries to skip.
  63. *
  64. * @returns String containing the call stack with each function on its own line.
  65. */
  66. String win32_getStackTrace(CONTEXT context, UINT32 skip = 0)
  67. {
  68. UINT64 rawStackTrace[BS_MAX_STACKTRACE_DEPTH];
  69. UINT32 numEntries = win32_getRawStackTrace(context, rawStackTrace);
  70. numEntries = std::min((UINT32)BS_MAX_STACKTRACE_DEPTH, numEntries);
  71. UINT32 bufferSize = sizeof(PIMAGEHLP_SYMBOL64) + BS_MAX_STACKTRACE_NAME_BYTES;
  72. UINT8* buffer = (UINT8*)bs_alloc(bufferSize);
  73. PIMAGEHLP_SYMBOL64 symbol = (PIMAGEHLP_SYMBOL64)buffer;
  74. symbol->SizeOfStruct = bufferSize;
  75. symbol->MaxNameLength = BS_MAX_STACKTRACE_NAME_BYTES;
  76. HANDLE hProcess = GetCurrentProcess();
  77. StringStream outputStream;
  78. for (UINT32 i = skip; i < numEntries; i++)
  79. {
  80. if (i > skip)
  81. outputStream << std::endl;
  82. DWORD64 funcAddress = rawStackTrace[i];
  83. // Output function name
  84. DWORD64 dummy;
  85. if (SymGetSymFromAddr64(hProcess, funcAddress, &dummy, symbol))
  86. outputStream << StringUtil::format("{0}() - ", symbol->Name);
  87. // Output file name and line
  88. IMAGEHLP_LINE64 lineData;
  89. lineData.SizeOfStruct = sizeof(lineData);
  90. String addressString = toString(funcAddress, 0, ' ', std::ios::hex);
  91. DWORD column;
  92. if (SymGetLineFromAddr64(hProcess, funcAddress, &column, &lineData))
  93. {
  94. Path filePath = lineData.FileName;
  95. outputStream << StringUtil::format("0x{0} File[{1}:{2} ({3})]", addressString,
  96. filePath.getFilename(), lineData.LineNumber, column);
  97. }
  98. else
  99. {
  100. outputStream << StringUtil::format("0x{0}", addressString);
  101. }
  102. // Output module name
  103. IMAGEHLP_MODULE64 moduleData;
  104. moduleData.SizeOfStruct = sizeof(moduleData);
  105. if (SymGetModuleInfo64(hProcess, funcAddress, &moduleData))
  106. {
  107. Path filePath = moduleData.ImageName;
  108. outputStream << StringUtil::format(" Module[{0}]", filePath.getFilename());
  109. }
  110. }
  111. bs_free(buffer);
  112. return outputStream.str();
  113. }
  114. typedef bool(WINAPI *EnumProcessModulesType)(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded);
  115. typedef DWORD(WINAPI *GetModuleBaseNameType)(HANDLE hProcess, HMODULE hModule, LPSTR lpBaseName, DWORD nSize);
  116. typedef DWORD(WINAPI *GetModuleFileNameExType)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize);
  117. typedef bool(WINAPI *GetModuleInformationType)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb);
  118. static DynLib* gPSAPILib = nullptr;
  119. static EnumProcessModulesType gEnumProcessModules;
  120. static GetModuleBaseNameType gGetModuleBaseName;
  121. static GetModuleFileNameExType gGetModuleFileNameEx;
  122. static GetModuleInformationType gGetModuleInformation;
  123. /**
  124. * @brief Dynamically load the PSAPI.dll and the required symbols, if not already loaded.
  125. */
  126. void win32_initPSAPI()
  127. {
  128. if (gPSAPILib != nullptr)
  129. return;
  130. gPSAPILib = bs_new<DynLib>("PSAPI.dll");
  131. gEnumProcessModules = (EnumProcessModulesType)gPSAPILib->getSymbol("EnumProcessModules");
  132. gGetModuleBaseName = (GetModuleBaseNameType)gPSAPILib->getSymbol("GetModuleFileNameExA");
  133. gGetModuleFileNameEx = (GetModuleFileNameExType)gPSAPILib->getSymbol("GetModuleBaseNameA");
  134. gGetModuleInformation = (GetModuleInformationType)gPSAPILib->getSymbol("GetModuleInformation");
  135. }
  136. /**
  137. * @brief Unloads the PSAPI.dll if is loaded.
  138. */
  139. void win32_unloadPSAPI()
  140. {
  141. if (gPSAPILib == nullptr)
  142. return;
  143. gPSAPILib->unload();
  144. bs_delete(gPSAPILib);
  145. gPSAPILib = nullptr;
  146. }
  147. static bool gSymbolsLoaded = false;
  148. /**
  149. * @brief Loads symbols for all modules in the current process. Loaded symbols allow the stack walker to retrieve
  150. * human readable method, file, module names and other information.
  151. */
  152. void win32_loadSymbols()
  153. {
  154. if (gSymbolsLoaded)
  155. return;
  156. HANDLE hProcess = GetCurrentProcess();
  157. UINT32 options = SymGetOptions();
  158. options |= SYMOPT_LOAD_LINES;
  159. options |= SYMOPT_EXACT_SYMBOLS;
  160. options |= SYMOPT_UNDNAME;
  161. options |= SYMOPT_FAIL_CRITICAL_ERRORS;
  162. options |= SYMOPT_NO_PROMPTS;
  163. options |= SYMOPT_DEFERRED_LOADS;
  164. SymSetOptions(options);
  165. SymInitialize(hProcess, nullptr, true);
  166. DWORD bufferSize;
  167. gEnumProcessModules(hProcess, nullptr, 0, &bufferSize);
  168. HMODULE* modules = (HMODULE*)bs_alloc(bufferSize);
  169. gEnumProcessModules(hProcess, modules, bufferSize, &bufferSize);
  170. UINT32 numModules = bufferSize / sizeof(HMODULE);
  171. for (UINT32 i = 0; i < numModules; i++)
  172. {
  173. MODULEINFO moduleInfo;
  174. char moduleName[BS_MAX_STACKTRACE_NAME_BYTES];
  175. char imageName[BS_MAX_STACKTRACE_NAME_BYTES];
  176. gGetModuleInformation(hProcess, modules[i], &moduleInfo, sizeof(moduleInfo));
  177. gGetModuleFileNameEx(hProcess, modules[i], imageName, BS_MAX_STACKTRACE_NAME_BYTES);
  178. gGetModuleBaseName(hProcess, modules[i], moduleName, BS_MAX_STACKTRACE_NAME_BYTES);
  179. char pdbSearchPath[BS_MAX_STACKTRACE_NAME_BYTES];
  180. GetFullPathNameA(imageName, BS_MAX_STACKTRACE_NAME_BYTES, pdbSearchPath, nullptr);
  181. SymSetSearchPath(GetCurrentProcess(), pdbSearchPath);
  182. SymLoadModule64(hProcess, modules[i], imageName, moduleName, (DWORD64)moduleInfo.lpBaseOfDll,
  183. (DWORD)moduleInfo.SizeOfImage);
  184. }
  185. bs_free(modules);
  186. gSymbolsLoaded = true;
  187. }
  188. /**
  189. * @brief Converts an exception record into a human readable error message.
  190. */
  191. String win32_getExceptionMessage(EXCEPTION_RECORD* record)
  192. {
  193. String exceptionAddress = toString((UINT64)record->ExceptionAddress, 0, ' ', std::ios::hex);
  194. String format;
  195. switch (record->ExceptionCode)
  196. {
  197. case EXCEPTION_ACCESS_VIOLATION:
  198. {
  199. DWORD_PTR violatedAddress = 0;
  200. if (record->NumberParameters == 2)
  201. {
  202. if (record->ExceptionInformation[0] == 0)
  203. format = "Unhandled exception at 0x{0}. Access violation reading 0x{1}.";
  204. else if (record->ExceptionInformation[0] == 8)
  205. format = "Unhandled exception at 0x{0}. Access violation DEP 0x{1}.";
  206. else
  207. format = "Unhandled exception at 0x{0}. Access violation writing 0x{1}.";
  208. violatedAddress = record->ExceptionInformation[1];
  209. }
  210. else
  211. format = "Unhandled exception at 0x{0}. Access violation.";
  212. String violatedAddressStr = toString(violatedAddress, 0, ' ', std::ios::hex);
  213. return StringUtil::format(format, exceptionAddress, violatedAddressStr);
  214. }
  215. case EXCEPTION_IN_PAGE_ERROR:
  216. {
  217. DWORD_PTR violatedAddress = 0;
  218. DWORD_PTR code = 0;
  219. if (record->NumberParameters == 3)
  220. {
  221. if (record->ExceptionInformation[0] == 0)
  222. format = "Unhandled exception at 0x{0}. Page fault reading 0x{1} with code 0x{2}.";
  223. else if (record->ExceptionInformation[0] == 8)
  224. format = "Unhandled exception at 0x{0}. Page fault DEP 0x{1} with code 0x{2}.";
  225. else
  226. format = "Unhandled exception at 0x{0}. Page fault writing 0x{1} with code 0x{2}.";
  227. violatedAddress = record->ExceptionInformation[1];
  228. code = record->ExceptionInformation[3];
  229. }
  230. else
  231. format = "Unhandled exception at 0x{0}. Page fault.";
  232. String violatedAddressStr = toString(violatedAddress, 0, ' ', std::ios::hex);
  233. String codeStr = toString(code, 0, ' ', std::ios::hex);
  234. return StringUtil::format(format, exceptionAddress, violatedAddressStr, codeStr);
  235. }
  236. case STATUS_ARRAY_BOUNDS_EXCEEDED:
  237. {
  238. format = "Unhandled exception at 0x{0}. Attempting to access an out of range array element.";
  239. return StringUtil::format(format, exceptionAddress);
  240. }
  241. case EXCEPTION_DATATYPE_MISALIGNMENT:
  242. {
  243. format = "Unhandled exception at 0x{0}. Attempting to access missaligned data.";
  244. return StringUtil::format(format, exceptionAddress);
  245. }
  246. case EXCEPTION_FLT_DENORMAL_OPERAND:
  247. {
  248. format = "Unhandled exception at 0x{0}. Floating point operand too small.";
  249. return StringUtil::format(format, exceptionAddress);
  250. }
  251. case EXCEPTION_FLT_DIVIDE_BY_ZERO:
  252. {
  253. format = "Unhandled exception at 0x{0}. Floating point operation attempted to divide by zero.";
  254. return StringUtil::format(format, exceptionAddress);
  255. }
  256. case EXCEPTION_FLT_INVALID_OPERATION:
  257. {
  258. format = "Unhandled exception at 0x{0}. Floating point invalid operation.";
  259. return StringUtil::format(format, exceptionAddress);
  260. }
  261. case EXCEPTION_FLT_OVERFLOW:
  262. {
  263. format = "Unhandled exception at 0x{0}. Floating point overflow.";
  264. return StringUtil::format(format, exceptionAddress);
  265. }
  266. case EXCEPTION_FLT_UNDERFLOW:
  267. {
  268. format = "Unhandled exception at 0x{0}. Floating point underflow.";
  269. return StringUtil::format(format, exceptionAddress);
  270. }
  271. case EXCEPTION_FLT_STACK_CHECK:
  272. {
  273. format = "Unhandled exception at 0x{0}. Floating point stack overflow/underflow.";
  274. return StringUtil::format(format, exceptionAddress);
  275. }
  276. case EXCEPTION_ILLEGAL_INSTRUCTION:
  277. {
  278. format = "Unhandled exception at 0x{0}. Attempting to execute an illegal instruction.";
  279. return StringUtil::format(format, exceptionAddress);
  280. }
  281. case EXCEPTION_PRIV_INSTRUCTION:
  282. {
  283. format = "Unhandled exception at 0x{0}. Attempting to execute a private instruction.";
  284. return StringUtil::format(format, exceptionAddress);
  285. }
  286. case EXCEPTION_INT_DIVIDE_BY_ZERO:
  287. {
  288. format = "Unhandled exception at 0x{0}. Integer operation attempted to divide by zero.";
  289. return StringUtil::format(format, exceptionAddress);
  290. }
  291. case EXCEPTION_INT_OVERFLOW:
  292. {
  293. format = "Unhandled exception at 0x{0}. Integer operation result has overflown.";
  294. return StringUtil::format(format, exceptionAddress);
  295. }
  296. case EXCEPTION_STACK_OVERFLOW:
  297. {
  298. format = "Unhandled exception at 0x{0}. Stack overflow.";
  299. return StringUtil::format(format, exceptionAddress);
  300. }
  301. default:
  302. {
  303. format = "Unhandled exception at 0x{0}. Code 0x{1}.";
  304. String exceptionCode = toString((UINT32)record->ExceptionCode, 0, ' ', std::ios::hex);
  305. return StringUtil::format(format, exceptionAddress, exceptionCode);
  306. }
  307. }
  308. }
  309. void win32_writeMiniDump(const Path& filePath, EXCEPTION_POINTERS* exceptionData)
  310. {
  311. HANDLE hFile = CreateFileW(filePath.toWString().c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS,
  312. FILE_ATTRIBUTE_NORMAL, nullptr);
  313. if (hFile != INVALID_HANDLE_VALUE)
  314. {
  315. MINIDUMP_EXCEPTION_INFORMATION DumpExceptionInfo;
  316. DumpExceptionInfo.ThreadId = GetCurrentThreadId();
  317. DumpExceptionInfo.ExceptionPointers = exceptionData;
  318. DumpExceptionInfo.ClientPointers = false;
  319. MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal,
  320. &DumpExceptionInfo, nullptr, nullptr);
  321. CloseHandle(hFile);
  322. }
  323. }
  324. static const wchar_t* gMiniDumpName = L"minidump.dmp";
  325. const wchar_t* CrashHandler::CrashReportFolder = L"CrashReport-{0}/";
  326. const wchar_t* CrashHandler::CrashLogName = L"log.html";
  327. struct CrashHandler::Data
  328. {
  329. Mutex mutex;
  330. };
  331. CrashHandler::CrashHandler()
  332. {
  333. m = bs_new<Data>();
  334. }
  335. CrashHandler::~CrashHandler()
  336. {
  337. win32_unloadPSAPI();
  338. bs_delete(m);
  339. }
  340. void CrashHandler::reportCrash(const String& type, const String& description, const String& function,
  341. const String& file, UINT32 line)
  342. {
  343. // Win32 debug methods are not thread safe
  344. Lock<>(m->mutex);
  345. String stackTrace = getStackTrace();
  346. StringStream errorMessageStream;
  347. errorMessageStream << "Fatal error occurred and the program has to terminate!" << std::endl;
  348. errorMessageStream << "\t\t" << type << " - " << description << std::endl;
  349. errorMessageStream << "\t\t in " << function << " [" << file << ":" << line << "]" << std::endl;
  350. errorMessageStream << std::endl;
  351. errorMessageStream << "Stack trace: " << std::endl;
  352. errorMessageStream << stackTrace;
  353. String errorMessage = errorMessageStream.str();
  354. gDebug().logError(errorMessage);
  355. Path crashFolder = getCrashFolder();
  356. FileSystem::createDir(crashFolder);
  357. gDebug().saveLog(crashFolder + WString(CrashLogName));
  358. win32_writeMiniDump(crashFolder + WString(gMiniDumpName), nullptr);
  359. WString simpleErrorMessage = L"Fatal error occurred and the program has to terminate! " \
  360. L"\n\nFor more information check the crash report located at:\n " + crashFolder.toWString();
  361. MessageBoxW(nullptr, simpleErrorMessage.c_str(), L"Banshee fatal error!", MB_OK);
  362. // Note: Potentially also log Windows Error Report and/or send crash data to server
  363. }
  364. int CrashHandler::reportCrash(void* exceptionDataPtr)
  365. {
  366. EXCEPTION_POINTERS* exceptionData = (EXCEPTION_POINTERS*)exceptionDataPtr;
  367. // Win32 debug methods are not thread safe
  368. Lock<>(m->mutex);
  369. win32_initPSAPI();
  370. win32_loadSymbols();
  371. String stackTrace = win32_getStackTrace(*exceptionData->ContextRecord, 0);
  372. StringStream errorMessageStream;
  373. errorMessageStream << "Fatal error occurred and the program has to terminate!" << std::endl;
  374. errorMessageStream << "\t\t" << win32_getExceptionMessage(exceptionData->ExceptionRecord) << std::endl;;
  375. errorMessageStream << std::endl;
  376. errorMessageStream << "Stack trace: " << std::endl;
  377. errorMessageStream << stackTrace;
  378. String errorMessage = errorMessageStream.str();
  379. gDebug().logError(errorMessage);
  380. Path crashFolder = getCrashFolder();
  381. FileSystem::createDir(crashFolder);
  382. gDebug().saveLog(crashFolder + WString(CrashLogName));
  383. win32_writeMiniDump(crashFolder + WString(gMiniDumpName), exceptionData);
  384. WString simpleErrorMessage = L"Fatal error occurred and the program has to terminate! " \
  385. L"\n\nFor more information check the crash report located at:\n" + crashFolder.toWString();
  386. MessageBoxW(nullptr, simpleErrorMessage.c_str(), L"Banshee fatal error!", MB_OK);
  387. // Note: Potentially also log Windows Error Report and/or send crash data to server
  388. return EXCEPTION_EXECUTE_HANDLER;
  389. }
  390. Path CrashHandler::getCrashFolder()
  391. {
  392. SYSTEMTIME systemTime;
  393. GetLocalTime(&systemTime);
  394. WString timeStamp = L"{0}-{1}-{2}_{3}-{4}";
  395. timeStamp = StringUtil::format(timeStamp, systemTime.wYear, systemTime.wMonth, systemTime.wDay,
  396. systemTime.wHour, systemTime.wMinute);
  397. WString folderName = StringUtil::format(CrashReportFolder, timeStamp);
  398. return FileSystem::getWorkingDirectoryPath() + folderName;
  399. }
  400. String CrashHandler::getStackTrace()
  401. {
  402. CONTEXT context;
  403. RtlCaptureContext(&context);
  404. win32_initPSAPI();
  405. win32_loadSymbols();
  406. return win32_getStackTrace(context, 2);
  407. }
  408. CrashHandler& gCrashHandler()
  409. {
  410. return CrashHandler::instance();
  411. }
  412. }