Skip to content

Commit e44f63d

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 e44f63d

3 files changed

Lines changed: 40 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: 19 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,21 @@ 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+
CHECK_NULL_PTR(result);
125+
126+
return result;
127+
}
128+
#endif /* HAVE_WEAK_MALLOC */

util/mem.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@
55
#include <stddef.h>
66
#include <stdbool.h>
77

8+
#define CHECK_NULL_PTR(ptr) \
9+
do { \
10+
if (!ptr) \
11+
abort(); \
12+
} while (false)
13+
814
void *nvme_alloc(size_t len);
915
void *nvme_realloc(void *p, size_t len);
1016

0 commit comments

Comments
 (0)