Truly independent web browser
LibGC: Move block pools, cell allocators and sweeping to Rust
Andreas Kling31b0ed2ec718
diff --git a/Libraries/LibGC/BlockAllocator.cpp b/Libraries/LibGC/BlockAllocator.cppindex 6fdcb7b2832..ddf575a9101 100644--- a/Libraries/LibGC/BlockAllocator.cpp+++ b/Libraries/LibGC/BlockAllocator.cpp@@ -6,33 +6,17 @@*/#include <AK/Assertions.h>-#include <AK/Atomic.h>#include <AK/Checked.h>+#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/Platform.h>#include <AK/Time.h>#include <AK/Try.h>-#include <AK/Vector.h>#include <LibCore/System.h>#include <LibGC/BlockAllocator.h>#include <LibGC/BlockDescriptor.h>#include <LibGC/HeapBlock.h>#include <LibGC/HeapRegion.h>-#include <LibThreading/Thread.h>-#include <sys/mman.h>--#ifdef HAS_ADDRESS_SANITIZER-# include <sanitizer/asan_interface.h>-# include <sanitizer/lsan_interface.h>-#endif--#if defined(AK_OS_WINDOWS)-# include <AK/Windows.h>-# include <memoryapi.h>-#else-# include <sched.h>-# include <unistd.h>-#endifextern "C" {GC_API FlatPtr js_heap_region_base = 0;@@ -40,34 +24,13 @@ GC_API FlatPtr js_heap_region_base = 0;namespace GC {-// Every BlockAllocator takes 16 KiB HeapBlock slots from one process-wide-// reserved region, which commits them 2 MiB at a time. A slot that was never-// used belongs to nobody, so the allocators can all take their slots from the-// same chunk, and a pool for a type that only needs one block costs one block.-// A slot that was used stays with the allocator that took it.-//-// Per-block madvise() is deferred to a single global background "decommit-// worker" so it never costs us GC pause time, and slots that are recycled-// before the worker sees them skip the madvise pair entirely.-static constexpr size_t CHUNK_SIZE = 2 * MiB;-static constexpr size_t BLOCKS_PER_CHUNK = CHUNK_SIZE / HeapBlock::BLOCK_SIZE;--// How long a block with MADV_FREE'd pages can sit unused before its pages go back for real. This is longer than most-// heaps take between collections, so that blocks they reuse keep skipping the page faults. And as the collections of-// every heap drive the decommit worker, it keeps a busy heap from making the blocks of a slower one look cold.-static Atomic<i64, AK::MemoryOrder::memory_order_relaxed> s_cold_block_age_in_milliseconds { 5000 };--static AK::Duration cold_block_age()-{- return AK::Duration::from_milliseconds(s_cold_block_age_in_milliseconds.load());-}--static_assert((HeapBlock::BLOCK_SIZE & (HeapBlock::BLOCK_SIZE - 1)) == 0);-static_assert(CHUNK_SIZE % HeapBlock::BLOCK_SIZE == 0);-static_assert(BLOCKS_PER_CHUNK == 128);-static_assert(HEAP_REGION_LOW_GUARD_SIZE % CHUNK_SIZE == 0);-static_assert(HEAP_REGION_HIGH_GUARD_SIZE % CHUNK_SIZE == 0);+static_assert(FFI::CHUNK_SIZE % HeapBlock::BLOCK_SIZE == 0);+static_assert(HEAP_REGION_LOW_GUARD_SIZE % FFI::CHUNK_SIZE == 0);+static_assert(HEAP_REGION_HIGH_GUARD_SIZE % FFI::CHUNK_SIZE == 0);+// Every block of every heap is in one process-wide region, which this reserves at an address aligned to its size, so+// that a cell's offset in the region is its address modulo the region's size. LibGC's Rust core commits the region's+// chunks and hands out its blocks, see block_pool.rs.class HeapRegion {public:static constexpr size_t size = HEAP_REGION_SIZE;@@ -98,9 +61,11 @@ public:(void)tail_size;#endif- m_base = reinterpret_cast<u8*>(aligned_start);- VERIFY(reinterpret_cast<FlatPtr>(m_base) % size == 0);- publish_base(reinterpret_cast<FlatPtr>(m_base));+ m_base = aligned_start;+ VERIFY(m_base % size == 0);+ // NB: The guards at either end of the region are never committed.+ FFI::rust_gc_heap_region_init(reinterpret_cast<u8*>(m_base), HEAP_REGION_LOW_GUARD_SIZE, size - HEAP_REGION_HIGH_GUARD_SIZE - FFI::CHUNK_SIZE);+ publish_base(m_base);}static void register_base_copy(HeapRegionBaseCopyRegistration& registration)@@ -111,58 +76,10 @@ public:*registration.m_copy = js_heap_region_base;}- // This process-global region is shared by every Heap, and heaps allocate blocks on their own threads while the- // decommit worker prepares the next chunk ahead of time, so the chunk bookkeeping is under a lock.- void* take_unused_block()- {- u8* block = nullptr;- bool took_chunk = false;- {- MutexLocker locker(m_mutex);- if (m_next_unused_block == m_unused_blocks_end) {- take_chunk();- took_chunk = true;- }- block = m_next_unused_block;- m_next_unused_block += HeapBlock::BLOCK_SIZE;- }- if (took_chunk)- request_prepared_chunk();- return block;- }-- // Commits the next chunk and faults its pages in, so that the first touches of its blocks take no page faults- // on the thread that allocates them. Runs on the decommit worker.- void prepare_chunk()- {- u8* chunk = nullptr;- {- MutexLocker locker(m_mutex);- // NB: Running out of the region is left to take_unused_block(), on the thread that needs another chunk.- if (m_prepared_chunk || m_next_chunk_offset > LAST_CHUNK_OFFSET)- return;- chunk = commit_next_chunk();- }-#if defined(MADV_POPULATE_WRITE)- // NB: This only fails if the kernel is too old to know it, which leaves the faults to the first touches.- (void)madvise(chunk, CHUNK_SIZE, MADV_POPULATE_WRITE);-#endif- MutexLocker locker(m_mutex);- m_prepared_chunk = chunk;- }-- FlatPtr start() const { return reinterpret_cast<FlatPtr>(m_base); }+ FlatPtr start() const { return m_base; }FlatPtr end() const { return start() + size; }- FlatPtr committed_end()- {- MutexLocker locker(m_mutex);- return start() + m_next_chunk_offset;- }-private:- static void request_prepared_chunk();-static void publish_base(FlatPtr base){MutexLocker locker(base_copies_mutex());@@ -181,53 +98,7 @@ private:static constinit inline HeapRegionBaseCopyRegistration* s_base_copies { nullptr };- // The guards at either end of the region are never committed.- static constexpr size_t FIRST_CHUNK_OFFSET = HEAP_REGION_LOW_GUARD_SIZE;- static constexpr size_t LAST_CHUNK_OFFSET = size - HEAP_REGION_HIGH_GUARD_SIZE - CHUNK_SIZE;-- u8* commit_next_chunk()- {- VERIFY(m_next_chunk_offset >= FIRST_CHUNK_OFFSET);- VERIFY(m_next_chunk_offset <= LAST_CHUNK_OFFSET);- auto* chunk = m_base + m_next_chunk_offset;- MUST(Core::System::commit_memory(chunk, CHUNK_SIZE, Core::System::MemoryTag::GarbageCollector));- // NB: Conservative pointer lookups read the descriptor of any block below the committed end, see- // allocated_cell_containing(), so the descriptors of a chunk are committed with it.- FFI::rust_gc_block_descriptor_commit(m_next_chunk_offset / HeapBlock::BLOCK_SIZE, BLOCKS_PER_CHUNK);- m_next_chunk_offset += CHUNK_SIZE;- return chunk;- }-- void take_chunk()- {- auto* chunk = exchange(m_prepared_chunk, nullptr);- if (!chunk)- chunk = commit_next_chunk();--#if defined(MADV_FREE_REUSE) && defined(MADV_FREE_REUSABLE)- // Mark the whole chunk reusable upfront so MADV_FREE_REUSE pairs- // symmetrically when its blocks are handed out. (Linux and Windows- // fall through with no-op.)- if (madvise(chunk, CHUNK_SIZE, MADV_FREE_REUSABLE) < 0) {- perror("madvise(MADV_FREE_REUSABLE)");- VERIFY_NOT_REACHED();- }-#endif-- ASAN_POISON_MEMORY_REGION(chunk, CHUNK_SIZE);-- m_next_unused_block = chunk;- m_unused_blocks_end = chunk + CHUNK_SIZE;- }-- u8* m_base { nullptr };- Mutex m_mutex;- size_t m_next_chunk_offset { FIRST_CHUNK_OFFSET };- // A committed chunk whose pages are faulted in already, which is the next one that blocks come from.- u8* m_prepared_chunk { nullptr };- // The blocks of the current chunk that were never used.- u8* m_next_unused_block { nullptr };- u8* m_unused_blocks_end { nullptr };+ FlatPtr m_base { 0 };};static HeapRegion& heap_region()@@ -236,324 +107,41 @@ static HeapRegion& heap_region()return *region;}-static void madvise_block_for_decommit(void* block)-{-#if defined(AK_OS_WINDOWS)- // NB: DiscardVirtualMemory() validates its range with VirtualQuery(), which makes the kernel check every page in- // the run of identical pages that starts at the block. All chunks are committed back to back in one- // reservation, so that run is the whole committed heap. MEM_RESET drops the contents without that walk, and- // VirtualUnlock() on pages that are not locked takes them out of the working set right away.- if (!VirtualAlloc(block, HeapBlock::BLOCK_SIZE, MEM_RESET, PAGE_READWRITE)) {- warnln("{}", Error::from_windows_error());- VERIFY_NOT_REACHED();- }- (void)VirtualUnlock(block, HeapBlock::BLOCK_SIZE);-#elif defined(MADV_FREE_REUSE) && defined(MADV_FREE_REUSABLE)- // macOS uses the FREE_REUSABLE/FREE_REUSE paired protocol, which integrates- // with its RSS accounting properly.- if (madvise(block, HeapBlock::BLOCK_SIZE, MADV_FREE_REUSABLE) < 0) {- perror("madvise(MADV_FREE_REUSABLE)");- VERIFY_NOT_REACHED();- }-#elif defined(MADV_FREE)- // MADV_FREE keeps the pages mapped until the kernel needs them, so a block reused before then takes no page fault.- if (madvise(block, HeapBlock::BLOCK_SIZE, MADV_FREE) < 0) {- perror("madvise(MADV_FREE)");- VERIFY_NOT_REACHED();- }-#elif defined(MADV_DONTNEED)- if (madvise(block, HeapBlock::BLOCK_SIZE, MADV_DONTNEED) < 0) {- perror("madvise(MADV_DONTNEED)");- VERIFY_NOT_REACHED();- }-#endif-}--static void return_block_to_system(void* block)-{-#if defined(AK_OS_LINUX)- if (madvise(block, HeapBlock::BLOCK_SIZE, MADV_DONTNEED) < 0) {- perror("madvise(MADV_DONTNEED)");- VERIFY_NOT_REACHED();- }-#else- madvise_block_for_decommit(block);-#endif-}--static void sleep_before_decommit()-{-#if defined(AK_OS_WINDOWS)- Sleep(50);-#else- usleep(50 * 1000);-#endif-}--static void yield_during_decommit()-{-#if defined(AK_OS_WINDOWS)- Sleep(0);-#else- sched_yield();-#endif-}--class DecommitWorker {-public:- static DecommitWorker& the();- static DecommitWorker* the_if_started() { return s_the.load(AK::MemoryOrder::memory_order_acquire); }-- void register_pending(BlockAllocator&);- void deregister(BlockAllocator&);- void kick();- void request_prepared_chunk();-- DecommitWorker();--private:- enum class ReturnColdBlocks {- No,- Yes,- };-- void run();- void process_one(BlockAllocator&, ReturnColdBlocks);-- Mutex m_mutex;- ConditionVariable m_cv { m_mutex };- RefPtr<Threading::Thread> m_thread;- Vector<BlockAllocator*> m_pending;- bool m_kicked { false };- bool m_chunk_requested { false };- MonotonicTime m_last_return_of_cold_blocks { MonotonicTime::now_coarse() };-- static Atomic<DecommitWorker*> s_the;-};--Atomic<DecommitWorker*> DecommitWorker::s_the { nullptr };--void HeapRegion::request_prepared_chunk()-{- // NB: Preparing a chunk only pays off where its pages can be faulted in ahead of time. And only a worker that is- // already running prepares chunks: starting it here could start a second thread before the process is- // sandboxed, which some sandboxes do not allow.-#if defined(MADV_POPULATE_WRITE)- if (auto* worker = DecommitWorker::the_if_started())- worker->request_prepared_chunk();-#endif-}--DecommitWorker& DecommitWorker::the()-{- static AK::NeverDestroyed<DecommitWorker> instance;- return *instance;-}--DecommitWorker::DecommitWorker()-{- m_thread = Threading::Thread::construct("DecommitWorker"sv, [this] {- run();- return static_cast<intptr_t>(0);- });- m_thread->start();- m_thread->detach();- s_the.store(this, AK::MemoryOrder::memory_order_release);-}--void DecommitWorker::register_pending(BlockAllocator& a)-{- MutexLocker locker(m_mutex);- m_pending.append(&a);-}--void DecommitWorker::deregister(BlockAllocator& a)-{- MutexLocker locker(m_mutex);- m_pending.remove_first_matching([&](auto* p) { return p == &a; });-}--void DecommitWorker::kick()-{- {- MutexLocker locker(m_mutex);- m_kicked = true;- }- m_cv.signal();-}--void DecommitWorker::request_prepared_chunk()-{- {- MutexLocker locker(m_mutex);- m_chunk_requested = true;- }- m_cv.signal();-}--void DecommitWorker::run()-{- while (true) {- Vector<BlockAllocator*> snapshot;- bool chunk_requested = false;- {- MutexLocker locker(m_mutex);- while (!m_kicked && !m_chunk_requested) {- // NB: Collections may never come again, and what is on the list must not wait for one. Each block- // only takes a few rounds of this, after which the list is empty and this thread sleeps for good.- if (m_pending.is_empty())- m_cv.wait();- else if (!m_cv.wait_for(cold_block_age()))- m_kicked = true;- }- chunk_requested = exchange(m_chunk_requested, false);- if (m_kicked) {- m_kicked = false;- snapshot = move(m_pending);- // Pin every allocator we're about to process so destructors- // block until we drop our reference.- for (auto* a : snapshot)- a->m_worker_refcount.fetch_add(1);- }- }-- if (chunk_requested)- heap_region().prepare_chunk();-- if (snapshot.is_empty())- continue;-- // Stagger: give the JS thread some breathing room after the kick- // (typically right after sweep ends) before we consume CPU and- // syscall bandwidth.- sleep_before_decommit();-- auto return_cold_blocks = ReturnColdBlocks::No;- if (auto now = MonotonicTime::now_coarse(); now - m_last_return_of_cold_blocks >= cold_block_age()) {- return_cold_blocks = ReturnColdBlocks::Yes;- m_last_return_of_cold_blocks = now;- }-- for (auto* a : snapshot) {- process_one(*a, return_cold_blocks);- // The count drops under the allocator's lock, so its destructor can't see the count reach zero, and destroy- // the lock, before this thread is done with the lock.- MutexLocker locker(a->m_mutex);- if (a->m_worker_refcount.fetch_sub(1) == 1)- a->m_worker_cv.broadcast();- }- }-}--void DecommitWorker::process_one(BlockAllocator& a, [[maybe_unused]] ReturnColdBlocks return_cold_blocks)-{- Vector<void*> to_process;- Vector<void*> cold_blocks;- {- MutexLocker locker(a.m_mutex);- a.m_in_decommit_registry = false;- to_process = move(a.m_freshly_freed);-#if defined(AK_OS_LINUX)- // Blocks that went through MADV_FREE stay in the process until the system runs short of memory, and only their- // own type can reuse them. What that type did not reuse since the last time will likely stay unused.- if (return_cold_blocks == ReturnColdBlocks::Yes)- cold_blocks = move(a.m_blocks);-#endif- }-- // Madvise each slot outside the per-allocator lock so the JS thread can- // continue to allocate/free; yield every 64 slots to avoid hogging the- // kernel's mm subsystem.- constexpr size_t BATCH = 64;- for (size_t i = 0; i < to_process.size(); ++i) {- madvise_block_for_decommit(to_process[i]);- if ((i + 1) % BATCH == 0)- yield_during_decommit();- }- for (size_t i = 0; i < cold_blocks.size(); ++i) {- return_block_to_system(cold_blocks[i]);- if ((i + 1) % BATCH == 0)- yield_during_decommit();- }-- bool need_to_register = false;- {- MutexLocker locker(a.m_mutex);- a.m_blocks.extend(move(to_process));- a.m_returned_blocks.extend(move(cold_blocks));-#if defined(AK_OS_LINUX)- // NB: So an allocator is only on the list while it has blocks to look at, however many allocators there are.- if (!a.m_blocks.is_empty() && !a.m_in_decommit_registry) {- a.m_in_decommit_registry = true;- need_to_register = true;- }-#endif- }- if (need_to_register)- register_pending(a);-}-void BlockAllocator::wake_decommit_worker_async(){- DecommitWorker::the().kick();+ FFI::rust_gc_wake_decommit_worker();}AK::Duration BlockAllocator::set_cold_block_age_for_testing(AK::Duration age){- return AK::Duration::from_milliseconds(s_cold_block_age_in_milliseconds.exchange(age.to_milliseconds()));-}--void BlockAllocator::return_freed_blocks_to_system()-{- Vector<void*> blocks;- {- MutexLocker locker(m_mutex);- blocks = move(m_freshly_freed);-#if defined(AK_OS_LINUX)- // NB: MADV_FREE leaves these pages in the process until the system runs short of memory.- blocks.extend(move(m_blocks));-#endif- }-- for (auto* block : blocks)- return_block_to_system(block);-- MutexLocker locker(m_mutex);- m_returned_blocks.extend(move(blocks));+ return AK::Duration::from_milliseconds(static_cast<i64>(FFI::rust_gc_set_cold_block_age_in_milliseconds(static_cast<u64>(age.to_milliseconds()))));}BlockAllocator::BlockAllocator()- : m_worker_cv(m_mutex)+ : m_pool(FFI::rust_gc_block_pool_create()){+ // NB: LibGC's Rust core takes blocks from the pool directly, out of the region this reserves.+ (void)heap_region();}BlockAllocator::~BlockAllocator(){- // Chunks are permanent -- we never tear them down. The destructor only- // exists to make sure the global decommit worker has finished any- // in-flight processing of *this before our storage goes away. That- // processing can put us back on its list, so look again after it.- while (true) {- DecommitWorker::the().deregister(*this);+ FFI::rust_gc_block_pool_destroy(m_pool);+}- MutexLocker locker(m_mutex);- while (m_worker_refcount.load() != 0)- m_worker_cv.wait();- if (!exchange(m_in_decommit_registry, false))- break;- }+void BlockAllocator::return_freed_blocks_to_system()+{+ FFI::rust_gc_block_pool_return_freed_blocks_to_system(m_pool);}size_t BlockAllocator::block_count(){- MutexLocker locker(m_mutex);- return m_blocks.size() + m_returned_blocks.size();+ return FFI::rust_gc_block_pool_block_count(m_pool);}size_t BlockAllocator::returned_block_count_for_testing(){- MutexLocker locker(m_mutex);- return m_returned_blocks.size();+ return FFI::rust_gc_block_pool_returned_block_count(m_pool);}HeapRegionBaseCopyRegistration::HeapRegionBaseCopyRegistration(FlatPtr& copy)@@ -574,72 +162,20 @@ FlatPtr BlockAllocator::heap_region_end()FlatPtr BlockAllocator::heap_region_committed_end(){- return heap_region().committed_end();+ (void)heap_region();+ return FFI::rust_gc_heap_region_committed_end();}void* BlockAllocator::allocate_block([[maybe_unused]] char const* name){- void* block = nullptr;- bool needs_madvise_reuse = false;-- {- MutexLocker locker(m_mutex);-- // Prefer m_freshly_freed: those slots were never madvised, so we- // can hand them back out with zero syscalls. This is the deferred-- // decommit payoff -- hot recycle skips both MADV_FREE_REUSABLE- // and MADV_FREE_REUSE.- if (!m_freshly_freed.is_empty()) {- block = m_freshly_freed.take_last();- } else if (!m_blocks.is_empty()) {- block = m_blocks.take_last();- needs_madvise_reuse = true;- } else if (!m_returned_blocks.is_empty()) {- block = m_returned_blocks.take_last();- needs_madvise_reuse = true;- }- }-- if (block == nullptr) {- block = heap_region().take_unused_block();- needs_madvise_reuse = true;- }-- ASAN_UNPOISON_MEMORY_REGION(block, HeapBlock::BLOCK_SIZE);- LSAN_REGISTER_ROOT_REGION(block, HeapBlock::BLOCK_SIZE);-#if defined(MADV_FREE_REUSE) && defined(MADV_FREE_REUSABLE)- if (needs_madvise_reuse) {- if (madvise(block, HeapBlock::BLOCK_SIZE, MADV_FREE_REUSE) < 0) {- perror("madvise(MADV_FREE_REUSE)");- VERIFY_NOT_REACHED();- }- }-#else- (void)needs_madvise_reuse;-#endif- return block;+ (void)heap_region();+ return FFI::rust_gc_block_pool_allocate_block(m_pool);}void BlockAllocator::deallocate_block(void* block, DeferDecommit defer_decommit){VERIFY(block);-- // Fast path: bookkeep only. The actual madvise is deferred to the- // global decommit worker, which the GC kicks at the end of sweep.- ASAN_POISON_MEMORY_REGION(block, HeapBlock::BLOCK_SIZE);- LSAN_UNREGISTER_ROOT_REGION(block, HeapBlock::BLOCK_SIZE);-- bool need_to_register = false;- {- MutexLocker locker(m_mutex);- m_freshly_freed.append(block);- if (defer_decommit == DeferDecommit::Yes && !m_in_decommit_registry) {- m_in_decommit_registry = true;- need_to_register = true;- }- }- if (need_to_register && defer_decommit == DeferDecommit::Yes)- DecommitWorker::the().register_pending(*this);+ FFI::rust_gc_block_pool_deallocate_block(m_pool, static_cast<u8*>(block), defer_decommit == DeferDecommit::Yes);}}diff --git a/Libraries/LibGC/BlockAllocator.h b/Libraries/LibGC/BlockAllocator.hindex 315e2ee31d1..c5f5cad460a 100644--- a/Libraries/LibGC/BlockAllocator.h+++ b/Libraries/LibGC/BlockAllocator.h@@ -6,14 +6,18 @@#pragma once-#include <AK/Atomic.h>-#include <AK/ConditionVariable.h>-#include <AK/Mutex.h>+#include <AK/Badge.h>+#include <AK/Noncopyable.h>#include <AK/Time.h>-#include <AK/Vector.h>#include <AK/kmalloc.h>#include <LibGC/Forward.h>+namespace GC::FFI {++struct BlockPool;++}+namespace GC {enum class DeferDecommit {@@ -21,10 +25,12 @@ enum class DeferDecommit {Yes,};-class DecommitWorker;--// The blocks of one type of cell in all heaps, see CellAllocatorDescriptorBase::block_allocator().+// The blocks of one type of cell in all heaps, see CellAllocatorDescriptorBase::block_allocator(). The pool itself, the+// heap region's chunks and the thread that gives the pages of freed blocks back to the system are LibGC's Rust core.class GC_API BlockAllocator {+ AK_MAKE_NONCOPYABLE(BlockAllocator);+ AK_MAKE_NONMOVABLE(BlockAllocator);+public:AK_ALLOC_WITH_KMALLOC;@@ -56,38 +62,10 @@ public:// Returns the age it replaces.static AK::Duration set_cold_block_age_for_testing(AK::Duration);+ FFI::BlockPool const* rust_pool(Badge<CellAllocator>) const { return m_pool; }+private:- friend class DecommitWorker;-- // Slots in "ready to reuse" state -- have been MADV_FREE_REUSABLE'd by- // the worker (Darwin) so allocate_block pairs them with MADV_FREE_REUSE.- Vector<void*> m_blocks;-- // Slots whose pages went back for real, as their heap went away or they- // stayed unused for long. They are the last ones to reuse, as their pages- // have to be faulted in again.- Vector<void*> m_returned_blocks;-- // Slots freed by deallocate_block but not yet madvised. allocate_block- // pops directly from here to skip the madvise round-trip on hot recycle- // paths -- this is the main payoff of deferring decommit.- Vector<void*> m_freshly_freed;-- // Protects the slots above and m_in_decommit_registry. Held- // briefly on the alloc/dealloc hot path; uncontended in the common case.- Mutex m_mutex;-- // Refcount the decommit worker bumps while it has a reference to this- // allocator. The destructor waits on m_worker_cv until it hits zero so- // we never let our storage go away while the worker is still running.- AK::Atomic<int> m_worker_refcount { 0 };- ConditionVariable m_worker_cv;-- // True iff this allocator is currently in the worker's pending list.- // Avoids re-registering on every dealloc; cleared by the worker at the- // start of process_one, set by deallocate_block under m_mutex, and by- // process_one for blocks that it has to look at again.- bool m_in_decommit_registry { false };+ FFI::BlockPool const* m_pool { nullptr };};}diff --git a/Libraries/LibGC/BlockDescriptor.h b/Libraries/LibGC/BlockDescriptor.hindex b20125795ce..9d84107fe3b 100644--- a/Libraries/LibGC/BlockDescriptor.h+++ b/Libraries/LibGC/BlockDescriptor.h@@ -70,42 +70,13 @@ ALWAYS_INLINE void clear_marks(FFI::BlockDescriptor& descriptor)}// A cell is allocated from when it is handed out until the sweep or a move frees its slot. While an allocator has taken-// the free cells of a block to hand them out itself, they all count as allocated, see HeapBlock::take_free_cells(). Only+// a run of free cells of a block to hand them out, they all count as allocated, see CellAllocator::LocalFreeCells. Only// the thread that owns the block's heap reads and writes these bits.ALWAYS_INLINE bool is_allocated(FFI::BlockDescriptor const& descriptor, size_t index){return descriptor.allocated[index / 64] & cell_bit(index);}-ALWAYS_INLINE void set_allocated(FFI::BlockDescriptor& descriptor, size_t index)-{- descriptor.allocated[index / 64] |= cell_bit(index);-}--ALWAYS_INLINE void clear_allocated(FFI::BlockDescriptor& descriptor, size_t index)-{- descriptor.allocated[index / 64] &= ~cell_bit(index);-}--// The bits of the word of a bitmap whose first bit is at `first` that are for indices below `limit`.-ALWAYS_INLINE u64 bits_below(size_t limit, size_t first)-{- if (limit <= first)- return 0;- if (limit >= first + 64)- return ~static_cast<u64>(0);- return cell_bit(limit - first) - 1;-}--// The cells of a block are the ones from first_cell_index on, see cell_index().-ALWAYS_INLINE void set_all_allocated(FFI::BlockDescriptor& descriptor)-{- size_t begin = descriptor.first_cell_index;- size_t end = begin + descriptor.cell_count;- for (size_t word = 0; word < FFI::CELL_BITMAP_WORDS; ++word)- descriptor.allocated[word] = bits_below(end, word * 64) & ~bits_below(begin, word * 64);-}-ALWAYS_INLINE u32 allocated_cell_count_of(FFI::BlockDescriptor const& descriptor){u32 count = 0;@@ -134,8 +105,4 @@ ALWAYS_INLINE void* allocated_cell_containing(void const* heap, FlatPtr address,return bit_cast<void*>(cell);}-// Fills in the descriptor of a block that is about to hold cells, and empties it once the block goes away.-void publish_block_descriptor(HeapBlock&, CellAllocator&);-void retire_block_descriptor(HeapBlock&);-}diff --git a/Libraries/LibGC/CMakeLists.txt b/Libraries/LibGC/CMakeLists.txtindex 45c02ef1463..a61b0ceeb2d 100644--- a/Libraries/LibGC/CMakeLists.txt+++ b/Libraries/LibGC/CMakeLists.txt@@ -23,11 +23,15 @@ target_link_libraries(LibGC PRIVATE LibCore)target_link_libraries(LibGC PUBLIC LibThreading)# The collector's core: the descriptors of blocks, and marking.-import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust FEATURES allocator FFI_HEADER RustFFI.h)+set(LIBGC_RUST_FEATURES allocator)+if (ENABLE_ADDRESS_SANITIZER)+ list(APPEND LIBGC_RUST_FEATURES address-sanitizer)+endif()+import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust FEATURES ${LIBGC_RUST_FEATURES} FFI_HEADER RustFFI.h)test_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust)target_link_libraries(LibGC PRIVATE libgc_rust)get_target_property(_libgc_rust_lib libgc_rust IMPORTED_LOCATION)-set_property(SOURCE BlockAllocator.cpp CAPI.cpp Cell.cpp Heap.cpp HeapBlock.cpp WeakBlock.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libgc_rust_lib})+set_property(SOURCE BlockAllocator.cpp CAPI.cpp Cell.cpp CellAllocator.cpp Heap.cpp HeapBlock.cpp WeakBlock.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libgc_rust_lib})# The first word of a GC::ForeignCell belongs to its foreign implementation rather than holding a vtable pointer, so# UBSan's vptr checks misfire whenever LibGC handles such a cell as a GC::Cell.diff --git a/Libraries/LibGC/CellAllocator.cpp b/Libraries/LibGC/CellAllocator.cppindex 76b959c2673..fa2a59532de 100644--- a/Libraries/LibGC/CellAllocator.cpp+++ b/Libraries/LibGC/CellAllocator.cpp@@ -8,8 +8,10 @@#include <AK/HashMap.h>#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>+#include <AK/Time.h>#include <AK/Vector.h>#include <LibGC/BlockAllocator.h>+#include <LibGC/BlockDescriptor.h>#include <LibGC/CellAllocator.h>#include <LibGC/Heap.h>#include <LibGC/HeapBlock.h>@@ -80,116 +82,108 @@ BlockAllocator& CellAllocatorDescriptorBase::block_allocator() constreturn *pools->ensure(key, [] { return make<BlockAllocator>(); });}-CellAllocator::CellAllocator(CellAllocatorDescriptorBase& descriptor)+void CellAllocator::initialize_block(void* context, void* block)+{+ auto& allocator = *static_cast<CellAllocator*>(context);+ HeapBlock::initialize(block, allocator.m_heap, allocator);+}++// Frees the slot of a cell for LibGC's Rust core: runs its destructor first if it died, and marks it dead.+void CellAllocator::free_cell(void* context, void* address, bool destroy)+{+ auto& allocator = *static_cast<CellAllocator*>(context);+ auto* cell = static_cast<Cell*>(address);+ VERIFY(cell->state() == Cell::State::Live);+ if (auto* destroy_cell = allocator.type_info().destroy; destroy && destroy_cell) {+ allocator.m_heap.will_destroy_swept_cell({});+ destroy_cell(cell);+ allocator.m_heap.did_destroy_swept_cell({});+ }+ cell->set_state(Cell::State::Dead);++#ifdef HAS_ADDRESS_SANITIZER+ // NB: The header of a free cell, where its state is, stays accessible.+ auto after_header = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(cell) + HeapBlock::min_possible_cell_size, 8);+ VERIFY(after_header - reinterpret_cast<uintptr_t>(cell) <= allocator.cell_size());+ ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(after_header), allocator.cell_size() - (after_header - reinterpret_cast<uintptr_t>(cell)));+#endif+}++CellAllocator::CellAllocator(Heap& heap, CellAllocatorDescriptorBase& descriptor): m_descriptor(descriptor), m_block_allocator(descriptor.block_allocator())+ , m_heap(heap){m_local.cell_size = cell_size();+ FFI::AllocatorConfig config {+ .heap_region_base = heap_region_base(),+ .heap = &heap,+ .type_info = &type_info(),+ .pool = m_block_allocator.rust_pool({}),+ .local = reinterpret_cast<FFI::LocalFreeCells*>(&m_local),+ .cells_offset = static_cast<u32>(HeapBlock::cells_offset()),+ .cell_size = static_cast<u32>(cell_size()),+ .traced_on_owner_thread_only = descriptor.trace_thread() == TraceThread::OwnerThreadOnly,+ .movable = descriptor.is_movable(),+ .context = this,+ .initialize_block = initialize_block,+ .free_cell = free_cell,+ };+ m_allocator = FFI::rust_gc_allocator_create(&config);}CellAllocator::~CellAllocator(){- m_blocks_pending_sweep.clear();-- auto reclaim_all = [this](BlockList& blocks) {- while (auto* block = blocks.take_first()) {- block->~HeapBlock();- m_block_allocator.deallocate_block(block, DeferDecommit::No);- }- };- reclaim_all(m_full_blocks);- reclaim_all(m_usable_blocks);-- // NB: This heap is gone, and another one may not come along to use the blocks of this type for a long time.- m_block_allocator.return_freed_blocks_to_system();+ FFI::rust_gc_allocator_destroy(m_allocator);}+static_assert(sizeof(CellAllocator::LocalFreeCells) == sizeof(FFI::LocalFreeCells));+static_assert(__builtin_offsetof(CellAllocator::LocalFreeCells, cursor) == __builtin_offsetof(FFI::LocalFreeCells, cursor));+static_assert(__builtin_offsetof(CellAllocator::LocalFreeCells, end) == __builtin_offsetof(FFI::LocalFreeCells, end));+static_assert(__builtin_offsetof(CellAllocator::LocalFreeCells, cell_size) == __builtin_offsetof(FFI::LocalFreeCells, cell_size));+Cell* CellAllocator::allocate_cell_slow(Heap& heap){- // NB: The local block has no free cells left, and take_free_cells() left it full.- VERIFY(HeapBlock::is_end_of_freelist(m_local.free_list.ptr()));- VERIFY(m_local.cursor == m_local.end);- m_local.free_list = nullptr;- m_local.cursor = 0;- m_local.end = 0;- m_local_block = nullptr;-if (!m_list_node.is_in_list())heap.register_cell_allocator({}, *this);+ // NB: A heap that collects on every allocation hands out single cells, as code that bumps through runs itself+ // would take cells from them without collecting.bool can_sweep = heap.is_incremental_sweep_active() && !heap.is_gc_deferred();- for (;;) {- if (m_usable_blocks.is_empty() && can_sweep && !m_blocks_pending_sweep.is_empty()) {- // Sweep our own pending blocks first to try to find free cells- // before allocating a new block.- heap.sweep_block(*m_blocks_pending_sweep.first());- continue;- }-- if (m_usable_blocks.is_empty()) {- auto block = HeapBlock::create(heap, *this);- m_usable_blocks.append(*block.leak_ptr());- }-- auto& block = *m_usable_blocks.last();- if (block.is_pending_sweep() && can_sweep) {- heap.sweep_block(block);- continue;- }-- // NB: Without sweeping the block first, take a single cell from it,- // which the heap marks as allocated during the sweep. The same- // goes for the block the sweep is in the middle of, which a- // destructor may allocate from. A heap that collects on every- // allocation has no local free lists, which code that pops them- // itself would take cells from without collecting.- if (block.is_pending_sweep() || block.is_being_swept() || heap.should_collect_on_every_allocation()) {- auto* cell = block.allocate();- VERIFY(cell);- if (block.is_full())- m_full_blocks.append(block);- return cell;- }-- auto free_cells = block.take_free_cells();- VERIFY(!HeapBlock::is_end_of_freelist(free_cells.free_list.ptr()) || free_cells.lazy_start < free_cells.lazy_end);- m_local.free_list = free_cells.free_list;- m_local.cursor = free_cells.lazy_start;- m_local.end = free_cells.lazy_end;- m_full_blocks.append(block);- m_local_block = █- return allocate_cell(heap);- }+ FFI::SweepStats stats {};+ // NB: The time spent sweeping goes into how far the heap grows before the next collection, see+ // Heap::next_growth_factor().+ auto start_ns = can_sweep ? MonotonicTime::now().nanoseconds() : 0;+ auto* cell = static_cast<Cell*>(FFI::rust_gc_allocator_allocate(m_allocator, can_sweep, heap.should_collect_on_every_allocation(), &stats));+ if (stats.swept_blocks)+ heap.did_sweep_blocks_for_allocation({}, stats.swept_blocks, MonotonicTime::now().nanoseconds() - start_ns);+ ASAN_UNPOISON_MEMORY_REGION(cell, cell_size());+ return cell;}void CellAllocator::give_back_local_free_list(Badge<Heap>){- if (!m_local_block)- return;- if (!HeapBlock::is_end_of_freelist(m_local.free_list.ptr()) || m_local.cursor < m_local.end) {- m_local_block->give_back_free_cells(m_local.free_list.ptr(), m_local.cursor);- m_usable_blocks.append(*m_local_block);- }- m_local.free_list = nullptr;- m_local.cursor = 0;- m_local.end = 0;- m_local_block = nullptr;+ FFI::rust_gc_allocator_give_back_local_free_cells(m_allocator);+}++size_t CellAllocator::block_count() const+{+ return FFI::rust_gc_allocator_block_count(m_allocator);+}++HeapBlock* CellAllocator::block_at(size_t index) const+{+ return static_cast<HeapBlock*>(FFI::rust_gc_allocator_block_at(m_allocator, index));}-void CellAllocator::block_did_become_empty(Badge<Heap>, HeapBlock& block, DeferDecommit defer_decommit)+bool CellAllocator::is_local_block(HeapBlock const& block) const{- block.m_list_node.remove();- --block.heap().m_block_count;- block.heap().forget_cells_kept_by_pins(block);- // NOTE: HeapBlocks are managed by the BlockAllocator, so we don't want to `delete` the block here.- block.~HeapBlock();- m_block_allocator.deallocate_block(&block, defer_decommit);+ return FFI::rust_gc_allocator_local_block(m_allocator) == █}-void CellAllocator::block_did_become_usable(Badge<Heap>, HeapBlock& block)+bool CellAllocator::has_blocks_pending_sweep() const{- VERIFY(!block.is_full());- m_usable_blocks.append(block);+ return FFI::rust_gc_allocator_has_blocks_pending_sweep(m_allocator);}}diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.hindex 79967a51493..bcbcd4ba977 100644--- a/Libraries/LibGC/CellAllocator.h+++ b/Libraries/LibGC/CellAllocator.h@@ -7,6 +7,7 @@#pragma once#include <AK/IntrusiveList.h>+#include <AK/IterationDecision.h>#include <AK/NeverDestroyed.h>#include <LibGC/BlockAllocator.h>#include <LibGC/CellTypeInfo.h>@@ -14,6 +15,10 @@#include <LibGC/HeapBlock.h>#include <LibGC/Ptr.h>+#ifdef HAS_ADDRESS_SANITIZER+# include <sanitizer/asan_interface.h>+#endif+// The default allocator, which isolates different Cell types from being allocated in the same blocks.#define GC_DECLARE_ALLOCATOR(ClassName) \using gc_allocator_marker = ClassName; \@@ -22,6 +27,12 @@#define GC_DEFINE_ALLOCATOR(ClassName) \GC::TypeIsolatingCellAllocator<ClassName> ClassName::cell_allocator { #ClassName##sv }+namespace GC::FFI {++struct Allocator;++}+namespace GC {// Which threads may trace the cells of an allocator while the collector marks. C++ cells are only traced on the thread@@ -72,11 +83,16 @@ private:bool m_movable { false };};+// The cells of one type in one heap. LibGC's Rust core keeps the allocator's blocks, hands out their free cells in runs+// and sweeps them, see allocator.rs. This keeps the run that cells are allocated from inline.class GC_API CellAllocator {+ AK_MAKE_NONCOPYABLE(CellAllocator);+ AK_MAKE_NONMOVABLE(CellAllocator);+public:AK_ALLOC_WITH_KMALLOC;- explicit CellAllocator(CellAllocatorDescriptorBase&);+ CellAllocator(Heap&, CellAllocatorDescriptorBase&);~CellAllocator();CellAllocatorDescriptorBase const& descriptor() const { return m_descriptor; }@@ -85,23 +101,21 @@ public:CellTypeInfo const& type_info() const { return m_descriptor.type_info(); }void const* foreign_type() const { return m_descriptor.foreign_type(); }- // Cells come from the free cells that the allocator took from one of its- // blocks (the local block) at once, so allocating is usually just popping- // a list of freed cells, or bumping a cursor over cells that were never- // allocated.+ // Cells come from a run of free cells that the allocator took from one+ // of its blocks (the local block) at once, so allocating is usually just+ // bumping a cursor.//// Invariants of the local free cells:- // - They are dead and belong to the local block, which is in the full- // block list while it has local free cells.+ // - They are free cells of the local block, whose allocated bits are set+ // while they are out, see BlockDescriptor.h.// - The local block is never pending incremental sweep: they come from// swept or new blocks only, and are handed back to their block whenever// a collection starts. So cells from them never need marking.- // - The list is empty when its head is at the start of a block (or null),- // which is where following the link of the last cell leads (see- // HeapBlock::follow_freelist_link()).- // - The cells from the cursor up to the end are cells of the local block- // that were never allocated, and cell_size apart. There are none when the- // cursor is at the end.+ // - The list is always empty, which its head being null says. It is only+ // there for code that allocates from it itself, which still checks it,+ // see gc_heap_allocator_local_free_list().+ // - The cells from the cursor up to the end are cell_size apart. There+ // are none when the cursor is at the end.struct LocalFreeCells {RawPtr<Cell> free_list;FlatPtr cursor { 0 };@@ -111,11 +125,6 @@ public:ALWAYS_INLINE Cell* allocate_cell(Heap& heap){- if (auto* cell = m_local.free_list.ptr(); !HeapBlock::is_end_of_freelist(cell)) [[likely]] {- m_local.free_list = HeapBlock::next_free_cell(cell);- ASAN_UNPOISON_MEMORY_REGION(cell, cell_size());- return cell;- }if (m_local.cursor < m_local.end) [[likely]] {auto* cell = bit_cast<Cell*>(m_local.cursor);m_local.cursor += m_local.cell_size;@@ -134,23 +143,16 @@ public:template<typename Callback>IterationDecision for_each_block(Callback callback){- for (auto& block : m_full_blocks) {- if (callback(block) == IterationDecision::Break)- return IterationDecision::Break;- }- for (auto& block : m_usable_blocks) {- if (callback(block) == IterationDecision::Break)+ for (size_t i = 0; i < block_count(); ++i) {+ if (callback(*block_at(i)) == IterationDecision::Break)return IterationDecision::Break;}return IterationDecision::Continue;}- void block_did_become_empty(Badge<Heap>, HeapBlock&, DeferDecommit = DeferDecommit::Yes);- void block_did_become_usable(Badge<Heap>, HeapBlock&);-- bool is_local_block(HeapBlock const& block) const { return m_local_block == █ }-- bool has_blocks_pending_sweep() const { return !m_blocks_pending_sweep.is_empty(); }+ size_t block_count() const;+ bool is_local_block(HeapBlock const&) const;+ bool has_blocks_pending_sweep() const;IntrusiveListNode<CellAllocator> m_list_node;using List = IntrusiveList<&CellAllocator::m_list_node>;@@ -159,23 +161,21 @@ public:using SweepList = IntrusiveList<&CellAllocator::m_sweep_list_node>;BlockAllocator& block_allocator() { return m_block_allocator; }+ FFI::Allocator* rust_allocator(Badge<Heap>) { return m_allocator; }private:- friend class Heap;+ friend class HeapBlock;+ HeapBlock* block_at(size_t index) const;Cell* allocate_cell_slow(Heap&);+ static void initialize_block(void* context, void* block);+ static void free_cell(void* context, void* cell, bool destroy);CellAllocatorDescriptorBase& m_descriptor;LocalFreeCells m_local;- HeapBlock* m_local_block { nullptr };-BlockAllocator& m_block_allocator;-- using BlockList = IntrusiveList<&HeapBlock::m_list_node>;- using SweepBlockList = IntrusiveList<&HeapBlock::m_sweep_list_node>;- BlockList m_full_blocks;- BlockList m_usable_blocks;- SweepBlockList m_blocks_pending_sweep;+ Heap& m_heap;+ FFI::Allocator* m_allocator { nullptr };};template<typename T>diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 62c4dbc54d3..113168d7cfe 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -141,28 +141,22 @@ i32 libgc_log_level()// LIBGC_MOVE_EVERYTHING=1 has every collection that may move cells (one that does not scan the stack) evacuate every// block of cells defined outside of C++, moving each cell that can move to another slot. This tests that moving cells// is safe, and its report tells what keeps cells from moving.-bool read_libgc_move_everything()-{- char const* env = getenv("LIBGC_MOVE_EVERYTHING");- return env && *env && atoi(env) != 0;-}-bool libgc_move_everything(){- static bool const value = read_libgc_move_everything();+ static bool const value = [] {+ char const* env = getenv("LIBGC_MOVE_EVERYTHING");+ return env && *env && atoi(env) != 0;+ }();return value;}// LIBGC_COMPACT=0 turns compaction off, so that collections never move cells unless LIBGC_MOVE_EVERYTHING asks them to.-bool read_libgc_compact()-{- char const* env = getenv("LIBGC_COMPACT");- return !env || !*env || atoi(env) != 0;-}-bool libgc_compact(){- static bool const value = read_libgc_compact();+ static bool const value = [] {+ char const* env = getenv("LIBGC_COMPACT");+ return !env || !*env || atoi(env) != 0;+ }();return value;}@@ -518,7 +512,7 @@ CellAllocator& Heap::create_cell_allocator(CellAllocatorDescriptorBase& descriptm_cell_allocators_by_descriptor_index.resize(index + 1);auto& allocator = m_cell_allocators_by_descriptor_index[index];VERIFY(!allocator);- allocator = make<CellAllocator>(descriptor);+ allocator = make<CellAllocator>(*this, descriptor);return *allocator;}@@ -582,8 +576,8 @@ void Heap::add_stats(AK::JsonObject& values) constVERIFY(m_stats);values.set("gc.allocated_bytes_total"sv, m_total_allocated_bytes);values.set("gc.allocated_bytes_since_gc"sv, m_allocated_bytes_since_last_gc);- values.set("gc.heap_blocks"sv, m_block_count);- values.set("gc.heap_block_bytes"sv, m_block_count * HeapBlock::BLOCK_SIZE);+ values.set("gc.heap_blocks"sv, block_count());+ values.set("gc.heap_block_bytes"sv, block_count() * HeapBlock::BLOCK_SIZE);values.set("gc.cell_allocators"sv, m_all_cell_allocators.size_slow());values.set("gc.threshold_bytes"sv, m_gc_bytes_threshold);values.set("gc.live_cell_bytes"sv, m_stats->live_cell_bytes);@@ -608,7 +602,7 @@ void Heap::finish_stats_collection()data.set("pause_duration_ns"sv, stats.pause_duration_ns);data.set("sweep_duration_ns"sv, stats.sweep_duration_ns);data.set("bytes_before"sv, stats.bytes_before);- data.set("bytes_after"sv, m_block_count * HeapBlock::BLOCK_SIZE);+ data.set("bytes_after"sv, block_count() * HeapBlock::BLOCK_SIZE);data.set("live_cell_bytes"sv, stats.live_cell_bytes);data.set("live_external_bytes"sv, stats.live_external_bytes);log->event("gc"sv, move(data));@@ -713,6 +707,18 @@ void Heap::update_gc_bytes_threshold()}// The part of the heap region that can hold cells, read once per scan.+// Calls the callback for each allocated cell of the block, which includes the cells of a run that an allocator has out.+template<typename Callback>+static void for_each_allocated_cell(HeapBlock& block, Callback callback)+{+ auto& descriptor = block_descriptor_for(&block);+ auto first_cell = bit_cast<FlatPtr>(&block) + HeapBlock::cells_offset();+ for (size_t index = descriptor.first_cell_index; index < descriptor.first_cell_index + descriptor.cell_count; ++index) {+ if (is_allocated(descriptor, index))+ callback(bit_cast<Cell*>(first_cell + (index - descriptor.first_cell_index) * descriptor.cell_size));+ }+}+struct PossiblePointerBounds {static PossiblePointerBounds current(){@@ -1042,9 +1048,6 @@ void Heap::clear_weak_pointers_to_dead_cells(bool report)void Heap::run_post_mark_phases(bool report){- // NB: The side table keeps the identity hashes of cells by address, which other cells may take once these are swept.- FFI::rust_gc_identity_hashes_drop_dead(m_identity_hashes, heap_region_base());-{ScopedPhaseTimer timer { report, g_phase_timings.finalize_unmarked_cells_us };finalize_unmarked_cells();@@ -1142,7 +1145,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti}if (m_stats) {++m_stats->collections;- m_stats->bytes_before = m_block_count * HeapBlock::BLOCK_SIZE;+ m_stats->bytes_before = block_count() * HeapBlock::BLOCK_SIZE;m_stats->sweep_duration_ns = 0;}compaction_stats().active = false;@@ -1255,6 +1258,14 @@ bool Heap::should_move_cells(CollectionType collection_type, bool scan_stack) coreturn m_moves_everything || m_should_compact;}+size_t Heap::block_count() const+{+ size_t count = 0;+ for (auto& allocator : m_all_cell_allocators)+ count += allocator.block_count();+ return count;+}+// The blocks of the movable allocators, as candidates for compaction, see rust_gc_compaction_select().static Vector<FFI::CompactionCandidate> compaction_candidates(CellAllocator::List& allocators, size_t block_count){@@ -1265,8 +1276,8 @@ static Vector<FFI::CompactionCandidate> compaction_candidates(CellAllocator::Lisif (!allocator.descriptor().is_movable())continue;auto cell_size = static_cast<u32>(allocator.cell_size());- auto cell_count = static_cast<u32>((HeapBlock::BLOCK_SIZE - sizeof(HeapBlock)) / cell_size);allocator.for_each_block([&](HeapBlock& block) {+ auto cell_count = static_cast<u32>(block.cell_count());candidates.unchecked_append({.block = &block,.allocator = allocator_index,@@ -1297,7 +1308,7 @@ void Heap::schedule_compaction_if_worthwhile()if (last.freed_blocks * HeapBlock::BLOCK_SIZE >= GC_COMPACTION_MIN_RECOVERABLE_BYTES)recoverable_blocks = last.blocks_left_by_budget;} else {- auto candidates = compaction_candidates(m_all_cell_allocators, m_block_count);+ auto candidates = compaction_candidates(m_all_cell_allocators, block_count());recoverable_blocks = FFI::rust_gc_compaction_select(candidates.data(), candidates.size(), 0).fitting_blocks;}if (recoverable_blocks * HeapBlock::BLOCK_SIZE < GC_COMPACTION_MIN_RECOVERABLE_BYTES) {@@ -1307,7 +1318,7 @@ void Heap::schedule_compaction_if_worthwhile()}m_should_compact = true;if (libgc_log_level() >= 1)- dbgln("Scheduling a collection that compacts: {} of {} recoverable", human_readable_size(recoverable_blocks * HeapBlock::BLOCK_SIZE), human_readable_size(m_block_count * HeapBlock::BLOCK_SIZE));+ dbgln("Scheduling a collection that compacts: {} of {} recoverable", human_readable_size(recoverable_blocks * HeapBlock::BLOCK_SIZE), human_readable_size(block_count() * HeapBlock::BLOCK_SIZE));schedule_collection_that_moves_cells();}@@ -1341,7 +1352,7 @@ void Heap::begin_evacuation()} else {m_should_compact = false;auto select_start_ns = MonotonicTime::now().nanoseconds();- auto candidates = compaction_candidates(m_all_cell_allocators, m_block_count);+ auto candidates = compaction_candidates(m_all_cell_allocators, block_count());auto selection = FFI::rust_gc_compaction_select(candidates.data(), candidates.size(), GC_COMPACTION_BUDGET_BYTES);for (auto const& candidate : candidates) {if (candidate.selected)@@ -1372,19 +1383,9 @@ void Heap::begin_evacuation()Cell* Heap::allocate_destination_for_moved_cell(CellAllocator& allocator){- for (;;) {- if (allocator.m_usable_blocks.is_empty()) {- auto block = HeapBlock::create(*this, allocator);- allocator.m_usable_blocks.append(*block.leak_ptr());- ++compaction_stats().new_blocks;- }- auto& block = *allocator.m_usable_blocks.first();- auto* cell = block.allocate();- if (block.is_full())- allocator.m_full_blocks.append(block);- if (cell)- return cell;- }+ auto* cell = static_cast<Cell*>(FFI::rust_gc_allocator_allocate_destination(allocator.rust_allocator({})));+ ASAN_UNPOISON_MEMORY_REGION(cell, allocator.cell_size());+ return cell;}// Moves the live cells of the evacuated blocks that nothing pinned to free slots of other blocks of their allocator:@@ -1413,8 +1414,6 @@ void Heap::evacuate()};Vector<AllocatorMoves> all_moves;Array<void*, FFI::MAX_CELLS_PER_BLOCK> cells;- // NB: The evacuated blocks wait here while cells move, so that no cell moves into one of them.- CellAllocator::BlockList blocks_being_evacuated;Vector<HeapBlock*> blocks_kept_by_pins;auto copy_start_ns = MonotonicTime::now().nanoseconds();@@ -1435,10 +1434,9 @@ void Heap::evacuate()Vector<Cell*> cells_to_move;for (size_t i = exchange(first_block_of_allocator, end); i < end; ++i) {auto& block = *m_evacuated_blocks[i];- blocks_being_evacuated.append(block);auto& descriptor = block_descriptor_for(&block);if (count_by_type || !allocator.descriptor().is_movable()) {- block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {+ for_each_allocated_cell(block, [&](Cell* cell) {if (!allocator.descriptor().is_movable())count_pinned(cell, cell_size, CompactionStats::NonMovableAllocator);else if (auto reason = FFI::rust_gc_evacuation_pin_reason(m_evacuation, cell); reason != FFI::PinReason::Unpinned)@@ -1503,38 +1501,20 @@ void Heap::evacuate()stats.copy_us += (release_start_ns - copy_start_again_ns) / 1000;for (auto& [allocator, moves] : all_moves) {- for (auto& cell_move : moves) {- auto* cell = static_cast<Cell*>(cell_move.from);- HeapBlock::from_cell(cell)->release_moved_cell(cell);- }+ for (auto& cell_move : moves)+ FFI::rust_gc_allocator_release_moved_cell(allocator->rust_allocator({}), cell_move.from);}// NB: What is left in these blocks is what pins kept there, and evacuating them again would not free them, see// rust_gc_compaction_select().- for (auto* block : blocks_kept_by_pins) {- auto& descriptor = block_descriptor_for(block);- static_assert(cell_bitmap_words == FFI::CELL_BITMAP_WORDS);- Array<u64, cell_bitmap_words> kept {};- for (size_t i = 0; i < cell_bitmap_words; ++i)- kept[i] = descriptor.allocated[i];- m_cells_kept_by_pins.set(block, kept);- descriptor.kept_by_pins = true;- }-- // Puts the evacuated blocks back with their allocators, and lets go of the ones that are empty now.- for (auto* evacuated_block : m_evacuated_blocks) {- auto& block = *evacuated_block;- auto& allocator = block.cell_allocator();- if (block.allocated_cell_count() == 0) {- allocator.block_did_become_empty({}, block, DeferDecommit::Yes);+ for (auto* block : blocks_kept_by_pins)+ FFI::rust_gc_allocator_keep_cells_pinned(block->cell_allocator().rust_allocator({}), block);++ // Lets go of the evacuated blocks that are empty now, and lists the others as usable again.+ for (auto* block : m_evacuated_blocks) {+ if (FFI::rust_gc_allocator_finish_evacuated_block(block->cell_allocator().rust_allocator({}), block))++stats.freed_blocks;- } else if (block.is_full()) {- allocator.m_full_blocks.append(block);- } else {- allocator.m_usable_blocks.append(block);- }}- VERIFY(blocks_being_evacuated.is_empty());stats.release_us = (MonotonicTime::now().nanoseconds() - release_start_ns) / 1000;}@@ -1546,30 +1526,11 @@ bool Heap::is_live_cell(Cell const* cell) constauto address = bit_cast<FlatPtr>(cell);if (address < heap_region_base() + HEAP_REGION_LOW_GUARD_SIZE || address >= BlockAllocator::heap_region_committed_end())return false;- // NB: A cell that an allocator took along with the other free cells of its block counts as allocated, but it is- // still a free cell until the allocator hands it out.+ // NB: A cell of a run that an allocator took counts as allocated, but it is still a free cell until the allocator+ // hands it out. Every collection gives the runs back before it marks.return allocated_cell_containing(this, address, HeapBlock::cells_offset()) == cell && cell->state() == Cell::State::Live;}-void Heap::forget_cells_kept_by_pins(HeapBlock& block)-{- auto& descriptor = block_descriptor_for(&block);- if (!descriptor.kept_by_pins)- return;- descriptor.kept_by_pins = false;- m_cells_kept_by_pins.remove(&block);-}--void Heap::cell_in_block_kept_by_pins_died(HeapBlock& block, Cell const* cell)-{- auto& descriptor = block_descriptor_for(&block);- auto index = cell_index(descriptor, cell);- auto kept = m_cells_kept_by_pins.get(&block);- VERIFY(kept.has_value());- if (kept.value()[index / 64] & (static_cast<u64>(1) << (index % 64)))- forget_cells_kept_by_pins(block);-}-void Heap::end_evacuation(){FFI::rust_gc_evacuation_destroy(m_evacuation);@@ -1640,8 +1601,8 @@ void Heap::run_post_gc_tasks()void Heap::dump_allocators(){- // NB: While an allocator has a block's never-allocated cells out, the block counts them as cells. Give them back,- // so that they are the block's lazy region again and are not counted.+ // NB: While an allocator has a run of a block's free cells out, they count as allocated. Give them back, so that+ // they are not counted.give_back_local_free_lists();size_t total_in_committed_blocks = 0;@@ -1662,14 +1623,11 @@ void Heap::dump_allocators()allocator.for_each_block([&](HeapBlock& heap_block) {BlockStats block { heap_block };- heap_block.for_each_cell([&](Cell* cell) {- if (cell->state() == Cell::State::Live)- ++block.live_cells;- else if (cell->state() == Cell::State::Dead)- ++block.dead_cells;- else- VERIFY_NOT_REACHED();+ for_each_allocated_cell(heap_block, [&](Cell* cell) {+ VERIFY(cell->state() == Cell::State::Live);+ ++block.live_cells;});+ block.dead_cells = heap_block.cell_count() - block.live_cells;total_live_cells += block.live_cells;total_dead_cells += block.dead_cells;@@ -1730,8 +1688,8 @@ AK::JsonObject Heap::census(){VERIFY(!m_collecting_garbage);- // NB: Unswept cells of the last collection are still in the Live state, and cells an allocator has taken out of- // its block's lazy region would count as dead ones, so finish the sweep and give those back first.+ // NB: Unswept cells of the last collection are still allocated, and so are the cells of the runs that allocators+ // have out, so finish the sweep and give those back first.finish_pending_incremental_sweep();give_back_local_free_lists();@@ -1754,9 +1712,7 @@ AK::JsonObject Heap::census()allocator.for_each_block([&](HeapBlock& block) {++blocks;cell_slots += block.cell_count();- block.for_each_cell([&](Cell* cell) {- if (cell->state() != Cell::State::Live)- return;+ for_each_allocated_cell(block, [&](Cell* cell) {++live_cells;auto edges_before = visitor.cell_edges;type_info.visit_edges(cell, &visitor);@@ -1827,7 +1783,7 @@ void Heap::register_sweep_callback(AK::Function<void()> callback)void Heap::gather_roots(ConservativeScanOrigin const& origin, HashMap<Cell*, HeapRoot>& roots, Vector<StackFrameInfo>* out_stack_frames, IncludeIncomingCrossHeapMembers include_incoming_cross_heap_members){for (auto& allocator : m_all_cell_allocators)- VERIFY(!allocator.m_local_block);+ VERIFY(!FFI::rust_gc_allocator_local_block(allocator.rust_allocator({})));// Cross-heap members targeting this heap act as roots for local collections (as the foreign holder is invisible to a local mark).if (include_incoming_cross_heap_members == IncludeIncomingCrossHeapMembers::Yes) {@@ -2115,7 +2071,7 @@ void Heap::mark_live_cells_across(ReadonlySpan<Heap* const> heaps, HashMap<Cell*for (auto* root : roots.keys())root_cells.unchecked_append(root);for (auto* heap : heaps)- heap_bytes += heap->m_block_count * HeapBlock::BLOCK_SIZE;+ heap_bytes += heap->block_count() * HeapBlock::BLOCK_SIZE;}Vector<size_t, 1> marked_cell_bytes;@@ -2179,7 +2135,7 @@ void Heap::finalize_unmarked_cells()if (!finalize)return IterationDecision::Continue;auto& descriptor = block_descriptor_for(&block);- block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {+ for_each_allocated_cell(block, [&](Cell* cell) {if (!is_marked(descriptor, cell))finalize(cell);});@@ -2207,73 +2163,32 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure{dbgln_if(HEAP_DEBUG, "sweep_dead_cells:");auto sweep_start_ns = MonotonicTime::now().nanoseconds();- Vector<HeapBlock*, 32> empty_blocks;- Vector<HeapBlock*, 32> full_blocks_that_became_usable;size_t collected_cells = 0;size_t live_cells = 0;size_t collected_cell_bytes = 0;size_t live_cell_bytes = 0;+ size_t freed_blocks = 0;{ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_block_iteration_us };- for_each_block([&](auto& block) {- u32 block_live_cells = 0;- bool block_was_full = block.is_full();- auto& descriptor = block_descriptor_for(&block);- block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {- if (!is_marked(descriptor, cell)) {- dbgln_if(HEAP_DEBUG, " ~ {}", cell);- if (descriptor.kept_by_pins)- cell_in_block_kept_by_pins_died(block, cell);- block.deallocate(cell);- ++collected_cells;- collected_cell_bytes += block.cell_size();- } else {- ++block_live_cells;- ++live_cells;- live_cell_bytes += block.cell_size();- }- });- bool block_has_live_cells = block_live_cells > 0;- // NB: An evacuated block keeps its marks until its cells have moved, which tells the cells that marking- // knows about from the ones allocated since.- if (!descriptor.evacuation)- clear_marks(descriptor);- if (!block_has_live_cells)- empty_blocks.append(&block);- else if (block_was_full != block.is_full())- full_blocks_that_became_usable.append(&block);- return IterationDecision::Continue;- });- }-- {- ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_block_reclassify_us };// NB: A collection that moves cells is an ordinary one that sweeps synchronously, and gives its empty blocks// back to the system like the incremental sweep does. Only the collection of a heap that goes away keeps// them for whoever comes next.- auto defer_decommit = m_evacuation ? DeferDecommit::Yes : DeferDecommit::No;- for (auto* block : empty_blocks) {- dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", block, block->cell_size());- if (block_descriptor_for(block).evacuation)- clear_marks(block_descriptor_for(block));- block->cell_allocator().block_did_become_empty({}, *block, defer_decommit);- }-- for (auto* block : full_blocks_that_became_usable) {- dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", block, block->cell_size());- block->cell_allocator().block_did_become_usable({}, *block);+ bool defer_decommit = m_evacuation;+ for (auto& allocator : m_all_cell_allocators) {+ auto* rust_allocator = allocator.rust_allocator({});+ FFI::SweepStats stats {};+ FFI::rust_gc_allocator_start_sweep(rust_allocator);+ while (FFI::rust_gc_allocator_sweep_next_block(rust_allocator, defer_decommit, &stats)) { }+ collected_cells += stats.collected_cells;+ live_cells += stats.live_cells;+ collected_cell_bytes += stats.collected_cells * allocator.cell_size();+ live_cell_bytes += stats.live_cells * allocator.cell_size();+ freed_blocks += stats.freed_blocks;}}- if constexpr (HEAP_DEBUG) {- for_each_block([&](auto& block) {- dbgln(" > Live HeapBlock @ {}: cell_size={}", &block, block.cell_size());- return IterationDecision::Continue;- });- }-{ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_update_threshold_us };m_sweep_duration_ns += MonotonicTime::now().nanoseconds() - sweep_start_ns;@@ -2287,7 +2202,7 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure.collected_cell_bytes = collected_cell_bytes,.live_cell_bytes = live_cell_bytes,.live_external_bytes = m_marked_external_bytes,- .freed_block_count = empty_blocks.size(),+ .freed_block_count = freed_blocks,};}(void)measurement_timer;@@ -2299,61 +2214,24 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measurevoid Heap::sweep_block(HeapBlock& block){- // A destructor can allocate and sweep another block. Its time is included in the outermost sweep.- bool record_duration = m_block_sweeps_in_progress == 0;- auto start_ns = record_duration ? MonotonicTime::now().nanoseconds() : 0;- ScopeGuard record_duration_guard = [&] {- if (!record_duration)- return;- auto duration_ns = MonotonicTime::now().nanoseconds() - start_ns;- m_sweep_duration_ns += duration_ns;- if (m_stats)- m_stats->sweep_duration_ns += duration_ns;- };- ++m_block_sweeps_in_progress;- ScopeGuard finish_block_sweep = [&] { --m_block_sweeps_in_progress; };-- // Remove from the allocator's pending sweep list.- block.m_sweep_list_node.remove();- ++m_blocks_swept;+ auto start_ns = MonotonicTime::now().nanoseconds();+ FFI::SweepStats stats {};+ FFI::rust_gc_allocator_sweep_pending_block(block.cell_allocator().rust_allocator({}), &block, &stats);+ did_sweep(stats.swept_blocks, MonotonicTime::now().nanoseconds() - start_ns);+}- block.set_being_swept(true);- bool block_has_live_cells = false;- bool block_was_full = block.is_full();- size_t collected_cells = 0;- size_t live_cells = 0;+void Heap::did_sweep(size_t swept_blocks, i64 duration_ns)+{+ m_blocks_swept += swept_blocks;+ m_sweep_duration_ns += duration_ns;+ if (m_stats)+ m_stats->sweep_duration_ns += duration_ns;+}- auto& descriptor = block_descriptor_for(&block);- block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {- if (!is_marked(descriptor, cell)) {- dbgln_if(HEAP_DEBUG, " ~ {}", cell);- if (descriptor.kept_by_pins)- cell_in_block_kept_by_pins_died(block, cell);- block.deallocate(cell);- ++collected_cells;- } else {- block_has_live_cells = true;- ++live_cells;- }- });- block.set_being_swept(false);- // NB: This also clears the marks of the cells that were allocated in the block while it was swept.- clear_marks(descriptor);-- if (!block_has_live_cells) {- dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", &block, block.cell_size());- dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] Block @ {} freed ({} cells collected)",- &block, collected_cells);- block.cell_allocator().block_did_become_empty({}, block);- } else if (block_was_full && !block.is_full()) {- dbgln_if(HEAP_DEBUG, " - HeapBlock usable again @ {}: cell_size={}", &block, block.cell_size());- dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] Block @ {} now usable (live: {}, collected: {})",- &block, live_cells, collected_cells);- block.cell_allocator().block_did_become_usable({}, block);- } else if constexpr (INCREMENTAL_SWEEP_DEBUG) {- dbgln("[sweep] Block @ {} swept (live: {}, collected: {})",- &block, live_cells, collected_cells);- }+void Heap::did_sweep_blocks_for_allocation(Badge<CellAllocator>, size_t swept_blocks, i64 duration_ns)+{+ // NB: An allocation from a destructor that a sweep runs is part of that sweep, whose time already counts.+ did_sweep(swept_blocks, m_block_sweeps_in_progress == 0 ? duration_ns : 0);}bool Heap::sweep_next_block()@@ -2366,8 +2244,10 @@ bool Heap::sweep_next_block()// Find the next allocator that has blocks pending sweep.while (auto* allocator = m_allocators_to_sweep.first()) {- if (auto* block = allocator->m_blocks_pending_sweep.first()) {- sweep_block(*block);+ auto start_ns = MonotonicTime::now().nanoseconds();+ FFI::SweepStats stats {};+ if (FFI::rust_gc_allocator_sweep_next_block(allocator->rust_allocator({}), true, &stats)) {+ did_sweep(stats.swept_blocks, MonotonicTime::now().nanoseconds() - start_ns);if (!allocator->has_blocks_pending_sweep())allocator->m_sweep_list_node.remove();return false;@@ -2397,13 +2277,9 @@ void Heap::start_incremental_sweep()// and don't need sweeping.size_t total_blocks = 0;for (auto& allocator : m_all_cell_allocators) {- VERIFY(!allocator.m_local_block);- allocator.for_each_block([&](HeapBlock& block) {- allocator.m_blocks_pending_sweep.append(block);- ++total_blocks;- return IterationDecision::Continue;- });- if (allocator.has_blocks_pending_sweep())+ auto blocks = FFI::rust_gc_allocator_start_sweep(allocator.rust_allocator({}));+ total_blocks += blocks;+ if (blocks)m_allocators_to_sweep.append(allocator);}incremental_sweep_stats().total_blocks = total_blocks;diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex cfa5d61128d..85a17cff7fd 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -6,7 +6,6 @@#pragma once-#include <AK/Array.h>#include <AK/Badge.h>#include <AK/Function.h>#include <AK/HashTable.h>@@ -199,12 +198,22 @@ public:FunctionTable& function_table() { return m_function_table; }bool is_incremental_sweep_active() const { return m_incremental_sweep_active; }+ // Sweeps the block now if the incremental sweep has yet to, as the sweep timer would.void sweep_block(HeapBlock&);// Whether `cell` points at a cell of this heap that is allocated: one that the sweep did not free yet. Code that keeps// pointers to cells that may have died since uses this to tell them apart from live ones.bool is_live_cell(Cell const*) const;+ // How many blocks the heap has, for all types of cells.+ size_t block_count() const;++ void did_sweep_blocks_for_allocation(Badge<CellAllocator>, size_t swept_blocks, i64 duration_ns);++ // A sweep runs the destructors of dead cells between these, see will_allocate().+ void will_destroy_swept_cell(Badge<CellAllocator>) { ++m_block_sweeps_in_progress; }+ void did_destroy_swept_cell(Badge<CellAllocator>) { --m_block_sweeps_in_progress; }+template<typename Callback>void for_each_block(Callback callback){@@ -347,6 +356,7 @@ private:void run_post_gc_tasks();bool sweep_next_block();+ void did_sweep(size_t swept_blocks, i64 duration_ns);void start_incremental_sweep();void finish_incremental_sweep();void finish_pending_incremental_sweep();@@ -412,15 +422,14 @@ private:Vector<AK::Function<void()>> m_post_gc_tasks;Vector<AK::Function<void()>> m_sweep_callbacks;- size_t m_block_count { 0 };-WeakBlock::List m_usable_weak_blocks;WeakBlock::List m_full_weak_blocks;bool m_incremental_sweep_active { false };- size_t m_block_sweeps_in_progress { 0 };size_t m_blocks_to_sweep { 0 };size_t m_blocks_swept { 0 };+ // How many destructors of swept cells are running, see will_allocate().+ size_t m_block_sweeps_in_progress { 0 };size_t m_marked_cell_bytes { 0 };size_t m_marked_external_bytes { 0 };CellAllocator::SweepList m_allocators_to_sweep;@@ -436,12 +445,6 @@ private:FFI::EvacuationSet* m_evacuation { nullptr };// The blocks it evacuates, those of an allocator one after another.Vector<HeapBlock*> m_evacuated_blocks;- // The cells that pins kept in the blocks that a collection could not empty, one bit per cell, see- // FFI::BlockDescriptor::kept_by_pins. A sweep that frees one of them lets compaction take the block again.- static constexpr size_t cell_bitmap_words = 11;- HashMap<HeapBlock*, Array<u64, cell_bitmap_words>> m_cells_kept_by_pins;- void forget_cells_kept_by_pins(HeapBlock&);- void cell_in_block_kept_by_pins_died(HeapBlock&, Cell const*);// The identity hashes of the cells that moved since they were hashed, see identity_hash().FFI::IdentityHashes* m_identity_hashes { nullptr };bool m_moves_everything { moves_everything() };diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cppindex 5c7bc1469f0..c61bd1453d8 100644--- a/Libraries/LibGC/HeapBlock.cpp+++ b/Libraries/LibGC/HeapBlock.cpp@@ -4,12 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/Assertions.h>-#include <AK/NonnullOwnPtr.h>#include <AK/Platform.h>#include <LibGC/BlockDescriptor.h>#include <LibGC/CellAllocator.h>-#include <LibGC/Forward.h>#include <LibGC/Heap.h>#include <LibGC/HeapBlock.h>@@ -23,25 +20,6 @@ static_assert(HeapBlock::min_possible_cell_size >= FFI::MIN_CELL_SIZE);FFI::BlockDescriptor* const g_block_descriptors = FFI::rust_gc_block_descriptor_table(HEAP_REGION_SIZE);-void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator)-{- auto& descriptor = block_descriptor_for(&block);- descriptor.type_info = &allocator.type_info();- descriptor.cell_size = allocator.cell_size();- descriptor.cell_index_magic = static_cast<u32>(((static_cast<u64>(1) << 32) + descriptor.cell_size - 1) / descriptor.cell_size);- descriptor.traced_on_owner_thread_only = allocator.descriptor().trace_thread() == TraceThread::OwnerThreadOnly;- descriptor.movable = allocator.descriptor().is_movable();- descriptor.kept_by_pins = false;- descriptor.cell_count = static_cast<u16>(block.cell_count());- descriptor.first_cell_index = static_cast<u16>(cell_index(descriptor, bit_cast<u8 const*>(&block) + HeapBlock::cells_offset()));- for (auto& word : descriptor.allocated)- word = 0;- descriptor.evacuation = nullptr;- clear_marks(descriptor);- // NB: Markers of other heaps read the heap of any block their cells point into, to leave it alone if it is not theirs.- __atomic_store_n(&descriptor.heap, static_cast<void*>(&block.heap()), __ATOMIC_RELEASE);-}-#pragma GCC diagnostic push#pragma GCC diagnostic ignored "-Winvalid-offsetof"size_t HeapBlock::cells_offset()@@ -53,18 +31,9 @@ size_t HeapBlock::cells_offset()}#pragma GCC diagnostic pop-void retire_block_descriptor(HeapBlock& block)+void HeapBlock::initialize(void* block, Heap& heap, CellAllocator& cell_allocator){- __atomic_store_n(&block_descriptor_for(&block).heap, static_cast<void*>(nullptr), __ATOMIC_RELEASE);-}--NonnullOwnPtr<HeapBlock> HeapBlock::create(Heap& heap, CellAllocator& cell_allocator)-{- char const* name = nullptr;- auto* block = static_cast<HeapBlock*>(cell_allocator.block_allocator().allocate_block(name));new (block) HeapBlock(heap, cell_allocator);- ++heap.m_block_count;- return adopt_own(*block);}HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator)@@ -73,34 +42,18 @@ HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator), m_cell_size(cell_allocator.cell_size()), m_cell_count((BLOCK_SIZE - sizeof(HeapBlock)) / m_cell_size){- VERIFY(m_cell_size >= sizeof(FreelistEntry));- VERIFY(m_cell_size >= FFI::MIN_CELL_SIZE);- publish_block_descriptor(*this, cell_allocator);+ VERIFY(m_cell_size >= min_possible_cell_size);ASAN_POISON_MEMORY_REGION(m_storage, BLOCK_SIZE - sizeof(HeapBlock));}-HeapBlock::~HeapBlock()+bool HeapBlock::is_pending_sweep() const{- retire_block_descriptor(*this);+ return block_descriptor_for(this).pending_sweep;}-Cell* HeapBlock::allocate()+bool HeapBlock::is_being_swept() const{- Cell* allocated_cell = nullptr;- if (auto* head = freelist_head(); !is_end_of_freelist(head)) {- VERIFY(is_valid_cell_pointer(head));- m_freelist = static_cast<FreelistEntry*>(head)->next;- allocated_cell = head;- } else if (has_lazy_freelist()) {- allocated_cell = cell(m_next_lazy_freelist_index++);- }-- if (allocated_cell) {- ASAN_UNPOISON_MEMORY_REGION(allocated_cell, m_cell_size);- auto& descriptor = block_descriptor_for(this);- set_allocated(descriptor, cell_index(descriptor, allocated_cell));- }- return allocated_cell;+ return block_descriptor_for(this).being_swept;}u32 HeapBlock::allocated_cell_count() const@@ -108,85 +61,4 @@ u32 HeapBlock::allocated_cell_count() constreturn allocated_cell_count_of(block_descriptor_for(this));}-HeapBlock::FreeCells HeapBlock::take_free_cells()-{- FreeCells free_cells {- .free_list = freelist_head(),- .lazy_start = bit_cast<FlatPtr>(cell(m_next_lazy_freelist_index)),- .lazy_end = bit_cast<FlatPtr>(cell(cell_count())),- };- // NB: Inline allocators bump through these cells without further checks, so make sure they are within the block.- VERIFY(free_cells.lazy_start <= free_cells.lazy_end);- VERIFY(free_cells.lazy_end <= bit_cast<FlatPtr>(this) + BLOCK_SIZE);- m_freelist = 0;- m_next_lazy_freelist_index = cell_count();- set_all_allocated(block_descriptor_for(this));- return free_cells;-}--void HeapBlock::give_back_free_cells(Cell* free_list, FlatPtr lazy_cursor)-{- // NB: take_free_cells() left the block without free cells of its own, and nothing frees cells in a block while- // its free cells are out, so the list becomes the block's free list as it is. Its links can only lead into- // this block (see follow_freelist_link()).- VERIFY(is_end_of_freelist(freelist_head()));- VERIFY(!has_lazy_freelist());- VERIFY(is_end_of_freelist(free_list) || is_valid_cell_pointer(free_list));- m_freelist = bit_cast<FlatPtr>(free_list);-- auto storage = reinterpret_cast<FlatPtr>(m_storage);- VERIFY(lazy_cursor >= storage);- VERIFY((lazy_cursor - storage) % m_cell_size == 0);- auto lazy_index = (lazy_cursor - storage) / m_cell_size;- VERIFY(lazy_index <= cell_count());- m_next_lazy_freelist_index = lazy_index;-- // NB: The cells that come back were never handed out, so they are not allocated after all.- auto& descriptor = block_descriptor_for(this);- for (auto* free_cell = freelist_head(); !is_end_of_freelist(free_cell); free_cell = next_free_cell(free_cell))- clear_allocated(descriptor, cell_index(descriptor, free_cell));- for (auto index = lazy_index; index < cell_count(); ++index)- clear_allocated(descriptor, cell_index(descriptor, cell(index)));-}--void HeapBlock::deallocate(Cell* cell)-{- // NB: The cell is one of this block's, since for_each_cell() found it, and the free list only ever holds cells- // that this function or give_back_free_cells() put there.- VERIFY(cell->state() == Cell::State::Live);- VERIFY(!GC::is_marked(cell));-- if (auto* destroy = type_info().destroy)- destroy(cell);- free_slot(cell);-}--void HeapBlock::release_moved_cell(Cell* cell)-{- VERIFY(cell->state() == Cell::State::Live);- VERIFY(is_valid_cell_pointer(cell));- free_slot(cell);-}--void HeapBlock::free_slot(Cell* cell)-{- auto* freelist_entry = new (cell) FreelistEntry();- freelist_entry->set_state(Cell::State::Dead);- freelist_entry->next = m_freelist;- m_freelist = bit_cast<FlatPtr>(freelist_entry);- auto& descriptor = block_descriptor_for(this);- clear_allocated(descriptor, cell_index(descriptor, cell));--#ifdef HAS_ADDRESS_SANITIZER- auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);- VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);- VERIFY(m_cell_size >= sizeof(FreelistEntry));- VERIFY(m_cell_size >= FFI::MIN_CELL_SIZE);- // We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer- // This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write- // On x86_64, this ends up being 24 bytes due to the size of the FreeListEntry's vtable, while on x86, it's only 12 bytes.- ASAN_POISON_MEMORY_REGION(reinterpret_cast<void*>(dword_after_freelist), m_cell_size - sizeof(FreelistEntry));-#endif-}-}diff --git a/Libraries/LibGC/HeapBlock.h b/Libraries/LibGC/HeapBlock.hindex d593561dc1f..baf21fa4963 100644--- a/Libraries/LibGC/HeapBlock.h+++ b/Libraries/LibGC/HeapBlock.h@@ -6,7 +6,6 @@#pragma once-#include <AK/IntrusiveList.h>#include <AK/Platform.h>#include <AK/StringView.h>#include <AK/Types.h>@@ -16,161 +15,65 @@#include <LibGC/Forward.h>#include <LibGC/Internals.h>-#ifdef HAS_ADDRESS_SANITIZER-# include <sanitizer/asan_interface.h>-#endif-namespace GC {+// The header of a block of cells. LibGC's Rust core creates blocks and keeps track of which of their cells are+// allocated, in the block's descriptor, see BlockDescriptor.h. The header is only what C++ reads from a cell's block.class GC_API HeapBlock : public HeapBlockBase {AK_MAKE_NONCOPYABLE(HeapBlock);AK_MAKE_NONMOVABLE(HeapBlock);public:using HeapBlockBase::BLOCK_SIZE;- static NonnullOwnPtr<HeapBlock> create(Heap&, CellAllocator&);- ~HeapBlock();++ // Fills in the header of a block that an allocator just took.+ static void initialize(void* block, Heap&, CellAllocator&);size_t cell_size() const { return m_cell_size; }size_t cell_count() const { return m_cell_count; }- bool is_full() const { return !has_lazy_freelist() && is_end_of_freelist(freelist_head()); }-- Cell* allocate();-- // Deallocates a cell that for_each_cell() found, which the sweep- // found unmarked.- void deallocate(Cell*);-- // Frees the slot of a live cell that moved to another slot, without- // destroying it, since its copy lives on.- void release_moved_cell(Cell*);-- // The free cells of a block: the cells that were freed, as a list linked- // through freelist_next_offset, and the cells that were never allocated,- // which are the cells from lazy_start up to lazy_end.- struct FreeCells {- RawPtr<Cell> free_list;- FlatPtr lazy_start { 0 };- FlatPtr lazy_end { 0 };- };-- // Takes every free cell of the block, leaving the block full. The cells- // that were never allocated are taken as they are, without writing them.- FreeCells take_free_cells();-- // Gives back the free cells of a list taken from this block, and the- // cells from lazy_cursor up to the end of the block, which must be the- // part of the never-allocated cells taken from this block that is still- // unallocated.- void give_back_free_cells(Cell* free_list, FlatPtr lazy_cursor);- // The offset of the link to the next cell in a free cell.+ // The offset of the link to the next cell in a free cell, and the bits of a link that count, for code that pops+ // free lists itself, see gc_heap_allocator_local_free_list(). The allocator hands out runs of cells only, so the+ // lists it hands out are empty.static constexpr size_t freelist_next_offset();+ static constexpr FlatPtr freelist_link_mask = BLOCK_SIZE - 1;// How far into a block its first cell is.static size_t cells_offset();- // Free cells are in the heap region, where anything may have been- // corrupted, so a link read from a free cell must never lead out of its- // block: only the bits of the link under freelist_link_mask count, as- // the offset of the next cell in the block of the cell holding the link- // (or of the block holding the head of the list). Offset 0, where the- // block's header is, ends the list, so a null link ends it as well.- static constexpr FlatPtr freelist_link_mask = BLOCK_SIZE - 1;- static Cell* follow_freelist_link(void const* holder, FlatPtr link)- {- return bit_cast<Cell*>((bit_cast<FlatPtr>(holder) & ~freelist_link_mask) | (link & freelist_link_mask));- }- static Cell* next_free_cell(Cell const* free_cell)- {- return follow_freelist_link(free_cell, *bit_cast<FlatPtr const*>(bit_cast<FlatPtr>(free_cell) + freelist_next_offset()));- }- static bool is_end_of_freelist(Cell const* cell) { return !(bit_cast<FlatPtr>(cell) & freelist_link_mask); }-// Whether the incremental sweep has yet to sweep the block, or is// sweeping it right now. Cells allocated in such a block during the// sweep must be marked so that the sweep keeps them.- bool is_pending_sweep() const { return m_sweep_list_node.is_in_list(); }- bool is_being_swept() const { return m_is_being_swept; }- void set_being_swept(bool being_swept) { m_is_being_swept = being_swept; }+ bool is_pending_sweep() const;+ bool is_being_swept() const;- // How many cells of the block are allocated. While an allocator has taken the block's free cells, they count as- // allocated too, see take_free_cells().+ // How many cells of the block are allocated. The cells of a run that an allocator took from the block to hand out+ // count as allocated too, see CellAllocator::LocalFreeCells.u32 allocated_cell_count() const;- template<typename Callback>- void for_each_cell(Callback callback)- {- auto end = has_lazy_freelist() ? m_next_lazy_freelist_index : cell_count();- for (size_t i = 0; i < end; ++i)- callback(cell(i));- }-- template<Cell::State state, typename Callback>- void for_each_cell_in_state(Callback callback)- {- for_each_cell([&](auto* cell) {- if (cell->state() == state)- callback(cell);- });- }-static HeapBlock* from_cell(Cell const* cell){return static_cast<HeapBlock*>(HeapBlockBase::from_cell(cell));}- Cell* cell_from_possible_pointer(FlatPtr pointer)- {- if (pointer < reinterpret_cast<FlatPtr>(m_storage))- return nullptr;- size_t cell_index = (pointer - reinterpret_cast<FlatPtr>(m_storage)) / m_cell_size;- auto end = has_lazy_freelist() ? m_next_lazy_freelist_index : cell_count();- if (cell_index >= end)- return nullptr;- return cell(cell_index);- }-- bool is_valid_cell_pointer(Cell const* cell)- {- return cell_from_possible_pointer((FlatPtr)cell);- }-- IntrusiveListNode<HeapBlock> m_list_node;- IntrusiveListNode<HeapBlock> m_sweep_list_node;-CellAllocator& cell_allocator() { return m_cell_allocator; }private:HeapBlock(Heap&, CellAllocator&);- bool has_lazy_freelist() const { return m_next_lazy_freelist_index < cell_count(); }- void free_slot(Cell*);-struct FreelistEntry final : public Cell {GC_CELL(FreelistEntry, Cell);- // See follow_freelist_link().FlatPtr next { 0 };};- Cell* freelist_head() const { return follow_freelist_link(this, m_freelist); }-- Cell* cell(size_t index)- {- return reinterpret_cast<Cell*>(&m_storage[index * cell_size()]);- }-CellAllocator& m_cell_allocator;u32 m_cell_size { 0 };- u32 m_next_lazy_freelist_index { 0 };// NB: Computed once, since dividing by the cell size is slow.u32 m_cell_count { 0 };- bool m_is_being_swept { false };-- // See follow_freelist_link().- FlatPtr m_freelist { 0 };- alignas(max_cell_alignment) u8 m_storage[];+ // NB: Pads the header to the size that sets how many cells of each size a block holds, see cells_offset().+ [[maybe_unused]] u8 m_reserved[72];+ [[maybe_unused]] alignas(max_cell_alignment) u8 m_storage[];public:static constexpr size_t min_possible_cell_size = sizeof(FreelistEntry);diff --git a/Libraries/LibGC/Rust/Cargo.toml b/Libraries/LibGC/Rust/Cargo.tomlindex e2b01ec8125..b49668c4669 100644--- a/Libraries/LibGC/Rust/Cargo.toml+++ b/Libraries/LibGC/Rust/Cargo.toml@@ -7,6 +7,7 @@ edition = "2024"crate-type = ["staticlib", "rlib"][features]+address-sanitizer = []allocator = ["dep:ladybird_allocator"]# After changing dependencies, regenerate the Flatpak sources:diff --git a/Libraries/LibGC/Rust/src/allocator.rs b/Libraries/LibGC/Rust/src/allocator.rsnew file mode 100644index 00000000000..1eb535e8e6e--- /dev/null+++ b/Libraries/LibGC/Rust/src/allocator.rs@@ -0,0 +1,1028 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The cell allocators of a heap, one for each type of cell, and the sweep of their blocks.+//!+//! Which cells of a block are free is in the allocated bitmap of the block's descriptor, never in the cells. An+//! allocator hands out the free cells of a block in runs: it takes the first run of free cells of a block at once, sets+//! their bits, and gives the code that allocates (C++, LibJS's Rust code and the JIT) the run as a cursor and an end to+//! bump through, see LocalFreeCells. Whatever is left of the run when a collection starts goes back to the block.+//!+//! Sweeping a block frees the cells that are allocated and not marked. Freeing a cell runs its destructor, which may+//! allocate cells and sweep other blocks, so nothing here keeps a borrow of the allocator's lists, or a reference into+//! a descriptor, across a call into C++.++use core::cell::RefCell;+use core::ffi::c_void;+use core::sync::atomic::{AtomicPtr, AtomicU64, Ordering};+use std::collections::HashMap;++use crate::bitmap::{self, CellBits};+use crate::block::{BLOCK_SIZE, BlockDescriptor, CELL_BITMAP_WORDS, MIN_CELL_SIZE, descriptor_table};+use crate::block_pool::{self, BlockPool};+use crate::identity_hash::{forget_identity_hash, has_moved_since_hashed};+use crate::rust_panic::abort_on_panic;++/// The free cells that code allocates from without calling into the allocator, which C++ `CellAllocator` keeps and+/// which `gc_get_layout` describes to LibJS's Rust code and the JIT. The allocator only ever hands out runs, so the free+/// list is always empty: null, which ends a free list as an address at the start of a block does.+#[repr(C)]+pub struct LocalFreeCells {+ pub free_list: *mut c_void,+ pub cursor: usize,+ pub end: usize,+ pub cell_size: usize,+}++/// Fills in the header of a block that is about to hold cells.+pub type InitializeBlock = unsafe extern "C" fn(context: *mut c_void, block: *mut c_void);++/// Frees a cell's slot: runs its destructor first if `destroy` is set, and marks it dead.+pub type FreeCell = unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, destroy: bool);++/// What an allocator needs to know about its heap and its type of cell.+#[repr(C)]+pub struct AllocatorConfig {+ pub heap_region_base: usize,+ pub heap: *mut c_void,+ pub type_info: *const c_void,+ pub pool: *const BlockPool,+ pub local: *mut LocalFreeCells,+ /// How far into a block its first cell is.+ pub cells_offset: u32,+ pub cell_size: u32,+ pub traced_on_owner_thread_only: bool,+ pub movable: bool,+ /// What the callbacks get, which is C++'s `CellAllocator`.+ pub context: *mut c_void,+ pub initialize_block: InitializeBlock,+ pub free_cell: FreeCell,+}++/// What sweeping blocks did, which the sweeps add to what the caller passes in.+#[repr(C)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct SweepStats {+ pub swept_blocks: usize,+ pub freed_blocks: usize,+ pub collected_cells: usize,+ pub live_cells: usize,+}++pub struct Allocator {+ config: AllocatorConfig,+ cell_count: usize,+ first_cell_index: usize,+ cell_index_magic: u32,+ lists: RefCell<Lists>,+}++#[derive(Default)]+struct Lists {+ /// Every block of the allocator, at the list index in its descriptor.+ blocks: Vec<usize>,+ /// The blocks that have free cells and are swept, the last one first.+ usable: Vec<usize>,+ /// The blocks the incremental sweep has yet to sweep.+ pending_sweep: Vec<usize>,+ /// The block of the run the local free cells come from, or 0.+ local_block: usize,+ /// The cells of the blocks that a collection could not empty because of pins, see BlockDescriptor::kept_by_pins.+ kept_by_pins: HashMap<usize, CellBits>,+}++enum Next {+ Sweep(usize),+ Take(usize),+ TakeOneFromPending(usize),+ Create,+}++impl Allocator {+ fn new(config: AllocatorConfig) -> Allocator {+ let cell_size = config.cell_size as usize;+ assert!((MIN_CELL_SIZE..BLOCK_SIZE).contains(&cell_size));+ let cell_count = (BLOCK_SIZE - config.cells_offset as usize) / cell_size;+ let cell_index_magic = (1u64 << 32).div_ceil(cell_size as u64);+ Allocator {+ first_cell_index: config.cells_offset as usize / cell_size,+ cell_count,+ cell_index_magic: cell_index_magic as u32,+ config,+ lists: RefCell::new(Lists::default()),+ }+ }++ /// The descriptor of `block`. Other threads only ever read its heap, atomically, so the thread that owns the heap+ /// writes the rest through this pointer, never through a reference to the whole descriptor.+ fn descriptor(&self, block: usize) -> *mut BlockDescriptor {+ // SAFETY: Every block of the allocator is in the region, whose table has a descriptor for each block.+ unsafe {+ descriptor_table()+ .add((block - self.config.heap_region_base) / BLOCK_SIZE)+ .as_ptr()+ }+ }++ #[allow(clippy::mut_from_ref)]+ fn allocated(&self, block: usize) -> &mut CellBits {+ // SAFETY: Only the thread that owns the heap accesses the allocated bits, and none of the callers keeps the+ // reference past a call that could access them again.+ unsafe { &mut (*self.descriptor(block)).allocated }+ }++ fn mark_word(&self, block: usize, word: usize) -> &AtomicU64 {+ // SAFETY: The block is one of this allocator's, whose descriptor only this thread writes to, but for the mark+ // bits, which are atomic.+ unsafe { &*self.descriptor(block) }.mark_word(word)+ }++ fn cells(&self) -> (usize, usize) {+ (self.first_cell_index, self.first_cell_index + self.cell_count)+ }++ fn cell_address(&self, block: usize, index: usize) -> usize {+ block + self.config.cells_offset as usize + (index - self.first_cell_index) * self.config.cell_size as usize+ }++ fn cell_index(&self, cell: usize) -> usize {+ (((cell & (BLOCK_SIZE - 1)) as u64 * u64::from(self.cell_index_magic)) >> 32) as usize+ }++ fn has_free_cells(&self, block: usize) -> bool {+ bitmap::count(self.allocated(block)) < self.cell_count+ }++ fn create_block(&self) -> usize {+ // SAFETY: The pool outlives every allocator that takes blocks from it.+ let block = unsafe { &*self.config.pool }.allocate_block();+ let descriptor = self.descriptor(block);+ // SAFETY: The block is not anyone's, so nothing else accesses its descriptor but markers of other heaps, which+ // only read its heap atomically, and see this one only after the descriptor is filled in.+ unsafe {+ (*descriptor).type_info = self.config.type_info;+ (*descriptor).cell_size = self.config.cell_size;+ (*descriptor).cell_index_magic = self.cell_index_magic;+ (*descriptor).traced_on_owner_thread_only = self.config.traced_on_owner_thread_only;+ (*descriptor).movable = self.config.movable;+ (*descriptor).kept_by_pins = false;+ (*descriptor).cell_count = self.cell_count as u16;+ (*descriptor).first_cell_index = self.first_cell_index as u16;+ (*descriptor).pending_sweep = false;+ (*descriptor).being_swept = false;+ (*descriptor).usable = false;+ AtomicPtr::from_ptr(&raw mut (*descriptor).evacuation).store(core::ptr::null_mut(), Ordering::Relaxed);+ (*descriptor).allocated = [0; CELL_BITMAP_WORDS];+ }+ for word in 0..CELL_BITMAP_WORDS {+ self.mark_word(block, word).store(0, Ordering::Relaxed);+ }+ // SAFETY: The block is ours now, and its header is for C++ to fill in.+ unsafe { (self.config.initialize_block)(self.config.context, block as *mut c_void) };+ // NB: Markers of other heaps read the heap of any block their cells point into, to leave it alone if it is not+ // theirs.+ // SAFETY: As above.+ unsafe { AtomicPtr::from_ptr(&raw mut (*descriptor).heap).store(self.config.heap, Ordering::Release) };++ let mut lists = self.lists.borrow_mut();+ // SAFETY: As above.+ unsafe { (*descriptor).list_index = lists.blocks.len() as u32 };+ lists.blocks.push(block);+ block+ }++ fn release_block(&self, block: usize, defer_decommit: bool) {+ let descriptor = self.descriptor(block);+ {+ let mut lists = self.lists.borrow_mut();+ // SAFETY: Only this thread writes the list indices of the allocator's blocks.+ let index = unsafe { (*descriptor).list_index } as usize;+ debug_assert_eq!(lists.blocks[index], block);+ lists.blocks.swap_remove(index);+ if let Some(&moved) = lists.blocks.get(index) {+ // SAFETY: As above.+ unsafe { (*self.descriptor(moved)).list_index = index as u32 };+ }+ lists.kept_by_pins.remove(&block);+ debug_assert!(lists.local_block != block);+ }+ // SAFETY: As in create_block().+ unsafe {+ debug_assert!(!(*descriptor).usable && !(*descriptor).pending_sweep);+ AtomicPtr::from_ptr(&raw mut (*descriptor).heap).store(core::ptr::null_mut(), Ordering::Release);+ }+ // SAFETY: The block came from this pool, and nothing uses it any more.+ unsafe { block_pool::deallocate_block_of(self.config.pool, block, defer_decommit) };+ }++ #[allow(clippy::mut_from_ref)]+ fn local(&self) -> &mut LocalFreeCells {+ // SAFETY: The local free cells outlive the allocator, and only the thread that owns the heap accesses them.+ unsafe { &mut *self.config.local }+ }++ /// Hands out a cell once the local free cells ran out: a cell of a new run, or a single cell if `single_cell` is+ /// set, or if the free cells left are in blocks that the incremental sweep has yet to sweep and `can_sweep` is not.+ fn allocate(&self, can_sweep: bool, single_cell: bool, stats: &mut SweepStats) -> usize {+ {+ let local = self.local();+ debug_assert!(local.cursor == local.end);+ *local = LocalFreeCells {+ free_list: core::ptr::null_mut(),+ cursor: 0,+ end: 0,+ cell_size: self.config.cell_size as usize,+ };+ self.lists.borrow_mut().local_block = 0;+ }+ loop {+ // NB: A destructor that a sweep below ran may have allocated a cell of this type, which took a new run.+ // Its cells count as allocated, so they have to be handed out rather than dropped.+ let local = self.local();+ if local.cursor < local.end {+ let cell = local.cursor;+ local.cursor += local.cell_size;+ return cell;+ }+ let next = {+ let mut lists = self.lists.borrow_mut();+ if let Some(&block) = lists.usable.last() {+ Next::Take(block)+ } else if can_sweep && let Some(block) = lists.pending_sweep.pop() {+ Next::Sweep(block)+ } else if let Some(&block) = lists.pending_sweep.last()+ && self.has_free_cells(block)+ {+ Next::TakeOneFromPending(block)+ } else {+ Next::Create+ }+ };+ match next {+ Next::Sweep(block) => self.sweep_block(block, true, stats),+ Next::Create => {+ let block = self.create_block();+ self.make_usable(block);+ }+ // NB: The sweep keeps a cell allocated in a block it has yet to sweep if it is marked, which the+ // caller sees to, see Heap::mark_if_allocated_during_incremental_sweep().+ Next::TakeOneFromPending(block) => return self.take_one(block),+ Next::Take(block) => {+ if single_cell {+ return self.take_one(block);+ }+ return self.take_run(block);+ }+ }+ }+ }++ fn make_usable(&self, block: usize) {+ let descriptor = self.descriptor(block);+ // SAFETY: Only this thread accesses the flags of the allocator's blocks.+ unsafe {+ if !(*descriptor).usable {+ (*descriptor).usable = true;+ self.lists.borrow_mut().usable.push(block);+ }+ }+ }++ /// Takes `block` off the list of usable blocks once it has no free cells left.+ fn forget_usable_if_full(&self, block: usize) {+ if self.has_free_cells(block) {+ return;+ }+ let descriptor = self.descriptor(block);+ // SAFETY: As in make_usable().+ unsafe {+ if (*descriptor).usable {+ (*descriptor).usable = false;+ let mut lists = self.lists.borrow_mut();+ let index = lists+ .usable+ .iter()+ .rposition(|&usable| usable == block)+ .expect("a usable block is listed");+ lists.usable.remove(index);+ }+ }+ }++ fn take_one(&self, block: usize) -> usize {+ let (begin, end) = self.cells();+ let (index, _) = bitmap::first_clear_run(self.allocated(block), begin, end).expect("the block has a free cell");+ bitmap::set(self.allocated(block), index);+ self.forget_usable_if_full(block);+ self.cell_address(block, index)+ }++ fn take_run(&self, block: usize) -> usize {+ let (begin, end) = self.cells();+ let (first, run_end) =+ bitmap::first_clear_run(self.allocated(block), begin, end).expect("the block has a free cell");+ bitmap::set_range(self.allocated(block), first, run_end);+ self.forget_usable_if_full(block);+ let cell = self.cell_address(block, first);+ let cell_size = self.config.cell_size as usize;+ let local = self.local();+ local.cursor = cell + cell_size;+ local.end = cell + (run_end - first) * cell_size;+ self.lists.borrow_mut().local_block = block;+ cell+ }++ /// Gives the cells of the local run that were not handed out back to their block.+ fn give_back_local_free_cells(&self) {+ let block = core::mem::take(&mut self.lists.borrow_mut().local_block);+ let local = self.local();+ let (cursor, end) = (local.cursor, local.end);+ local.cursor = 0;+ local.end = 0;+ if block == 0 || cursor == end {+ return;+ }+ let cell_size = self.config.cell_size as usize;+ let first = self.cell_index(cursor);+ bitmap::clear_range(self.allocated(block), first, first + (end - cursor) / cell_size);+ self.make_usable(block);+ }++ /// Makes every block pending sweep, after a collection marked them.+ fn start_sweep(&self) -> usize {+ // NB: The local free cells not handed out yet are no cells the sweep may free. The collection gave them back+ // already, and nothing allocates during one, so this only makes sure.+ self.give_back_local_free_cells();+ let mut lists = self.lists.borrow_mut();+ for &block in &lists.usable {+ // SAFETY: As in make_usable().+ unsafe { (*self.descriptor(block)).usable = false };+ }+ lists.usable.clear();+ let blocks = lists.blocks.clone();+ for &block in &blocks {+ // SAFETY: As above.+ unsafe { (*self.descriptor(block)).pending_sweep = true };+ }+ // NB: Blocks are swept from the end of the list, so this sweeps them in the order of the list.+ lists.pending_sweep = blocks.into_iter().rev().collect();+ lists.pending_sweep.len()+ }++ fn sweep_next_block(&self, defer_decommit: bool, stats: &mut SweepStats) -> bool {+ let Some(block) = self.lists.borrow_mut().pending_sweep.pop() else {+ return false;+ };+ self.sweep_block(block, defer_decommit, stats);+ true+ }++ /// Sweeps `block` now if the incremental sweep has yet to, which a test does instead of the sweep timer.+ fn sweep_pending_block(&self, block: usize, stats: &mut SweepStats) {+ {+ let mut lists = self.lists.borrow_mut();+ let Some(index) = lists.pending_sweep.iter().position(|&pending| pending == block) else {+ return;+ };+ lists.pending_sweep.remove(index);+ }+ self.sweep_block(block, true, stats);+ }++ /// Frees the cells of `block` that are allocated and not marked, after taking it off the list of pending blocks.+ fn sweep_block(&self, block: usize, defer_decommit: bool, stats: &mut SweepStats) {+ let descriptor = self.descriptor(block);+ // SAFETY: As in make_usable().+ unsafe {+ (*descriptor).pending_sweep = false;+ (*descriptor).being_swept = true;+ }+ let kept = self.lists.borrow().kept_by_pins.get(&block).copied();+ let mut kept_cell_died = false;+ for word in 0..CELL_BITMAP_WORDS {+ loop {+ // NB: Read again after each destructor, which may have allocated or freed cells elsewhere.+ let dead = self.allocated(block)[word] & !self.mark_word(block, word).load(Ordering::Relaxed);+ if dead == 0 {+ break;+ }+ let index = word * 64 + dead.trailing_zeros() as usize;+ kept_cell_died |= kept.is_some_and(|kept| bitmap::get(&kept, index));+ let cell = self.cell_address(block, index);+ // SAFETY: The cell is allocated.+ let moved_since_hashed = unsafe { has_moved_since_hashed(cell) };+ // NB: The cell stays allocated while its destructor runs, so nothing that it allocates takes its slot.+ // SAFETY: The cell is allocated and nothing marked it, so nothing reaches it any more.+ unsafe { (self.config.free_cell)(self.config.context, cell as *mut c_void, true) };+ if moved_since_hashed {+ // SAFETY: The cell is one of the heap's, and moved since it was hashed.+ unsafe { forget_identity_hash(self.config.heap, cell) };+ }+ bitmap::clear(self.allocated(block), index);+ stats.collected_cells += 1;+ }+ }+ // SAFETY: As above.+ unsafe { (*descriptor).being_swept = false };+ let evacuated = self.is_evacuated(block);+ if kept_cell_died {+ self.forget_cells_kept_by_pins(block);+ }+ stats.swept_blocks += 1;+ let live = bitmap::count(self.allocated(block));+ // NB: An evacuated block keeps its marks until its cells have moved, which tells the cells that marking knows+ // about from the ones allocated since.+ if !evacuated || live == 0 {+ self.clear_marks(block);+ }+ if live == 0 {+ self.release_block(block, defer_decommit);+ stats.freed_blocks += 1;+ return;+ }+ stats.live_cells += live;+ if live < self.cell_count && self.lists.borrow().local_block != block {+ self.make_usable(block);+ }+ }++ fn clear_marks(&self, block: usize) {+ for word in 0..CELL_BITMAP_WORDS {+ self.mark_word(block, word).store(0, Ordering::Relaxed);+ }+ }++ fn forget_cells_kept_by_pins(&self, block: usize) {+ self.lists.borrow_mut().kept_by_pins.remove(&block);+ // SAFETY: As in make_usable().+ unsafe { (*self.descriptor(block)).kept_by_pins = false };+ }++ /// Remembers that a collection could not empty `block` because of pins, so that compaction leaves it alone until+ /// one of the cells left in it dies.+ fn keep_cells_pinned(&self, block: usize) {+ let kept = *self.allocated(block);+ self.lists.borrow_mut().kept_by_pins.insert(block, kept);+ // SAFETY: As in make_usable().+ unsafe { (*self.descriptor(block)).kept_by_pins = true };+ }++ fn is_evacuated(&self, block: usize) -> bool {+ // SAFETY: Only the thread that owns the heap writes the evacuation state of its blocks, and not while it+ // allocates.+ !unsafe { AtomicPtr::from_ptr(&raw mut (*self.descriptor(block)).evacuation) }+ .load(Ordering::Relaxed)+ .is_null()+ }++ /// Takes a slot for a cell that moves, in a block that the collection does not evacuate. The evacuated blocks it+ /// comes across stop being usable, until finish_evacuated_block() puts them back.+ fn allocate_destination(&self) -> usize {+ loop {+ let last = self.lists.borrow().usable.last().copied();+ match last {+ Some(block) if self.is_evacuated(block) => {+ self.lists.borrow_mut().usable.pop();+ // SAFETY: As in make_usable().+ unsafe { (*self.descriptor(block)).usable = false };+ }+ Some(block) => return self.take_one(block),+ None => {+ let block = self.create_block();+ self.make_usable(block);+ }+ }+ }+ }++ /// Frees the slot of a cell that moved, without destroying it, since its copy lives on.+ fn release_moved_cell(&self, cell: usize) {+ let block = cell & !(BLOCK_SIZE - 1);+ let index = self.cell_index(cell);+ assert!(+ bitmap::get(self.allocated(block), index),+ "a cell that moved was allocated"+ );+ // SAFETY: The cell moved, so nothing uses its old slot.+ unsafe { (self.config.free_cell)(self.config.context, cell as *mut c_void, false) };+ bitmap::clear(self.allocated(block), index);+ }++ /// Lets go of a block that a collection evacuated if it is empty now, or lists it as usable again.+ fn finish_evacuated_block(&self, block: usize) -> bool {+ if bitmap::count(self.allocated(block)) != 0 {+ if self.has_free_cells(block) && self.lists.borrow().local_block != block {+ self.make_usable(block);+ }+ return false;+ }+ let descriptor = self.descriptor(block);+ // SAFETY: As in make_usable().+ unsafe {+ if (*descriptor).usable {+ (*descriptor).usable = false;+ self.lists.borrow_mut().usable.retain(|&usable| usable != block);+ }+ }+ self.release_block(block, true);+ true+ }+}++impl Drop for Allocator {+ fn drop(&mut self) {+ let blocks = core::mem::take(&mut self.lists.get_mut().blocks);+ for block in blocks {+ let descriptor = self.descriptor(block);+ // SAFETY: The heap is going away, so nothing accesses its blocks any more but markers of other heaps, which+ // only read the heap of a block.+ unsafe {+ (*descriptor).usable = false;+ (*descriptor).pending_sweep = false;+ AtomicPtr::from_ptr(&raw mut (*descriptor).heap).store(core::ptr::null_mut(), Ordering::Release);+ // NB: Another heap may not come along to use the blocks of this type for a long time.+ block_pool::deallocate_block_of(self.config.pool, block, false);+ }+ }+ // SAFETY: The pool outlives every allocator that takes blocks from it.+ unsafe { &*self.config.pool }.return_freed_blocks_to_system();+ }+}++/// # Safety+///+/// `config` must describe a live heap, pool and local free cells, which outlive the allocator.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_create(config: *const AllocatorConfig) -> *mut Allocator {+ // SAFETY: The caller passes a valid config.+ abort_on_panic(|| Box::into_raw(Box::new(Allocator::new(unsafe { config.read() }))))+}++/// Lets go of every block of the allocator, whose heap is going away.+///+/// # Safety+///+/// `allocator` must come from rust_gc_allocator_create(), and nothing may use it after this.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_destroy(allocator: *mut Allocator) {+ // SAFETY: The caller passes an allocator from rust_gc_allocator_create().+ abort_on_panic(|| drop(unsafe { Box::from_raw(allocator) }));+}++/// # Safety+///+/// `allocator` must be a live allocator from rust_gc_allocator_create(), used on the thread that owns its heap.+unsafe fn allocator_from<'a>(allocator: *const Allocator) -> &'a Allocator {+ // SAFETY: The caller passes a live allocator.+ unsafe { &*allocator }+}++/// Hands out a cell once the local free cells ran out, see Allocator::allocate(). What the blocks it swept for that+/// did is added to `stats`.+///+/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_allocate(+ allocator: *const Allocator,+ can_sweep: bool,+ single_cell: bool,+ stats: &mut SweepStats,+) -> *mut c_void {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.allocate(can_sweep, single_cell, stats) as *mut c_void)+}++/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_give_back_local_free_cells(allocator: *const Allocator) {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.give_back_local_free_cells());+}++/// Makes every block of the allocator pending sweep, and returns how many there are.+///+/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_start_sweep(allocator: *const Allocator) -> usize {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.start_sweep())+}++/// Sweeps the next block that is pending sweep, if there is one, and returns whether there was.+///+/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_sweep_next_block(+ allocator: *const Allocator,+ defer_decommit: bool,+ stats: &mut SweepStats,+) -> bool {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.sweep_next_block(defer_decommit, stats))+}++/// Sweeps `block` now if the incremental sweep has yet to.+///+/// # Safety+///+/// As for allocator_from(), and `block` must be one of the allocator's blocks.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_sweep_pending_block(+ allocator: *const Allocator,+ block: *mut c_void,+ stats: &mut SweepStats,+) {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.sweep_pending_block(block as usize, stats));+}++/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_has_blocks_pending_sweep(allocator: *const Allocator) -> bool {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| {+ !unsafe { allocator_from(allocator) }+ .lists+ .borrow()+ .pending_sweep+ .is_empty()+ })+}++/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_block_count(allocator: *const Allocator) -> usize {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.lists.borrow().blocks.len())+}++/// The block at `index` of the allocator's list of blocks, which only changes as blocks come and go.+///+/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_block_at(allocator: *const Allocator, index: usize) -> *mut c_void {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.lists.borrow().blocks[index] as *mut c_void)+}++/// The block that the local free cells come from, or null.+///+/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_local_block(allocator: *const Allocator) -> *mut c_void {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.lists.borrow().local_block as *mut c_void)+}++/// # Safety+///+/// As for allocator_from().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_allocate_destination(allocator: *const Allocator) -> *mut c_void {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.allocate_destination() as *mut c_void)+}++/// # Safety+///+/// As for allocator_from(), and `cell` must be an allocated cell of the allocator that moved.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_release_moved_cell(allocator: *const Allocator, cell: *mut c_void) {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.release_moved_cell(cell as usize));+}++/// Puts a block that a collection evacuated back, and returns whether it let go of it as it was empty.+///+/// # Safety+///+/// As for allocator_from(), and `block` must be one of the allocator's blocks.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_finish_evacuated_block(+ allocator: *const Allocator,+ block: *mut c_void,+) -> bool {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.finish_evacuated_block(block as usize))+}++/// # Safety+///+/// As for allocator_from(), and `block` must be one of the allocator's blocks.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_allocator_keep_cells_pinned(allocator: *const Allocator, block: *mut c_void) {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { allocator_from(allocator) }.keep_cells_pinned(block as usize));+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::block_pool::CHUNK_SIZE;+ use core::cell::UnsafeCell;+ use std::sync::OnceLock;++ /// A heap region of its own for the tests, set up once for all of them.+ fn region_base() -> usize {+ static BASE: OnceLock<usize> = OnceLock::new();+ *BASE.get_or_init(|| {+ const SIZE: usize = 256 * 1024 * 1024;+ let reservation = crate::os::reserve_zeroed(2 * SIZE)+ .expect("reserve a test region")+ .as_ptr() as usize;+ let base = reservation.next_multiple_of(SIZE);+ crate::block::rust_gc_block_descriptor_table(SIZE);+ block_pool::rust_gc_heap_region_init(+ core::ptr::with_exposed_provenance_mut(base),+ CHUNK_SIZE,+ SIZE - 2 * CHUNK_SIZE,+ );+ base+ })+ }++ struct TestHeap {+ allocator: *mut Allocator,+ /// The allocator writes to these through the pointer in its config, so they are in an UnsafeCell.+ local: Box<UnsafeCell<LocalFreeCells>>,+ freed: RefCell<Vec<(usize, bool)>>,+ /// How many cells the destructor of the next cells to die allocates.+ allocations_in_destructor: core::cell::Cell<usize>,+ pool: *const BlockPool,+ }++ unsafe extern "C" fn initialize_block(_: *mut c_void, _: *mut c_void) {}++ unsafe extern "C" fn free_cell(context: *mut c_void, cell: *mut c_void, destroy: bool) {+ // SAFETY: The tests pass their heap as the context.+ let heap = unsafe { &*(context as *const TestHeap) };+ heap.freed.borrow_mut().push((cell as usize, destroy));+ if destroy {+ for _ in 0..heap.allocations_in_destructor.replace(0) {+ heap.allocate();+ }+ }+ }++ impl TestHeap {+ fn new(cell_size: u32) -> Box<TestHeap> {+ let base = region_base();+ let mut heap = Box::new(TestHeap {+ allocator: core::ptr::null_mut(),+ local: Box::new(UnsafeCell::new(LocalFreeCells {+ free_list: core::ptr::null_mut(),+ cursor: 0,+ end: 0,+ cell_size: cell_size as usize,+ })),+ freed: RefCell::new(Vec::new()),+ allocations_in_destructor: core::cell::Cell::new(0),+ pool: block_pool::rust_gc_block_pool_create(),+ });+ let config = AllocatorConfig {+ heap_region_base: base,+ heap: &raw mut *heap as *mut c_void,+ type_info: core::ptr::null(),+ pool: heap.pool,+ local: heap.local.get(),+ cells_offset: 64,+ cell_size,+ traced_on_owner_thread_only: false,+ movable: true,+ context: &raw mut *heap as *mut c_void,+ initialize_block,+ free_cell,+ };+ // SAFETY: The config describes this heap, which outlives the allocator.+ heap.allocator = unsafe { rust_gc_allocator_create(&config) };+ heap+ }++ fn local(&self) -> &LocalFreeCells {+ // SAFETY: Only this thread uses the local free cells, and the callers drop this reference before the+ // allocator runs again.+ unsafe { &*self.local.get() }+ }++ fn allocator(&self) -> &Allocator {+ // SAFETY: The allocator lives as long as the heap.+ unsafe { &*self.allocator }+ }++ /// Allocates as the inline fast path does, falling back to the allocator.+ fn allocate(&self) -> usize {+ {+ // SAFETY: Only this thread uses the local free cells, and the allocator does not run while this+ // reference lives.+ let local = unsafe { &mut *self.local.get() };+ if local.cursor < local.end {+ let cell = local.cursor;+ local.cursor += local.cell_size;+ return cell;+ }+ }+ self.allocator().allocate(true, false, &mut SweepStats::default())+ }++ fn mark(&self, cell: usize) {+ let block = cell & !(BLOCK_SIZE - 1);+ let index = self.allocator().cell_index(cell);+ self.allocator()+ .mark_word(block, index / 64)+ .fetch_or(bitmap::bit(index), Ordering::Relaxed);+ }++ fn collect(&self, marked: &[usize]) -> SweepStats {+ self.allocator().give_back_local_free_cells();+ for &cell in marked {+ self.mark(cell);+ }+ self.allocator().start_sweep();+ let mut stats = SweepStats::default();+ while self.allocator().sweep_next_block(true, &mut stats) {}+ stats+ }++ fn allocated_count(&self) -> usize {+ let lists = self.allocator().lists.borrow();+ lists+ .blocks+ .iter()+ .map(|&block| bitmap::count(self.allocator().allocated(block)))+ .sum()+ }+ }++ impl Drop for TestHeap {+ fn drop(&mut self) {+ // SAFETY: Nothing uses the allocator or the pool after this.+ unsafe {+ rust_gc_allocator_destroy(self.allocator);+ block_pool::rust_gc_block_pool_destroy(self.pool);+ }+ }+ }++ #[test]+ fn hands_out_runs_of_distinct_cells() {+ let heap = TestHeap::new(48);+ let cell_count = heap.allocator().cell_count;+ let cells: Vec<usize> = (0..cell_count * 3 + 5).map(|_| heap.allocate()).collect();+ let mut sorted = cells.clone();+ sorted.sort();+ sorted.dedup();+ assert_eq!(sorted.len(), cells.len());+ assert_eq!(heap.allocator().lists.borrow().blocks.len(), 4);+ for &cell in &cells {+ let offset = (cell & (BLOCK_SIZE - 1)) - 64;+ assert_eq!(offset % 48, 0);+ assert!(offset / 48 < cell_count);+ }+ }++ #[test]+ fn sweeps_unmarked_cells_and_reuses_their_slots() {+ let heap = TestHeap::new(64);+ let cells: Vec<usize> = (0..100).map(|_| heap.allocate()).collect();+ let survivors: Vec<usize> = cells.iter().copied().step_by(2).collect();+ let stats = heap.collect(&survivors);+ assert_eq!(stats.collected_cells, 50);+ assert_eq!(stats.live_cells, 50);+ assert_eq!(heap.allocated_count(), 50);+ let freed: Vec<usize> = heap.freed.borrow().iter().map(|&(cell, _)| cell).collect();+ assert!(freed.iter().all(|cell| !survivors.contains(cell)));++ // The holes come back one run of one cell at a time.+ let first = heap.allocate();+ assert_eq!(first, cells[1]);+ let second = heap.allocate();+ assert_eq!(second, cells[3]);+ }++ #[test]+ fn gives_back_what_is_left_of_the_local_run() {+ let heap = TestHeap::new(64);+ heap.allocate();+ heap.allocator().give_back_local_free_cells();+ assert_eq!(heap.allocated_count(), 1);+ assert_eq!(heap.local().cursor, heap.local().end);+ }++ #[test]+ fn lets_go_of_blocks_whose_cells_all_died() {+ let heap = TestHeap::new(128);+ let cell_count = heap.allocator().cell_count;+ let cells: Vec<usize> = (0..cell_count * 2).map(|_| heap.allocate()).collect();+ let stats = heap.collect(&cells[cell_count..]);+ assert_eq!(stats.freed_blocks, 1);+ assert_eq!(heap.allocator().lists.borrow().blocks.len(), 1);+ // SAFETY: The block was released, so its descriptor no longer names a heap.+ let descriptor = unsafe { &*heap.allocator().descriptor(cells[0] & !(BLOCK_SIZE - 1)) };+ assert!(descriptor.heap().is_null());+ }++ #[test]+ fn a_destructor_may_allocate_while_its_block_is_swept() {+ let heap = TestHeap::new(64);+ let cell_count = heap.allocator().cell_count;+ // Two full blocks, where the cells of the first die and the second keeps one cell.+ let cells: Vec<usize> = (0..cell_count * 2).map(|_| heap.allocate()).collect();+ heap.allocations_in_destructor.set(cell_count + 3);+ heap.collect(&cells[cell_count..cell_count + 1]);+ // NB: The sweep of the second block happened for an allocation of the destructor.+ let destroyed = heap.freed.borrow().iter().filter(|&&(_, destroy)| destroy).count();+ assert_eq!(destroyed, cell_count * 2 - 1);+ // The destructor allocated cell_count + 3 cells, which a new block and the slots the sweep freed already took.+ let allocated_by_destructor = heap.allocated_count() - 1;+ // NB: The cells of the local run that were not handed out yet count as allocated.+ let local_left = (heap.local().end - heap.local().cursor) / 64;+ assert_eq!(allocated_by_destructor - local_left, cell_count + 3);+ // No slot that a destructor ran for was handed out before its destructor returned.+ let freed: Vec<usize> = heap.freed.borrow().iter().map(|&(cell, _)| cell).collect();+ let mut distinct = freed.clone();+ distinct.sort();+ distinct.dedup();+ assert_eq!(distinct.len(), freed.len());+ }++ #[test]+ fn a_run_that_a_destructor_takes_during_an_allocation_is_handed_out() {+ let heap = TestHeap::new(64);+ let cell_count = heap.allocator().cell_count;+ let cells: Vec<usize> = (0..cell_count).map(|_| heap.allocate()).collect();+ heap.allocator().give_back_local_free_cells();+ heap.mark(cells[0]);+ heap.allocator().start_sweep();+ // The next allocation sweeps the block, whose first dead cell's destructor allocates one cell.+ heap.allocations_in_destructor.set(1);+ let cell = heap.allocate();+ // NB: Every allocated cell is the destructor's, this one, or the survivor, or is still in the local run.+ let local_left = (heap.local().end - heap.local().cursor) / 64;+ assert_eq!(heap.allocated_count(), 3 + local_left);+ assert_ne!(cell, cells[0]);+ }++ #[test]+ fn evacuation_moves_cells_out_of_blocks_it_then_lets_go_of() {+ let heap = TestHeap::new(64);+ let cell_count = heap.allocator().cell_count;+ let cells: Vec<usize> = (0..cell_count * 2).map(|_| heap.allocate()).collect();+ // Half of each block survives.+ let survivors: Vec<usize> = cells.iter().copied().step_by(2).collect();+ heap.collect(&survivors);+ let evacuated = cells[0] & !(BLOCK_SIZE - 1);+ let mut evacuation = 0u8;+ // SAFETY: Nothing else uses the descriptor while this test runs.+ unsafe { (*heap.allocator().descriptor(evacuated)).evacuation = (&raw mut evacuation).cast() };+ for &cell in survivors.iter().filter(|&&cell| cell & !(BLOCK_SIZE - 1) == evacuated) {+ let destination = heap.allocator().allocate_destination();+ assert_ne!(destination & !(BLOCK_SIZE - 1), evacuated);+ heap.allocator().release_moved_cell(cell);+ }+ // SAFETY: As above.+ unsafe { (*heap.allocator().descriptor(evacuated)).evacuation = core::ptr::null_mut() };+ assert!(heap.allocator().finish_evacuated_block(evacuated));+ assert_eq!(heap.allocator().lists.borrow().blocks.len(), 1);+ }++ #[test]+ fn blocks_kept_by_pins_are_forgotten_once_a_kept_cell_dies() {+ let heap = TestHeap::new(64);+ let cells: Vec<usize> = (0..10).map(|_| heap.allocate()).collect();+ heap.collect(&cells);+ let block = cells[0] & !(BLOCK_SIZE - 1);+ heap.allocator().keep_cells_pinned(block);+ // SAFETY: Nothing else uses the descriptor while this test runs.+ let kept_by_pins = || unsafe { (*heap.allocator().descriptor(block)).kept_by_pins };+ assert!(kept_by_pins());++ // A cell that came after the block was kept dies, which leaves it kept.+ let newcomer = heap.allocate();+ heap.collect(&cells);+ assert!(heap.freed.borrow().iter().any(|&(cell, _)| cell == newcomer));+ assert!(kept_by_pins());++ // One of the cells it kept dies.+ heap.collect(&cells[1..]);+ assert!(!kept_by_pins());+ }+}diff --git a/Libraries/LibGC/Rust/src/bitmap.rs b/Libraries/LibGC/Rust/src/bitmap.rsnew file mode 100644index 00000000000..bf4a0387430--- /dev/null+++ b/Libraries/LibGC/Rust/src/bitmap.rs@@ -0,0 +1,107 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The per-cell bitmaps of a block: one bit for each cell, at the cell's index (see BlockDescriptor::cell_index()).++use crate::block::CELL_BITMAP_WORDS;++pub type CellBits = [u64; CELL_BITMAP_WORDS];++#[inline(always)]+pub fn bit(index: usize) -> u64 {+ 1 << (index % 64)+}++#[inline(always)]+pub fn get(bits: &CellBits, index: usize) -> bool {+ bits[index / 64] & bit(index) != 0+}++#[inline(always)]+pub fn set(bits: &mut CellBits, index: usize) {+ bits[index / 64] |= bit(index);+}++#[inline(always)]+pub fn clear(bits: &mut CellBits, index: usize) {+ bits[index / 64] &= !bit(index);+}++pub fn count(bits: &CellBits) -> usize {+ bits.iter().map(|word| word.count_ones() as usize).sum()+}++/// The bits of word `word` that are within `begin..end`.+fn word_mask(word: usize, begin: usize, end: usize) -> u64 {+ let first = word * 64;+ let below = |limit: usize| match limit.saturating_sub(first) {+ 0 => 0,+ n if n >= 64 => u64::MAX,+ n => (1 << n) - 1,+ };+ below(end) & !below(begin)+}++pub fn set_range(bits: &mut CellBits, begin: usize, end: usize) {+ for (word, value) in bits.iter_mut().enumerate() {+ *value |= word_mask(word, begin, end);+ }+}++pub fn clear_range(bits: &mut CellBits, begin: usize, end: usize) {+ for (word, value) in bits.iter_mut().enumerate() {+ *value &= !word_mask(word, begin, end);+ }+}++/// The first run of clear bits within `begin..end`, as the range of their indices.+pub fn first_clear_run(bits: &CellBits, begin: usize, end: usize) -> Option<(usize, usize)> {+ let start = first_with(bits, begin, end, false)?;+ let run_end = first_with(bits, start, end, true).unwrap_or(end);+ Some((start, run_end))+}++/// The first index within `begin..end` whose bit is `value`.+fn first_with(bits: &CellBits, begin: usize, end: usize, value: bool) -> Option<usize> {+ for (word, &bits) in bits.iter().enumerate().take(end.div_ceil(64)).skip(begin / 64) {+ let candidates = if value { bits } else { !bits } & word_mask(word, begin, end);+ if candidates != 0 {+ return Some(word * 64 + candidates.trailing_zeros() as usize);+ }+ }+ None+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sets_and_clears_ranges_across_words() {+ let mut bits: CellBits = [0; CELL_BITMAP_WORDS];+ set_range(&mut bits, 3, 130);+ assert_eq!(count(&bits), 127);+ assert!(!get(&bits, 2) && get(&bits, 3) && get(&bits, 129) && !get(&bits, 130));+ clear_range(&mut bits, 60, 70);+ assert_eq!(count(&bits), 117);+ assert!(get(&bits, 59) && !get(&bits, 60) && !get(&bits, 69) && get(&bits, 70));+ }++ #[test]+ fn finds_runs_of_clear_bits() {+ let mut bits: CellBits = [0; CELL_BITMAP_WORDS];+ assert_eq!(first_clear_run(&bits, 2, 500), Some((2, 500)));+ set_range(&mut bits, 2, 100);+ set(&mut bits, 120);+ assert_eq!(first_clear_run(&bits, 2, 500), Some((100, 120)));+ set_range(&mut bits, 100, 120);+ assert_eq!(first_clear_run(&bits, 2, 500), Some((121, 500)));+ set_range(&mut bits, 121, 500);+ assert_eq!(first_clear_run(&bits, 2, 500), None);+ // NB: Bits past the end, which belong to no cell, never count.+ assert!(!get(&bits, 500));+ }+}diff --git a/Libraries/LibGC/Rust/src/block.rs b/Libraries/LibGC/Rust/src/block.rsindex f8365b3d787..a21ef0e79b8 100644--- a/Libraries/LibGC/Rust/src/block.rs+++ b/Libraries/LibGC/Rust/src/block.rs@@ -8,10 +8,9 @@//!//! A block holds cells of one type and one size. What the collector knows about a block is in its descriptor, which//! lives outside the heap region: the heap and the type of the block, and which of its cells are allocated and which-//! are marked. So nothing that-//! writes to a cell, or past it, can change what the collector does with the block. The descriptor of a block is at the-//! block's index in the region in a table of descriptors, which is reserved once for the whole region and only backed-//! by memory where blocks are.+//! are marked. So nothing that writes to a cell, or past it, can change what the collector does with the block. The+//! descriptor of a block is at the block's index in the region in a table of descriptors, which is reserved once for the+//! whole region and only backed by memory where blocks are.use core::cell::UnsafeCell;use core::ffi::c_void;@@ -74,7 +73,7 @@ pub struct BlockDescriptor {/// Whether the block is on its allocator's list of blocks with free cells.pub usable: bool,/// Rounds the descriptor up to 256 bytes, four whole cache lines in the table.- pub reserved3: [u8; 33],+ pub reserved2: [u8; 33],}const _: () = assert!(size_of::<BlockDescriptor>() == 256);@@ -177,7 +176,7 @@ unsafe impl Sync for Table {}static TABLE: OnceLock<Table> = OnceLock::new();-/// The table of block descriptors, which this reserves for a region of `region_size` bytes on first use.+/// The table of block descriptors, see rust_gc_block_descriptor_table().pub fn descriptor_table() -> NonNull<BlockDescriptor> {TABLE.get().expect("the table of block descriptors exists").descriptors}@@ -270,8 +269,7 @@ pub extern "C" fn rust_gc_block_descriptor_table(region_size: usize) -> *mut Blo}/// Makes sure that the `count` descriptors from `first_index` on are backed by memory, before blocks are created there.-#[unsafe(no_mangle)]-pub extern "C" fn rust_gc_block_descriptor_commit(first_index: usize, count: usize) {+pub fn commit_descriptors(first_index: usize, count: usize) {let table = TABLE.get().expect("the table of block descriptors exists");assert!(first_index + count <= table.count,diff --git a/Libraries/LibGC/Rust/src/block_pool.rs b/Libraries/LibGC/Rust/src/block_pool.rsnew file mode 100644index 00000000000..3a57a250b81--- /dev/null+++ b/Libraries/LibGC/Rust/src/block_pool.rs@@ -0,0 +1,529 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Where the blocks of the heap come from, and where they go when they are empty.+//!+//! Every block is a 16 KiB slot of one process-wide region, which C++ reserves and which this commits 2 MiB at a time. A+//! slot that was never used belongs to nobody, so the pools of all types take their slots from the same chunk, and a+//! pool for a type that only needs one block costs one block. A slot that was used stays with the pool that took it, so+//! an address that held a cell of one type never holds a cell of another type.+//!+//! Giving the pages of an empty block back to the system is left to a single background thread, the decommit worker,+//! so it never costs a collection time, and a block that is used again before the worker sees it skips the system calls+//! altogether.++use core::ptr::NonNull;+use core::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};+use std::time::{Duration, Instant};++use crate::block::BLOCK_SIZE;+use crate::rust_panic::abort_on_panic;+use crate::{os, sanitizer};++pub const CHUNK_SIZE: usize = 2 * 1024 * 1024;+pub const BLOCKS_PER_CHUNK: usize = CHUNK_SIZE / BLOCK_SIZE;++const _: () = assert!(CHUNK_SIZE.is_multiple_of(BLOCK_SIZE));+const _: () = assert!(BLOCKS_PER_CHUNK == 128);++/// How long a block whose pages were discarded can sit unused before its pages go back for real. This is longer than+/// most heaps take between collections, so that blocks they reuse keep skipping the page faults. And as the collections+/// of every heap drive the decommit worker, it keeps a busy heap from making the blocks of a slower one look cold.+static COLD_BLOCK_AGE_IN_MILLISECONDS: AtomicU64 = AtomicU64::new(5000);++fn cold_block_age() -> Duration {+ Duration::from_millis(COLD_BLOCK_AGE_IN_MILLISECONDS.load(Ordering::Relaxed))+}++fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {+ // NB: Nothing panics while holding these locks without aborting the process, so a poisoned lock never happens.+ mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())+}++fn block_pointer(address: usize) -> NonNull<u8> {+ // NB: Blocks are in the heap region, whose provenance rust_gc_heap_region_init() exposed.+ NonNull::new(core::ptr::with_exposed_provenance_mut(address)).expect("a block is never at address 0")+}++/// The part of the heap region that blocks come from: the chunks between the guards at either end.+struct Region {+ base: usize,+ last_chunk_offset: usize,+ chunks: Mutex<Chunks>,+}++struct Chunks {+ next_chunk_offset: usize,+ /// A committed chunk whose pages are faulted in already, which is the next one that blocks come from.+ prepared_chunk: Option<usize>,+ /// The blocks of the current chunk that were never used.+ next_unused_block: usize,+ unused_blocks_end: usize,+}++static REGION: OnceLock<Region> = OnceLock::new();++fn region() -> &'static Region {+ REGION.get().expect("the heap region is reserved")+}++impl Region {+ fn commit_next_chunk(&self, chunks: &mut Chunks) -> usize {+ assert!(+ chunks.next_chunk_offset <= self.last_chunk_offset,+ "the heap region has room for another chunk"+ );+ let chunk = self.base + chunks.next_chunk_offset;+ // SAFETY: The chunk is within the reserved region, past every chunk committed so far.+ unsafe { os::commit(block_pointer(chunk), CHUNK_SIZE) };+ // NB: Every block of a committed chunk has a descriptor backed by memory, so that any address in the committed+ // part of the region can be looked up.+ crate::block::commit_descriptors(chunks.next_chunk_offset / BLOCK_SIZE, BLOCKS_PER_CHUNK);+ chunks.next_chunk_offset += CHUNK_SIZE;+ chunk+ }++ fn take_unused_block(&self) -> usize {+ let block;+ let mut took_chunk = false;+ {+ let mut chunks = lock(&self.chunks);+ if chunks.next_unused_block == chunks.unused_blocks_end {+ let chunk = match chunks.prepared_chunk.take() {+ Some(chunk) => chunk,+ None => self.commit_next_chunk(&mut chunks),+ };+ // SAFETY: The chunk was just committed, and nothing uses it yet.+ unsafe { os::mark_reusable(block_pointer(chunk), CHUNK_SIZE) };+ sanitizer::poison(chunk, CHUNK_SIZE);+ chunks.next_unused_block = chunk;+ chunks.unused_blocks_end = chunk + CHUNK_SIZE;+ took_chunk = true;+ }+ block = chunks.next_unused_block;+ chunks.next_unused_block += BLOCK_SIZE;+ }+ // NB: Preparing a chunk only pays off where its pages can be faulted in ahead of time. And only a worker that+ // is already running prepares chunks: starting it here could start a second thread before the process is+ // sandboxed, which some sandboxes do not allow.+ if took_chunk+ && cfg!(any(target_os = "linux", target_os = "android"))+ && let Some(worker) = DecommitWorker::the_if_started()+ {+ worker.request_prepared_chunk();+ }+ block+ }++ /// Commits the next chunk and faults its pages in, so that the first touches of its blocks take no page faults on+ /// the thread that allocates them. Runs on the decommit worker.+ fn prepare_chunk(&self) {+ let chunk = {+ let mut chunks = lock(&self.chunks);+ // NB: Running out of the region is left to take_unused_block(), on the thread that needs another chunk.+ if chunks.prepared_chunk.is_some() || chunks.next_chunk_offset > self.last_chunk_offset {+ return;+ }+ let chunk = self.commit_next_chunk(&mut chunks);+ // NB: The chunk is there to take before its pages are in, so that a thread that needs another chunk+ // meanwhile takes this one rather than commit the next, which might not exist.+ chunks.prepared_chunk = Some(chunk);+ chunk+ };+ // SAFETY: The chunk was just committed. Faulting its pages in leaves their contents alone, so a thread may use+ // its blocks already.+ unsafe { os::populate(block_pointer(chunk), CHUNK_SIZE) };+ }++ fn committed_end(&self) -> usize {+ self.base + lock(&self.chunks).next_chunk_offset+ }+}++/// The blocks of one type of cell in all heaps.+pub struct BlockPool {+ state: Mutex<PoolState>,+}++#[derive(Default)]+struct PoolState {+ /// Blocks whose pages were discarded, which the system may have taken back.+ blocks: Vec<usize>,+ /// Blocks whose pages went back for real, as their heap went away or they stayed unused for long. They are the last+ /// ones to reuse, as their pages have to be faulted in again.+ returned_blocks: Vec<usize>,+ /// Blocks that were freed but not discarded yet. They are the first ones to reuse, with no system call at all.+ freshly_freed: Vec<usize>,+ /// Whether the pool is on the decommit worker's list.+ in_decommit_registry: bool,+}++impl BlockPool {+ pub(crate) fn allocate_block(&self) -> usize {+ let (block, needs_reuse) = {+ let mut state = lock(&self.state);+ if let Some(block) = state.freshly_freed.pop() {+ (Some(block), false)+ } else if let Some(block) = state.blocks.pop() {+ (Some(block), true)+ } else {+ (state.returned_blocks.pop(), true)+ }+ };+ let block = block.unwrap_or_else(|| region().take_unused_block());+ sanitizer::unpoison(block, BLOCK_SIZE);+ sanitizer::register_root_region(block, BLOCK_SIZE);+ if needs_reuse {+ // SAFETY: The block is committed, and was discarded or is part of a chunk that was marked reusable.+ unsafe { os::reuse(block_pointer(block), BLOCK_SIZE) };+ }+ block+ }++ fn deallocate_block(self: &Arc<Self>, block: usize, defer_decommit: bool) {+ sanitizer::poison(block, BLOCK_SIZE);+ sanitizer::unregister_root_region(block, BLOCK_SIZE);+ let needs_registering = {+ let mut state = lock(&self.state);+ state.freshly_freed.push(block);+ defer_decommit && !core::mem::replace(&mut state.in_decommit_registry, true)+ };+ if needs_registering {+ DecommitWorker::the().register_pending(self.clone());+ }+ }++ pub(crate) fn return_freed_blocks_to_system(&self) {+ let blocks = {+ let mut state = lock(&self.state);+ let mut blocks = core::mem::take(&mut state.freshly_freed);+ // NB: Discarded pages stay in the process until the system runs short of memory.+ if cfg!(any(target_os = "linux", target_os = "android")) {+ blocks.append(&mut state.blocks);+ }+ blocks+ };+ for &block in &blocks {+ // SAFETY: The blocks are free, so nothing needs their contents.+ unsafe { os::return_to_system(block_pointer(block), BLOCK_SIZE) };+ }+ lock(&self.state).returned_blocks.extend(blocks);+ }+}++/// The thread that gives the pages of freed blocks back to the system, and prepares the next chunk.+struct DecommitWorker {+ state: Mutex<WorkerState>,+ condition: Condvar,+}++struct WorkerState {+ pending: Vec<Arc<BlockPool>>,+ kicked: bool,+ chunk_requested: bool,+ last_return_of_cold_blocks: Instant,+}++static DECOMMIT_WORKER: OnceLock<&'static DecommitWorker> = OnceLock::new();++impl DecommitWorker {+ fn the() -> &'static DecommitWorker {+ DECOMMIT_WORKER.get_or_init(|| {+ let worker: &'static DecommitWorker = Box::leak(Box::new(DecommitWorker {+ state: Mutex::new(WorkerState {+ pending: Vec::new(),+ kicked: false,+ chunk_requested: false,+ last_return_of_cold_blocks: Instant::now(),+ }),+ condition: Condvar::new(),+ }));+ std::thread::Builder::new()+ .name("DecommitWorker".into())+ .spawn(move || abort_on_panic(|| worker.run()))+ .expect("start the decommit worker");+ worker+ })+ }++ fn the_if_started() -> Option<&'static DecommitWorker> {+ DECOMMIT_WORKER.get().copied()+ }++ fn register_pending(&self, pool: Arc<BlockPool>) {+ lock(&self.state).pending.push(pool);+ }++ fn deregister(&self, pool: &Arc<BlockPool>) {+ lock(&self.state).pending.retain(|pending| !Arc::ptr_eq(pending, pool));+ }++ fn kick(&self) {+ lock(&self.state).kicked = true;+ self.condition.notify_one();+ }++ fn request_prepared_chunk(&self) {+ lock(&self.state).chunk_requested = true;+ self.condition.notify_one();+ }++ fn run(&self) {+ loop {+ let mut snapshot = Vec::new();+ let chunk_requested;+ {+ let mut state = lock(&self.state);+ while !state.kicked && !state.chunk_requested {+ // NB: Collections may never come again, and what is on the list must not wait for one. Each block+ // only takes a few rounds of this, after which the list is empty and this thread sleeps for+ // good.+ if state.pending.is_empty() {+ state = self+ .condition+ .wait(state)+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ } else {+ let (next_state, timeout) = self+ .condition+ .wait_timeout(state, cold_block_age())+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ state = next_state;+ if timeout.timed_out() {+ state.kicked = true;+ }+ }+ }+ chunk_requested = core::mem::replace(&mut state.chunk_requested, false);+ if core::mem::replace(&mut state.kicked, false) {+ snapshot = core::mem::take(&mut state.pending);+ }+ }++ if chunk_requested {+ region().prepare_chunk();+ }+ if snapshot.is_empty() {+ continue;+ }++ // NB: Give the thread that kicked this, typically at the end of a sweep, some room before this takes CPU+ // time and system calls.+ std::thread::sleep(Duration::from_millis(50));++ let return_cold_blocks = {+ let mut state = lock(&self.state);+ let now = Instant::now();+ if now.duration_since(state.last_return_of_cold_blocks) >= cold_block_age() {+ state.last_return_of_cold_blocks = now;+ true+ } else {+ false+ }+ };+ for pool in snapshot {+ self.process_one(pool, return_cold_blocks);+ }+ }+ }++ fn process_one(&self, pool: Arc<BlockPool>, return_cold_blocks: bool) {+ let (to_process, cold_blocks) = {+ let mut state = lock(&pool.state);+ state.in_decommit_registry = false;+ let to_process = core::mem::take(&mut state.freshly_freed);+ // NB: Blocks whose pages were discarded stay in the process until the system runs short of memory, and+ // only their own type can reuse them. What that type did not reuse since the last time will likely+ // stay unused.+ let cold_blocks = if cfg!(any(target_os = "linux", target_os = "android")) && return_cold_blocks {+ core::mem::take(&mut state.blocks)+ } else {+ Vec::new()+ };+ (to_process, cold_blocks)+ };++ // NB: The system calls happen outside the pool's lock, so that its heaps can go on allocating and freeing, and+ // this yields now and then to leave the kernel's memory management to others as well.+ const BATCH: usize = 64;+ for (index, &block) in to_process.iter().enumerate() {+ // SAFETY: The block is free, so nothing needs its contents.+ unsafe { os::discard(block_pointer(block), BLOCK_SIZE) };+ if (index + 1) % BATCH == 0 {+ std::thread::yield_now();+ }+ }+ for (index, &block) in cold_blocks.iter().enumerate() {+ // SAFETY: As above.+ unsafe { os::return_to_system(block_pointer(block), BLOCK_SIZE) };+ if (index + 1) % BATCH == 0 {+ std::thread::yield_now();+ }+ }++ let needs_registering = {+ let mut state = lock(&pool.state);+ state.blocks.extend(to_process);+ state.returned_blocks.extend(cold_blocks);+ // NB: So a pool is only on the list while it has blocks to look at, however many pools there are.+ cfg!(any(target_os = "linux", target_os = "android"))+ && !state.blocks.is_empty()+ && !core::mem::replace(&mut state.in_decommit_registry, true)+ };+ if needs_registering {+ self.register_pending(pool);+ }+ }+}++/// Takes the heap region that C++ reserved at `base`, whose first and last chunks are `first_chunk_offset` and+/// `last_chunk_offset` bytes into it.+#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_heap_region_init(base: *mut u8, first_chunk_offset: usize, last_chunk_offset: usize) {+ abort_on_panic(|| {+ // NB: The collector keeps the addresses of blocks and cells as integers, and compresses them, so this exposes+ // the provenance of the region, which turning them back into pointers picks up with+ // with_exposed_provenance().+ let base = base.expose_provenance();+ assert!(base.is_multiple_of(CHUNK_SIZE) && first_chunk_offset.is_multiple_of(CHUNK_SIZE));+ let region = Region {+ base,+ last_chunk_offset,+ chunks: Mutex::new(Chunks {+ next_chunk_offset: first_chunk_offset,+ prepared_chunk: None,+ next_unused_block: 0,+ unused_blocks_end: 0,+ }),+ };+ assert!(REGION.set(region).is_ok(), "the heap region is set up once");+ });+}++/// The end of the part of the region that chunks were committed from so far. No block starts at or above it.+#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_heap_region_committed_end() -> usize {+ abort_on_panic(|| region().committed_end())+}++#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_block_pool_create() -> *const BlockPool {+ Arc::into_raw(Arc::new(BlockPool {+ state: Mutex::new(PoolState::default()),+ }))+}++/// # Safety+///+/// `pool` must come from rust_gc_block_pool_create(), and nothing may use it after this.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_destroy(pool: *const BlockPool) {+ abort_on_panic(|| {+ // SAFETY: The caller passes a pool from rust_gc_block_pool_create(), whose reference this takes back.+ let pool = unsafe { Arc::from_raw(pool) };+ // NB: The worker keeps its own reference while it looks at the pool, which it drops once its blocks are done.+ if let Some(worker) = DecommitWorker::the_if_started() {+ worker.deregister(&pool);+ }+ });+}++/// Puts a block back into the pool it came from, see rust_gc_block_pool_deallocate_block().+///+/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create(), and `block` a block it handed out that nothing uses.+pub(crate) unsafe fn deallocate_block_of(pool: *const BlockPool, block: usize, defer_decommit: bool) {+ // SAFETY: The caller passes a live pool, whose reference count the Arc it came from keeps up.+ let pool = core::mem::ManuallyDrop::new(unsafe { Arc::from_raw(pool) });+ pool.deallocate_block(block, defer_decommit);+}++/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create().+unsafe fn pool_from<'a>(pool: *const BlockPool) -> &'a BlockPool {+ // SAFETY: The caller passes a live pool.+ unsafe { &*pool }+}++/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_allocate_block(pool: *const BlockPool) -> *mut u8 {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { pool_from(pool) }.allocate_block() as *mut u8)+}++/// Puts a block that `pool` handed out back into it. Unless `defer_decommit` is false, the decommit worker discards its+/// pages after its next kick, if the block is not used again before.+///+/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create(), and `block` a block it handed out that nothing uses.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_deallocate_block(+ pool: *const BlockPool,+ block: *mut u8,+ defer_decommit: bool,+) {+ abort_on_panic(|| {+ assert!(!block.is_null());+ // SAFETY: Forwarded from the caller.+ unsafe { deallocate_block_of(pool, block as usize, defer_decommit) };+ });+}++/// How many blocks of the pool are free after the decommit worker looked at them.+///+/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_block_count(pool: *const BlockPool) -> usize {+ abort_on_panic(|| {+ // SAFETY: Forwarded from the caller.+ let state = lock(&unsafe { pool_from(pool) }.state);+ state.blocks.len() + state.returned_blocks.len()+ })+}++/// How many blocks of the pool had their pages go back to the system for real.+///+/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_returned_block_count(pool: *const BlockPool) -> usize {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| lock(&unsafe { pool_from(pool) }.state).returned_blocks.len())+}++/// Gives the pages of the pool's free blocks back to the system right away, rather than leaving them for the system to+/// take when it runs short of memory. For a heap that went away, whose blocks may never be used again.+///+/// # Safety+///+/// `pool` must be a live pool from rust_gc_block_pool_create().+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_gc_block_pool_return_freed_blocks_to_system(pool: *const BlockPool) {+ // SAFETY: Forwarded from the caller.+ abort_on_panic(|| unsafe { pool_from(pool) }.return_freed_blocks_to_system());+}++/// Wakes the decommit worker, starting it if it is not running yet, so that it discards the blocks freed since.+#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_wake_decommit_worker() {+ abort_on_panic(|| DecommitWorker::the().kick());+}++/// Sets how long a block can sit unused before its pages go back to the system, and returns the age it replaces.+#[unsafe(no_mangle)]+pub extern "C" fn rust_gc_set_cold_block_age_in_milliseconds(milliseconds: u64) -> u64 {+ COLD_BLOCK_AGE_IN_MILLISECONDS.swap(milliseconds, Ordering::Relaxed)+}diff --git a/Libraries/LibGC/Rust/src/identity_hash.rs b/Libraries/LibGC/Rust/src/identity_hash.rsindex aa3b5c88c13..e15a163ff1b 100644--- a/Libraries/LibGC/Rust/src/identity_hash.rs+++ b/Libraries/LibGC/Rust/src/identity_hash.rs@@ -11,8 +11,8 @@//! LibGC leaves free tell where the hash is: in an unhashed cell nowhere yet, in a hashed cell in the cell's address, and//! in a cell that was hashed and then moved in the side table of its heap. Hashing an unhashed cell sets "hashed", so//! that the collector knows to keep its hash when it moves the cell: under the copy's address in the side table, with-//! "moved" set on the copy. A copy that moves again has its entry rekeyed, and the entries of cells that died are-//! dropped after marking.+//! "moved" set on the copy. A copy that moves again has its entry rekeyed, and the entry of a cell that died is dropped+//! when the sweep frees its slot.//!//! Every hash of a cell's identity goes through identity_hash(), or through the inline copies of its fast path in C++//! (GC::identity_hash()) and in LibJS's runtime, which hand the cells that moved to it.@@ -67,14 +67,6 @@ pub struct IdentityHashes {}impl IdentityHashes {- pub fn len(&self) -> usize {- self.hashes.len()- }-- pub fn is_empty(&self) -> bool {- self.hashes.is_empty()- }-/// Notes that a cell with identity hash state `state` moved from `from` to `to`, and returns the state of the copy.pub fn did_move(&mut self, state: u8, from: CompressedAddress, to: CompressedAddress) -> u8 {if state & IDENTITY_HASH_HASHED == 0 {@@ -91,9 +83,16 @@ impl IdentityHashes {state | IDENTITY_HASH_MOVED}- /// Drops the entries of the cells that `is_live` says died.- pub fn retain_live(&mut self, mut is_live: impl FnMut(CompressedAddress) -> bool) {- self.hashes.retain(|&address, _| is_live(address));+ /// Drops the entry of a cell that moved since it was hashed, whose slot is freed.+ fn forget(&mut self, address: CompressedAddress) {+ self.hashes+ .remove(&address)+ .expect("a cell that moved since it was hashed has an entry");+ // NB: The table gives its room back once most of its entries are gone, and keeps enough to grow again without+ // shrinking and growing over and over.+ if self.hashes.capacity() > 64 && self.hashes.len() < self.hashes.capacity() / 4 {+ self.hashes.shrink_to(self.hashes.len() * 2);+ }}fn get(&self, address: CompressedAddress) -> IdentityHash {@@ -109,6 +108,17 @@ unsafe extern "C" {fn gc_heap_identity_hashes(heap: *mut c_void) -> *mut *mut c_void;}+/// The tests of this crate link without CAPI.cpp, and none of their cells is hashed.+#[cfg(test)]+mod capi_for_tests {+ use core::ffi::c_void;++ #[unsafe(no_mangle)]+ extern "C" fn gc_heap_identity_hashes(_: *mut c_void) -> *mut *mut c_void {+ unreachable!("no cell of the tests is hashed")+ }+}+/// The side table of `heap`, which this creates if it has none yet.////// # Safety@@ -144,9 +154,9 @@ pub unsafe extern "C" fn rust_gc_identity_hashes_destroy(table: *mut IdentityHas////// `cell` must be a live cell, of a heap that this thread uses.#[inline]-pub unsafe fn identity_hash(heap_region_base: usize, cell: usize) -> IdentityHash {- let state = (cell + IDENTITY_HASH_STATE_OFFSET) as *mut u8;- let compressed = CompressedAddress((cell >> COMPRESSED_POINTER_SHIFT) as u32);+pub unsafe fn identity_hash(heap_region_base: usize, cell: *const c_void) -> IdentityHash {+ let state = cell.cast::<u8>().cast_mut().wrapping_add(IDENTITY_HASH_STATE_OFFSET);+ let compressed = CompressedAddress((cell.addr() >> COMPRESSED_POINTER_SHIFT) as u32);// SAFETY: The caller passes a live cell, whose header has the state byte, and which only this thread touches.unsafe {let value = state.read();@@ -156,7 +166,7 @@ pub unsafe fn identity_hash(heap_region_base: usize, cell: usize) -> IdentityHas}return IdentityHash(compressed.0);}- let heap = descriptor_for(heap_region_base, cell).heap();+ let heap = descriptor_for(heap_region_base, cell.addr()).heap();identity_hashes_of(heap).get(compressed)}}@@ -173,23 +183,28 @@ pub unsafe extern "C" fn rust_gc_cell_identity_hash(heap_region_base: usize, cel"a cell is never at the start of its block");// SAFETY: The caller passes a live cell.- unsafe { identity_hash(heap_region_base, cell.addr()) }.0+ unsafe { identity_hash(heap_region_base, cell) }.0}-/// Drops the entries of the cells that the collection that just marked found dead, from a heap's side table.+/// Whether the cell at `cell` moved since it was hashed, so that the side table of its heap has an entry for it.////// # Safety///-/// `table` must be null or the side table of the heap that just marked, while its marks are valid.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_gc_identity_hashes_drop_dead(table: *mut IdentityHashes, heap_region_base: usize) {- // SAFETY: The caller passes null or a live table.- let Some(table) = (unsafe { table.as_mut() }) else {- return;- };- table.retain_live(|address| {- let cell = heap_region_base + ((address.0 as usize) << COMPRESSED_POINTER_SHIFT);- // SAFETY: Every entry is of a cell of the heap that marked, whose block is live until the cell is swept.- unsafe { descriptor_for(heap_region_base, cell) }.is_marked(cell)- });+/// `cell` must be an allocated cell.+pub unsafe fn has_moved_since_hashed(cell: usize) -> bool {+ // NB: Cells are in the heap region, whose provenance rust_gc_heap_region_init() exposed.+ let state = core::ptr::with_exposed_provenance::<u8>(cell + IDENTITY_HASH_STATE_OFFSET);+ // SAFETY: The caller passes an allocated cell, whose header has the state byte.+ unsafe { state.read() & IDENTITY_HASH_MOVED != 0 }+}++/// Drops the entry of the cell at `cell` from the side table of `heap`, as the sweep frees the cell's slot, which the+/// next cell there must not inherit.+///+/// # Safety+///+/// `heap` must be a live LibGC heap, used on this thread, and `cell` a cell of it that has_moved_since_hashed().+pub unsafe fn forget_identity_hash(heap: *mut c_void, cell: usize) {+ // SAFETY: The caller passes a live heap.+ unsafe { identity_hashes_of(heap) }.forget(CompressedAddress((cell >> COMPRESSED_POINTER_SHIFT) as u32));}diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rsindex 57fef3df98c..e90b100cd5f 100644--- a/Libraries/LibGC/Rust/src/lib.rs+++ b/Libraries/LibGC/Rust/src/lib.rs@@ -15,15 +15,33 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;+mod allocator;+mod bitmap;mod block;+mod block_pool;mod compaction;mod evacuation;mod identity_hash;mod marker;mod os;mod pool;+mod sanitizer;-pub use block::{BlockDescriptor, rust_gc_block_descriptor_commit, rust_gc_block_descriptor_table};+pub use allocator::{+ Allocator, AllocatorConfig, LocalFreeCells, SweepStats, rust_gc_allocator_allocate,+ rust_gc_allocator_allocate_destination, rust_gc_allocator_block_at, rust_gc_allocator_block_count,+ rust_gc_allocator_create, rust_gc_allocator_destroy, rust_gc_allocator_finish_evacuated_block,+ rust_gc_allocator_give_back_local_free_cells, rust_gc_allocator_has_blocks_pending_sweep,+ rust_gc_allocator_keep_cells_pinned, rust_gc_allocator_local_block, rust_gc_allocator_release_moved_cell,+ rust_gc_allocator_start_sweep, rust_gc_allocator_sweep_next_block, rust_gc_allocator_sweep_pending_block,+};+pub use block::{BlockDescriptor, rust_gc_block_descriptor_table};+pub use block_pool::{+ BlockPool, rust_gc_block_pool_allocate_block, rust_gc_block_pool_block_count, rust_gc_block_pool_create,+ rust_gc_block_pool_deallocate_block, rust_gc_block_pool_destroy, rust_gc_block_pool_return_freed_blocks_to_system,+ rust_gc_block_pool_returned_block_count, rust_gc_heap_region_committed_end, rust_gc_heap_region_init,+ rust_gc_set_cold_block_age_in_milliseconds, rust_gc_wake_decommit_worker,+};pub use compaction::{CompactionCandidate, CompactionSelection, rust_gc_compaction_select};pub use evacuation::{CellMove, EvacuationLayout, EvacuationSet, PinReason, PinnedCells, rust_gc_evacuation_add_block,@@ -34,10 +52,10 @@ pub use evacuation::{};pub use identity_hash::{IDENTITY_HASH_HASHED, IDENTITY_HASH_MOVED, IDENTITY_HASH_STATE_OFFSET, IdentityHashes, rust_gc_cell_identity_hash,- rust_gc_identity_hashes_destroy, rust_gc_identity_hashes_drop_dead,+ rust_gc_identity_hashes_destroy,};pub use marker::{- MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell, rust_gc_marker_thread_count,- rust_gc_marker_visit_cell, rust_gc_marker_visit_ephemeron, rust_gc_marker_visit_interior_pointer,- rust_gc_marker_visit_member, rust_gc_marker_visit_self_pointer, rust_gc_marker_visit_values,+ MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell, rust_gc_marker_visit_cell,+ rust_gc_marker_visit_ephemeron, rust_gc_marker_visit_interior_pointer, rust_gc_marker_visit_member,+ rust_gc_marker_visit_self_pointer, rust_gc_marker_visit_values,};diff --git a/Libraries/LibGC/Rust/src/marker.rs b/Libraries/LibGC/Rust/src/marker.rsindex 3cb721d5611..111d668e574 100644--- a/Libraries/LibGC/Rust/src/marker.rs+++ b/Libraries/LibGC/Rust/src/marker.rs@@ -26,7 +26,7 @@ use crossbeam_deque::{Injector, Steal, Stealer, Worker};use crate::block::{BLOCK_SIZE, BlockDescriptor, descriptor_table, heap_of_descriptor};use crate::evacuation::{EvacuationSet, PinReason, RecordedSlot, SlotKind};-use crate::pool::{Pool, PoolGuard, thread_count};+use crate::pool::{Pool, PoolGuard};use crate::rust_panic::abort_on_panic;pub(crate) const COMPRESSED_POINTER_SHIFT: u32 = 3;@@ -600,12 +600,6 @@ pub unsafe extern "C" fn rust_gc_marker_visit_ephemeron(marker: *mut Marker, keyunsafe { &*marker }.visit_ephemeron(key.addr(), value.addr());}-/// The most threads that mark a heap, the thread that collects included.-#[unsafe(no_mangle)]-pub extern "C" fn rust_gc_marker_thread_count() -> usize {- thread_count()-}-/// Marks every cell of the heaps that the roots reach, and adds up the bytes they take.////// # Safetydiff --git a/Libraries/LibGC/Rust/src/os.rs b/Libraries/LibGC/Rust/src/os.rsindex 1011d2f64a3..14e00ce376a 100644--- a/Libraries/LibGC/Rust/src/os.rs+++ b/Libraries/LibGC/Rust/src/os.rs@@ -5,7 +5,8 @@*///! The virtual memory operations the collector needs: reserving zero-filled address space that is only backed by-//! memory where it is touched.+//! memory where it is touched, committing the chunks of the heap region that C++ reserved, and handing the pages of+//! unused blocks back to the system while keeping them committed.use core::ptr::NonNull;@@ -43,12 +44,126 @@ mod platform {pub unsafe fn commit_reserved_zeroed(_address: NonNull<u8>, _size: usize) {// NB: Anonymous mappings are backed by zeroed pages as they are first touched.}++ /// # Safety+ ///+ /// The range must be reserved address space that holds nothing yet.+ pub unsafe fn commit(address: NonNull<u8>, size: usize) {+ // SAFETY: The caller guarantees the range is reserved, so mapping over it replaces nothing else.+ let mapped = unsafe {+ libc::mmap(+ address.as_ptr().cast(),+ size,+ libc::PROT_READ | libc::PROT_WRITE,+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_FIXED,+ MEMORY_TAG,+ 0,+ )+ };+ assert!(mapped != libc::MAP_FAILED, "commit a chunk of the heap region");+ }++ /// # Safety+ ///+ /// The range must be committed memory.+ pub unsafe fn populate(address: NonNull<u8>, size: usize) {+ // NB: This only fails if the kernel is too old to know it, which leaves the faults to the first touches.+ #[cfg(any(target_os = "linux", target_os = "android"))]+ // SAFETY: The caller guarantees the range is committed memory.+ unsafe {+ libc::madvise(address.as_ptr().cast(), size, libc::MADV_POPULATE_WRITE);+ }+ #[cfg(not(any(target_os = "linux", target_os = "android")))]+ let _ = (address, size);+ }++ /// Whether the range is made of whole pages. Advice applies to whole pages, and where a page is larger than a+ /// block, as on systems with 64 KiB pages, it also holds other blocks, which may be in use.+ fn is_whole_pages(address: NonNull<u8>, size: usize) -> bool {+ static PAGE_SIZE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();+ let page_size = *PAGE_SIZE.get_or_init(|| {+ // SAFETY: Reading a system configuration value has no preconditions.+ let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };+ usize::try_from(page_size).expect("the page size is known")+ });+ address.as_ptr().addr().is_multiple_of(page_size) && size.is_multiple_of(page_size)+ }++ fn madvise(address: NonNull<u8>, size: usize, advice: i32, what: &str) {+ // SAFETY: Every caller passes committed memory whose contents nothing needs, or that it is about to use again.+ let result = unsafe { libc::madvise(address.as_ptr().cast(), size, advice) };+ assert_eq!(result, 0, "{what} failed");+ }++ /// # Safety+ ///+ /// The range must be committed memory whose contents nothing needs any more.+ pub unsafe fn discard(address: NonNull<u8>, size: usize) {+ // NB: Where pages hold more than one block, the pages of a free block stay as they are.+ if !is_whole_pages(address, size) {+ return;+ }+ // NB: macOS has a paired protocol for this, which its accounting of resident memory understands.+ #[cfg(target_os = "macos")]+ madvise(address, size, libc::MADV_FREE_REUSABLE, "madvise(MADV_FREE_REUSABLE)");+ // NB: MADV_FREE keeps the pages mapped until the kernel needs them, so a block reused before then takes no+ // page fault.+ #[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]+ madvise(address, size, libc::MADV_FREE, "madvise(MADV_FREE)");+ #[cfg(not(any(+ target_os = "macos",+ target_os = "linux",+ target_os = "android",+ target_os = "freebsd"+ )))]+ madvise(address, size, libc::MADV_DONTNEED, "madvise(MADV_DONTNEED)");+ }++ /// # Safety+ ///+ /// The range must be committed memory whose contents nothing needs any more.+ pub unsafe fn return_to_system(address: NonNull<u8>, size: usize) {+ // NB: As in discard().+ if !is_whole_pages(address, size) {+ return;+ }+ #[cfg(any(target_os = "linux", target_os = "android"))]+ madvise(address, size, libc::MADV_DONTNEED, "madvise(MADV_DONTNEED)");+ // SAFETY: Forwarded from the caller.+ #[cfg(not(any(target_os = "linux", target_os = "android")))]+ unsafe {+ discard(address, size)+ };+ }++ /// # Safety+ ///+ /// The range must be committed memory that was discarded, or that mark_reusable() was called on.+ pub unsafe fn reuse(address: NonNull<u8>, size: usize) {+ #[cfg(target_os = "macos")]+ madvise(address, size, libc::MADV_FREE_REUSE, "madvise(MADV_FREE_REUSE)");+ #[cfg(not(target_os = "macos"))]+ let _ = (address, size);+ }++ /// # Safety+ ///+ /// The range must be committed memory that holds nothing yet.+ pub unsafe fn mark_reusable(address: NonNull<u8>, size: usize) {+ // NB: So that reuse() pairs with this when the blocks of a new chunk are handed out.+ #[cfg(target_os = "macos")]+ madvise(address, size, libc::MADV_FREE_REUSABLE, "madvise(MADV_FREE_REUSABLE)");+ #[cfg(not(target_os = "macos"))]+ let _ = (address, size);+ }}#[cfg(windows)]mod platform {use core::ptr::NonNull;- use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc};+ use windows_sys::Win32::System::Memory::{+ MEM_COMMIT, MEM_RESERVE, MEM_RESET, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualUnlock,+ };pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {// NB: Windows has no lazily committed memory that does not count towards the commit limit, so this reserves@@ -67,6 +182,53 @@ mod platform {let committed = unsafe { VirtualAlloc(address.as_ptr().cast(), size, MEM_COMMIT, PAGE_READWRITE) };assert!(!committed.is_null(), "commit the table of block descriptors");}++ /// # Safety+ ///+ /// The range must be reserved address space that holds nothing yet.+ pub unsafe fn commit(address: NonNull<u8>, size: usize) {+ // SAFETY: The caller guarantees the range is reserved.+ let committed = unsafe { VirtualAlloc(address.as_ptr().cast(), size, MEM_COMMIT, PAGE_READWRITE) };+ assert!(!committed.is_null(), "commit a chunk of the heap region");+ }++ /// # Safety+ ///+ /// The range must be committed memory.+ pub unsafe fn populate(_address: NonNull<u8>, _size: usize) {}++ /// # Safety+ ///+ /// The range must be committed memory whose contents nothing needs any more.+ pub unsafe fn discard(address: NonNull<u8>, size: usize) {+ // NB: DiscardVirtualMemory() validates its range with VirtualQuery(), which makes the kernel check every page in+ // the run of identical pages that starts at the block. All chunks are committed back to back in one+ // reservation, so that run is the whole committed heap. MEM_RESET drops the contents without that walk, and+ // VirtualUnlock() on pages that are not locked takes them out of the working set right away.+ // SAFETY: The caller guarantees the contents are unused.+ let reset = unsafe { VirtualAlloc(address.as_ptr().cast(), size, MEM_RESET, PAGE_READWRITE) };+ assert!(!reset.is_null(), "VirtualAlloc(MEM_RESET) failed");+ // SAFETY: As above.+ unsafe { VirtualUnlock(address.as_ptr().cast(), size) };+ }++ /// # Safety+ ///+ /// The range must be committed memory whose contents nothing needs any more.+ pub unsafe fn return_to_system(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { discard(address, size) }+ }++ /// # Safety+ ///+ /// The range must be committed memory.+ pub unsafe fn reuse(_address: NonNull<u8>, _size: usize) {}++ /// # Safety+ ///+ /// The range must be committed memory.+ pub unsafe fn mark_reusable(_address: NonNull<u8>, _size: usize) {}}pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {@@ -82,3 +244,66 @@ pub unsafe fn commit_reserved_zeroed(address: NonNull<u8>, size: usize) {// SAFETY: The caller's guarantee is the platform's.unsafe { platform::commit_reserved_zeroed(address, size) }}++/// Commits a range of address space that the heap region reserved, which reads as zero until it is written.+///+/// # Safety+///+/// The range must be reserved address space that holds nothing yet.+pub unsafe fn commit(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::commit(address, size) }+}++/// Faults the pages of a committed range in at once, where the system can do that, which costs a fraction of faulting+/// them in one by one.+///+/// # Safety+///+/// The range must be committed memory.+pub unsafe fn populate(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::populate(address, size) }+}++/// Lets the system take back the pages of a committed range when it runs short of memory. Until then, they keep their+/// contents and cost no fault when they are written again.+///+/// # Safety+///+/// The range must be committed memory whose contents nothing needs any more.+pub unsafe fn discard(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::discard(address, size) }+}++/// Gives the pages of a committed range back to the system right away, where the system can tell that apart from+/// discard().+///+/// # Safety+///+/// The range must be committed memory whose contents nothing needs any more.+pub unsafe fn return_to_system(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::return_to_system(address, size) }+}++/// Tells the system that a range that discard() or mark_reusable() was called on is in use again.+///+/// # Safety+///+/// The range must be committed memory.+pub unsafe fn reuse(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::reuse(address, size) }+}++/// Marks a freshly committed range as unused, so that reuse() pairs with it as it does with discard().+///+/// # Safety+///+/// The range must be committed memory that holds nothing yet.+pub unsafe fn mark_reusable(address: NonNull<u8>, size: usize) {+ // SAFETY: Forwarded from the caller.+ unsafe { platform::mark_reusable(address, size) }+}diff --git a/Libraries/LibGC/Rust/src/sanitizer.rs b/Libraries/LibGC/Rust/src/sanitizer.rsnew file mode 100644index 00000000000..46191c7eb2e--- /dev/null+++ b/Libraries/LibGC/Rust/src/sanitizer.rs@@ -0,0 +1,69 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What AddressSanitizer and LeakSanitizer need to know about the heap: free cells are poisoned, so that any access to+//! a cell that was swept or never handed out is reported, and blocks are root regions, so that malloc memory that only+//! cells refer to is not reported as leaked. Without the address-sanitizer feature, all of this does nothing.++#[cfg(feature = "address-sanitizer")]+use core::ffi::c_void;++/// cbindgen:ignore+#[cfg(feature = "address-sanitizer")]+mod ffi {+ use core::ffi::c_void;++ unsafe extern "C" {+ pub(super) fn __asan_poison_memory_region(address: *const c_void, size: usize);+ pub(super) fn __asan_unpoison_memory_region(address: *const c_void, size: usize);+ pub(super) fn __lsan_register_root_region(address: *const c_void, size: usize);+ pub(super) fn __lsan_unregister_root_region(address: *const c_void, size: usize);+ }+}++#[cfg(feature = "address-sanitizer")]+use ffi::{+ __asan_poison_memory_region, __asan_unpoison_memory_region, __lsan_register_root_region,+ __lsan_unregister_root_region,+};++#[inline]+pub fn poison(address: usize, size: usize) {+ // SAFETY: Poisoning only changes what AddressSanitizer reports.+ #[cfg(feature = "address-sanitizer")]+ unsafe {+ __asan_poison_memory_region(address as *const c_void, size);+ }+ let _ = (address, size);+}++#[inline]+pub fn unpoison(address: usize, size: usize) {+ // SAFETY: As above.+ #[cfg(feature = "address-sanitizer")]+ unsafe {+ __asan_unpoison_memory_region(address as *const c_void, size);+ }+ let _ = (address, size);+}++pub fn register_root_region(address: usize, size: usize) {+ // SAFETY: The region is committed memory that LeakSanitizer only reads.+ #[cfg(feature = "address-sanitizer")]+ unsafe {+ __lsan_register_root_region(address as *const c_void, size);+ }+ let _ = (address, size);+}++pub fn unregister_root_region(address: usize, size: usize) {+ // SAFETY: The region was registered with register_root_region().+ #[cfg(feature = "address-sanitizer")]+ unsafe {+ __lsan_unregister_root_region(address as *const c_void, size);+ }+ let _ = (address, size);+}diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txtindex 69999e74147..33aae7611f8 100644--- a/Tests/LibGC/CMakeLists.txt+++ b/Tests/LibGC/CMakeLists.txt@@ -6,7 +6,6 @@ set(TEST_SOURCESTestExternalEntityTable.cppTestGCContainers.cppTestGCEphemeron.cpp- TestGCFreeList.cppTestGCFunction.cppTestGCHeapGroup.cppTestGCIdleCollection.cppdiff --git a/Tests/LibGC/TestGCFreeList.cpp b/Tests/LibGC/TestGCFreeList.cppdeleted file mode 100644index 686d8a1b6e8..00000000000--- a/Tests/LibGC/TestGCFreeList.cpp+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Cell.h>-#include <LibGC/CellAllocator.h>-#include <LibGC/Heap.h>-#include <LibGC/HeapBlock.h>-#include <LibGC/Root.h>-#include <LibGC/Testing.h>-#include <LibTest/TestCase.h>--namespace {--class FreeListTestCell final : public GC::Cell {- GC_CELL(FreeListTestCell, GC::Cell);- GC_DECLARE_ALLOCATOR(FreeListTestCell);--private:- FreeListTestCell() = default;-- [[maybe_unused]] FlatPtr m_room_for_a_freelist_entry[2] {};-};--GC_DEFINE_ALLOCATOR(FreeListTestCell);--NEVER_INLINE void allocate_unreachable_cells(GC::Heap& heap, size_t count)-{- for (size_t i = 0; i < count; ++i)- (void)heap.allocate<FreeListTestCell>();-}--}--TEST_CASE(a_corrupted_free_cell_link_leads_to_a_cell_of_the_same_block)-{- GC::Heap heap([](auto&) { }, GC::Heap::BecomeThreadDefault::No);- heap.set_incremental_sweep_enabled(false);-- // NB: The cells of a new block come in address order.- auto first = GC::make_root(heap.allocate<FreeListTestCell>());- auto cell_size = GC::HeapBlock::from_cell(first.ptr())->cell_size();- auto address_of = [&](size_t index) { return bit_cast<FlatPtr>(first.ptr()) + index * cell_size; };- allocate_unreachable_cells(heap, 4);- GC::scrub_stack_for_testing();-- // The sweep frees the four unreachable cells in address order, so the free list of the block leads from the last- // of them to the first.- heap.collect_garbage();-- // Overwrite the link of the cell at the head of the list with an address outside the heap region that has the- // offset of the second cell after it in its block.- auto link_mask = GC::HeapBlock::freelist_link_mask;- auto forged_link = (0x7fff'0000'0000'0000ull & ~link_mask) | (address_of(2) & link_mask);- *bit_cast<FlatPtr*>(address_of(4) + GC::HeapBlock::freelist_next_offset()) = forged_link;-- auto second = GC::make_root(heap.allocate<FreeListTestCell>());- EXPECT_EQ(bit_cast<FlatPtr>(second.ptr()), address_of(4));- auto third = GC::make_root(heap.allocate<FreeListTestCell>());- EXPECT_EQ(bit_cast<FlatPtr>(third.ptr()), address_of(2));-}