Skip to content

Commit b3fce85

Browse files
committed
mem: add malloc function to abort for failure
The __malloc_hook deprecated and malloc function is weak function. Then we can add malloc function to abort when failed to allocate. Signed-off-by: Tokunori Ikegami <[email protected]>
1 parent d16e8d8 commit b3fce85

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

meson.build

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,21 @@ conf.set(
190190
),
191191
description: 'Does struct tm have a tm_gmtoff field?'
192192
)
193+
conf.set(
194+
'HAVE_WEAK_MALLOC',
195+
cc.links(
196+
'''#include <malloc.h>
197+
void *malloc(size_t size) {
198+
return NULL;
199+
}
200+
int main(void) {
201+
malloc(1);
202+
}
203+
''',
204+
name: 'weak_malloc'
205+
),
206+
description: 'Is malloc() weak function?'
207+
)
193208

194209
if cc.has_function_attribute('fallthrough')
195210
conf.set('fallthrough', '__attribute__((__fallthrough__))')

util/mem.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
#include <unistd.h>
44
#include <malloc.h>
55
#include <string.h>
6+
#include <dlfcn.h>
67
#include <sys/mman.h>
8+
#include <ccan/likely/likely.h>
79

810
#include "mem.h"
911

@@ -107,3 +109,56 @@ void nvme_free_huge(struct nvme_mem_huge *mh)
107109
mh->len = 0;
108110
mh->p = NULL;
109111
}
112+
113+
#ifdef HAVE_WEAK_MALLOC
114+
void *malloc(size_t size)
115+
{
116+
static void *(*malloc_sym)(size_t size);
117+
void *result = NULL;
118+
119+
if (!malloc_sym)
120+
malloc_sym = dlsym(RTLD_NEXT, "malloc");
121+
122+
if (malloc_sym)
123+
result = malloc_sym(size);
124+
125+
if (unlikely(!result))
126+
abort();
127+
128+
return result;
129+
}
130+
131+
void *calloc(size_t number, size_t size)
132+
{
133+
static void *(*calloc_sym)(size_t number, size_t size);
134+
void *result = NULL;
135+
136+
if (!calloc_sym)
137+
calloc_sym = dlsym(RTLD_NEXT, "calloc");
138+
139+
if (calloc_sym)
140+
result = calloc_sym(number, size);
141+
142+
if (unlikely(!result))
143+
abort();
144+
145+
return result;
146+
}
147+
148+
void *realloc(void *ptr, size_t size)
149+
{
150+
static void *(*realloc_sym)(void *ptr, size_t size);
151+
void *result = NULL;
152+
153+
if (!realloc_sym)
154+
realloc_sym = dlsym(RTLD_NEXT, "realloc");
155+
156+
if (realloc_sym)
157+
result = realloc_sym(ptr, size);
158+
159+
if (unlikely(!result))
160+
abort();
161+
162+
return result;
163+
}
164+
#endif /* HAVE_WEAK_MALLOC */

0 commit comments

Comments
 (0)