-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemalloc.c
More file actions
127 lines (99 loc) · 2.07 KB
/
Copy pathemalloc.c
File metadata and controls
127 lines (99 loc) · 2.07 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include "emalloc.h"
#include <string.h>
spinlock_t global_lock = SPINLOCK_INIT;
void* emalloc(size_t size)
{
#ifdef DEBUG_LOG_CALLS
log_malloc_call_start(size);
#endif
spin_lock(&global_lock);
void* ptr = NULL;
if (size <= (1 << SLAB_ALLOCATOR_MAX_OBJECT))
{
ptr = slab_alloc(size);
}
else if (size <= (1 << BUDDY_ALLOCATOR_MAX_OBJECT))
{
ptr = buddy_alloc(size);
}
else
{
ptr = mmap_alloc(size);
}
spin_unlock(&global_lock);
#ifdef DEBUG_LOG_CALLS
log_malloc_call_end(ptr);
#endif
return ptr;
}
void* ecalloc(size_t count, size_t size)
{
if (size != 0 && count > SIZE_MAX / size)
{
return NULL;
}
const size_t actual_size = count * size;
void* ptr = emalloc(actual_size);
if (ptr != NULL)
{
memset(ptr, 0, actual_size);
}
return ptr;
}
void* erealloc(void* ptr, size_t size)
{
if (ptr == NULL)
{
return emalloc(size);
}
if (size == 0)
{
efree(ptr);
return NULL;
}
const size_t old_size = emalloc_usable_size(ptr);
void* new_ptr = emalloc(size);
const size_t copy_size = (size < old_size) ? size : old_size;
memcpy(new_ptr, ptr, copy_size);
efree(ptr);
return new_ptr;
}
void efree(void* ptr)
{
if (ptr == NULL)
{
return;
}
#ifdef DEBUG_LOG_CALLS
log_free_call(ptr);
#endif
spin_lock(&global_lock);
const void* heap_end = brk_get_allocated_heap_end();
if (ptr > heap_end)
{
mmap_free(ptr);
}
else
{
// Slab free is routed through the buddy allocator's free
buddy_free(ptr);
}
spin_unlock(&global_lock);
}
size_t emalloc_usable_size(void* ptr)
{
spin_lock(&global_lock);
const void* heap_end = brk_get_allocated_heap_end();
size_t size;
if (ptr > heap_end)
{
size = mmap_usable_size(ptr);
}
else
{
// Slab get_realloc_size is routed through the buddy allocator
size = buddy_usable_size(ptr);
}
spin_unlock(&global_lock);
return size;
}