1 // stacktrace.h (c) 2008, Timo Bingmann from http://idlebox.net/
2 // published under the WTFPL v2.0
4 #ifndef __STACKTRACE_H__
5 #define __STACKTRACE_H__
12 /** Print a demangled stack backtrace of the caller function to FILE* out. */
13 static inline void print_stacktrace(FILE *out = stderr, unsigned int max_frames = 63)
15 fprintf(out, "stack trace:\n");
17 // storage array for stack trace address data
18 void* addrlist[max_frames+1];
20 // retrieve current stack addresses
21 int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
24 fprintf(out, " <empty, possibly corrupt>\n");
28 // resolve addresses into strings containing "filename(function+address)",
29 // this array must be free()-ed
30 char** symbollist = backtrace_symbols(addrlist, addrlen);
32 // allocate string which will be filled with the demangled function name
33 size_t funcnamesize = 256;
34 char* funcname = (char*)malloc(funcnamesize);
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 char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
41 // find parentheses and +address offset surrounding the mangled name:
42 // ./module(function+0x15c) [0x8048a6d]
43 for (char *p = symbollist[i]; *p; ++p) {
48 else if (*p == ')' && begin_offset) {
54 if (begin_name && begin_offset && end_offset && begin_name < begin_offset) {
56 *begin_offset++ = '\0';
59 // mangled name is now in [begin_name, begin_offset) and caller
60 // offset in [begin_offset, end_offset). now apply
64 char* ret = abi::__cxa_demangle(begin_name,
65 funcname, &funcnamesize, &status);
67 funcname = ret; // use possibly realloc()-ed string
68 fprintf(out, " %s : %s+%s\n",
69 symbollist[i], funcname, begin_offset);
71 // demangling failed. Output function name as a C function with
73 fprintf(out, " %s : %s()+%s\n",
74 symbollist[i], begin_name, begin_offset);
77 // couldn't parse the line? print the whole line.
78 fprintf(out, " %s\n", symbollist[i]);
86 #endif // __STACKTRACE_H__