-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacktrace.cpp
64 lines (55 loc) · 1.78 KB
/
stacktrace.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <execinfo.h> // for backtrace
#include <dlfcn.h> // for dladdr
#include <cxxabi.h> // for __cxa_demangle
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
// This function produces a stack backtrace with demangled function & method names.
std::string Backtrace(int skip = 1)
{
void *callstack[128];
const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
char buf[1024];
int nFrames = backtrace(callstack, nMaxFrames);
char **symbols = backtrace_symbols(callstack, nFrames);
std::ostringstream trace_buf;
for (int i = skip; i < nFrames; i++) {
printf("%s\n", symbols[i]);
Dl_info info;
if (dladdr(callstack[i], &info) && info.dli_sname) {
char *demangled = NULL;
int status = -1;
if (info.dli_sname[0] == '_')
demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n",
i, int(2 + sizeof(void*) * 2), callstack[i],
status == 0 ? demangled :
info.dli_sname == 0 ? symbols[i] : info.dli_sname,
(char *)callstack[i] - (char *)info.dli_saddr);
free(demangled);
} else {
snprintf(buf, sizeof(buf), "%-3d %*p %s\n",
i, int(2 + sizeof(void*) * 2), callstack[i], symbols[i]);
}
trace_buf << buf;
}
free(symbols);
if (nFrames == nMaxFrames)
trace_buf << "[truncated]\n";
return trace_buf.str();
}
void f2(int arg2) {
auto btrace = Backtrace();
cout << btrace << std::endl;
}
void f1(int arg1) {
int arg2=arg1;
f2(arg2);
}
int main(int argc, char* argv[]) {
f1(1);
return 0;
}