serenity/Kernel/Heap/SlabAllocator.h
Daniel Bertalan 5491e0cdcc 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.
2021-06-24 17:35:49 +04:30

42 lines
1.8 KiB
C++

/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Function.h>
#include <AK/Types.h>
namespace Kernel {
#define SLAB_ALLOC_SCRUB_BYTE 0xab
#define SLAB_DEALLOC_SCRUB_BYTE 0xbc
void* slab_alloc(size_t slab_size);
void slab_dealloc(void*, size_t slab_size);
void slab_alloc_init();
void slab_alloc_stats(Function<void(size_t slab_size, size_t allocated, size_t free)>);
#define MAKE_SLAB_ALLOCATED(type) \
public: \
[[nodiscard]] void* operator new(size_t) \
{ \
void* ptr = slab_alloc(sizeof(type)); \
VERIFY(ptr); \
return ptr; \
} \
[[nodiscard]] void* operator new(size_t, const std::nothrow_t&) noexcept \
{ \
return slab_alloc(sizeof(type)); \
} \
void operator delete(void* ptr) noexcept \
{ \
slab_dealloc(ptr, sizeof(type)); \
} \
\
private:
}