Skip to content

Commit

Permalink
[Windows] Enable crash reporter on MinGW builds, use libbacktrace to…
Browse files Browse the repository at this point in the history
… generate stack trace from DWARF symbols.
  • Loading branch information
bruvzg committed Oct 11, 2022
1 parent e413d1c commit 1563368
Show file tree
Hide file tree
Showing 29 changed files with 7,865 additions and 14 deletions.
5 changes: 5 additions & 0 deletions COPYRIGHT.txt
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,11 @@ Comment: jpeg-compressor
Copyright: 2012, Rich Geldreich
License: public-domain or Apache-2.0

Files: ./thirdparty/libbacktrace/
Comment: libbacktrace
Copyright: 2012-2021, Free Software Foundation, Inc.
License: BSD-3-clause

Files: ./thirdparty/libogg/
Comment: OggVorbis
Copyright: 2002, Xiph.org Foundation
Expand Down
2 changes: 2 additions & 0 deletions drivers/SCsub
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ SConscript("coreaudio/SCsub")
SConscript("pulseaudio/SCsub")
if env["platform"] == "windows":
SConscript("wasapi/SCsub")
if not env.msvc:
SConscript("backtrace/SCsub")
if env["xaudio2"]:
SConscript("xaudio2/SCsub")

Expand Down
44 changes: 44 additions & 0 deletions drivers/backtrace/SCsub
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env python

Import("env")

env_backtrace = env.Clone()

# Thirdparty source files

thirdparty_obj = []

thirdparty_dir = "#thirdparty/libbacktrace/"
thirdparty_sources = [
"atomic.c",
"dwarf.c",
"fileline.c",
"posix.c",
"print.c",
"sort.c",
"state.c",
"backtrace.c",
"simple.c",
"pecoff.c",
"read.c",
"alloc.c",
]
thirdparty_sources = [thirdparty_dir + file for file in thirdparty_sources]

env_backtrace.Prepend(CPPPATH=[thirdparty_dir])

env_thirdparty = env_backtrace.Clone()
env_thirdparty.disable_warnings()
env_thirdparty.add_source_files(thirdparty_obj, thirdparty_sources)

env.drivers_sources += thirdparty_obj

# Godot source files

driver_obj = []

env_backtrace.add_source_files(driver_obj, "*.cpp")
env.drivers_sources += driver_obj

# Needed to force rebuilding the driver files when the thirdparty library is updated.
env.Depends(driver_obj, thirdparty_obj)
2 changes: 1 addition & 1 deletion drivers/unix/file_access_unix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
#include <unistd.h>
#endif

#ifdef MSVC
#ifdef _MSC_VER
#define S_ISREG(m) ((m)&_S_IFREG)
#include <io.h>
#endif
Expand Down
6 changes: 5 additions & 1 deletion platform/windows/SCsub
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import platform_windows_builders

common_win = [
"godot_windows.cpp",
"crash_handler_windows.cpp",
"os_windows.cpp",
"display_server_windows.cpp",
"key_mapping_windows.cpp",
Expand All @@ -19,6 +18,11 @@ common_win = [
"gl_manager_windows.cpp",
]

if env.msvc:
common_win += ["crash_handler_windows_seh.cpp"]
else:
common_win += ["crash_handler_windows_signal.cpp"]

res_file = "godot_res.rc"
res_target = "godot_res" + env["OBJSUFFIX"]
res_obj = env.RES(res_target, res_file)
Expand Down
5 changes: 4 additions & 1 deletion platform/windows/crash_handler_windows.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@
#include <windows.h>

// Crash handler exception only enabled with MSVC
#if defined(DEBUG_ENABLED) && defined(MSVC)
#if defined(DEBUG_ENABLED)
#define CRASH_HANDLER_EXCEPTION 1

#ifdef _MSC_VER
extern DWORD CrashHandlerException(EXCEPTION_POINTERS *ep);
#endif

#endif

class CrashHandler {
bool disabled;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*************************************************************************/
/* crash_handler_windows.cpp */
/* crash_handler_windows_seh.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
Expand Down Expand Up @@ -47,9 +47,6 @@

#include <psapi.h>

#pragma comment(lib, "psapi.lib")
#pragma comment(lib, "dbghelp.lib")

// Some versions of imagehlp.dll lack the proper packing directives themselves
// so we need to do it.
#pragma pack(push, before_imagehlp, 8)
Expand Down
208 changes: 208 additions & 0 deletions platform/windows/crash_handler_windows_signal.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*************************************************************************/
/* crash_handler_windows_signal.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/

#include "crash_handler_windows.h"

#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/string/print_string.h"
#include "core/version.h"
#include "main/main.h"

#ifdef CRASH_HANDLER_EXCEPTION

#include <cxxabi.h>
#include <signal.h>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

#include <psapi.h>

#include "thirdparty/libbacktrace/backtrace.h"

struct CrashHandlerData {
int64_t index = 0;
backtrace_state *state = nullptr;
int64_t offset = 0;
};

int symbol_callback(void *data, uintptr_t pc, const char *filename, int lineno, const char *function) {
CrashHandlerData *ch_data = reinterpret_cast<CrashHandlerData *>(data);
if (!function) {
return 0;
}

char fname[1024];
snprintf(fname, 1024, "%s", function);

if (function[0] == '_') {
int status;
char *demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status);

if (status == 0 && demangled) {
snprintf(fname, 1024, "%s", demangled);
}

if (demangled) {
free(demangled);
}
}

print_error(vformat("[%d] %s (%s:%d)", ch_data->index++, String::utf8(fname), String::utf8(filename), lineno));
return 0;
}

void error_callback(void *data, const char *msg, int errnum) {
CrashHandlerData *ch_data = reinterpret_cast<CrashHandlerData *>(data);
if (ch_data->index == 0) {
print_error(vformat("Error(%d): %s", errnum, String::utf8(msg)));
} else {
print_error(vformat("[%d] error(%d): %s", ch_data->index++, errnum, String::utf8(msg)));
}
}

int trace_callback(void *data, uintptr_t pc) {
CrashHandlerData *ch_data = reinterpret_cast<CrashHandlerData *>(data);
backtrace_pcinfo(ch_data->state, pc - ch_data->offset, &symbol_callback, &error_callback, data);
return 0;
}

int64_t get_image_base(const String &p_path) {
Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
if (f.is_null()) {
return 0;
}
{
f->seek(0x3c);
uint32_t pe_pos = f->get_32();

f->seek(pe_pos);
uint32_t magic = f->get_32();
if (magic != 0x00004550) {
return 0;
}
}
int64_t opt_header_pos = f->get_position() + 0x14;
f->seek(opt_header_pos);

uint16_t opt_header_magic = f->get_16();
if (opt_header_magic == 0x10B) {
f->seek(opt_header_pos + 0x1C);
return f->get_32();
} else if (opt_header_magic == 0x20B) {
f->seek(opt_header_pos + 0x18);
return f->get_64();
} else {
return 0;
}
}

extern void CrashHandlerException(int signal) {
CrashHandlerData data;

if (OS::get_singleton() == nullptr || OS::get_singleton()->is_disable_crash_handler() || IsDebuggerPresent()) {
return;
}

String msg;
const ProjectSettings *proj_settings = ProjectSettings::get_singleton();
if (proj_settings) {
msg = proj_settings->get("debug/settings/crash_handler/message");
}

// Tell MainLoop about the crash. This can be handled by users too in Node.
if (OS::get_singleton()->get_main_loop()) {
OS::get_singleton()->get_main_loop()->notification(MainLoop::NOTIFICATION_CRASH);
}

print_error("\n================================================================");
print_error(vformat("%s: Program crashed with signal %d", __FUNCTION__, signal));

// Print the engine version just before, so that people are reminded to include the version in backtrace reports.
if (String(VERSION_HASH).is_empty()) {
print_error(vformat("Engine version: %s", VERSION_FULL_NAME));
} else {
print_error(vformat("Engine version: %s (%s)", VERSION_FULL_NAME, VERSION_HASH));
}
print_error(vformat("Dumping the backtrace. %s", msg));

String _execpath = OS::get_singleton()->get_executable_path();

// Load process and image info to determine ASLR addresses offset.
MODULEINFO mi;
GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &mi, sizeof(mi));
int64_t image_mem_base = reinterpret_cast<int64_t>(mi.lpBaseOfDll);
int64_t image_file_base = get_image_base(_execpath);
data.offset = image_mem_base - image_file_base;

print_error(vformat("Image memory base: 0x%x, image file base: 0x%x", image_mem_base, image_file_base));
print_error(vformat("Dumping the backtrace. %s", msg));

data.state = backtrace_create_state(_execpath.utf8().get_data(), 0, &error_callback, reinterpret_cast<void *>(&data));
if (data.state != nullptr) {
data.index = 1;
backtrace_simple(data.state, 1, &trace_callback, &error_callback, reinterpret_cast<void *>(&data));
}

print_error("-- END OF BACKTRACE --");
print_error("================================================================");
}
#endif

CrashHandler::CrashHandler() {
disabled = false;
}

CrashHandler::~CrashHandler() {
}

void CrashHandler::disable() {
if (disabled) {
return;
}

#if defined(CRASH_HANDLER_EXCEPTION)
signal(SIGSEGV, nullptr);
signal(SIGFPE, nullptr);
signal(SIGILL, nullptr);
#endif

disabled = true;
}

void CrashHandler::initialize() {
#if defined(CRASH_HANDLER_EXCEPTION)
signal(SIGSEGV, CrashHandlerException);
signal(SIGFPE, CrashHandlerException);
signal(SIGILL, CrashHandlerException);
#endif
}
16 changes: 10 additions & 6 deletions platform/windows/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,6 @@ def configure_msvc(env, vcvars_msvc_config):
"WINMIDI_ENABLED",
"TYPED_METHOD_BIND",
"WIN32",
"MSVC",
"WINVER=%s" % env["target_win_version"],
"_WIN32_WINNT=%s" % env["target_win_version"],
]
Expand Down Expand Up @@ -412,6 +411,9 @@ def configure_msvc(env, vcvars_msvc_config):
env.AppendUnique(CPPDEFINES=["GLES3_ENABLED"])
LIBS += ["opengl32"]

if env["target"] in ["editor", "template_debug"]:
LIBS += ["psapi", "dbghelp"]

env.Append(LINKFLAGS=[p + env["LIBSUFFIX"] for p in LIBS])

if vcvars_msvc_config:
Expand Down Expand Up @@ -580,12 +582,14 @@ def configure_mingw(env):
]
)

env.Append(CPPDEFINES=["VULKAN_ENABLED"])
if not env["use_volk"]:
env.Append(LIBS=["vulkan"])
if env["vulkan"]:
env.Append(CPPDEFINES=["VULKAN_ENABLED"])
if not env["use_volk"]:
env.Append(LIBS=["vulkan"])

env.Append(CPPDEFINES=["GLES3_ENABLED"])
env.Append(LIBS=["opengl32"])
if env["opengl3"]:
env.Append(CPPDEFINES=["GLES3_ENABLED"])
env.Append(LIBS=["opengl32"])

env.Append(CPPDEFINES=["MINGW_ENABLED", ("MINGW_HAS_SECURE_API", 1)])

Expand Down
2 changes: 1 addition & 1 deletion platform/windows/godot_windows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ int main(int argc, char **argv) {

// _argc and _argv are ignored
// we are going to use the WideChar version of them instead
#ifdef CRASH_HANDLER_EXCEPTION
#if defined(CRASH_HANDLER_EXCEPTION) && defined(_MSC_VER)
__try {
return _main();
} __except (CrashHandlerException(GetExceptionInformation())) {
Expand Down
Loading

0 comments on commit 1563368

Please sign in to comment.