Skip to content

Commit dd78fdf

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 dd78fdf

2 files changed

Lines changed: 35 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: 'Does struct tm have a tm_gmtoff field?'
207+
)
193208

194209
if cc.has_function_attribute('fallthrough')
195210
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)