Path: blob/master/platform/windows/crash_handler_windows_seh.cpp
11352 views
/**************************************************************************/1/* crash_handler_windows_seh.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "crash_handler_windows.h"3132#include "core/config/project_settings.h"33#include "core/object/script_language.h"34#include "core/os/main_loop.h"35#include "core/os/os.h"36#include "core/string/print_string.h"37#include "core/version.h"38#include "main/main.h"3940#ifdef CRASH_HANDLER_EXCEPTION4142// Backtrace code based on: https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app4344#include <algorithm>45#include <cstdlib>46#include <iterator>47#include <string>48#include <vector>4950#include <psapi.h>5152// Some versions of imagehlp.dll lack the proper packing directives themselves53// so we need to do it.54#pragma pack(push, before_imagehlp, 8)55#include <imagehlp.h>56#pragma pack(pop, before_imagehlp)5758struct module_data {59std::string image_name;60std::string module_name;61void *base_address = nullptr;62DWORD load_size;63};6465class symbol {66typedef IMAGEHLP_SYMBOL64 sym_type;67sym_type *sym;68static const int max_name_len = 1024;6970public:71symbol(HANDLE process, DWORD64 address) :72sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {73memset(sym, '\0', sizeof(*sym) + max_name_len);74sym->SizeOfStruct = sizeof(*sym);75sym->MaxNameLength = max_name_len;76DWORD64 displacement;7778SymGetSymFromAddr64(process, address, &displacement, sym);79}8081std::string name() { return std::string(sym->Name); }82std::string undecorated_name() {83if (*sym->Name == '\0') {84return "<couldn't map PC to fn name>";85}86std::vector<char> und_name(max_name_len);87UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);88return std::string(&und_name[0], strlen(&und_name[0]));89}90};9192class get_mod_info {93HANDLE process;9495public:96get_mod_info(HANDLE h) :97process(h) {}9899module_data operator()(HMODULE module) {100module_data ret;101char temp[4096];102MODULEINFO mi;103104GetModuleInformation(process, module, &mi, sizeof(mi));105ret.base_address = mi.lpBaseOfDll;106ret.load_size = mi.SizeOfImage;107108GetModuleFileNameEx(process, module, temp, sizeof(temp));109ret.image_name = temp;110GetModuleBaseName(process, module, temp, sizeof(temp));111ret.module_name = temp;112std::vector<char> img(ret.image_name.begin(), ret.image_name.end());113std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());114SymLoadModule64(process, nullptr, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);115return ret;116}117};118119DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) {120HANDLE process = GetCurrentProcess();121HANDLE hThread = GetCurrentThread();122DWORD offset_from_symbol = 0;123IMAGEHLP_LINE64 line = {};124std::vector<module_data> modules;125DWORD cbNeeded;126std::vector<HMODULE> module_handles(1);127128if (OS::get_singleton() == nullptr || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) {129return EXCEPTION_CONTINUE_SEARCH;130}131132if (OS::get_singleton()->is_crash_handler_silent()) {133std::_Exit(0);134}135136String msg;137if (ProjectSettings::get_singleton()) {138msg = GLOBAL_GET("debug/settings/crash_handler/message");139}140141// Tell MainLoop about the crash. This can be handled by users too in Node.142if (OS::get_singleton()->get_main_loop()) {143OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH);144}145146print_error("\n================================================================");147print_error(vformat("%s: Program crashed", __FUNCTION__));148149// Print the engine version just before, so that people are reminded to include the version in backtrace reports.150if (String(GODOT_VERSION_HASH).is_empty()) {151print_error(vformat("Engine version: %s", GODOT_VERSION_FULL_NAME));152} else {153print_error(vformat("Engine version: %s (%s)", GODOT_VERSION_FULL_NAME, GODOT_VERSION_HASH));154}155print_error(vformat("Dumping the backtrace. %s", msg));156157// Load the symbols:158if (!SymInitialize(process, nullptr, false)) {159return EXCEPTION_CONTINUE_SEARCH;160}161162SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME | SYMOPT_EXACT_SYMBOLS);163EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);164module_handles.resize(cbNeeded / sizeof(HMODULE));165EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);166std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));167void *base = modules[0].base_address;168169// Setup stuff:170CONTEXT *context = ep->ContextRecord;171STACKFRAME64 frame;172bool skip_first = false;173174frame.AddrPC.Mode = AddrModeFlat;175frame.AddrStack.Mode = AddrModeFlat;176frame.AddrFrame.Mode = AddrModeFlat;177178#if defined(_M_X64)179frame.AddrPC.Offset = context->Rip;180frame.AddrStack.Offset = context->Rsp;181frame.AddrFrame.Offset = context->Rbp;182#elif defined(_M_ARM64) || defined(_M_ARM64EC)183frame.AddrPC.Offset = context->Pc;184frame.AddrStack.Offset = context->Sp;185frame.AddrFrame.Offset = context->Fp;186#elif defined(_M_ARM)187frame.AddrPC.Offset = context->Pc;188frame.AddrStack.Offset = context->Sp;189frame.AddrFrame.Offset = context->R11;190#else191frame.AddrPC.Offset = context->Eip;192frame.AddrStack.Offset = context->Esp;193frame.AddrFrame.Offset = context->Ebp;194195// Skip the first one to avoid a duplicate on 32-bit mode196skip_first = true;197#endif198199line.SizeOfStruct = sizeof(line);200IMAGE_NT_HEADERS *h = ImageNtHeader(base);201DWORD image_type = h->FileHeader.Machine;202203int n = 0;204do {205if (skip_first) {206skip_first = false;207} else {208if (frame.AddrPC.Offset != 0) {209std::string fnName = symbol(process, frame.AddrPC.Offset).undecorated_name();210211if (SymGetLineFromAddr64(process, frame.AddrPC.Offset, &offset_from_symbol, &line)) {212print_error(vformat("[%d] %s (%s:%d)", n, fnName.c_str(), (char *)line.FileName, (int)line.LineNumber));213} else {214print_error(vformat("[%d] %s", n, fnName.c_str()));215}216} else {217print_error(vformat("[%d] ???", n));218}219220n++;221}222223if (!StackWalk64(image_type, process, hThread, &frame, context, nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) {224break;225}226} while (frame.AddrReturn.Offset != 0 && n < 256);227228print_error("-- END OF C++ BACKTRACE --");229print_error("================================================================");230231SymCleanup(process);232233for (const Ref<ScriptBacktrace> &backtrace : ScriptServer::capture_script_backtraces(false)) {234if (!backtrace->is_empty()) {235print_error(backtrace->format());236print_error(vformat("-- END OF %s BACKTRACE --", backtrace->get_language_name().to_upper()));237print_error("================================================================");238}239}240241// Pass the exception to the OS242return EXCEPTION_CONTINUE_SEARCH;243}244#endif245246CrashHandler::CrashHandler() {247disabled = false;248}249250CrashHandler::~CrashHandler() {251}252253void CrashHandler::disable() {254if (disabled) {255return;256}257258disabled = true;259}260261void CrashHandler::initialize() {262}263264265