crash_handler_win.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*************************************************************************/
  2. /* crash_handler_win.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "core/project_settings.h"
  31. #include "main/main.h"
  32. #include "os_windows.h"
  33. #ifdef CRASH_HANDLER_EXCEPTION
  34. // Backtrace code code based on: https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app
  35. #include <psapi.h>
  36. #include <algorithm>
  37. #include <iterator>
  38. #pragma comment(lib, "psapi.lib")
  39. #pragma comment(lib, "dbghelp.lib")
  40. // Some versions of imagehlp.dll lack the proper packing directives themselves
  41. // so we need to do it.
  42. #pragma pack(push, before_imagehlp, 8)
  43. #include <imagehlp.h>
  44. #pragma pack(pop, before_imagehlp)
  45. struct module_data {
  46. std::string image_name;
  47. std::string module_name;
  48. void *base_address;
  49. DWORD load_size;
  50. };
  51. class symbol {
  52. typedef IMAGEHLP_SYMBOL64 sym_type;
  53. sym_type *sym;
  54. static const int max_name_len = 1024;
  55. public:
  56. symbol(HANDLE process, DWORD64 address) :
  57. sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {
  58. memset(sym, '\0', sizeof(*sym) + max_name_len);
  59. sym->SizeOfStruct = sizeof(*sym);
  60. sym->MaxNameLength = max_name_len;
  61. DWORD64 displacement;
  62. SymGetSymFromAddr64(process, address, &displacement, sym);
  63. }
  64. std::string name() { return std::string(sym->Name); }
  65. std::string undecorated_name() {
  66. if (*sym->Name == '\0')
  67. return "<couldn't map PC to fn name>";
  68. std::vector<char> und_name(max_name_len);
  69. UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);
  70. return std::string(&und_name[0], strlen(&und_name[0]));
  71. }
  72. };
  73. class get_mod_info {
  74. HANDLE process;
  75. public:
  76. get_mod_info(HANDLE h) :
  77. process(h) {}
  78. module_data operator()(HMODULE module) {
  79. module_data ret;
  80. char temp[4096];
  81. MODULEINFO mi;
  82. GetModuleInformation(process, module, &mi, sizeof(mi));
  83. ret.base_address = mi.lpBaseOfDll;
  84. ret.load_size = mi.SizeOfImage;
  85. GetModuleFileNameEx(process, module, temp, sizeof(temp));
  86. ret.image_name = temp;
  87. GetModuleBaseName(process, module, temp, sizeof(temp));
  88. ret.module_name = temp;
  89. std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
  90. std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
  91. SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);
  92. return ret;
  93. }
  94. };
  95. DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) {
  96. HANDLE process = GetCurrentProcess();
  97. HANDLE hThread = GetCurrentThread();
  98. DWORD offset_from_symbol = 0;
  99. IMAGEHLP_LINE64 line = { 0 };
  100. std::vector<module_data> modules;
  101. DWORD cbNeeded;
  102. std::vector<HMODULE> module_handles(1);
  103. if (OS::get_singleton() == NULL || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) {
  104. return EXCEPTION_CONTINUE_SEARCH;
  105. }
  106. fprintf(stderr, "%s: Program crashed\n", __FUNCTION__);
  107. if (OS::get_singleton()->get_main_loop())
  108. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH);
  109. // Load the symbols:
  110. if (!SymInitialize(process, NULL, false))
  111. return EXCEPTION_CONTINUE_SEARCH;
  112. SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);
  113. EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
  114. module_handles.resize(cbNeeded / sizeof(HMODULE));
  115. EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
  116. std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));
  117. void *base = modules[0].base_address;
  118. // Setup stuff:
  119. CONTEXT *context = ep->ContextRecord;
  120. STACKFRAME64 frame;
  121. bool skip_first = false;
  122. frame.AddrPC.Mode = AddrModeFlat;
  123. frame.AddrStack.Mode = AddrModeFlat;
  124. frame.AddrFrame.Mode = AddrModeFlat;
  125. #ifdef _M_X64
  126. frame.AddrPC.Offset = context->Rip;
  127. frame.AddrStack.Offset = context->Rsp;
  128. frame.AddrFrame.Offset = context->Rbp;
  129. #else
  130. frame.AddrPC.Offset = context->Eip;
  131. frame.AddrStack.Offset = context->Esp;
  132. frame.AddrFrame.Offset = context->Ebp;
  133. // Skip the first one to avoid a duplicate on 32-bit mode
  134. skip_first = true;
  135. #endif
  136. line.SizeOfStruct = sizeof(line);
  137. IMAGE_NT_HEADERS *h = ImageNtHeader(base);
  138. DWORD image_type = h->FileHeader.Machine;
  139. int n = 0;
  140. String msg = GLOBAL_GET("debug/settings/crash_handler/message");
  141. fprintf(stderr, "Dumping the backtrace. %ls\n", msg.c_str());
  142. do {
  143. if (skip_first) {
  144. skip_first = false;
  145. } else {
  146. if (frame.AddrPC.Offset != 0) {
  147. std::string fnName = symbol(process, frame.AddrPC.Offset).undecorated_name();
  148. if (SymGetLineFromAddr64(process, frame.AddrPC.Offset, &offset_from_symbol, &line))
  149. fprintf(stderr, "[%d] %s (%s:%d)\n", n, fnName.c_str(), line.FileName, line.LineNumber);
  150. else
  151. fprintf(stderr, "[%d] %s\n", n, fnName.c_str());
  152. } else
  153. fprintf(stderr, "[%d] ???\n", n);
  154. n++;
  155. }
  156. if (!StackWalk64(image_type, process, hThread, &frame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
  157. break;
  158. } while (frame.AddrReturn.Offset != 0 && n < 256);
  159. fprintf(stderr, "-- END OF BACKTRACE --\n");
  160. SymCleanup(process);
  161. // Pass the exception to the OS
  162. return EXCEPTION_CONTINUE_SEARCH;
  163. }
  164. #endif
  165. CrashHandler::CrashHandler() {
  166. disabled = false;
  167. }
  168. CrashHandler::~CrashHandler() {
  169. }
  170. void CrashHandler::disable() {
  171. if (disabled)
  172. return;
  173. disabled = true;
  174. }
  175. void CrashHandler::initialize() {
  176. }