mirror of
https://github.com/RGBCube/serenity
synced 2025-05-16 19:15:07 +00:00
AK+Kernel: Make fallible allocations compiler-agnostic
In standard C++, operators `new` and `new[]` are guaranteed to return a valid (non-null) pointer and throw an exception if the allocation couldn't be performed. Based on this, compilers did not check the returned pointer before attempting to use them for object construction. To avoid this, the allocator operators were changed to be `noexcept` in PR #7026, which made GCC emit the desired null checks. Unfortunately, this is a non-standard feature which meant that Clang would not accept these function definitions, as it did not match its expected declaration. To make compiling using Clang possible, the special "nothrow" versions of `new` are implemented in this commit. These take a tag type of `std::nothrow_t` (used for disambiguating from placement new/etc.), and are allowed by the standard to return null. There is a global variable, `std::nothrow`, declared with this type, which is also exported into the global namespace. To perform fallible allocations, the following syntax should be used: ```cpp auto ptr = new (nothrow) T; ``` As we don't support exceptions in the kernel, the only way of uphold the "throwing" new's guarantee is to abort if the allocation couldn't be performed. Once we have proper OOM handling in the kernel, this should only be used for critical allocations, where we wouldn't be able to recover from allocation failures anyway.
This commit is contained in:
parent
d6138df490
commit
5491e0cdcc
4 changed files with 83 additions and 18 deletions
|
@ -29,6 +29,10 @@
|
|||
#define POOL_SIZE (2 * MiB)
|
||||
#define ETERNAL_RANGE_SIZE (2 * MiB)
|
||||
|
||||
namespace std {
|
||||
const nothrow_t nothrow;
|
||||
}
|
||||
|
||||
static RecursiveSpinLock s_lock; // needs to be recursive because of dump_backtrace()
|
||||
|
||||
static void kmalloc_allocate_backup_memory();
|
||||
|
@ -300,12 +304,26 @@ size_t kmalloc_good_size(size_t size)
|
|||
return size;
|
||||
}
|
||||
|
||||
void* operator new(size_t size) noexcept
|
||||
void* operator new(size_t size)
|
||||
{
|
||||
void* ptr = kmalloc(size);
|
||||
VERIFY(ptr);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void* operator new(size_t size, const std::nothrow_t&) noexcept
|
||||
{
|
||||
return kmalloc(size);
|
||||
}
|
||||
|
||||
void* operator new[](size_t size) noexcept
|
||||
void* operator new[](size_t size)
|
||||
{
|
||||
void* ptr = kmalloc(size);
|
||||
VERIFY(ptr);
|
||||
return ptr;
|
||||
}
|
||||
|
||||
void* operator new[](size_t size, const std::nothrow_t&) noexcept
|
||||
{
|
||||
return kmalloc(size);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue