-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBacktrace.cpp
More file actions
99 lines (81 loc) · 1.86 KB
/
Copy pathBacktrace.cpp
File metadata and controls
99 lines (81 loc) · 1.86 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <libunwind-x86_64.h>
#include <libunwind.h>
#include <string>
using namespace std;
class Backtrace
{
private:
unw_context_t context; //current register context
unw_cursor_t cursor; // traverse stack frames
unw_word_t pc, offset;
public:
Backtrace(){}
void enterFunction(const string &funcName);
void exitFunction(const string &funcName);
void printBacktrace();
};
//Class Functions
void Backtrace::enterFunction(const string &funcName)
{
cout << "[ENTER] " << funcName << endl;
}
void Backtrace::exitFunction(const string &funcName)
{
cout << "[EXIT] " << funcName << endl;
}
void Backtrace::printBacktrace()
{
unw_getcontext(&context); //excution state
unw_init_local(&cursor, &context); //Initailize cursor to the current frame
cout << "Backtrace:" << endl;
while( unw_step(&cursor) > 0 )
{
char fname[256];
unw_get_reg(&cursor, UNW_REG_IP, &pc);
if(unw_get_proc_name(&cursor, fname, sizeof(fname), &offset) == 0)
{
cout << fname << " " << "+ 0x" << hex << offset << "[0x" << pc << "]" << dec << endl;
}
else
{
cout << "Unknown function " << endl;
}
}
}
//Test Functions
void fun2();
void fun3();
void fun1()
{
Backtrace f1bt;
f1bt.enterFunction(__func__);
fun2();
f1bt.exitFunction(__func__);
}
void fun2()
{
Backtrace f2bt;
f2bt.enterFunction(__func__);
fun3();
f2bt.exitFunction(__func__);
}
void fun3()
{
Backtrace f3bt;
f3bt.enterFunction(__func__);
f3bt.printBacktrace();
f3bt.exitFunction(__func__);
}
int main()
{
Backtrace mainbt;
mainbt.enterFunction(__func__);
fun1();
mainbt.exitFunction(__func__);
return 0;
}
/*
Compilation:
g++ -g Backtrace.cpp -lunwind -lunwind-x86_64 -o backtrace
*/