mail archive of the barebox mailing list
 help / color / mirror / Atom feed
* [PATCH] calloc: handle wrap around in total buffer size correctly
@ 2024-07-24  9:47 Ahmad Fatoum
  2024-07-30  8:14 ` Sascha Hauer
  0 siblings, 1 reply; 2+ messages in thread
From: Ahmad Fatoum @ 2024-07-24  9:47 UTC (permalink / raw)
  To: barebox; +Cc: Ahmad Fatoum

calloc() should allocate a memory buffer that fits the product of its
arguments or return NULL if this is not possible.

We violated this so far and a wraparound would result in allocating a
too small buffer leading to buffer overflows.

Fix this by using size_mull which saturates at SIZE_MAX, which malloc
should gracefully return NULL for.

Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
---
 common/calloc.c   | 3 ++-
 common/dlmalloc.c | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)

diff --git a/common/calloc.c b/common/calloc.c
index 65e843350d47..12f18474a4c8 100644
--- a/common/calloc.c
+++ b/common/calloc.c
@@ -2,13 +2,14 @@
 
 #include <common.h>
 #include <malloc.h>
+#include <linux/overflow.h>
 
 /*
  * calloc calls malloc, then zeroes out the allocated chunk.
  */
 void *calloc(size_t n, size_t elem_size)
 {
-	size_t size = elem_size * n;
+	size_t size = size_mul(elem_size, n);
 	void *r = malloc(size);
 
 	if (!r)
diff --git a/common/dlmalloc.c b/common/dlmalloc.c
index c41487d54b4a..3a77a344576c 100644
--- a/common/dlmalloc.c
+++ b/common/dlmalloc.c
@@ -4,6 +4,7 @@
 #include <malloc.h>
 #include <string.h>
 #include <memory.h>
+#include <linux/overflow.h>
 #include <linux/build_bug.h>
 
 #include <stdio.h>
@@ -1739,7 +1740,7 @@ void *calloc(size_t n, size_t elem_size)
 {
 	mchunkptr p;
 	INTERNAL_SIZE_T csz;
-	INTERNAL_SIZE_T sz = n * elem_size;
+	INTERNAL_SIZE_T sz = size_mul(n, elem_size);
 	void *mem;
 
 	/* check if expand_top called, in which case don't need to clear */
-- 
2.39.2




^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2024-07-30  8:15 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-07-24  9:47 [PATCH] calloc: handle wrap around in total buffer size correctly Ahmad Fatoum
2024-07-30  8:14 ` Sascha Hauer

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox