From df88f5645085dd8de2ff8206bda75e13d10db9b6 Mon Sep 17 00:00:00 2001 From: Josh Holtrop Date: Thu, 14 May 2026 09:37:08 -0400 Subject: [PATCH] Add stackdump source --- .gitignore | 1 + Makefile | 2 ++ stackdump.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 stackdump.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a86233a --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/stackdump diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..05a2e0b --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +stackdump: stackdump.c Makefile + clang -o $@ -Wall -g stackdump.c -lunwind diff --git a/stackdump.c b/stackdump.c new file mode 100644 index 0000000..b6d7a82 --- /dev/null +++ b/stackdump.c @@ -0,0 +1,54 @@ +#define UNW_LOCAL_ONLY +#include +#include +#include + +// Function to print the current stack trace +void show_backtrace(void) +{ + unw_cursor_t cursor; + unw_context_t context; + unw_word_t ip, sp; + char sym[256]; + unw_word_t offset; + + // Initialize cursor to current frame for local unwinding + unw_getcontext(&context); + unw_init_local(&cursor, &context); + + printf("--- Stack Trace ---\n"); + // Unwind frames one by one + while (unw_step(&cursor) > 0) { + unw_get_reg(&cursor, UNW_REG_IP, &ip); + unw_get_reg(&cursor, UNW_REG_SP, &sp); + + // Try to get the function name + if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) { + printf("0x%lx: (%s+0x%lx)\n", (long)ip, sym, (long)offset); + } else { + printf("0x%lx: -- no symbol name found --\n", (long)ip); + } + } + printf("-------------------\n"); +} + +void function_c(void) +{ + show_backtrace(); +} + +void function_b(void) +{ + function_c(); +} + +void function_a(void) +{ + function_b(); +} + +int main(int argc, char **argv) +{ + function_a(); + return 0; +}