crash_handler_windows_seh.cpp 8.9 KB

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