Path: blob/master/platform/windows/crash_handler_windows_seh.cpp
10277 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/os.h"35#include "core/string/print_string.h"36#include "core/version.h"37#include "main/main.h"3839#ifdef CRASH_HANDLER_EXCEPTION4041// Backtrace code based on: https://stackoverflow.com/questions/6205981/windows-c-stack-trace-from-a-running-app4243#include <algorithm>44#include <cstdlib>45#include <iterator>46#include <string>47#include <vector>4849#include <psapi.h>5051// Some versions of imagehlp.dll lack the proper packing directives themselves52// so we need to do it.53#pragma pack(push, before_imagehlp, 8)54#include <imagehlp.h>55#pragma pack(pop, before_imagehlp)5657struct module_data {58std::string image_name;59std::string module_name;60void *base_address = nullptr;61DWORD load_size;62};6364class symbol {65typedef IMAGEHLP_SYMBOL64 sym_type;66sym_type *sym;67static const int max_name_len = 1024;6869public:70symbol(HANDLE process, DWORD64 address) :71sym((sym_type *)::operator new(sizeof(*sym) + max_name_len)) {72memset(sym, '\0', sizeof(*sym) + max_name_len);73sym->SizeOfStruct = sizeof(*sym);74sym->MaxNameLength = max_name_len;75DWORD64 displacement;7677SymGetSymFromAddr64(process, address, &displacement, sym);78}7980std::string name() { return std::string(sym->Name); }81std::string undecorated_name() {82if (*sym->Name == '\0') {83return "<couldn't map PC to fn name>";84}85std::vector<char> und_name(max_name_len);86UnDecorateSymbolName(sym->Name, &und_name[0], max_name_len, UNDNAME_COMPLETE);87return std::string(&und_name[0], strlen(&und_name[0]));88}89};9091class get_mod_info {92HANDLE process;9394public:95get_mod_info(HANDLE h) :96process(h) {}9798module_data operator()(HMODULE module) {99module_data ret;100char temp[4096];101MODULEINFO mi;102103GetModuleInformation(process, module, &mi, sizeof(mi));104ret.base_address = mi.lpBaseOfDll;105ret.load_size = mi.SizeOfImage;106107GetModuleFileNameEx(process, module, temp, sizeof(temp));108ret.image_name = temp;109GetModuleBaseName(process, module, temp, sizeof(temp));110ret.module_name = temp;111std::vector<char> img(ret.image_name.begin(), ret.image_name.end());112std::vector<char> mod(ret.module_name.begin(), ret.module_name.end());113SymLoadModule64(process, nullptr, &img[0], &mod[0], (DWORD64)ret.base_address, ret.load_size);114return ret;115}116};117118DWORD CrashHandlerException(EXCEPTION_POINTERS *ep) {119HANDLE process = GetCurrentProcess();120HANDLE hThread = GetCurrentThread();121DWORD offset_from_symbol = 0;122IMAGEHLP_LINE64 line = {};123std::vector<module_data> modules;124DWORD cbNeeded;125std::vector<HMODULE> module_handles(1);126127if (OS::get_singleton() == nullptr || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) {128return EXCEPTION_CONTINUE_SEARCH;129}130131if (OS::get_singleton()->is_crash_handler_silent()) {132std::_Exit(0);133}134135String msg;136if (ProjectSettings::get_singleton()) {137msg = GLOBAL_GET("debug/settings/crash_handler/message");138}139140// Tell MainLoop about the crash. This can be handled by users too in Node.141if (OS::get_singleton()->get_main_loop()) {142OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH);143}144145print_error("\n================================================================");146print_error(vformat("%s: Program crashed", __FUNCTION__));147148// Print the engine version just before, so that people are reminded to include the version in backtrace reports.149if (String(GODOT_VERSION_HASH).is_empty()) {150print_error(vformat("Engine version: %s", GODOT_VERSION_FULL_NAME));151} else {152print_error(vformat("Engine version: %s (%s)", GODOT_VERSION_FULL_NAME, GODOT_VERSION_HASH));153}154print_error(vformat("Dumping the backtrace. %s", msg));155156// Load the symbols:157if (!SymInitialize(process, nullptr, false)) {158return EXCEPTION_CONTINUE_SEARCH;159}160161SymSetOptions(SymGetOptions() | SYMOPT_LOAD_LINES | SYMOPT_UNDNAME | SYMOPT_EXACT_SYMBOLS);162EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);163module_handles.resize(cbNeeded / sizeof(HMODULE));164EnumProcessModules(process, &module_handles[0], module_handles.size() * sizeof(HMODULE), &cbNeeded);165std::transform(module_handles.begin(), module_handles.end(), std::back_inserter(modules), get_mod_info(process));166void *base = modules[0].base_address;167168// Setup stuff:169CONTEXT *context = ep->ContextRecord;170STACKFRAME64 frame;171bool skip_first = false;172173frame.AddrPC.Mode = AddrModeFlat;174frame.AddrStack.Mode = AddrModeFlat;175frame.AddrFrame.Mode = AddrModeFlat;176177#if defined(_M_X64)178frame.AddrPC.Offset = context->Rip;179frame.AddrStack.Offset = context->Rsp;180frame.AddrFrame.Offset = context->Rbp;181#elif defined(_M_ARM64) || defined(_M_ARM64EC)182frame.AddrPC.Offset = context->Pc;183frame.AddrStack.Offset = context->Sp;184frame.AddrFrame.Offset = context->Fp;185#elif defined(_M_ARM)186frame.AddrPC.Offset = context->Pc;187frame.AddrStack.Offset = context->Sp;188frame.AddrFrame.Offset = context->R11;189#else190frame.AddrPC.Offset = context->Eip;191frame.AddrStack.Offset = context->Esp;192frame.AddrFrame.Offset = context->Ebp;193194// Skip the first one to avoid a duplicate on 32-bit mode195skip_first = true;196#endif197198line.SizeOfStruct = sizeof(line);199IMAGE_NT_HEADERS *h = ImageNtHeader(base);200DWORD image_type = h->FileHeader.Machine;201202int n = 0;203do {204if (skip_first) {205skip_first = false;206} else {207if (frame.AddrPC.Offset != 0) {208std::string fnName = symbol(process, frame.AddrPC.Offset).undecorated_name();209210if (SymGetLineFromAddr64(process, frame.AddrPC.Offset, &offset_from_symbol, &line)) {211print_error(vformat("[%d] %s (%s:%d)", n, fnName.c_str(), (char *)line.FileName, (int)line.LineNumber));212} else {213print_error(vformat("[%d] %s", n, fnName.c_str()));214}215} else {216print_error(vformat("[%d] ???", n));217}218219n++;220}221222if (!StackWalk64(image_type, process, hThread, &frame, context, nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) {223break;224}225} while (frame.AddrReturn.Offset != 0 && n < 256);226227print_error("-- END OF C++ BACKTRACE --");228print_error("================================================================");229230SymCleanup(process);231232for (const Ref<ScriptBacktrace> &backtrace : ScriptServer::capture_script_backtraces(false)) {233if (!backtrace->is_empty()) {234print_error(backtrace->format());235print_error(vformat("-- END OF %s BACKTRACE --", backtrace->get_language_name().to_upper()));236print_error("================================================================");237}238}239240// Pass the exception to the OS241return EXCEPTION_CONTINUE_SEARCH;242}243#endif244245CrashHandler::CrashHandler() {246disabled = false;247}248249CrashHandler::~CrashHandler() {250}251252void CrashHandler::disable() {253if (disabled) {254return;255}256257disabled = true;258}259260void CrashHandler::initialize() {261}262263264