SDRAngel  4.11.5
Developer docs for <a href="https://github.com/f4exb/sdrangel">SDRangel<\a>, an Open Source Qt5 / OpenGL 3.0+ SDR and signal analyzer frontend to various hardware.
stacktrace.h
Go to the documentation of this file.
1 // stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/
2 // published under the WTFPL v2.0
3 
4 #ifndef _STACKTRACE_H_
5 #define _STACKTRACE_H_
6 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <execinfo.h>
10 #include <cxxabi.h>
11 
13 static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames = 63)
14 {
15  fprintf(out, "stack trace:\n");
16 
17  // storage array for stack trace address data
18  void* addrlist[max_frames+1];
19 
20  // retrieve current stack addresses
21  int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
22 
23  if (addrlen == 0) {
24  fprintf(out, " <empty, possibly corrupt>\n");
25  return;
26  }
27 
28  // resolve addresses into strings containing "filename(function+address)",
29  // this array must be free()-ed
30  char** symbollist = backtrace_symbols(addrlist, addrlen);
31 
32  // allocate string which will be filled with the demangled function name
33  size_t funcnamesize = 256;
34  char* funcname = (char*)malloc(funcnamesize);
35 
36  // iterate over the returned symbol lines. skip the first, it is the
37  // address of this function.
38  for (int i = 1; i < addrlen; i++)
39  {
40  char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
41 
42  // find parentheses and +address offset surrounding the mangled name:
43  // ./module(function+0x15c) [0x8048a6d]
44  for (char *p = symbollist[i]; *p; ++p)
45  {
46  if (*p == '(')
47  begin_name = p;
48  else if (*p == '+')
49  begin_offset = p;
50  else if (*p == ')' && begin_offset) {
51  end_offset = p;
52  break;
53  }
54  }
55 
56  if (begin_name && begin_offset && end_offset
57  && begin_name < begin_offset)
58  {
59  *begin_name++ = '\0';
60  *begin_offset++ = '\0';
61  *end_offset = '\0';
62 
63  // mangled name is now in [begin_name, begin_offset) and caller
64  // offset in [begin_offset, end_offset). now apply
65  // __cxa_demangle():
66 
67  int status;
68  char* ret = abi::__cxa_demangle(begin_name,
69  funcname, &funcnamesize, &status);
70  if (status == 0) {
71  funcname = ret; // use possibly realloc()-ed string
72  fprintf(out, " %s : %s+%s\n",
73  symbollist[i], funcname, begin_offset);
74  }
75  else {
76  // demangling failed. Output function name as a C function with
77  // no arguments.
78  fprintf(out, " %s : %s()+%s\n",
79  symbollist[i], begin_name, begin_offset);
80  }
81  }
82  else
83  {
84  // couldn't parse the line? print the whole line.
85  fprintf(out, " %s\n", symbollist[i]);
86  }
87  }
88 
89  free(funcname);
90  free(symbollist);
91 }
92 
93 #endif // _STACKTRACE_H_
int32_t i
Definition: decimators.h:244