Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions category/core/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ add_library(
"assert.h"
"backtrace.cpp"
"backtrace.hpp"
"terminate_handler.cpp"
"terminate_handler.h"
"basic_formatter.hpp"
"blake3.hpp"
"byte_string.hpp"
Expand Down
8 changes: 8 additions & 0 deletions category/core/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@
} \
MONAD_NAMESPACE_END

// Macro for marking C++ functions as noexcept in C++ mode, empty in C mode
// This is primarily used for extern "C" functions that should not throw
#ifdef __cplusplus
#define MONAD_NOEXCEPT noexcept
#else
#define MONAD_NOEXCEPT
#endif

static_assert(CHAR_BIT == 8);

static_assert(
Expand Down
148 changes: 148 additions & 0 deletions category/core/terminate_handler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright (C) 2025 Category Labs, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include <category/core/terminate_handler.h>

#include <cxxabi.h>
#include <exception>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <typeinfo>
#include <unistd.h>

extern char const *__progname; // NOLINT(bugprone-reserved-identifier)

extern "C" void monad_stack_backtrace_capture_and_print(
char *buffer, size_t size, int fd, unsigned indent,
bool print_async_unsafe_info);

namespace
{
void monad_terminate_handler_impl() noexcept
{
char buffer[16384];
ssize_t written = 0;

// Print header
written = snprintf(
buffer,
sizeof(buffer),
"\n"
"=================================================================="
"==============\n"
"%s: std::terminate() called\n"
"=================================================================="
"==============\n",
__progname);

if (written > 0 && (size_t)written < sizeof(buffer)) {
if (write(STDERR_FILENO, buffer, (size_t)written) == -1) {
// Suppress warning
}
}

// Try to get exception information
std::type_info *exception_type = abi::__cxa_current_exception_type();
if (exception_type != nullptr) {
char const *exception_name = exception_type->name();

// Try to demangle the name
int status = 0;
char *demangled =
abi::__cxa_demangle(exception_name, nullptr, nullptr, &status);
char const *display_name = (status == 0 && demangled != nullptr)
? demangled
: exception_name;

written = snprintf(
buffer,
sizeof(buffer),
"Reason: Uncaught exception\n"
"Exception type: %s\n",
display_name);

if (written > 0 && (size_t)written < sizeof(buffer)) {
if (write(STDERR_FILENO, buffer, (size_t)written) == -1) {
// Suppress warning
}
}

// Try to get exception message if it's a std::exception
try {
std::rethrow_exception(std::current_exception());
}
catch (std::exception const &e) {
written = snprintf(
buffer,
sizeof(buffer),
"Exception message: %s\n",
e.what());

if (written > 0 && (size_t)written < sizeof(buffer)) {
if (write(STDERR_FILENO, buffer, (size_t)written) == -1) {
// Suppress warning
}
}
}
catch (...) {
// Not a std::exception, no message available
char const *msg = "Exception message: <not a std::exception>\n";
if (write(STDERR_FILENO, msg, strlen(msg)) == -1) {
// Suppress warning
}
}

if (demangled != nullptr) {
free(demangled);
}
}
else {
// No active exception - std::terminate() was called for another
// reason.
char const *msg = "No active exception detected\n";
if (write(STDERR_FILENO, msg, strlen(msg)) == -1) {
// Suppress warning
}
}

char const *separator = "----------------------------------------------"
"----------------------------------\n"
"Stack trace:\n"
"----------------------------------------------"
"----------------------------------\n";
if (write(STDERR_FILENO, separator, strlen(separator)) == -1) {
// Suppress warning
}

monad_stack_backtrace_capture_and_print(
buffer, sizeof(buffer), STDERR_FILENO, 3, true);

char const *footer = "================================================="
"===============================\n"
"Aborting process...\n"
"================================================="
"===============================\n";
if (write(STDERR_FILENO, footer, strlen(footer)) == -1) {
// Suppress warning
}
abort();
}
}

extern "C" void monad_set_terminate_handler()
{
std::set_terminate(monad_terminate_handler_impl);
}
30 changes: 30 additions & 0 deletions category/core/terminate_handler.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright (C) 2025 Category Labs, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#pragma once

#ifdef __cplusplus
extern "C"
{
#endif

/// Install custom terminate handler that prints exception info and backtrace
/// before aborting. This should be called early in main() to catch exceptions
/// that escape noexcept functions (e.g., FFI boundaries).
void monad_set_terminate_handler();

#ifdef __cplusplus
}
#endif
1 change: 1 addition & 0 deletions category/core/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ monad_add_test(monad_exception_test "monad_exception.cpp")
monad_add_test(path_util_test "path_util.cpp")
monad_add_test(priority_pool_test "priority_pool_test.cpp")
set_tests_properties(priority_pool_test PROPERTIES RUN_SERIAL TRUE)
monad_add_test(terminate_handler_test "terminate_handler_test.cpp")
107 changes: 107 additions & 0 deletions category/core/test/terminate_handler_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (C) 2025 Category Labs, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include <category/core/terminate_handler.h>

#include <gtest/gtest.h>

#include <exception>
#include <stdexcept>

namespace
{

void throwing_function()
{
throw std::runtime_error("Test exception from throwing_function");
}

// NOLINTNEXTLINE(bugprone-exception-escape)
void noexcept_function() noexcept
{
// This will call std::terminate because we're throwing from noexcept
throwing_function();
}

} // namespace

// Death tests must be named with DeathTest suffix for proper test ordering
TEST(TerminateHandlerDeathTest, ExceptionEscapingNoexcept)
{
// Install the custom terminate handler
monad_set_terminate_handler();

// Verify that calling noexcept_function causes termination
// and that the output contains expected exception information
EXPECT_DEATH(
{ noexcept_function(); },
// Regex pattern matching expected output:
// - Should contain "std::terminate" or "terminate()"
// - Should contain the exception type "runtime_error"
// - Should contain the exception message
// - Should contain "Stack trace"
"std::terminate.*"
".*runtime_error.*"
".*Test exception from throwing_function.*"
".*Stack trace.*");
}

TEST(TerminateHandlerDeathTest, DirectTerminateCall)
{
// Install the custom terminate handler
monad_set_terminate_handler();

// Verify that directly calling std::terminate works
EXPECT_DEATH(
{ std::terminate(); },
// Should indicate no active exception
"std::terminate.*"
".*No active exception detected.*"
".*Stack trace.*");
}

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexceptions"
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wterminate"
#endif

// Helper function for testing different exception type
// NOLINTNEXTLINE(bugprone-exception-escape)
[[noreturn]] void throw_logic_error_noexcept() noexcept
{
throw std::logic_error("Logic error test");
}

#ifdef __clang__
#pragma clang diagnostic pop
#else
#pragma GCC diagnostic pop
#endif

TEST(TerminateHandlerDeathTest, ExceptionTypeInOutput)
{
// Install the custom terminate handler
monad_set_terminate_handler();

// Test with a different exception type
EXPECT_DEATH(
{ throw_logic_error_noexcept(); },
"std::terminate.*"
".*logic_error.*"
".*Logic error test.*");
}
Loading
Loading