• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <corkscrew/backtrace.h>
2 #include <corkscrew/symbol_table.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 
do_backtrace(float)6 int do_backtrace(float /* just to test demangling */) {
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   if (frame_count <= 0) {
12     return frame_count;
13   }
14 
15   backtrace_symbol_t* backtrace_symbols = (backtrace_symbol_t*) malloc(sizeof(backtrace_symbol_t) * frame_count);
16   get_backtrace_symbols(frames, frame_count, backtrace_symbols);
17 
18   for (size_t i = 0; i < (size_t) frame_count; ++i) {
19     char line[MAX_BACKTRACE_LINE_LENGTH];
20     format_backtrace_line(i, &frames[i], &backtrace_symbols[i],
21                           line, MAX_BACKTRACE_LINE_LENGTH);
22     if (backtrace_symbols[i].symbol_name != NULL) {
23       // get_backtrace_symbols found the symbol's name with dladdr(3).
24       fprintf(stderr, "  %s\n", line);
25     } else {
26       // We don't have a symbol. Maybe this is a static symbol, and
27       // we can look it up?
28       symbol_table_t* symbols = NULL;
29       if (backtrace_symbols[i].map_name != NULL) {
30         symbols = load_symbol_table(backtrace_symbols[i].map_name);
31       }
32       const symbol_t* symbol = NULL;
33       if (symbols != NULL) {
34         symbol = find_symbol(symbols, frames[i].absolute_pc);
35       }
36       if (symbol != NULL) {
37         int offset = frames[i].absolute_pc - symbol->start;
38         fprintf(stderr, "  %s (%s%+d)\n", line, symbol->name, offset);
39       } else {
40         fprintf(stderr, "  %s (\?\?\?)\n", line);
41       }
42       free_symbol_table(symbols);
43     }
44   }
45 
46   free_backtrace_symbols(backtrace_symbols, frame_count);
47   free(backtrace_symbols);
48   free(frames);
49   return frame_count;
50 }
51 
52 struct C {
53   int g(int i);
54 };
55 
g(int i)56 __attribute__ ((noinline)) int C::g(int i) {
57   if (i == 0) {
58     return do_backtrace(0.1);
59   }
60   return g(i - 1);
61 }
62 
f()63 extern "C" __attribute__ ((noinline)) int f() {
64   C c;
65   return c.g(5);
66 }
67 
main()68 int main() {
69   flush_my_map_info_list();
70   f();
71 
72   flush_my_map_info_list();
73   f();
74 
75   return 0;
76 }
77