mirror of
https://github.com/SerenityOS/serenity.git
synced 2025-01-23 09:51:57 -05:00
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:
parent
c94c15d45c
commit
2189524cb3
1 changed files with 17 additions and 1 deletions
18
AK/kmalloc.h
18
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>
|
* Copyright (c) 2021, Daniel Bertalan <dani@danielbertalan.dev>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: BSD-2-Clause
|
* SPDX-License-Identifier: BSD-2-Clause
|
||||||
|
@ -7,6 +7,8 @@
|
||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#include <AK/Checked.h>
|
||||||
|
|
||||||
#if defined(KERNEL)
|
#if defined(KERNEL)
|
||||||
# include <Kernel/Heap/kmalloc.h>
|
# include <Kernel/Heap/kmalloc.h>
|
||||||
#else
|
#else
|
||||||
|
@ -47,3 +49,17 @@ inline size_t malloc_good_size(size_t size) { return size; }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
using std::nothrow;
|
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());
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue