backtrace: Add a library to access the backtrace

Provide an API to access the backtrace, in an arch-neutral way.

The backtrace can be retrieved, examined and printed.

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <simon.glass@canonical.com>
This commit is contained in:
Simon Glass
2025-11-28 05:29:39 -07:00
committed by Simon Glass
parent e0b8e54f52
commit cdde93a9e3
4 changed files with 121 additions and 0 deletions

40
lib/backtrace.c Normal file
View File

@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-2.0+
/*
* Stack-backtrace support
*
* Copyright 2025 Canonical Ltd
* Written by Simon Glass <simon.glass@canonical.com>
*/
#include <backtrace.h>
#include <stdio.h>
int backtrace_show(void)
{
char buf[BACKTRACE_BUFSZ];
struct backtrace_ctx ctx;
uint i;
int ret;
ret = backtrace_init(&ctx, 1);
if (ret < 0)
return ret;
ret = backtrace_get_syms(&ctx, buf, sizeof(buf));
if (ret) {
backtrace_uninit(&ctx);
return ret;
}
printf("backtrace: %d addresses\n", ctx.count);
for (i = 0; i < ctx.count; i++) {
if (ctx.syms[i])
printf(" %s\n", ctx.syms[i]);
else
printf(" %p\n", ctx.addrs[i]);
}
backtrace_uninit(&ctx);
return 0;
}