-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmalloc_bt.cpp
108 lines (80 loc) · 2.18 KB
/
malloc_bt.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
#include "libc_malloc.hpp"
#include "libc_allocator.hpp"
#ifdef ZERO
#ifdef __STDC_LIB_EXT1__
#error STDC_LIB_EXT1 is required!
#endif
#define __STDC_WANT_LIB_EXT1__ 1
#include <cstring>
#endif
#include <iostream>
#include <cassert>
#include <cstdint>
// TODO no overflow check
static uint64_t malloc_counter = 0;
static uint64_t free_counter = 0;
static uint64_t realloc_counter = 0;
static uint64_t calloc_counter = 0;
extern "C" void *malloc(size_t size) {
++malloc_counter;
size_t new_size = size;
#ifdef ZERO
new_size += sizeof(size_t);
#endif
char *temp = static_cast<char *>(__libc_malloc(new_size));
#ifdef ZERO
*reinterpret_cast<size_t *>(temp) = size;
temp += sizeof(size_t);
#endif
return static_cast<void *>(temp);
}
extern "C" void free(void *ptr) {
++free_counter;
if (ptr == 0) return;
#ifdef ZERO
char *ptr_ch = static_cast<char *>(ptr);
size_t *size_ptr = reinterpret_cast<size_t *>(ptr_ch - sizeof(size_t));
assert(0 = memset_s(ptr, *size_ptr, 0, *size_ptr));
*size_ptr = 0;
void *real_ptr = static_cast<void *>(ptr_ch - sizeof(size_t));
#else
void *real_ptr = ptr;
#endif
__libc_free(real_ptr);
}
extern "C" void *realloc(void *ptr, size_t new_size) {
++realloc_counter;
if (new_size == 0) return nullptr;
#ifdef ZERO
if (ptr == NULL) {
void *temp = malloc(new_size);
return temp;
}
void *temp = malloc(new_size);
size_t old_size = *(size_t *)(static_cast<char *>(ptr) - sizeof(size_t));
size_t copy_size = (old_size < new_size) ? old_size : new_size;
std::memcpy(temp, ptr, copy_size);
free(ptr);
#else
void *temp = __libc_realloc(ptr, new_size);
#endif
return temp;
}
extern "C" void *calloc(size_t num, size_t size) {
#ifdef ZERO
++calloc_counter;
void *ptr = malloc(num * size);
std::memset(ptr, 0, num * size);
#else
void *ptr = __libc_calloc(num, size);
#endif
return ptr;
}
__attribute__((destructor)) static void destructor() {
std::cout << "===" << std::endl;
std::cout << "malloc: \t" << malloc_counter << std::endl;
std::cout << "free: \t" << free_counter << std::endl;
std::cout << "realloc: \t" << realloc_counter << std::endl;
std::cout << "calloc: \t" << calloc_counter << std::endl;
std::cout << "===" << std::endl;
}