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 Apr 22, 2024
1 parent 7529c0b commit c1b3467
Show file tree
Hide file tree
Showing 28 changed files with 7,854 additions and 4 deletions.
5 changes: 5 additions & 0 deletions COPYRIGHT.txt
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,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/libktx/
Comment: KTX
Copyright: 2013-2020, Mark Callow
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)
6 changes: 5 additions & 1 deletion platform/windows/SCsub
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ sources = []

common_win = [
"godot_windows.cpp",
"crash_handler_windows.cpp",
"os_windows.cpp",
"display_server_windows.cpp",
"key_mapping_windows.cpp",
Expand All @@ -25,6 +24,11 @@ common_win = [
"rendering_context_driver_vulkan_windows.cpp",
]

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

common_win_wrap = [
"console_wrapper_windows.cpp",
]
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(_MSC_VER)
#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
205 changes: 205 additions & 0 deletions platform/windows/crash_handler_windows_signal.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/**************************************************************************/
/* crash_handler_windows_signal.cpp */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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;

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
}
3 changes: 3 additions & 0 deletions platform/windows/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,9 @@ def spawn_capture(sh, escape, cmd, args, env):
LIBS += ["dxgi", "d3d9", "d3d11"]
env.Prepend(CPPPATH=["#thirdparty/angle/include"])

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
2 changes: 1 addition & 1 deletion platform/windows/godot_windows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,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
12 changes: 12 additions & 0 deletions thirdparty/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,18 @@ Files extracted from upstream source:
- `jpge*.{c,h}`


## libbacktrace

- Upstream: https://github.com/ianlancetaylor/libbacktrace
- Version: git (4d2dd0b172f2c9192f83ba93425f868f2a13c553, 2022)
- License: BSD-3-Clause

Files extracted from upstream source:

- `*.{c,h}` files for Windows platform
- `LICENSE`


## libktx

- Upstream: https://github.com/KhronosGroup/KTX-Software
Expand Down
29 changes: 29 additions & 0 deletions thirdparty/libbacktrace/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright (C) 2012-2016 Free Software Foundation, Inc.

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:

# (1) Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.

# (2) Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.

# (3) The name of the author may not be used to
# endorse or promote products derived from this software without
# specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
Loading

0 comments on commit c1b3467

Please sign in to comment.