crash_handler_windows_seh.cpp 8.4 KB

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