1 // Copyright 2024 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef PARTITION_ALLOC_INTERNAL_ALLOCATOR_FORWARD_H_ 6 #define PARTITION_ALLOC_INTERNAL_ALLOCATOR_FORWARD_H_ 7 8 #include <new> 9 #include <type_traits> 10 11 #include "partition_alloc/partition_alloc_base/component_export.h" 12 #include "partition_alloc/partition_alloc_forward.h" 13 14 // Internal Allocator can be used to get heap allocations required to 15 // implement PartitionAlloc's feature. 16 // As Internal Allocator being PartitionAlloc with minimal configuration, 17 // it is not allowed to use this allocator for PA's core implementation to avoid 18 // reentrancy issues. Also don't use this when satisfying the very first PA-E 19 // allocation of the process. 20 21 namespace partition_alloc::internal { 22 23 PA_COMPONENT_EXPORT(PARTITION_ALLOC) 24 PartitionRoot& InternalAllocatorRoot(); 25 26 // A class that meets C++ named requirements, Allocator. 27 template <typename T> 28 class InternalAllocator { 29 public: 30 using value_type = T; 31 using is_always_equal = std::true_type; 32 33 InternalAllocator() = default; 34 35 template <typename U> InternalAllocator(const InternalAllocator<U> &)36 InternalAllocator(const InternalAllocator<U>&) {} // NOLINT 37 38 template <typename U> 39 InternalAllocator& operator=(const InternalAllocator<U>&) { 40 return *this; 41 } 42 43 template <typename U> 44 bool operator==(const InternalAllocator<U>&) { 45 // InternalAllocator<T> can free allocations made by InternalAllocator<U>. 46 return true; 47 } 48 49 value_type* allocate(std::size_t count); 50 51 void deallocate(value_type* ptr, std::size_t); 52 }; 53 54 // Inherit this to make a class allocated on the internal partition. PA_COMPONENT_EXPORT(PARTITION_ALLOC)55struct PA_COMPONENT_EXPORT(PARTITION_ALLOC) InternalPartitionAllocated { 56 static void* operator new(size_t count); 57 static void* operator new(size_t count, std::align_val_t alignment); 58 // Though we do not forward placement new, we need to define this explicitly 59 // to allow it. 60 static void* operator new(std::size_t, void* ptr) { return ptr; } 61 static void operator delete(void* ptr); 62 static void operator delete(void* ptr, std::align_val_t); 63 }; 64 65 // Create an object on heap in the internal partition. 66 template <typename T, typename... Args> 67 T* ConstructAtInternalPartition(Args&&... args); 68 69 // Destroy an object on heap in the internal partition. 70 template <typename T> 71 void DestroyAtInternalPartition(T* ptr); 72 73 // A deleter for `std::unique_ptr<T>`. PA_COMPONENT_EXPORT(PARTITION_ALLOC)74struct PA_COMPONENT_EXPORT(PARTITION_ALLOC) InternalPartitionDeleter final { 75 void operator()(void* ptr) const; 76 }; 77 78 } // namespace partition_alloc::internal 79 80 #endif // PARTITION_ALLOC_INTERNAL_ALLOCATOR_FORWARD_H_ 81