Truly independent web browser
LibGC: Keep the blocks of a cell type with that type for good
Andreas Kling88dae176c461
diff --git a/Libraries/LibGC/BlockAllocator.cpp b/Libraries/LibGC/BlockAllocator.cppindex d0a9080934a..c05265cbdb3 100644--- a/Libraries/LibGC/BlockAllocator.cpp+++ b/Libraries/LibGC/BlockAllocator.cpp@@ -38,8 +38,11 @@ GC_API FlatPtr js_heap_region_base = 0;namespace GC {-// Every BlockAllocator takes 2 MiB chunks from one process-wide reserved-// region, and carves 16 KiB HeapBlock slots out of those chunks.+// 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@@ -97,17 +100,22 @@ public:// 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* allocate_chunk()+ void* take_unused_block(){- u8* chunk = nullptr;+ u8* block = nullptr;+ bool took_chunk = false;{MutexLocker locker(m_mutex);- chunk = exchange(m_prepared_chunk, nullptr);- if (!chunk)- chunk = commit_next_chunk();+ 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;}- request_prepared_chunk();- return chunk;+ 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@@ -117,7 +125,7 @@ public:u8* chunk = nullptr;{MutexLocker locker(m_mutex);- // NB: Running out of the region is left to allocate_chunk(), on the thread that needs another chunk.+ // 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();@@ -174,11 +182,36 @@ private: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 the next allocate_chunk() takes.+ // 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 };};static HeapRegion& heap_region()@@ -496,25 +529,7 @@ void* BlockAllocator::allocate_block([[maybe_unused]] char const* name)}if (block == nullptr) {- // Both pools empty: commit a fresh 2 MiB chunk and slice it.- auto* chunk_base = heap_region().allocate_chunk();--#if defined(MADV_FREE_REUSE) && defined(MADV_FREE_REUSABLE)- // Mark the whole chunk reusable upfront so MADV_FREE_REUSE pairs- // symmetrically when slots are popped from m_blocks later. (Linux- // and Windows fall through with no-op.)- if (madvise(chunk_base, CHUNK_SIZE, MADV_FREE_REUSABLE) < 0) {- perror("madvise(MADV_FREE_REUSABLE)");- VERIFY_NOT_REACHED();- }-#endif-- ASAN_POISON_MEMORY_REGION(chunk_base, CHUNK_SIZE);-- MutexLocker locker(m_mutex);- for (size_t i = 0; i < BLOCKS_PER_CHUNK; ++i)- m_blocks.append(static_cast<u8*>(chunk_base) + i * HeapBlock::BLOCK_SIZE);- block = m_blocks.take_last();+ block = heap_region().take_unused_block();needs_madvise_reuse = true;}diff --git a/Libraries/LibGC/BlockAllocator.h b/Libraries/LibGC/BlockAllocator.hindex 9ed700a1b09..8541d601826 100644--- a/Libraries/LibGC/BlockAllocator.h+++ b/Libraries/LibGC/BlockAllocator.h@@ -10,6 +10,7 @@#include <AK/ConditionVariable.h>#include <AK/Mutex.h>#include <AK/Vector.h>+#include <AK/kmalloc.h>#include <LibGC/Forward.h>namespace GC {@@ -21,8 +22,11 @@ enum class DeferDecommit {class DecommitWorker;+// The blocks of one type of cell in all heaps, see CellAllocatorDescriptorBase::block_allocator().class GC_API BlockAllocator {public:+ AK_ALLOC_WITH_KMALLOC;+BlockAllocator();~BlockAllocator();diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cppindex bdd563c4044..7019936d62e 100644--- a/Libraries/LibGC/CAPI.cpp+++ b/Libraries/LibGC/CAPI.cpp@@ -70,7 +70,12 @@ public:{}- ~CAPICellAllocator() { release_index(); }+ ~CAPICellAllocator()+ {+ // NB: The address of a descriptor without a foreign type names the type of its blocks, so it may never be reused.+ VERIFY(foreign_type());+ release_index();+ }};class RootGatheringVisitor final : public Cell::Visitor {diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.hindex 427257df709..df2a3b2ee5e 100644--- a/Libraries/LibGC/CAPI.h+++ b/Libraries/LibGC/CAPI.h@@ -133,7 +133,10 @@ GC_API void gc_heap_did_allocate_external_memory(GCHeap*, size_t);GC_API void gc_heap_did_free_external_memory(GCHeap*, size_t);// The type info and the name must outlive the allocator, and the allocator must outlive every heap it allocated from.-// The blocks of the allocator hold foreign_type, which LibGC never reads.+// The blocks of the allocator hold foreign_type, which also names the type of the cells for the whole process:+// allocators with the same foreign_type and cell size share a pool of blocks, across all heaps, and blocks never leave+// their pool. Different types must have different ones. An allocator without one has a pool of its own, and must never+// be destroyed.GC_API GCAllocator* gc_allocator_create(GCCellTypeInfo const*, char const* name, size_t name_length, void const* foreign_type);GC_API void gc_allocator_destroy(GCAllocator*);diff --git a/Libraries/LibGC/CellAllocator.cpp b/Libraries/LibGC/CellAllocator.cppindex 85ef801040d..3ed560d5e51 100644--- a/Libraries/LibGC/CellAllocator.cpp+++ b/Libraries/LibGC/CellAllocator.cpp@@ -5,6 +5,7 @@*/#include <AK/Badge.h>+#include <AK/HashMap.h>#include <AK/Mutex.h>#include <AK/NeverDestroyed.h>#include <AK/Vector.h>@@ -15,6 +16,22 @@namespace GC {+struct BlockPoolKey {+ void const* type { nullptr };+ size_t cell_size { 0 };++ bool operator==(BlockPoolKey const&) const = default;+};++}++template<>+struct AK::Traits<GC::BlockPoolKey> : public DefaultTraits<GC::BlockPoolKey> {+ static unsigned hash(GC::BlockPoolKey const& key) { return pair_int_hash(ptr_hash(key.type), u64_hash(key.cell_size)); }+};++namespace GC {+// Descriptors are shared by the heaps of all threads, so they keep no per-heap state. Each has an index instead, which// keeps the tables of the heaps dense: the indices of descriptors that went away are used again.struct DescriptorIndices {@@ -46,15 +63,26 @@ void CellAllocatorDescriptorBase::release_index()indices.free_indices.append(m_index);}-BlockAllocator& CellAllocator::shared_block_allocator()+// A block that was used for a type stays with that type for as long as the process lives, whichever heap had it. So a+// stale pointer into the region can only ever find a cell of the type it was made for, at the same offsets. Heaps die+// while the process lives, so this has to hold across heaps: the pools outlive them, and a new heap reuses the blocks.+//+// A foreign type names the type for the whole process, while its descriptors come and go with the heaps. A descriptor+// without one lives as long as the process, as C++ ones do, so its own address does. The cell size tells the size+// classes of a foreign type apart, whose blocks do not fit each other.+BlockAllocator& CellAllocatorDescriptorBase::block_allocator() const{- static AK::NeverDestroyed<BlockAllocator> allocator;- return *allocator;+ static AK::NeverDestroyed<Mutex> mutex;+ static AK::NeverDestroyed<HashMap<BlockPoolKey, NonnullOwnPtr<BlockAllocator>>> pools;++ BlockPoolKey key { m_foreign_type ? m_foreign_type : this, cell_size() };+ MutexLocker locker { *mutex };+ return *pools->ensure(key, [] { return make<BlockAllocator>(); });}CellAllocator::CellAllocator(CellAllocatorDescriptorBase& descriptor): m_descriptor(descriptor)- , m_block_allocator(shared_block_allocator())+ , m_block_allocator(descriptor.block_allocator()){m_local.cell_size = cell_size();}diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.hindex b5e9177c303..93bf7301501 100644--- a/Libraries/LibGC/CellAllocator.h+++ b/Libraries/LibGC/CellAllocator.h@@ -39,6 +39,9 @@ public:// Where each heap keeps its allocator for this descriptor, see Heap::cell_allocator_for().size_t index() const { return m_index; }+ // The blocks of the type of this descriptor, for every heap of the process and for as long as the process lives.+ BlockAllocator& block_allocator() const;+protected:CellAllocatorDescriptorBase(CellTypeInfo const& type_info, StringView class_name, void const* foreign_type = nullptr);@@ -60,8 +63,6 @@ public:explicit CellAllocator(CellAllocatorDescriptorBase&);~CellAllocator();- static BlockAllocator& shared_block_allocator();-CellAllocatorDescriptorBase const& descriptor() const { return m_descriptor; }Optional<StringView> class_name() const { return m_descriptor.class_name(); }size_t cell_size() const { return m_descriptor.cell_size(); }diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.hindex 724c00bf06d..781f5c4a45c 100644--- a/Libraries/LibGC/Heap.h+++ b/Libraries/LibGC/Heap.h@@ -168,6 +168,15 @@ public:bool is_live_heap_block(HeapBlock* block) const { return m_live_heap_blocks.contains(block); }+ template<typename Callback>+ void for_each_block(Callback callback)+ {+ for (auto& allocator : m_all_cell_allocators) {+ if (allocator.for_each_block(callback) == IterationDecision::Break)+ return;+ }+ }+void enqueue_post_gc_task(AK::Function<void()>);WeakImpl* create_weak_impl(void*);@@ -311,15 +320,6 @@ private:void start_idle_gc_timer();void idle_gc_on_timer();- template<typename Callback>- void for_each_block(Callback callback)- {- for (auto& allocator : m_all_cell_allocators) {- if (allocator.for_each_block(callback) == IterationDecision::Break)- return;- }- }-struct Stats {AK_ALLOC_WITH_KMALLOC;diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txtindex 0d1906527d9..46603347e71 100644--- a/Tests/LibGC/CMakeLists.txt+++ b/Tests/LibGC/CMakeLists.txt@@ -11,6 +11,7 @@ set(TEST_SOURCESTestGCIdleCollection.cppTestGCIncrementalSweep.cppTestGCThreads.cpp+ TestGCTypeIsolation.cppTestGCVisitor.cppTestMember.cppTestNanBoxedValue.cppdiff --git a/Tests/LibGC/TestGCTypeIsolation.cpp b/Tests/LibGC/TestGCTypeIsolation.cppnew file mode 100644index 00000000000..022a723e427--- /dev/null+++ b/Tests/LibGC/TestGCTypeIsolation.cpp@@ -0,0 +1,172 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Atomic.h>+#include <AK/HashTable.h>+#include <LibGC/CAPI.h>+#include <LibGC/Cell.h>+#include <LibGC/CellAllocator.h>+#include <LibGC/DeferGC.h>+#include <LibGC/Heap.h>+#include <LibGC/HeapBlock.h>+#include <LibGC/Testing.h>+#include <LibTest/TestCase.h>+#include <LibThreading/Thread.h>++namespace {++Atomic<size_t> s_live_cells { 0 };++// Each test uses types of its own, so that it starts out with empty pools.+template<int Tag>+class TaggedCell final : public GC::Cell {+ GC_CELL(TaggedCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(TaggedCell);++public:+ virtual ~TaggedCell() override { s_live_cells.fetch_sub(1); }++private:+ TaggedCell() { s_live_cells.fetch_add(1); }++ [[maybe_unused]] FlatPtr m_room_for_a_freelist_entry[2] {};+};++template<int Tag>+GC_DEFINE_ALLOCATOR(TaggedCell<Tag>);++using Blocks = HashTable<FlatPtr>;++static constexpr size_t BLOCK_COUNT = 64;++// Fills cells until they are in BLOCK_COUNT blocks, and returns those.+template<typename T>+NEVER_INLINE Blocks allocate_blocks(GC::Heap& heap)+{+ GC::DeferGC defer_gc { heap };+ Blocks blocks;+ while (blocks.size() < BLOCK_COUNT)+ blocks.set(bit_cast<FlatPtr>(GC::HeapBlock::from_cell(heap.allocate<T>().ptr())));+ return blocks;+}++bool have_a_block_in_common(Blocks const& first, Blocks const& second)+{+ for (auto block : first) {+ if (second.contains(block))+ return true;+ }+ return false;+}++template<typename Callback>+void run_on_a_new_thread(IGNORE_USE_IN_ESCAPING_LAMBDA Callback callback)+{+ auto thread = Threading::Thread::construct("TypeIsolationTest"sv, [&callback] {+ callback();+ return static_cast<intptr_t>(0);+ });+ thread->start();+ MUST(thread->join());+}++}++TEST_CASE(blocks_stay_with_their_type_after_their_heap_dies)+{+ using A = TaggedCell<0>;+ using B = TaggedCell<1>;++ Blocks blocks_of_a;+ run_on_a_new_thread([&] {+ GC::Heap heap([](auto&) { });+ blocks_of_a = allocate_blocks<A>(heap);+ });+ EXPECT_EQ(blocks_of_a.size(), BLOCK_COUNT);++#if defined(AK_OS_LINUX) && !defined(HAS_ADDRESS_SANITIZER)+ // The pages went back with the heap: a page that is still there holds the block's header.+ for (auto block : blocks_of_a) {+ FlatPtr first_word = *bit_cast<FlatPtr volatile*>(block);+ EXPECT_EQ(first_word, 0u);+ }+#endif++ run_on_a_new_thread([&] {+ GC::Heap heap([](auto&) { });+ EXPECT(!have_a_block_in_common(blocks_of_a, allocate_blocks<B>(heap)));++ // The new heap reuses the blocks of the type it needs, and so takes no others.+ auto blocks_of_a_again = allocate_blocks<A>(heap);+ EXPECT_EQ(blocks_of_a_again.size(), blocks_of_a.size());+ for (auto block : blocks_of_a_again)+ EXPECT(blocks_of_a.contains(block));+ });+}++TEST_CASE(blocks_stay_with_their_type_after_a_collection_frees_them)+{+ using A = TaggedCell<2>;+ using B = TaggedCell<3>;++ run_on_a_new_thread([] {+ GC::Heap heap([](auto&) { });+ heap.set_incremental_sweep_enabled(false);++ auto live_cells_before = s_live_cells.load();+ auto blocks_of_a = allocate_blocks<A>(heap);+ auto allocated_cells = s_live_cells.load() - live_cells_before;++ GC::scrub_stack_for_testing();+ heap.collect_garbage();+ // NB: A value left in a register can keep a cell, and its block, alive. Nearly all of them have to go, or+ // this proves nothing.+ EXPECT(s_live_cells.load() - live_cells_before < allocated_cells / 8);++ EXPECT(!have_a_block_in_common(blocks_of_a, allocate_blocks<B>(heap)));++ auto blocks_of_a_again = allocate_blocks<A>(heap);+ for (auto block : blocks_of_a_again)+ EXPECT(blocks_of_a.contains(block));+ });+}++TEST_CASE(a_foreign_type_has_the_same_pool_in_every_heap)+{+ static GCCellTypeInfo const small_cell_info {+ .cell_size = 64,+ .alignment = 8,+ .kind = 0,+ .visit_edges = [](GCCell*, GCVisitor*) { },+ .finalize = nullptr,+ .destroy = nullptr,+ .external_memory_size = nullptr,+ .class_name = nullptr,+ };+ static GCCellTypeInfo const large_cell_info { [] {+ auto info = small_cell_info;+ info.cell_size = 128;+ return info;+ }() };+ static int first_type;+ static int second_type;++ auto pool_of = [](GCCellTypeInfo const& info, void const* foreign_type) {+ auto* allocator = gc_allocator_create(&info, "Foreign", 7, foreign_type);+ auto* pool = &reinterpret_cast<GC::CellAllocatorDescriptorBase*>(allocator)->block_allocator();+ if (foreign_type)+ gc_allocator_destroy(allocator);+ return pool;+ };++ auto* pool = pool_of(small_cell_info, &first_type);+ EXPECT_EQ(pool_of(small_cell_info, &first_type), pool);+ EXPECT_NE(pool_of(small_cell_info, &second_type), pool);+ EXPECT_NE(pool_of(large_cell_info, &first_type), pool);++ // NB: Allocators without a foreign type live as long as the process.+ EXPECT_NE(pool_of(small_cell_info, nullptr), pool_of(small_cell_info, nullptr));+}diff --git a/Tests/LibJS/TestVMThreads.cpp b/Tests/LibJS/TestVMThreads.cppindex 62c5137c506..de16ab476df 100644--- a/Tests/LibJS/TestVMThreads.cpp+++ b/Tests/LibJS/TestVMThreads.cpp@@ -7,6 +7,8 @@#include <AK/Array.h>#include <AK/Atomic.h>#include <AK/ByteString.h>+#include <AK/HashMap.h>+#include <AK/HashTable.h>#include <AK/StackInfo.h>#include <AK/Time.h>#include <AK/Utf16String.h>@@ -14,8 +16,12 @@#include <LibCore/Environment.h>#include <LibCore/System.h>#include <LibGC/BlockAllocator.h>+#include <LibGC/DeferGC.h>+#include <LibGC/HeapBlock.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/GlobalObject.h>+#include <LibJS/Runtime/HostObject.h>#include <LibJS/Runtime/NativeFunction.h>#include <LibJS/Runtime/VM.h>#include <LibJS/Script.h>@@ -149,6 +155,108 @@ TEST_CASE(heap_blocks_come_back_when_vms_go_away)EXPECT(GC::BlockAllocator::heap_region_committed_end() <= committed_end + 16 * MiB);}+namespace {++// What a block holds, in terms that mean the same in every heap: the descriptor of a Rust type goes with its heap.+struct BlockContents {+ void const* type { nullptr };+ size_t cell_size { 0 };++ bool operator==(BlockContents const&) const = default;+};++}++static HashMap<FlatPtr, BlockContents> contents_of_blocks(GC::Heap& heap)+{+ HashMap<FlatPtr, BlockContents> blocks;+ heap.for_each_block([&](GC::HeapBlock& block) {+ auto const* foreign_type = block.foreign_type();+ auto const* type = foreign_type ? foreign_type : &block.cell_allocator().descriptor();+ blocks.set(bit_cast<FlatPtr>(&block), { type, block.cell_size() });+ return IterationDecision::Continue;+ });+ return blocks;+}++static void run_script(JS::VM& vm, JS::Realm& realm, StringView source)+{+ auto source_text = Utf16String::from_utf8_without_validation(source.bytes());+ auto script = JS::Script::parse(source_text.utf16_view(), realm);+ VERIFY(!script.is_error());+ VERIFY(!vm.run(script.value()).is_error());+}++TEST_CASE(block_addresses_stay_with_their_type_across_vms)+{+ // Keeps what it allocates, as the blocks are looked at while the VM still has them.+ static constexpr auto FIRST_SCRIPT = R"(+ globalThis.kept = [];+ for (let i = 0; i < 40000; ++i)+ kept.push({ i }, [i], `string-${i}`, () => i, new Map(), Symbol("s"));+ )"sv;+ // Different types, in different amounts.+ static constexpr auto SECOND_SCRIPT = R"(+ globalThis.kept = [];+ for (let i = 0; i < 40000; ++i)+ kept.push(new Date(i), new Set([i]), new Uint8Array(4), /a/g, new Error("e"), `string-${i}`, { i, j: i, k: i, l: i });+ )"sv;++ HashMap<FlatPtr, BlockContents> first_blocks;+ run_on_vm_threads(1, [&] {+ auto vm = JS::VM::create();+ vm->heap().set_incremental_sweep_enabled(false);+ auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);+ run_script(*vm, *root_execution_context->realm, FIRST_SCRIPT);+ first_blocks = contents_of_blocks(vm->heap());+ });++ run_on_vm_threads(1, [&] {+ auto vm = JS::VM::create();+ vm->heap().set_incremental_sweep_enabled(false);+ auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);+ run_script(*vm, *root_execution_context->realm, SECOND_SCRIPT);++ size_t reused_blocks = 0;+ for (auto const& [address, contents] : contents_of_blocks(vm->heap())) {+ auto first_contents = first_blocks.get(address);+ if (!first_contents.has_value())+ continue;+ ++reused_blocks;+ EXPECT(first_contents.value() == contents);+ }+ // Realms, shapes and strings, at least.+ EXPECT(reused_blocks > 10);+ });+}++TEST_CASE(a_host_class_keeps_its_blocks_across_vms)+{+ static JSHostClass const host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "TestHostObject"sv, nullptr, nullptr, nullptr, 0);++ auto allocate_host_objects = [](JS::VM& vm) {+ auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(vm);+ GC::DeferGC defer_gc { vm.heap() };+ HashTable<FlatPtr> blocks;+ while (blocks.size() < 16) {+ auto object = JS::HostObject::create(*root_execution_context->realm, host_class, nullptr);+ blocks.set(bit_cast<FlatPtr>(GC::HeapBlock::from_cell(GC::as_cell(object.ptr()))));+ }+ return blocks;+ };++ HashTable<FlatPtr> first_blocks;+ run_on_vm_threads(1, [&] {+ auto vm = JS::VM::create();+ first_blocks = allocate_host_objects(*vm);+ });+ run_on_vm_threads(1, [&] {+ auto vm = JS::VM::create();+ for (auto block : allocate_host_objects(*vm))+ EXPECT(first_blocks.contains(block));+ });+}+// Scripts that never end by themselves. Those that set `reached` show what an interrupt must not let run.static constexpr StringView NEVER_ENDING_SCRIPTS[] = {"while (true) {}"sv,