aboutsummaryrefslogtreecommitdiff
path: root/lib/util
diff options
context:
space:
mode:
authorDavid Oberhollenzer <david.oberhollenzer@sigma-star.at>2019-08-23 01:29:52 +0200
committerDavid Oberhollenzer <david.oberhollenzer@sigma-star.at>2019-08-23 02:06:31 +0200
commit0a5383ccdf8e87d2259d02a9ff44420b3bc3f58d (patch)
treeb92fb06a065a201c0cd21aafd3ee265c847c9b84 /lib/util
parent8c8467a824c950fd1094e46a74c1f57048e5f099 (diff)
Add wrappers for calloc style functions with size overflow checking
Signed-off-by: David Oberhollenzer <david.oberhollenzer@sigma-star.at>
Diffstat (limited to 'lib/util')
-rw-r--r--lib/util/alloc.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/lib/util/alloc.c b/lib/util/alloc.c
new file mode 100644
index 0000000..2d748a7
--- /dev/null
+++ b/lib/util/alloc.c
@@ -0,0 +1,54 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later */
+/*
+ * alloc.c
+ *
+ * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
+ */
+#include "config.h"
+
+#include "util.h"
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <errno.h>
+
+void *alloc_flex(size_t base_size, size_t item_size, size_t nmemb)
+{
+ size_t size;
+
+ if (SZ_MUL_OV(nmemb, item_size, &size)) {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+
+ if (SZ_ADD_OV(base_size, size, &size)) {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+
+ return calloc(1, size);
+}
+
+void *alloc_array(size_t item_size, size_t nmemb)
+{
+ size_t size;
+
+ if (SZ_MUL_OV(nmemb, item_size, &size)) {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+
+ return calloc(1, size);
+}
+
+void *alloc_string(size_t len)
+{
+ size_t size;
+
+ if (SZ_ADD_OV(len, 1, &size)) {
+ errno = EOVERFLOW;
+ return NULL;
+ }
+
+ return calloc(1, len);
+}