1 // Copyright 2021 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 BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_STARSCAN_METADATA_ALLOCATOR_H_ 6 #define BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_STARSCAN_METADATA_ALLOCATOR_H_ 7 8 #include <utility> 9 10 #include "partition_alloc/partition_alloc_base/component_export.h" 11 #include "partition_alloc/partition_alloc_constants.h" 12 #include "partition_alloc/partition_root.h" 13 14 namespace partition_alloc::internal { 15 16 PA_COMPONENT_EXPORT(PARTITION_ALLOC) 17 PartitionRoot& PCScanMetadataAllocator(); 18 void ReinitPCScanMetadataAllocatorForTesting(); 19 20 // STL allocator which is needed to keep internal data structures required by 21 // PCScan. 22 template <typename T> 23 class MetadataAllocator { 24 public: 25 using value_type = T; 26 27 MetadataAllocator() = default; 28 29 template <typename U> MetadataAllocator(const MetadataAllocator<U> &)30 MetadataAllocator(const MetadataAllocator<U>&) {} // NOLINT 31 32 template <typename U> 33 MetadataAllocator& operator=(const MetadataAllocator<U>&) { 34 return *this; 35 } 36 37 template <typename U> 38 bool operator==(const MetadataAllocator<U>&) { 39 return true; 40 } 41 42 template <typename U> 43 bool operator!=(const MetadataAllocator<U>& o) { 44 return !operator==(o); 45 } 46 allocate(size_t size)47 value_type* allocate(size_t size) { 48 return static_cast<value_type*>( 49 PCScanMetadataAllocator() 50 .AllocInline<partition_alloc::AllocFlags::kNoHooks>( 51 size * sizeof(value_type))); 52 } 53 deallocate(value_type * ptr,size_t size)54 void deallocate(value_type* ptr, size_t size) { 55 PCScanMetadataAllocator().FreeInline<FreeFlags::kNoHooks>(ptr); 56 } 57 }; 58 59 // Inherit from it to make a class allocated on the metadata partition. 60 struct AllocatedOnPCScanMetadataPartition { newAllocatedOnPCScanMetadataPartition61 static void* operator new(size_t size) { 62 return PCScanMetadataAllocator() 63 .AllocInline<partition_alloc::AllocFlags::kNoHooks>(size); 64 } deleteAllocatedOnPCScanMetadataPartition65 static void operator delete(void* ptr) { 66 PCScanMetadataAllocator().FreeInline<FreeFlags::kNoHooks>(ptr); 67 } 68 }; 69 70 template <typename T, typename... Args> MakePCScanMetadata(Args &&...args)71T* MakePCScanMetadata(Args&&... args) { 72 auto* memory = static_cast<T*>( 73 PCScanMetadataAllocator() 74 .AllocInline<partition_alloc::AllocFlags::kNoHooks>(sizeof(T))); 75 return new (memory) T(std::forward<Args>(args)...); 76 } 77 78 struct PCScanMetadataDeleter final { operatorfinal79 inline void operator()(void* ptr) const { 80 PCScanMetadataAllocator().FreeInline<FreeFlags::kNoHooks>(ptr); 81 } 82 }; 83 84 } // namespace partition_alloc::internal 85 86 #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_SRC_PARTITION_ALLOC_STARSCAN_METADATA_ALLOCATOR_H_ 87