1#include <corkscrew/backtrace.h>
2#include <corkscrew/symbol_table.h>
3#include <stdio.h>
4#include <stdlib.h>
5
6void do_backtrace() {
7  const size_t MAX_DEPTH = 32;
8  backtrace_frame_t* frames = (backtrace_frame_t*) malloc(sizeof(backtrace_frame_t) * MAX_DEPTH);
9  ssize_t frame_count = unwind_backtrace(frames, 0, MAX_DEPTH);
10  fprintf(stderr, "frame_count=%d\n", (int) frame_count);
11
12  backtrace_symbol_t* backtrace_symbols = (backtrace_symbol_t*) malloc(sizeof(backtrace_symbol_t) * frame_count);
13  get_backtrace_symbols(frames, frame_count, backtrace_symbols);
14
15  for (size_t i = 0; i < (size_t) frame_count; ++i) {
16    char line[MAX_BACKTRACE_LINE_LENGTH];
17    format_backtrace_line(i, &frames[i], &backtrace_symbols[i],
18                          line, MAX_BACKTRACE_LINE_LENGTH);
19    if (backtrace_symbols[i].symbol_name != NULL) {
20      // get_backtrace_symbols found the symbol's name with dladdr(3).
21      fprintf(stderr, "  %s\n", line);
22    } else {
23      // We don't have a symbol. Maybe this is a static symbol, and
24      // we can look it up?
25      symbol_table_t* symbols = NULL;
26      if (backtrace_symbols[i].map_name != NULL) {
27        symbols = load_symbol_table(backtrace_symbols[i].map_name);
28      }
29      const symbol_t* symbol = NULL;
30      if (symbols != NULL) {
31        symbol = find_symbol(symbols, frames[i].absolute_pc);
32      }
33      if (symbol != NULL) {
34        uintptr_t offset = frames[i].absolute_pc - symbol->start;
35        fprintf(stderr, "  %s (%s%+d)\n", line, symbol->name, offset);
36      } else {
37        fprintf(stderr, "  %s (\?\?\?)\n", line);
38      }
39      free_symbol_table(symbols);
40    }
41  }
42
43  free_backtrace_symbols(backtrace_symbols, frame_count);
44  free(backtrace_symbols);
45  free(frames);
46}
47
48__attribute__ ((noinline)) void g() {
49  fprintf(stderr, "g()\n");
50  do_backtrace();
51}
52
53__attribute__ ((noinline)) int f(int i) {
54  fprintf(stderr, "f(%i)\n", i);
55  if (i == 0) {
56    g();
57    return 0;
58  }
59  return f(i - 1);
60}
61
62int main() {
63  return f(5);
64}
65