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));
This commit is contained in:
Andreas Kling 2021-08-07 22:32:45 +02:00
parent c94c15d45c
commit 2189524cb3

View file

@ -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());
}