Backtracing in C++/ Linux.

How to backtrace stack symbols for logging.

need -rdynamic option flag for linker to generate export symbol in ELF.
#include <execinfo.h>  
// backtrace header file.
#include <cstdlib> #include <string> #include <cxxabi.h>  
//name mangling header file.
int main() { testbacktrace(); } int testbacktrace() { printf( "[backtracelog]:\n"); void*backtracelog[128]; memset( &backtracelog, 0, sizeof( backtracelog ) ); char** strsymbols; int backtracenptrs = backtrace(backtracelog, 128); printf("number of stackframe %d\n",backtracenptrs);         strsymbols=backtrace_symbols(backtracelog,backtracenptrs); for(int i=0; i<backtracenptrs; ++i){ demangle(strsymbols[i]); } free(strsymbols); backtrace_symbols_fd( backtracelog, backtracenptrs, 1 ); return 0; }
std::string demangle(const char* symbol) { size_t size; int status; char temp[128]; char* demangled;
//first, try to demangle a c++ name
if (1 == sscanf(symbol, "%*[^(]%*[^_]%127[^)+]", temp)) { if (NULL != (demangled = abi::__cxa_demangle(temp, NULL, &size, &status))) { std::string result(demangled); free(demangled); return result; } }
//if that didn't work, try to get a regular c symbol
if (1 == sscanf(symbol, "%127s", temp)) { return temp; }
//if all else fails, just return the symbol
return symbol; }

you can get more details here.                                             

No comments:

Post a Comment

would you like it. :)