Initial library build
This commit is contained in:
90
.gitignore
vendored
Normal file
90
.gitignore
vendored
Normal file
@@ -0,0 +1,90 @@
|
||||
# ---> Qt
|
||||
# C++ objects and libs
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.a
|
||||
*.la
|
||||
*.lai
|
||||
*.so
|
||||
*.so.*
|
||||
*.dll
|
||||
*.dylib
|
||||
|
||||
# Qt-es
|
||||
object_script.*.Release
|
||||
object_script.*.Debug
|
||||
*_plugin_import.cpp
|
||||
/.qmake.cache
|
||||
/.qmake.stash
|
||||
*.pro.user
|
||||
*.pro.user.*
|
||||
*.qbs.user
|
||||
*.qbs.user.*
|
||||
*.moc
|
||||
moc_*.cpp
|
||||
moc_*.h
|
||||
qrc_*.cpp
|
||||
ui_*.h
|
||||
*.qmlc
|
||||
*.jsc
|
||||
Makefile*
|
||||
*build-*
|
||||
*.qm
|
||||
*.prl
|
||||
|
||||
# Qt unit tests
|
||||
target_wrapper.*
|
||||
|
||||
# QtCreator
|
||||
*.autosave
|
||||
|
||||
# QtCreator Qml
|
||||
*.qmlproject.user
|
||||
*.qmlproject.user.*
|
||||
|
||||
# QtCreator CMake
|
||||
CMakeLists.txt.user*
|
||||
|
||||
# QtCreator 4.8< compilation database
|
||||
compile_commands.json
|
||||
|
||||
# QtCreator local machine specific files for imported projects
|
||||
*creator.user*
|
||||
|
||||
*_qmlcache.qrc
|
||||
|
||||
# ---> C++
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
19
CopyHeaders.pri
Normal file
19
CopyHeaders.pri
Normal file
@@ -0,0 +1,19 @@
|
||||
# Copy headers to output:
|
||||
win32 {
|
||||
include_headers.commands = "$$QMAKE_MKDIR $$shell_path($$OUT_PWD/include/$$PROJECT_NAME)"
|
||||
for (f, HEADERS): \
|
||||
include_headers.commands += "$$QMAKE_COPY $$shell_path($$absolute_path($$f, $$_PRO_FILE_PWD_)) $$shell_path($$OUT_PWD/include/$$PROJECT_NAME/)"
|
||||
|
||||
write_file($$OUT_PWD/copy_headers.bat, include_headers.commands)
|
||||
QMAKE_CLEAN += -r $$OUT_PWD/include/
|
||||
QMAKE_POST_LINK += $$OUT_PWD/copy_headers.bat
|
||||
}
|
||||
unix {
|
||||
include_headers.commands = $$QMAKE_MKDIR $$shell_path($$OUT_PWD/include/$$PROJECT_NAME)
|
||||
for (f, HEADERS): \
|
||||
include_headers.commands += ; $$QMAKE_COPY $$shell_path($$absolute_path($$f, $$_PRO_FILE_PWD_)) $$shell_path($$OUT_PWD/include/$$PROJECT_NAME/)
|
||||
|
||||
QMAKE_CLEAN += -r $$OUT_PWD/include/
|
||||
QMAKE_EXTRA_TARGETS += include_headers
|
||||
QMAKE_POST_LINK += make include_headers
|
||||
}
|
||||
71
LICENSE
Normal file
71
LICENSE
Normal file
@@ -0,0 +1,71 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license document.
|
||||
|
||||
4. Combined Works.
|
||||
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
|
||||
3
README.md
Normal file
3
README.md
Normal file
@@ -0,0 +1,3 @@
|
||||
## LibCrashCatch
|
||||
|
||||
LibCrashCatch is a Qt Project bounding around the CrashCatch library (https://github.com/keithpotz/CrashCatch/) privided under MIT license
|
||||
49
libCrashCatch.pro
Normal file
49
libCrashCatch.pro
Normal file
@@ -0,0 +1,49 @@
|
||||
PROJECT_NAME = libCrashCatch
|
||||
|
||||
TARGET = CrashCatch
|
||||
|
||||
CONFIG -= qt
|
||||
CONFIG += c++17
|
||||
CONFIG += warn_on
|
||||
CONFIG -= app_bundle
|
||||
|
||||
TEMPLATE = lib
|
||||
|
||||
DEFINES += $$upper($${TARGET})_LIBRARY
|
||||
DEFINES += QT_DEPRECATED_WARNINGS
|
||||
|
||||
win32:LIBS += -ladvapi32 -lDbgHelp -luser32
|
||||
unix:LIBS += -ldl -rdynamic
|
||||
|
||||
INCLUDEPATH += \
|
||||
$$PWD/$$PROJECT_NAME
|
||||
|
||||
contains(staticlib, CONFIG): DEFINES += STATIC_LIB
|
||||
|
||||
CONFIG(debug, debug|release): BUILD = debug
|
||||
CONFIG(release, debug|release): BUILD = release
|
||||
|
||||
equals(BUILD, "debug"): DEFINES += DEBUG
|
||||
# equals(BUILD, "debug"): DEFINES += DEBUG_GPB_CLIENTS
|
||||
equals(BUILD, "release"): DEFINES += QT_NO_DEBUG_OUTPUT
|
||||
|
||||
equals(BUILD, "debug"): TARGET = $$join(TARGET,,,d)
|
||||
|
||||
DESTDIR = $$shadowed(./lib)
|
||||
MOC_DIR = $$shadowed(./)
|
||||
OBJECTS_DIR = $$shadowed(./)
|
||||
RCC_DIR = $$shadowed(./)
|
||||
UI_DIR = $$shadowed(./)
|
||||
|
||||
equals(MOC_DIR, "$$PWD") {
|
||||
MOC_DIR = $$PWD/build/$$BUILD
|
||||
OBJECTS_DIR = $$PWD/build/$$BUILD
|
||||
RCC_DIR = $$PWD/build/$$BUILD
|
||||
UI_DIR = $$PWD/build/$$BUILD
|
||||
}
|
||||
|
||||
QMAKE_CLEAN += $$DESTDIR
|
||||
|
||||
include($${PROJECT_NAME}/$${PROJECT_NAME}.pri)
|
||||
|
||||
include(CopyHeaders.pri)
|
||||
383
libCrashCatch/CrashCatch.hpp
Normal file
383
libCrashCatch/CrashCatch.hpp
Normal file
@@ -0,0 +1,383 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
CrashCatch - A simple cross-platform crash handler
|
||||
Version 1.4.0
|
||||
Created by Keith Pottratz
|
||||
Email: keithpotz@gmail.com
|
||||
License: MIT
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define CRASHCATCH_PLATFORM_WINDOWS
|
||||
#include <windows.h>
|
||||
#include <dbgHelp.h>
|
||||
#pragma comment(lib, "dbgHelp.lib") //Auto-link debugging support library
|
||||
#elif defined(__linux__)
|
||||
#define CRASHCATCH_PLATFORM_LINUX
|
||||
#include <signal.h>
|
||||
#include <execinfo.h>
|
||||
#include <unistd.h>
|
||||
#include <limits.h>
|
||||
#include <cxxabi.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#endif
|
||||
|
||||
namespace CrashCatch {
|
||||
|
||||
// Context data passed to crash callback (onCrash, onCrashUpload)
|
||||
struct CrashContext {
|
||||
std::string dumpFilePath = ""; // .dmp (Windows) or blank (Linux)
|
||||
std::string logFilePath = ""; // .txt summary log
|
||||
std::string timestamp = ""; // Crash timestamp
|
||||
int signalOrCode = 0; // Signal or exception code
|
||||
};
|
||||
|
||||
// Configuration structure for CrashCatch behavior
|
||||
struct Config {
|
||||
std::string dumpFolder = "./crash_dumps/"; // Where to save crash files
|
||||
std::string dumpFileName = "crash"; // Base name (timestamp added optionally)
|
||||
bool enableTextLog = true; // Output .txt human-readable crash report
|
||||
bool autoTimestamp = true; // Auto-append timestamp to filenames
|
||||
bool showCrashDialog = false; // (Windows only) Show MessageBox on crash
|
||||
std::function<void(const CrashContext&)> onCrash = nullptr; // Called on crash (log before exit)
|
||||
std::function<void(const CrashContext&)> onCrashUpload = nullptr; // Optional hook to upload crash report
|
||||
std::string appVersion = "unknown"; // Application version string
|
||||
std::string buildConfig =
|
||||
#ifdef _DEBUG
|
||||
"Debug";
|
||||
#else
|
||||
"Release";
|
||||
#endif
|
||||
std::string additionalNotes = ""; // Optional notes in crash log
|
||||
bool includeStackTrace = true; // Output stack trace in .txt log (Windows + Linux)
|
||||
};
|
||||
|
||||
inline Config globalConfig; // Global configuration
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
// Set by UnhandledExceptionHandler so writeCrashLog can walk the crash-site stack,
|
||||
// not the handler's own stack. Only valid during crash handling.
|
||||
inline CONTEXT* g_crashSiteContext = nullptr;
|
||||
#endif
|
||||
|
||||
// Generate timestamp string (YYYY-MM-DD_HH-MM-SS)
|
||||
inline std::string getTimestamp() {
|
||||
auto now = std::chrono::system_clock::now();
|
||||
auto time = std::chrono::system_clock::to_time_t(now);
|
||||
std::tm tm_result = {};
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
localtime_s(&tm_result, &time); // thread-safe on Windows
|
||||
#else
|
||||
localtime_r(&time, &tm_result); // thread-safe on POSIX
|
||||
#endif
|
||||
std::stringstream ss;
|
||||
ss << std::put_time(&tm_result, "%Y-%m-%d_%H-%M-%S");
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// Return full path to current executable
|
||||
inline std::string getExecutablePath() {
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
char buffer[MAX_PATH];
|
||||
GetModuleFileNameA(nullptr, buffer, MAX_PATH);
|
||||
return std::string(buffer);
|
||||
#elif defined(CRASHCATCH_PLATFORM_LINUX)
|
||||
char path[PATH_MAX];
|
||||
ssize_t len = readlink("/proc/self/exe", path, sizeof(path) - 1);
|
||||
if (len != -1) {
|
||||
path[len] = '\0';
|
||||
return std::string(path);
|
||||
}
|
||||
return "(unknown)";
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_LINUX
|
||||
// Demangle a C++ symbol name.
|
||||
// backtrace_symbols() returns strings like "./app(_Z3foov+0x10) [0x7f...]".
|
||||
// We extract just the mangled name between '(' and '+' before demangling.
|
||||
inline std::string demangle(const char* symbol) {
|
||||
std::string sym(symbol);
|
||||
|
||||
// Extract mangled name: between '(' and '+'
|
||||
auto parenOpen = sym.find('(');
|
||||
auto plusSign = sym.find('+', parenOpen);
|
||||
if (parenOpen != std::string::npos && plusSign != std::string::npos && plusSign > parenOpen + 1) {
|
||||
std::string mangled = sym.substr(parenOpen + 1, plusSign - parenOpen - 1);
|
||||
size_t size = 0;
|
||||
int status = 0;
|
||||
char* demangled = abi::__cxa_demangle(mangled.c_str(), nullptr, &size, &status);
|
||||
if (status == 0 && demangled) {
|
||||
std::string result = sym.substr(0, parenOpen + 1)
|
||||
+ demangled
|
||||
+ sym.substr(plusSign);
|
||||
free(demangled);
|
||||
return result;
|
||||
}
|
||||
if (demangled) free(demangled);
|
||||
}
|
||||
return sym; // return original if no mangled segment found or demangle failed
|
||||
}
|
||||
#endif
|
||||
|
||||
// Collect system/app info for inclusion in crash logs
|
||||
inline std::string getDiagnosticsInfo() {
|
||||
std::stringstream ss;
|
||||
ss << "App Version: " << globalConfig.appVersion << "\n";
|
||||
ss << "Build Config: " << globalConfig.buildConfig << "\n";
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
ss << "Platform: Windows\n";
|
||||
#elif defined(CRASHCATCH_PLATFORM_LINUX)
|
||||
ss << "Platform: Linux\n";
|
||||
#endif
|
||||
ss << "Executable: " << getExecutablePath() << "\n";
|
||||
if (!globalConfig.additionalNotes.empty()) {
|
||||
ss << "Notes: " << globalConfig.additionalNotes << "\n";
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// Write human-readable crash report to .txt file
|
||||
inline void writeCrashLog(const std::string& logPath, const std::string& timestamp, int signal = 0) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(std::filesystem::path(logPath).parent_path(), ec);
|
||||
if (ec) return; // can't create output directory — bail out silently
|
||||
|
||||
std::ofstream log(logPath);
|
||||
if (!log.is_open()) return;
|
||||
|
||||
log << "Crash Report\n============\n";
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_LINUX
|
||||
log << "Signal: " << strsignal(signal) << " (" << signal << ")\n";
|
||||
#endif
|
||||
log << "Timestamp: " << (timestamp.empty() ? "N/A" : timestamp) << "\n\n";
|
||||
log << "Environment Info:\n" << getDiagnosticsInfo() << "\n";
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
if (globalConfig.includeStackTrace) {
|
||||
// Walk the stack using DbgHelp (already linked via pragma comment)
|
||||
// SymInitialize was called at CrashCatch::initialize() time
|
||||
HANDLE process = GetCurrentProcess();
|
||||
HANDLE thread = GetCurrentThread();
|
||||
|
||||
// Use crash-site context if available (set by exception handler),
|
||||
// otherwise fall back to capturing here (e.g. called standalone).
|
||||
CONTEXT localContext = {};
|
||||
CONTEXT& context = g_crashSiteContext ? *g_crashSiteContext : localContext;
|
||||
if (!g_crashSiteContext) {
|
||||
localContext.ContextFlags = CONTEXT_FULL;
|
||||
RtlCaptureContext(&localContext);
|
||||
}
|
||||
|
||||
STACKFRAME64 frame = {};
|
||||
#if defined(_M_X64)
|
||||
DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
|
||||
frame.AddrPC.Offset = context.Rip;
|
||||
frame.AddrPC.Mode = AddrModeFlat;
|
||||
frame.AddrFrame.Offset = context.Rbp;
|
||||
frame.AddrFrame.Mode = AddrModeFlat;
|
||||
frame.AddrStack.Offset = context.Rsp;
|
||||
frame.AddrStack.Mode = AddrModeFlat;
|
||||
#elif defined(_M_IX86)
|
||||
DWORD machineType = IMAGE_FILE_MACHINE_I386;
|
||||
frame.AddrPC.Offset = context.Eip;
|
||||
frame.AddrPC.Mode = AddrModeFlat;
|
||||
frame.AddrFrame.Offset = context.Ebp;
|
||||
frame.AddrFrame.Mode = AddrModeFlat;
|
||||
frame.AddrStack.Offset = context.Esp;
|
||||
frame.AddrStack.Mode = AddrModeFlat;
|
||||
#else
|
||||
DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
|
||||
#endif \
|
||||
// Symbol buffer
|
||||
const int MAX_SYM_NAME_LEN = 256;
|
||||
char symBuffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME_LEN * sizeof(char)];
|
||||
SYMBOL_INFO* symbol = reinterpret_cast<SYMBOL_INFO*>(symBuffer);
|
||||
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
|
||||
symbol->MaxNameLen = MAX_SYM_NAME_LEN;
|
||||
|
||||
log << "\nStack Trace:\n";
|
||||
int frameIndex = 0;
|
||||
|
||||
while (StackWalk64(machineType, process, thread, &frame, &context,
|
||||
nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) {
|
||||
if (frame.AddrPC.Offset == 0) break;
|
||||
|
||||
log << " [" << frameIndex++ << "]: ";
|
||||
|
||||
DWORD64 displacement = 0;
|
||||
if (SymFromAddr(process, frame.AddrPC.Offset, &displacement, symbol)) {
|
||||
log << symbol->Name;
|
||||
|
||||
// Try to get file/line info
|
||||
IMAGEHLP_LINE64 line = {};
|
||||
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
|
||||
DWORD lineDisp = 0;
|
||||
if (SymGetLineFromAddr64(process, frame.AddrPC.Offset, &lineDisp, &line)) {
|
||||
log << " (" << line.FileName << ":" << line.LineNumber << ")";
|
||||
}
|
||||
} else {
|
||||
// No symbol — fall back to raw address
|
||||
log << "0x" << std::hex << frame.AddrPC.Offset << std::dec;
|
||||
}
|
||||
log << "\n";
|
||||
|
||||
// Avoid runaway stack walks
|
||||
if (frameIndex > 64) break;
|
||||
}
|
||||
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_LINUX
|
||||
if (globalConfig.includeStackTrace) {
|
||||
void* callstack[128];
|
||||
int frames = backtrace(callstack, 128);
|
||||
char** symbols = backtrace_symbols(callstack, frames);
|
||||
log << "\nStack Trace:\n";
|
||||
for (int i = 0; i < frames; ++i) {
|
||||
log << " [" << i << "]: " << demangle(symbols[i]) << "\n";
|
||||
}
|
||||
free(symbols);
|
||||
}
|
||||
#endif
|
||||
|
||||
log.close();
|
||||
}
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
// Windows unhandled exception handler
|
||||
inline LONG WINAPI UnhandledExceptionHandler(EXCEPTION_POINTERS* ep) {
|
||||
DWORD code = ep->ExceptionRecord->ExceptionCode;
|
||||
if (code == DBG_PRINTEXCEPTION_C || code == DBG_CONTROL_C) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
std::string timestamp = globalConfig.autoTimestamp ? getTimestamp() : "";
|
||||
std::string base = globalConfig.dumpFileName + (timestamp.empty() ? "" : ("_" + timestamp));
|
||||
std::string dumpPath = globalConfig.dumpFolder + base + ".dmp";
|
||||
std::string logPath = globalConfig.dumpFolder + base + ".txt";
|
||||
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(globalConfig.dumpFolder, ec);
|
||||
if (ec) return EXCEPTION_EXECUTE_HANDLER; // can't create output directory
|
||||
|
||||
// Point the stack walker at the actual crash site, not the handler frame
|
||||
g_crashSiteContext = ep->ContextRecord;
|
||||
|
||||
HANDLE hFile = CreateFileA(dumpPath.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (hFile != INVALID_HANDLE_VALUE) {
|
||||
MINIDUMP_EXCEPTION_INFORMATION dumpInfo = { GetCurrentThreadId(), ep, FALSE };
|
||||
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpWithDataSegs, &dumpInfo, nullptr, nullptr);
|
||||
CloseHandle(hFile);
|
||||
|
||||
if (globalConfig.enableTextLog) {
|
||||
writeCrashLog(logPath, timestamp);
|
||||
}
|
||||
|
||||
if (globalConfig.showCrashDialog) {
|
||||
std::string msg = "Crash occurred. Dump written to:\n" + dumpPath;
|
||||
MessageBoxA(nullptr, msg.c_str(), "Crash Detected", MB_OK | MB_ICONERROR);
|
||||
}
|
||||
}
|
||||
|
||||
// Build context once, after files are written, so callbacks can access them
|
||||
CrashContext context{ dumpPath, logPath, timestamp, static_cast<int>(code) };
|
||||
|
||||
if (globalConfig.onCrash) {
|
||||
globalConfig.onCrash(context);
|
||||
}
|
||||
|
||||
if (globalConfig.onCrashUpload) {
|
||||
globalConfig.onCrashUpload(context);
|
||||
}
|
||||
|
||||
return EXCEPTION_EXECUTE_HANDLER;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef CRASHCATCH_PLATFORM_LINUX
|
||||
// POSIX signal handler (Linux only).
|
||||
//
|
||||
// Signal handlers must only call async-signal-safe functions (see signal-safety(7)).
|
||||
// Heap allocation, std::string, file I/O, and C++ exceptions are NOT safe to call
|
||||
// directly from a signal handler.
|
||||
//
|
||||
// Solution: fork() a child process to do all the heavy work (logging, callbacks).
|
||||
// The child inherits the parent's memory image but runs in a clean execution context
|
||||
// where malloc locks are not held. The parent simply _exit()s immediately.
|
||||
inline void linuxSignalHandler(int signum) {
|
||||
// Build paths before fork using only already-constructed std::strings.
|
||||
// These copies are safe because we're single-threaded at the point of the crash
|
||||
// signal delivery (the faulting thread is the only one executing here).
|
||||
std::string timestamp = globalConfig.autoTimestamp ? getTimestamp() : "";
|
||||
std::string base = globalConfig.dumpFileName + (timestamp.empty() ? "" : ("_" + timestamp));
|
||||
std::string logPath = globalConfig.dumpFolder + base + ".txt";
|
||||
|
||||
pid_t pid = fork();
|
||||
if (pid == 0) {
|
||||
// Child process: safe to use heap, file I/O, std::string, etc.
|
||||
writeCrashLog(logPath, timestamp, signum);
|
||||
|
||||
// Build context once, after file is written, so callbacks can access it
|
||||
CrashContext context{ "", logPath, timestamp, signum };
|
||||
|
||||
if (globalConfig.onCrash) {
|
||||
globalConfig.onCrash(context);
|
||||
}
|
||||
|
||||
if (globalConfig.onCrashUpload) {
|
||||
globalConfig.onCrashUpload(context);
|
||||
}
|
||||
|
||||
_exit(0);
|
||||
} else if (pid > 0) {
|
||||
// Parent: wait for child to finish writing the report, then exit
|
||||
waitpid(pid, nullptr, 0);
|
||||
}
|
||||
// pid < 0 means fork failed — fall through and exit anyway
|
||||
_exit(1);
|
||||
}
|
||||
#endif
|
||||
|
||||
// Initialize CrashCatch with user configuration
|
||||
inline bool initialize(const Config& config = Config()) {
|
||||
globalConfig = config;
|
||||
#ifdef CRASHCATCH_PLATFORM_WINDOWS
|
||||
// Load symbols now so they're ready when a crash occurs
|
||||
SymInitialize(GetCurrentProcess(), nullptr, TRUE);
|
||||
SetUnhandledExceptionFilter(UnhandledExceptionHandler);
|
||||
#elif defined(CRASHCATCH_PLATFORM_LINUX)
|
||||
signal(SIGSEGV, linuxSignalHandler);
|
||||
signal(SIGABRT, linuxSignalHandler);
|
||||
signal(SIGFPE, linuxSignalHandler);
|
||||
signal(SIGILL, linuxSignalHandler);
|
||||
signal(SIGBUS, linuxSignalHandler);
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
// Shorthand: use default configuration
|
||||
inline bool enable() { return initialize(Config{}); }
|
||||
|
||||
// Auto-initialize when included (optional)
|
||||
#ifdef CRASHCATCH_AUTO_INIT
|
||||
namespace {
|
||||
const bool _autoInit = CrashCatch::enable();
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace CrashCatch
|
||||
|
||||
210
libCrashCatch/CrashCatchDLL.hpp
Normal file
210
libCrashCatch/CrashCatchDLL.hpp
Normal file
@@ -0,0 +1,210 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
CrashCatchDLL - C interface wrapper for CrashCatch
|
||||
Version 1.4.0
|
||||
Created by Keith Pottratz
|
||||
License: MIT
|
||||
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
PURPOSE
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
CrashCatch.hpp requires C++17. This file provides a plain C interface so that
|
||||
programs built with C++11, C++98, or plain C can use CrashCatch by linking
|
||||
against a pre-compiled DLL (Windows) or shared library (Linux).
|
||||
|
||||
The DLL itself is compiled once with C++17. Consumers only need to include
|
||||
this header and link against the compiled binary — no C++17 required on
|
||||
their end.
|
||||
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
BUILDING THE DLL
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
Create a single .cpp file in your DLL project:
|
||||
|
||||
// CrashCatchDLL.cpp
|
||||
#define CRASHCATCH_DLL_EXPORTS
|
||||
#include "CrashCatchDLL.hpp"
|
||||
|
||||
Compile with C++17. This produces:
|
||||
Windows : CrashCatch.dll + CrashCatch.lib
|
||||
Linux : libCrashCatch.so
|
||||
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
USING THE DLL (C++11 / C++98 / C consumer)
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
#include "CrashCatchDLL.hpp"
|
||||
|
||||
int main() {
|
||||
crashcatch_enable(); // zero-config
|
||||
// -- or --
|
||||
CrashCatch_Config cfg = crashcatch_default_config();
|
||||
cfg.show_crash_dialog = 1;
|
||||
cfg.include_stack_trace = 1;
|
||||
crashcatch_init(&cfg);
|
||||
}
|
||||
─────────────────────────────────────────────────────────────────────────────
|
||||
*/
|
||||
|
||||
// ── Export / import macros ────────────────────────────────────────────────
|
||||
#if defined(_WIN32)
|
||||
#if defined(CRASHCATCH_DLL_EXPORTS)
|
||||
#define CRASHCATCH_API __declspec(dllexport)
|
||||
#else
|
||||
#define CRASHCATCH_API __declspec(dllimport)
|
||||
#endif
|
||||
#else
|
||||
// GCC/Clang visibility
|
||||
#define CRASHCATCH_API __attribute__((visibility("default")))
|
||||
#endif
|
||||
|
||||
// ── C linkage — no name mangling, usable from C++98 / C++11 / C ──────────
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// ── Plain-C configuration struct ─────────────────────────────────────────
|
||||
// Mirrors CrashCatch::Config but uses only C-compatible types.
|
||||
typedef struct {
|
||||
const char* dump_folder; // Directory to write crash files (default: "./crash_dumps/")
|
||||
const char* dump_file_name; // Base filename (default: "crash")
|
||||
int enable_text_log; // Write .txt crash report (1 = yes, 0 = no)
|
||||
int auto_timestamp; // Append timestamp to filename (1 = yes)
|
||||
int show_crash_dialog; // Windows only: show MessageBox on crash
|
||||
int include_stack_trace;// Write stack trace to .txt log (1 = yes)
|
||||
const char* app_version; // Application version string
|
||||
const char* build_config; // "Debug" or "Release"
|
||||
const char* additional_notes; // Optional notes included in crash log
|
||||
|
||||
// Optional callbacks — set to NULL if not needed.
|
||||
// context_json: a JSON-formatted string of crash context fields.
|
||||
void (*on_crash)(const char* dump_path, const char* log_path,
|
||||
const char* timestamp, int signal_or_code);
|
||||
void (*on_crash_upload)(const char* dump_path, const char* log_path,
|
||||
const char* timestamp, int signal_or_code);
|
||||
} CrashCatch_Config;
|
||||
|
||||
// ── API ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Returns a CrashCatch_Config populated with sensible defaults.
|
||||
* Always call this first, then override only the fields you need.
|
||||
*
|
||||
* Example:
|
||||
* CrashCatch_Config cfg = crashcatch_default_config();
|
||||
* cfg.app_version = "2.0.0";
|
||||
* crashcatch_init(&cfg);
|
||||
*/
|
||||
CRASHCATCH_API CrashCatch_Config crashcatch_default_config(void);
|
||||
|
||||
/**
|
||||
* Initialize CrashCatch with a configuration struct.
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*
|
||||
* Example:
|
||||
* CrashCatch_Config cfg = crashcatch_default_config();
|
||||
* cfg.show_crash_dialog = 1;
|
||||
* crashcatch_init(&cfg);
|
||||
*/
|
||||
CRASHCATCH_API int crashcatch_init(const CrashCatch_Config* config);
|
||||
|
||||
/**
|
||||
* Initialize CrashCatch with all defaults. Equivalent to CrashCatch::enable().
|
||||
* Returns 1 on success, 0 on failure.
|
||||
*
|
||||
* Example:
|
||||
* crashcatch_enable();
|
||||
*/
|
||||
CRASHCATCH_API int crashcatch_enable(void);
|
||||
|
||||
/**
|
||||
* Returns the CrashCatch version string, e.g. "1.4.0".
|
||||
*/
|
||||
CRASHCATCH_API const char* crashcatch_version(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
|
||||
// ── Implementation (compiled into the DLL only) ───────────────────────────
|
||||
// This block is only compiled when building the DLL itself.
|
||||
// Consumers who only #include this header never see the C++17 code.
|
||||
#if defined(CRASHCATCH_DLL_EXPORTS)
|
||||
|
||||
#include "CrashCatch.hpp" // C++17 — only compiled inside the DLL project
|
||||
#include <cstring>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
CRASHCATCH_API CrashCatch_Config crashcatch_default_config(void) {
|
||||
CrashCatch_Config cfg;
|
||||
cfg.dump_folder = "./crash_dumps/";
|
||||
cfg.dump_file_name = "crash";
|
||||
cfg.enable_text_log = 1;
|
||||
cfg.auto_timestamp = 1;
|
||||
cfg.show_crash_dialog = 0;
|
||||
cfg.include_stack_trace = 1;
|
||||
cfg.app_version = "unknown";
|
||||
cfg.build_config = "Release";
|
||||
cfg.additional_notes = "";
|
||||
cfg.on_crash = nullptr;
|
||||
cfg.on_crash_upload = nullptr;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
CRASHCATCH_API int crashcatch_init(const CrashCatch_Config* cfg) {
|
||||
if (!cfg) return 0;
|
||||
|
||||
CrashCatch::Config cppConfig;
|
||||
|
||||
if (cfg->dump_folder) cppConfig.dumpFolder = cfg->dump_folder;
|
||||
if (cfg->dump_file_name) cppConfig.dumpFileName = cfg->dump_file_name;
|
||||
if (cfg->app_version) cppConfig.appVersion = cfg->app_version;
|
||||
if (cfg->build_config) cppConfig.buildConfig = cfg->build_config;
|
||||
if (cfg->additional_notes) cppConfig.additionalNotes = cfg->additional_notes;
|
||||
|
||||
cppConfig.enableTextLog = cfg->enable_text_log != 0;
|
||||
cppConfig.autoTimestamp = cfg->auto_timestamp != 0;
|
||||
cppConfig.showCrashDialog = cfg->show_crash_dialog != 0;
|
||||
cppConfig.includeStackTrace = cfg->include_stack_trace != 0;
|
||||
|
||||
// Wrap C callbacks into C++ std::function lambdas
|
||||
if (cfg->on_crash) {
|
||||
auto cb = cfg->on_crash; // capture raw pointer — safe, DLL lifetime
|
||||
cppConfig.onCrash = [cb](const CrashCatch::CrashContext& ctx) {
|
||||
cb(ctx.dumpFilePath.c_str(),
|
||||
ctx.logFilePath.c_str(),
|
||||
ctx.timestamp.c_str(),
|
||||
ctx.signalOrCode);
|
||||
};
|
||||
}
|
||||
|
||||
if (cfg->on_crash_upload) {
|
||||
auto cb = cfg->on_crash_upload;
|
||||
cppConfig.onCrashUpload = [cb](const CrashCatch::CrashContext& ctx) {
|
||||
cb(ctx.dumpFilePath.c_str(),
|
||||
ctx.logFilePath.c_str(),
|
||||
ctx.timestamp.c_str(),
|
||||
ctx.signalOrCode);
|
||||
};
|
||||
}
|
||||
|
||||
return CrashCatch::initialize(cppConfig) ? 1 : 0;
|
||||
}
|
||||
|
||||
CRASHCATCH_API int crashcatch_enable(void) {
|
||||
return CrashCatch::enable() ? 1 : 0;
|
||||
}
|
||||
|
||||
CRASHCATCH_API const char* crashcatch_version(void) {
|
||||
return "1.4.0";
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
|
||||
#endif // CRASHCATCH_DLL_EXPORTS
|
||||
2
libCrashCatch/CrashCatchLibrary.cpp
Normal file
2
libCrashCatch/CrashCatchLibrary.cpp
Normal file
@@ -0,0 +1,2 @@
|
||||
#define CRASHCATCH_DLL_EXPORTS
|
||||
#include "CrashCatchDLL.hpp"
|
||||
6
libCrashCatch/libCrashCatch.pri
Normal file
6
libCrashCatch/libCrashCatch.pri
Normal file
@@ -0,0 +1,6 @@
|
||||
HEADERS += \
|
||||
$$PWD/CrashCatchDLL.hpp \
|
||||
$$PWD/CrashCatch.hpp
|
||||
|
||||
SOURCES += \
|
||||
$$PWD/CrashCatchLibrary.cpp
|
||||
Reference in New Issue
Block a user