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, __FILE__, __LINE__);
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)
56 __ec_free(ptr, __FILE__, __LINE__);
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 char *__ec_strdup(const char *s, const char *file, unsigned int line)
87 size_t sz = strlen(s) + 1;
90 s2 = __ec_malloc(sz, file, line);
99 char *__ec_strndup(const char *s, size_t n, const char *file, unsigned int line)
101 size_t sz = strnlen(s, n);
104 s2 = __ec_malloc(sz + 1, file, line);
114 static int ec_malloc_init_func(void)
120 static struct ec_init ec_malloc_init = {
121 .init = ec_malloc_init_func,
125 EC_INIT_REGISTER(ec_malloc_init);
127 /* LCOV_EXCL_START */
128 static int ec_malloc_testcase(void)
130 int ret, testres = 0;
133 ret = ec_malloc_register(NULL, NULL, NULL);
134 testres |= EC_TEST_CHECK(ret == -1,
135 "should not be able to register NULL malloc handlers");
136 ret = ec_malloc_register(__ec_malloc, __ec_free, __ec_realloc);
137 testres |= EC_TEST_CHECK(ret == -1,
138 "should not be able to register after init");
140 /* registration is tested in the test main.c */
146 ptr2 = ec_realloc(ptr, 20);
147 EC_TEST_CHECK(ptr2 != NULL, "cannot realloc ptr\n");
155 ptr = ec_malloc_func(10);
162 ptr = ec_calloc(2, (size_t)-1);
163 EC_TEST_CHECK(ptr == NULL, "bad overflow check in ec_calloc\n");
169 static struct ec_test ec_malloc_test = {
171 .test = ec_malloc_testcase,
174 EC_TEST_REGISTER(ec_malloc_test);