summaryrefslogtreecommitdiffstats
path: root/rtrlib/lib/alloc_utils.c
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 09:54:46 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 09:54:46 +0000
commitcd7b005519ade8ab6c97fcb21590b71b7d1be6e3 (patch)
treec611a8d0cd5e8f68f41b8c2d16ba580e0f40a38d /rtrlib/lib/alloc_utils.c
parentInitial commit. (diff)
downloadlibrtr-cd7b005519ade8ab6c97fcb21590b71b7d1be6e3.tar.xz
librtr-cd7b005519ade8ab6c97fcb21590b71b7d1be6e3.zip
Adding upstream version 0.8.0.upstream/0.8.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r--rtrlib/lib/alloc_utils.c81
1 files changed, 81 insertions, 0 deletions
diff --git a/rtrlib/lib/alloc_utils.c b/rtrlib/lib/alloc_utils.c
new file mode 100644
index 0000000..e3d6831
--- /dev/null
+++ b/rtrlib/lib/alloc_utils.c
@@ -0,0 +1,81 @@
+/*
+ * This file is part of RTRlib.
+ *
+ * This file is subject to the terms and conditions of the MIT license.
+ * See the file LICENSE in the top level directory for more details.
+ *
+ * Website: http://rtrlib.realmv6.org/
+ */
+
+#include "alloc_utils_private.h"
+
+#include "rtrlib/rtrlib_export_private.h"
+
+#include <assert.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+static void *(*MALLOC_PTR)(size_t size) = malloc;
+static void *(*REALLOC_PTR)(void *ptr, size_t size) = realloc;
+static void (*FREE_PTR)(void *ptr) = free;
+
+/* cppcheck-suppress unusedFunction */
+RTRLIB_EXPORT void lrtr_set_alloc_functions(void *(*malloc_function)(size_t size),
+ void *(*realloc_function)(void *ptr, size_t size),
+ void(free_function)(void *ptr))
+{
+ MALLOC_PTR = malloc_function;
+ REALLOC_PTR = realloc_function;
+ FREE_PTR = free_function;
+}
+
+inline void *lrtr_malloc(size_t size)
+{
+ return MALLOC_PTR(size);
+}
+
+/* cppcheck-suppress unusedFunction */
+void *lrtr_calloc(size_t nmemb, size_t size)
+{
+ int bytes = 0;
+
+#if __GNUC__ >= 5
+ if (__builtin_mul_overflow(nmemb, size, &bytes)) {
+ errno = ENOMEM;
+ return 0;
+ }
+#else
+ if (size && nmemb > (size_t)-1 / size) {
+ errno = ENOMEM;
+ return 0;
+ }
+ bytes = size * nmemb;
+#endif
+ void *p = lrtr_malloc(bytes);
+
+ if (!p)
+ return p;
+
+ return memset(p, 0, bytes);
+}
+
+inline void lrtr_free(void *ptr)
+{
+ return FREE_PTR(ptr);
+}
+
+inline void *lrtr_realloc(void *ptr, size_t size)
+{
+ return REALLOC_PTR(ptr, size);
+}
+
+char *lrtr_strdup(const char *string)
+{
+ assert(string);
+
+ size_t length = strlen(string) + 1;
+ char *new_string = lrtr_malloc(length);
+
+ return new_string ? memcpy(new_string, string, length) : NULL;
+}