summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndreas Kling <kling@serenityos.org>2021-08-07 22:32:45 +0200
committerAndreas Kling <kling@serenityos.org>2021-08-08 00:03:45 +0200
commit2189524cb3ca4a12276007c6634d44170e2215ca (patch)
tree694a2002a4d9b5782fc039577c8a28b1db8b67e6
parentc94c15d45cbcca4e753c94665d698bb09d96313c (diff)
downloadserenity-2189524cb3ca4a12276007c6634d44170e2215ca.zip
AK: Add kmalloc_array() to trap multiplication overflows
This pattern is no good: kmalloc(elements * sizeof(T)); Since it silently swallows any multiplication overflow. This patch adds a simple kmalloc_array() that stops the program if overflow occurs: kmalloc_array(elements, sizeof(T));
-rw-r--r--AK/kmalloc.h18
1 files changed, 17 insertions, 1 deletions
diff --git a/AK/kmalloc.h b/AK/kmalloc.h
index 95e886f9cd..fedfcf7b8f 100644
--- a/AK/kmalloc.h
+++ b/AK/kmalloc.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
+ * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, Daniel Bertalan <dani@danielbertalan.dev>
*
* SPDX-License-Identifier: BSD-2-Clause
@@ -7,6 +7,8 @@
#pragma once
+#include <AK/Checked.h>
+
#if defined(KERNEL)
# include <Kernel/Heap/kmalloc.h>
#else
@@ -47,3 +49,17 @@ inline size_t malloc_good_size(size_t size) { return size; }
#endif
using std::nothrow;
+
+inline void* kmalloc_array(Checked<size_t> a, Checked<size_t> b)
+{
+ auto size = a * b;
+ VERIFY(!size.has_overflow());
+ return kmalloc(size.value());
+}
+
+inline void* kmalloc_array(Checked<size_t> a, Checked<size_t> b, Checked<size_t> c)
+{
+ auto size = a * b * c;
+ VERIFY(!size.has_overflow());
+ return kmalloc(size.value());
+}