-
Notifications
You must be signed in to change notification settings - Fork 4
/
mytrace.c
99 lines (84 loc) · 1.94 KB
/
mytrace.c
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 <stdio.h>
#include <string.h>
#define OK 0
#define ERROR -1
#define MAX_OFFSET 4
#define MAX_BUFF_SIZE 1024
int get_func_from_symbol(unsigned int address, char *func, const char *name)
{
FILE *p = NULL;
char line[MAX_BUFF_SIZE + 1] = { 0 };
sprintf(line, "addr2line -e %s -f -s 0x%x", name, address);
p = popen(line, "r");
if (p == NULL)
{
printf("popen() failed\n");
return ERROR;
}
else
{
fread(line, MAX_BUFF_SIZE, 1, p);
for (int i = 0; i < strlen(line); i++)
{
if ((line[i] == 0x0d) || (line[i] == 0x0a))
{
func[i] = 0;
break;
}
else
{
func[i] = line[i];
}
}
pclose(p);
}
return OK;
}
int main(int argc, char **argv)
{
char type;
char func[80];
FILE *fp = NULL;
unsigned int address;
int i = -1;
if (argc != 3)
{
printf("Usage: %s <test.exe> <trace.txt>\n", argv[0]);
return ERROR;
}
fp = fopen(argv[2], "r");
if (fp == NULL)
{
printf("fopen() failed\n");
return ERROR;
}
while (!feof(fp))
{
fscanf(fp, "%c0x%x\n", &type, &address);
memset(func, 0, sizeof(func));
// 通过函数地址获取函数名称
if (get_func_from_symbol(address, func, argv[1]) == ERROR)
{
fclose(fp);
return ERROR;
}
// 进入函数
if (type == 'E')
{
i ++;
for (int j = 0; j < i * MAX_OFFSET; j++)
printf(" ");
printf("--> %s() [%d]\n", func, i);
}
// 退出函数
else if (type == 'X')
{
for (int j = 0; j < i * MAX_OFFSET; j++)
printf(" ");
printf("<-- %s() [%d]\n", func, i);
i --;
}
}
fclose(fp);
return OK;
}