Skip to content

Commit 7694358

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 7694358

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

meson.build

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,23 @@ 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+
'''
197+
#include <malloc.h>
198+
void *malloc(size_t size)
199+
{
200+
return NULL;
201+
}
202+
int main(void) {
203+
malloc(1);
204+
}
205+
''',
206+
name: 'weak_malloc'
207+
),
208+
description: 'Does struct tm have a tm_gmtoff field?'
209+
)
193210

194211
if cc.has_function_attribute('fallthrough')
195212
conf.set('fallthrough', '__attribute__((__fallthrough__))')

util/mem.c

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

89
#include "mem.h"
@@ -107,3 +108,22 @@ void nvme_free_huge(struct nvme_mem_huge *mh)
107108
mh->len = 0;
108109
mh->p = NULL;
109110
}
111+
112+
#ifdef HAVE_WEAK_MALLOC
113+
void *malloc(size_t size)
114+
{
115+
static void *(*malloc_sym)(size_t size);
116+
void *result = NULL;
117+
118+
if (!malloc_sym)
119+
malloc_sym = dlsym(RTLD_NEXT, "malloc");
120+
121+
if (malloc_sym)
122+
result = malloc_sym(size);
123+
124+
if (!result)
125+
abort();
126+
127+
return result;
128+
}
129+
#endif /* HAVE_WEAK_MALLOC */

0 commit comments

Comments
 (0)