Skip to content

Instantly share code, notes, and snippets.

@NanXiao
Created September 2, 2021 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NanXiao/c55f6a299a9739518ac69733430986c4 to your computer and use it in GitHub Desktop.
Save NanXiao/c55f6a299a9739518ac69733430986c4 to your computer and use it in GitHub Desktop.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
void
backtrace(void)
{
unw_cursor_t cursor;
unw_context_t context;
int ret;
// Initialize cursor to current frame for local unwinding.
if (unw_getcontext(&context) != 0) {
fprintf(stderr, "unw_getcontext error!\n");
return;
}
ret = unw_init_local(&cursor, &context);
if (ret != 0) {
fprintf(stderr, "unw_init_local error: %s", unw_strerror(ret));
return;
}
int str_size = 0;
char stack_trace[4096];
// Unwind frames one by one, going up the frame stack.
while (unw_step(&cursor) > 0) {
unw_word_t offset, pc;
ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
if (ret != 0) {
fprintf(stderr, "unw_get_reg error: %s", unw_strerror(ret));
return;
}
if (pc == 0) {
break;
}
str_size += snprintf(
stack_trace + str_size,
sizeof(stack_trace) - str_size,
"0x%lx:", pc);
char sym[256];
ret = unw_get_proc_name(&cursor, sym, sizeof(sym), &offset);
if (ret == 0) {
str_size += snprintf(
stack_trace + str_size,
sizeof(stack_trace) - str_size,
" (%s+0x%lx)\n", sym, offset);
} else {
str_size += snprintf(
stack_trace + str_size,
sizeof(stack_trace) - str_size,
" -- error(%s): unable to obtain symbol name for this frame\n", unw_strerror(ret));
}
}
printf("%s", stack_trace);
}
void
foo(void)
{
backtrace(); // <-------- backtrace here!
}
void
bar(void)
{
foo();
}
int
main(int argc, char **argv)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, (void *(*)(void*))bar, NULL);
pthread_create(&t2, NULL, (void *(*)(void*))bar, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment