shithub: scc

Download patch

ref: 40c0dd60db401444abc61b122fb396af9b0c1114
parent: f5cc8f6eeb677435da24372f738055728c9acb93
author: Roberto E. Vargas Caballero <k0ga@shike2.com>
date: Sun Nov 21 13:45:58 EST 2021

libc: Add overflow check in malloc() and realloc()

--- a/src/libc/stdlib/malloc.c
+++ b/src/libc/stdlib/malloc.c
@@ -136,6 +136,9 @@
 	Header *cur, *prev;
 	size_t nunits;
 
+        if (nbytes == 0 || nbytes > SIZE_MAX - sizeof(Header)-1)
+		return NULL;
+
 	/* 1 unit for header plus enough units to fit nbytes */
 	nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;
 
--- a/src/libc/stdlib/realloc.c
+++ b/src/libc/stdlib/realloc.c
@@ -1,3 +1,4 @@
+#include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 
@@ -10,7 +11,7 @@
 	Header *oh, *prev, *next, *new;
 	size_t nunits, avail, onbytes, n;
 
-	if (nbytes == 0)
+	if (nbytes == 0 || nbytes > SIZE_MAX - sizeof(Header)-1)
 		return NULL;
 
 	if (!ptr)