1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright 2016, Olivier MATZ <zer0@droids-corp.org>
5 #include <ecoli_init.h>
6 #include <ecoli_test.h>
7 #include <ecoli_malloc.h>
13 EC_LOG_TYPE_REGISTER(malloc);
15 static int init_done = 0;
17 struct ec_malloc_handler ec_malloc_handler;
19 int ec_malloc_register(ec_malloc_t usr_malloc, ec_free_t usr_free,
20 ec_realloc_t usr_realloc)
22 if (usr_malloc == NULL || usr_free == NULL || usr_realloc == NULL) {
32 ec_malloc_handler.malloc = usr_malloc;
33 ec_malloc_handler.free = usr_free;
34 ec_malloc_handler.realloc = usr_realloc;
39 void *__ec_malloc(size_t size, const char *file, unsigned int line)
41 return ec_malloc_handler.malloc(size, file, line);
44 void *ec_malloc_func(size_t size)
46 return ec_malloc(size);
49 void __ec_free(void *ptr, const char *file, unsigned int line)
51 ec_malloc_handler.free(ptr, file, line);
54 void ec_free_func(void *ptr)
59 void *__ec_calloc(size_t nmemb, size_t size, const char *file,
67 if (nmemb != 0 && size != (total / nmemb)) {
72 ptr = __ec_malloc(total, file, line);
76 memset(ptr, 0, total);
80 void *__ec_realloc(void *ptr, size_t size, const char *file, unsigned int line)
82 return ec_malloc_handler.realloc(ptr, size, file, line);
85 void ec_realloc_func(void *ptr, size_t size)
87 ec_realloc(ptr, size);
90 char *__ec_strdup(const char *s, const char *file, unsigned int line)
92 size_t sz = strlen(s) + 1;
95 s2 = __ec_malloc(sz, file, line);
104 char *__ec_strndup(const char *s, size_t n, const char *file, unsigned int line)
106 size_t sz = strnlen(s, n);
109 s2 = __ec_malloc(sz + 1, file, line);
119 static int ec_malloc_init_func(void)
125 static struct ec_init ec_malloc_init = {
126 .init = ec_malloc_init_func,
130 EC_INIT_REGISTER(ec_malloc_init);
132 /* LCOV_EXCL_START */
133 static int ec_malloc_testcase(void)
135 int ret, testres = 0;
138 ret = ec_malloc_register(NULL, NULL, NULL);
139 testres |= EC_TEST_CHECK(ret == -1,
140 "should not be able to register NULL malloc handlers");
141 ret = ec_malloc_register(__ec_malloc, __ec_free, __ec_realloc);
142 testres |= EC_TEST_CHECK(ret == -1,
143 "should not be able to register after init");
145 /* registration is tested in the test main.c */
151 ptr2 = ec_realloc(ptr, 20);
152 EC_TEST_CHECK(ptr2 != NULL, "cannot realloc ptr\n");
160 ptr = ec_malloc_func(10);
167 ptr = ec_calloc(2, (size_t)-1);
168 EC_TEST_CHECK(ptr == NULL, "bad overflow check in ec_calloc\n");
174 static struct ec_test ec_malloc_test = {
176 .test = ec_malloc_testcase,
179 EC_TEST_REGISTER(ec_malloc_test);