mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00: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
Notes:
sideshowbarker
2024-07-18 07:17:55 +09:00
Author: https://github.com/awesomekling Commit: https://github.com/SerenityOS/serenity/commit/2189524cb3c
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>
|
||||
*
|
||||
* 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());
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue