Skip to content

Commit

Permalink
Default to __builtin_trap() when possible instead of abort()
Browse files Browse the repository at this point in the history
abort() raises SIGABRT which may run more code in process, while
__builtin_trap may generate a trap that debuggers can catch in debug
builds and produces smaller codegen (no function call).

See also: https://discourse.llvm.org/t/rfc-hardening-in-libc/73925#termination-2
  • Loading branch information
danakj committed Oct 10, 2023
1 parent cc38848 commit 7147b8f
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions sus/assertions/panic.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,16 @@ void print_panic_location(const std::source_location& location) noexcept;

/// Terminate the program.
///
/// The default behaviour of this function is to `abort()`. The behaviour of
/// this function can be overridden by defining a `SUS_PROVIDE_PANIC_HANDLER()`
/// macro when compiling the library.
/// The default behaviour of this function is to `__builtin_trap()` when
/// possible and `abort() otherwise`. The behaviour of this function can be
/// overridden by defining a `SUS_PROVIDE_PANIC_HANDLER()` macro when compiling
/// the library.
///
/// The panic message will be printed to stderr before aborting. This behaviour
/// can be overridden by defining a `SUS_PROVIDE_PRINT_PANIC_LOCATION_HANDLER()`
/// macro when compiling the library.
/// macro when compiling. The same handler must be used as when building the
/// library itself. So if used as a shared library, it can not be modified by
/// the calling code.
///
/// # Safety
///
Expand All @@ -78,8 +81,11 @@ void print_panic_location(const std::source_location& location) noexcept;
#else
__private::print_panic_location(location);
#endif

#if defined(SUS_PROVIDE_PANIC_HANDLER)
SUS_PROVIDE_PANIC_HANDLER();
#elif __has_builtin(__builtin_trap)
__builtin_trap();
#else
abort();
#endif
Expand Down

0 comments on commit 7147b8f

Please sign in to comment.