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>
14 EC_LOG_TYPE_REGISTER(malloc);
16 static int init_done = 0;
18 struct ec_malloc_handler ec_malloc_handler;
20 int ec_malloc_register(ec_malloc_t usr_malloc, ec_free_t usr_free,
21 ec_realloc_t usr_realloc)
23 if (usr_malloc == NULL || usr_free == NULL || usr_realloc == NULL) {
33 ec_malloc_handler.malloc = usr_malloc;
34 ec_malloc_handler.free = usr_free;
35 ec_malloc_handler.realloc = usr_realloc;
40 void *__ec_malloc(size_t size, const char *file, unsigned int line)
42 return ec_malloc_handler.malloc(size, file, line);
45 void *ec_malloc_func(size_t size)
47 return ec_malloc(size);
50 void __ec_free(void *ptr, const char *file, unsigned int line)
52 ec_malloc_handler.free(ptr, file, line);
55 void ec_free_func(void *ptr)
60 void *__ec_calloc(size_t nmemb, size_t size, const char *file,
68 if (nmemb != 0 && size != (total / nmemb)) {
73 ptr = __ec_malloc(total, file, line);
77 memset(ptr, 0, total);
81 void *__ec_realloc(void *ptr, size_t size, const char *file, unsigned int line)
83 return ec_malloc_handler.realloc(ptr, size, file, line);
86 void ec_realloc_func(void *ptr, size_t size)
88 ec_realloc(ptr, size);
91 char *__ec_strdup(const char *s, const char *file, unsigned int line)
93 size_t sz = strlen(s) + 1;
96 s2 = __ec_malloc(sz, file, line);
105 char *__ec_strndup(const char *s, size_t n, const char *file, unsigned int line)
107 size_t sz = strnlen(s, n);
110 s2 = __ec_malloc(sz + 1, file, line);
120 static int ec_malloc_init_func(void)
126 static struct ec_init ec_malloc_init = {
127 .init = ec_malloc_init_func,
131 EC_INIT_REGISTER(ec_malloc_init);
133 /* LCOV_EXCL_START */
134 static int ec_malloc_testcase(void)
136 int ret, testres = 0;
139 ret = ec_malloc_register(NULL, NULL, NULL);
140 testres |= EC_TEST_CHECK(ret == -1,
141 "should not be able to register NULL malloc handlers");
142 ret = ec_malloc_register(__ec_malloc, __ec_free, __ec_realloc);
143 testres |= EC_TEST_CHECK(ret == -1,
144 "should not be able to register after init");
146 /* registration is tested in the test main.c */
152 ptr2 = ec_realloc(ptr, 20);
153 EC_TEST_CHECK(ptr2 != NULL, "cannot realloc ptr\n");
161 ptr = ec_malloc_func(10);
168 /* here we use atoll() instead of a constant because we want to
169 * prevent the compiler to check the overflow at compilation
171 ptr = ec_calloc(2, atoll("0xffffffffffffffff"));
172 EC_TEST_CHECK(ptr == NULL, "bad overflow check in ec_calloc\n");
178 static struct ec_test ec_malloc_test = {
180 .test = ec_malloc_testcase,
183 EC_TEST_REGISTER(ec_malloc_test);