From 22f25a9e4feddbc093ae01cd53bdda3c2c3a82e9 Mon Sep 17 00:00:00 2001 From: Craig Barnes Date: Fri, 15 Jan 2021 20:39:45 +0000 Subject: Print stack trace on assert() failure or when calling fatal_error() Note: this uses the __sanitizer_print_stack_trace() function from the AddressSanitizer runtime, so it only works when AddressSanitizer is in use. --- debug.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 debug.c (limited to 'debug.c') diff --git a/debug.c b/debug.c new file mode 100644 index 00000000..03ead23b --- /dev/null +++ b/debug.c @@ -0,0 +1,48 @@ +#include "debug.h" + +#include +#include +#include +#include +#include +#include + +#if defined(__SANITIZE_ADDRESS__) || HAS_FEATURE(address_sanitizer) +#include +#define ASAN_ENABLED 1 +#endif + +static void +print_stack_trace(void) +{ +#ifdef ASAN_ENABLED + fputs("\nStack trace:\n", stderr); + __sanitizer_print_stack_trace(); +#endif +} + +noreturn void +fatal_error(const char *msg, int err) +{ + syslog(LOG_ERR, "%s: %s", msg, strerror(err)); + errno = err; + perror(msg); + print_stack_trace(); + abort(); +} + +noreturn void +bug(const char *file, int line, const char *func, const char *fmt, ...) +{ + fprintf(stderr, "\n%s:%d: BUG in %s(): ", file, line, func); + + va_list ap; + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + fputc('\n', stderr); + print_stack_trace(); + fflush(stderr); + abort(); +} -- cgit v1.3