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__
13 * @brief Print a demangled stack backtrace of the caller function to file
16 static inline void print_stacktrace(int fd = STDERR_FILENO, unsigned int max_frames = 63)
18 dprintf(fd, "stack trace:\n");
20 // storage array for stack trace address data
21 void* addrlist[max_frames+1];
23 // retrieve current stack addresses
24 int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
27 dprintf(fd, " <empty, possibly corrupt>\n");
31 // resolve addresses into strings containing "filename(function+address)",
32 // this array must be free()-ed
33 char** symbollist = backtrace_symbols(addrlist, addrlen);
35 // allocate string which will be filled with the demangled function name
36 size_t funcnamesize = 256;
37 char* funcname = (char*)malloc(funcnamesize);
39 // iterate over the returned symbol lines. skip the first, it is the
40 // address of this function.
41 for (int i = 1; i < addrlen; i++) {
42 char *begin_name = 0, *begin_offset = 0, *end_offset = 0;
44 // find parentheses and +address offset surrounding the mangled name:
45 // ./module(function+0x15c) [0x8048a6d]
46 for (char *p = symbollist[i]; *p; ++p) {
51 else if (*p == ')' && begin_offset) {
57 if (begin_name && begin_offset && end_offset && begin_name < begin_offset) {
59 *begin_offset++ = '\0';
62 // mangled name is now in [begin_name, begin_offset) and caller
63 // offset in [begin_offset, end_offset). now apply
67 char* ret = abi::__cxa_demangle(begin_name,
68 funcname, &funcnamesize, &status);
70 funcname = ret; // use possibly realloc()-ed string
71 dprintf(fd, " %s : %s+%s\n",
72 symbollist[i], funcname, begin_offset);
74 // demangling failed. Output function name as a C function with
76 dprintf(fd, " %s : %s()+%s\n",
77 symbollist[i], begin_name, begin_offset);
80 // couldn't parse the line? print the whole line.
81 dprintf(fd, " %s\n", symbollist[i]);
89 static inline void print_stacktrace(FILE *out, unsigned int max_frames = 63)
91 print_stacktrace(fileno(out), max_frames);
94 #endif // __STACKTRACE_H__