-
Notifications
You must be signed in to change notification settings - Fork 0
/
leakchecker.c
121 lines (112 loc) · 2.32 KB
/
leakchecker.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdint.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <stdio.h>
#include "leakchecker.h"
void *malloc(size_t size)
{
static void *(*memfunc)(size_t) = NULL;
if (!memfunc)
{
memfunc = dlsym(RTLD_NEXT, "malloc");
}
void *p = memfunc(size);
track(size, p, 0x0, 0x0);
printMem();
return p;
}
void free(void *p)
{
static void *(*memfree)(void *ptr) = NULL;
if (!memfree)
{
memfree = dlsym(RTLD_NEXT, "free");
}
track(0, p, 0x1, 0x0);
memfree(p);
printMem();
}
struct Block
{
void *ptr;
size_t size;
struct Block *next;
};
typedef struct Block Block;
void track(size_t size, void *ptr, char b, char p)
{
static void *(*memfunc)(size_t) = NULL;
if (!memfunc)
{
memfunc = dlsym(RTLD_NEXT, "malloc");
}
static void *(*memfree)(void *ptr) = NULL;
if (!memfree)
{
memfree = dlsym(RTLD_NEXT, "free");
}
static Block *inIt = NULL;
static size_t total = 0;
static Block *alloced = NULL;
if (p == 0x1)
{
printf("Allocated memory: %zu \n", total);
return;
}
if (!alloced)
{
alloced = (Block *)memfunc(sizeof(Block));
alloced->ptr = NULL;
alloced->size = 0;
alloced->next = NULL;
inIt = alloced;
}
if (b == 0x0)
{
Block *b = (Block *)memfunc(sizeof(Block));
b->ptr = ptr;
b->size = size;
b->next = NULL;
inIt->next = b;
inIt = b;
total += size;
}
else
{
if (ptr == NULL)
{
return;
}
Block *prev = NULL;
for (Block *t = alloced; t != inIt; t = t->next)
{
if (t->ptr == ptr)
{
total -= t->size;
if (t == alloced)
{
alloced = alloced->next;
memfree(t);
}
else
{
prev->next = t->next;
memfree(t);
}
break;
}
prev = t;
}
if (inIt->ptr == ptr)
{
total -= inIt->size;
prev->next = NULL;
memfree(inIt);
inIt = prev;
}
}
}
void printMem()
{
track(0, NULL, 0, 0x1);
}