summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorChristian Göttsche <cgzones@googlemail.com>2020-12-23 21:52:40 +0100
committercgzones <cgzones@googlemail.com>2021-01-02 22:35:13 +0100
commit8c8149d146f744b2c0c64b80ba9220bd464de013 (patch)
tree2ef7fe73216d7d9cc1926b6afad3ee0a3d0a2bb6
parenta150a81669027601aefc231f208a715e16b24c62 (diff)
XUtils: check for multiplication overflow in allocation size
-rw-r--r--XUtils.c22
-rw-r--r--XUtils.h4
-rw-r--r--linux/LinuxProcessList.c4
3 files changed, 28 insertions, 2 deletions
diff --git a/XUtils.c b/XUtils.c
index cd5edb91..01f33424 100644
--- a/XUtils.c
+++ b/XUtils.c
@@ -13,6 +13,7 @@ in the source distribution for its full text.
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@@ -36,9 +37,21 @@ void* xMalloc(size_t size) {
return data;
}
+void* xMallocArray(size_t nmemb, size_t size) {
+ assert(nmemb > 0);
+ assert(size > 0);
+ if (SIZE_MAX / nmemb < size) {
+ fail();
+ }
+ return xMalloc(nmemb * size);
+}
+
void* xCalloc(size_t nmemb, size_t size) {
assert(nmemb > 0);
assert(size > 0);
+ if (SIZE_MAX / nmemb < size) {
+ fail();
+ }
void* data = calloc(nmemb, size);
if (!data) {
fail();
@@ -56,6 +69,15 @@ void* xRealloc(void* ptr, size_t size) {
return data;
}
+void* xReallocArray(void* ptr, size_t nmemb, size_t size) {
+ assert(nmemb > 0);
+ assert(size > 0);
+ if (SIZE_MAX / nmemb < size) {
+ fail();
+ }
+ return xRealloc(ptr, nmemb * size);
+}
+
char* String_cat(const char* s1, const char* s2) {
const size_t l1 = strlen(s1);
const size_t l2 = strlen(s2);
diff --git a/XUtils.h b/XUtils.h
index 19cfadb3..9e5e62cf 100644
--- a/XUtils.h
+++ b/XUtils.h
@@ -23,10 +23,14 @@ void fail(void) ATTR_NORETURN;
void* xMalloc(size_t size);
+void* xMallocArray(size_t nmemb, size_t size);
+
void* xCalloc(size_t nmemb, size_t size);
void* xRealloc(void* ptr, size_t size);
+void* xReallocArray(void* ptr, size_t nmemb, size_t size);
+
/*
* String_startsWith gives better performance if strlen(match) can be computed
* at compile time (e.g. when they are immutable string literals). :)
diff --git a/linux/LinuxProcessList.c b/linux/LinuxProcessList.c
index 31f3ee21..77b1fc8e 100644
--- a/linux/LinuxProcessList.c
+++ b/linux/LinuxProcessList.c
@@ -102,7 +102,7 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) {
int numDrivers = 0;
int allocd = 10;
- ttyDrivers = xMalloc(sizeof(TtyDriver) * allocd);
+ ttyDrivers = xMallocArray(allocd, sizeof(TtyDriver));
char* at = buf;
while (*at != '\0') {
at = strchr(at, ' '); // skip first token
@@ -136,7 +136,7 @@ static void LinuxProcessList_initTtyDrivers(LinuxProcessList* this) {
numDrivers++;
if (numDrivers == allocd) {
allocd += 10;
- ttyDrivers = xRealloc(ttyDrivers, sizeof(TtyDriver) * allocd);
+ ttyDrivers = xReallocArray(ttyDrivers, allocd, sizeof(TtyDriver));
}
}
numDrivers++;

© 2014-2024 Faster IT GmbH | imprint | privacy policy