-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmallocTrace.cpp
117 lines (99 loc) · 2.44 KB
/
mallocTrace.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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <execinfo.h>
#include <libgen.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
static void myInitHook(void);
static void *myMallocHook(size_t, const void*);
static void myFreeHook(void*, const void*);
static void *(*old_malloc_hook)(size_t, const void *);
static void (*old_free_hook)(void*, const void *);
void (*__malloc_initialize_hook) (void) = myInitHook;
void Logout(const char *fmt, ...)
{
char path[128];
snprintf(path, sizeof(path), "pid_%d_trace.log", getpid());
FILE* pfile = fopen(path, "ab+");
if (pfile == NULL) {return;}
va_list ap;
va_start(ap, fmt);
fprintf(pfile, fmt, ap);
va_end(ap);
fclose(pfile);
}
__attribute__((constructor)) static void init_so()
{
// Logout("init so ...\n");
return;
}
static void myInitHook(void)
{
// Logout("setting up hooks...\n");
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
__malloc_hook = myMallocHook;
__free_hook = myFreeHook;
}
static void restoreOldHooks()
{
__malloc_hook = old_malloc_hook;
__free_hook = old_free_hook;
}
static void restoreMyHooks()
{
__malloc_hook = myMallocHook;
__free_hook = myFreeHook;
}
static void saveOldHooks()
{
old_malloc_hook = __malloc_hook;
old_free_hook = __free_hook;
}
void printBacktrace()
{
void *array[16];
size_t size = backtrace(array, 16);
char **strings = backtrace_symbols(array, (int)size);
if (strings == NULL)
{
Logout("backtrace symbols null");
return ;
}
size_t i = 0;
for (i = 0; i<size; ++i)
{
Logout(strings[i]);
}
free(strings);
}
static void* myMallocHook(size_t size, const void* caller)
{
void* res;
restoreOldHooks();
res = malloc(size);
saveOldHooks();
// Do your memory statistics here...
Logout("\n{\"Addr\" : \"%p\", \"type\" : \"alloc\", \"size\" : %u, \"backtrace\": \""
, res, (unsigned int) size);
printBacktrace();
Logout("\"} \n");
// Restore our own hooks
restoreMyHooks();
return res;
}
static void myFreeHook(void* ptr, const void* caller)
{
restoreOldHooks();
free(ptr);
saveOldHooks();
// Do your memory statistics here...
Logout("\n{\"Addr\" : \"%p\", \"type\" : \"free\", \"backtrace\": \"", ptr);
printBacktrace();
Logout("\"} \n");
// Restore our own hooks
restoreMyHooks();
}