crash_handler_windows.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. /*************************************************************************/
  2. /* crash_handler_windows.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "crash_handler_windows.h"
  31. #include "core/os/os.h"
  32. #include "core/project_settings.h"
  33. #include "core/version.h"
  34. #include "core/version_hash.gen.h"
  35. #include "main/main.h"
  36. #ifdef CRASH_HANDLER_EXCEPTION
  37. // Backtrace code code based on: https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app
  38. #include <algorithm>
  39. #include <iterator>
  40. #include <string>
  41. #include <vector>
  42. #include <psapi.h>
  43. #pragma comment(lib, "psapi.lib")
  44. #pragma comment(lib, "dbghelp.lib")
  45. // Some versions of imagehlp.dll lack the proper packing directives themselves
  46. // so we need to do it.
  47. #pragma pack(push, before_imagehlp, 8)
  48. #include <imagehlp.h>
  49. #pragma pack(pop, before_imagehlp)
  50. struct module_data {
  51. std::string image_name;
  52. std::string module_name;
  53. void *base_address;
  54. DWORD load_size;
  55. };
  56. class symbol {
  57. typedef IMAGEHLP_SYMBOL64 sym_type;
  58. sym_type *sym;
  59. static const int max_name_len = 1024;
  60. public:
  61. symbol(HANDLE process, DWORD64 address) :
  62. sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {
  63. memset(sym, '\0', sizeof(*sym) + max_name_len);
  64. sym->SizeOfStruct = sizeof(*sym);
  65. sym->MaxNameLength = max_name_len;
  66. DWORD64 displacement;
  67. SymGetSymFromAddr64(process, address, &displacement, sym);
  68. }
  69. std::string name() { return std::string(sym->Name); }
  70. std::string undecorated_name() {
  71. if (*sym->Name == '\0')
  72. return "<couldn't map PC to fn name>";
  73. std::vector<char> und_name(max_name_len);
  74. UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);
  75. return std::string(&und_name[0], strlen(&und_name[0]));
  76. }
  77. };
  78. class get_mod_info {
  79. HANDLE process;
  80. public:
  81. get_mod_info(HANDLE h) :
  82. process(h) {}
  83. module_data operator()(HMODULE module) {
  84. module_data ret;
  85. char temp[4096];
  86. MODULEINFO mi;
  87. GetModuleInformation(process, module, &mi, sizeof(mi));
  88. ret.base_address = mi.lpBaseOfDll;
  89. ret.load_size = mi.SizeOfImage;
  90. GetModuleFileNameEx(process, module, temp, sizeof(temp));
  91. ret.image_name = temp;
  92. GetModuleBaseName(process, module, temp, sizeof(temp));
  93. ret.module_name = temp;
  94. std::vector<char> img(ret.image_name.begin(), ret.image_name.end());
  95. std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());
  96. SymLoadModule64(process, 0, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);
  97. return ret;
  98. }
  99. };
  100. DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) {
  101. HANDLE process = GetCurrentProcess();
  102. HANDLE hThread = GetCurrentThread();
  103. DWORD offset_from_symbol = 0;
  104. IMAGEHLP_LINE64 line = { 0 };
  105. std::vector<module_data> modules;
  106. DWORD cbNeeded;
  107. std::vector<HMODULE> module_handles(1);
  108. if (OS::get_singleton() == NULL || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) {
  109. return EXCEPTION_CONTINUE_SEARCH;
  110. }
  111. fprintf(stderr, "\n================================================================\n");
  112. fprintf(stderr, "%s: Program crashed\n", __FUNCTION__);
  113. if (OS::get_singleton()->get_main_loop())
  114. OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH);
  115. // Load the symbols:
  116. if (!SymInitialize(process, NULL, false))
  117. return EXCEPTION_CONTINUE_SEARCH;
  118. SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME);
  119. EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
  120. module_handles.resize(cbNeeded / sizeof(HMODULE));
  121. EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);
  122. std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));
  123. void *base = modules[0].base_address;
  124. // Setup stuff:
  125. CONTEXT *context = ep->ContextRecord;
  126. STACKFRAME64 frame;
  127. bool skip_first = false;
  128. frame.AddrPC.Mode = AddrModeFlat;
  129. frame.AddrStack.Mode = AddrModeFlat;
  130. frame.AddrFrame.Mode = AddrModeFlat;
  131. #ifdef _M_X64
  132. frame.AddrPC.Offset = context->Rip;
  133. frame.AddrStack.Offset = context->Rsp;
  134. frame.AddrFrame.Offset = context->Rbp;
  135. #else
  136. frame.AddrPC.Offset = context->Eip;
  137. frame.AddrStack.Offset = context->Esp;
  138. frame.AddrFrame.Offset = context->Ebp;
  139. // Skip the first one to avoid a duplicate on 32-bit mode
  140. skip_first = true;
  141. #endif
  142. line.SizeOfStruct = sizeof(line);
  143. IMAGE_NT_HEADERS *h = ImageNtHeader(base);
  144. DWORD image_type = h->FileHeader.Machine;
  145. String msg;
  146. const ProjectSettings *proj_settings = ProjectSettings::get_singleton();
  147. if (proj_settings) {
  148. msg = proj_settings->get("debug/settings/crash_handler/message");
  149. }
  150. // Print the engine version just before, so that people are reminded to include the version in backtrace reports.
  151. if (String(VERSION_HASH).length() != 0) {
  152. fprintf(stderr, "Engine version: " VERSION_FULL_NAME " (" VERSION_HASH ")\n");
  153. } else {
  154. fprintf(stderr, "Engine version: " VERSION_FULL_NAME "\n");
  155. }
  156. fprintf(stderr, "Dumping the backtrace. %ls\n", msg.c_str());
  157. int n = 0;
  158. do {
  159. if (skip_first) {
  160. skip_first = false;
  161. } else {
  162. if (frame.AddrPC.Offset != 0) {
  163. std::string fnName = symbol(process, frame.AddrPC.Offset).undecorated_name();
  164. if (SymGetLineFromAddr64(process, frame.AddrPC.Offset, &offset_from_symbol, &line))
  165. fprintf(stderr, "[%d] %s (%s:%d)\n", n, fnName.c_str(), line.FileName, line.LineNumber);
  166. else
  167. fprintf(stderr, "[%d] %s\n", n, fnName.c_str());
  168. } else
  169. fprintf(stderr, "[%d] ???\n", n);
  170. n++;
  171. }
  172. if (!StackWalk64(image_type, process, hThread, &frame, context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL))
  173. break;
  174. } while (frame.AddrReturn.Offset != 0 && n < 256);
  175. fprintf(stderr, "-- END OF BACKTRACE --\n");
  176. fprintf(stderr, "================================================================\n");
  177. SymCleanup(process);
  178. // Pass the exception to the OS
  179. return EXCEPTION_CONTINUE_SEARCH;
  180. }
  181. #endif
  182. CrashHandler::CrashHandler() {
  183. disabled = false;
  184. }
  185. CrashHandler::~CrashHandler() {
  186. }
  187. void CrashHandler::disable() {
  188. if (disabled)
  189. return;
  190. disabled = true;
  191. }
  192. void CrashHandler::initialize() {
  193. }