Truly independent web browser
LibGC+LibJS: Give WeakMap values ephemeron semantics
Shannon Booth6efd7e815a96
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cppindex 95ea1a85945..4e1f43596b8 100644--- a/Libraries/LibGC/CAPI.cpp+++ b/Libraries/LibGC/CAPI.cpp@@ -422,6 +422,11 @@ void gc_visitor_visit_values(GCVisitor* visitor, uint64_t const* values, size_tas_visitor(visitor).visit(ReadonlySpan<NanBoxedValue> { reinterpret_cast<NanBoxedValue const*>(values), count });}+void gc_visitor_visit_ephemeron(GCVisitor* visitor, GCCell* key, uint64_t const* value)+{+ as_visitor(visitor).visit_ephemeron(*from_gc_cell(key), *reinterpret_cast<NanBoxedValue const*>(value));+}+void gc_visitor_visit_possible_values(GCVisitor* visitor, uint8_t const* data, size_t size){as_visitor(visitor).visit_possible_values(ReadonlyBytes { data, size });diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.hindex 52ba07d85f2..59e9ca24fba 100644--- a/Libraries/LibGC/CAPI.h+++ b/Libraries/LibGC/CAPI.h@@ -182,6 +182,8 @@ GC_API void gc_weak_impl_unref(GCWeakImpl*);GC_API void gc_visitor_visit_cell(GCVisitor*, GCCell*);GC_API void gc_visitor_visit_cells(GCVisitor*, GCCell* const*, size_t count);GC_API void gc_visitor_visit_values(GCVisitor*, uint64_t const*, size_t count);+// Visits a NaN-boxed value that is reachable only while key is, such as a WeakMap entry's.+GC_API void gc_visitor_visit_ephemeron(GCVisitor*, GCCell* key, uint64_t const* value);// Treats every aligned word in the range as a possible pointer to a cell or NaN-boxed cell value.GC_API void gc_visitor_visit_possible_values(GCVisitor*, uint8_t const*, size_t size);diff --git a/Libraries/LibGC/Cell.cpp b/Libraries/LibGC/Cell.cppindex c9ff9015909..1381e7f8a8a 100644--- a/Libraries/LibGC/Cell.cpp+++ b/Libraries/LibGC/Cell.cpp@@ -31,4 +31,9 @@ void GC::Cell::Visitor::visit(NanBoxedValue const& value)visit_impl(value.as_cell());}+void GC::Cell::Visitor::visit_ephemeron(Cell&, NanBoxedValue const& value)+{+ visit(value);+}+}diff --git a/Libraries/LibGC/Cell.h b/Libraries/LibGC/Cell.hindex 5c68e02d675..e3cef2c1c9d 100644--- a/Libraries/LibGC/Cell.h+++ b/Libraries/LibGC/Cell.h@@ -259,6 +259,10 @@ public:virtual void visit_possible_values(ReadonlyBytes) = 0;+ // Visits a value that is reachable only while key is, such as a WeakMap entry's. Only marking tells them apart.+ // The caller must drop its entries whose key died, or the next collection reads a freed key.+ virtual void visit_ephemeron(Cell& key, NanBoxedValue const& value);+protected:virtual void visit_impl(Cell&) = 0;virtual void visit_impl(ReadonlySpan<NanBoxedValue>) = 0;diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cppindex 4c2393ff904..ee9a44b2a49 100644--- a/Libraries/LibGC/Heap.cpp+++ b/Libraries/LibGC/Heap.cpp@@ -1252,19 +1252,51 @@ public:}}+ virtual void visit_ephemeron(Cell& key, NanBoxedValue const& value) override+ {+ if (!value.is_cell())+ return;+ // NB: This phase does not mark keys outside the domain, so their values stay reachable.+ if (key.is_marked() || !cell_is_in_domain(key)) {+ visit(value);+ return;+ }+ m_pending_ephemerons.append({ &key, &value.as_cell() });+ }+void mark_all_live_cells(){- while (!m_work_queue.is_empty()) {- auto cell = m_work_queue.take_last();- if (cell->state() != Cell::State::Live)- continue;- cell->type_info().visit_edges(cell.ptr(), this);+ // Marking can reach the key of a pending ephemeron, so repeat until no more values get marked.+ for (;;) {+ while (!m_work_queue.is_empty()) {+ auto cell = m_work_queue.take_last();+ if (cell->state() != Cell::State::Live)+ continue;+ cell->type_info().visit_edges(cell.ptr(), this);+ }++ bool marked_a_value = false;+ m_pending_ephemerons.remove_all_matching([&](auto const& ephemeron) {+ if (!ephemeron.key->is_marked())+ return false;+ visit(*ephemeron.value);+ marked_a_value = true;+ return true;+ });+ if (!marked_a_value)+ break;}}private:+ struct Ephemeron {+ Cell* key { nullptr };+ Cell* value { nullptr };+ };+ReadonlySpan<Heap* const> m_domain;Vector<Ref<Cell>> m_work_queue;+ Vector<Ephemeron> m_pending_ephemerons;FlatPtr m_heap_region_start;FlatPtr m_heap_region_end;};diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rsindex 230884f2105..f7670ee9912 100644--- a/Libraries/LibJS/Rust/src/gc/capi.rs+++ b/Libraries/LibJS/Rust/src/gc/capi.rs@@ -143,6 +143,7 @@ unsafe extern "C" {pub fn gc_visitor_visit_cell(visitor: *mut GCVisitor, cell: *mut c_void);pub fn gc_visitor_visit_cells(visitor: *mut GCVisitor, cells: *const *mut c_void, count: usize);pub fn gc_visitor_visit_values(visitor: *mut GCVisitor, values: *const u64, count: usize);+ pub fn gc_visitor_visit_ephemeron(visitor: *mut GCVisitor, key: *mut c_void, value: *const u64);pub fn gc_visitor_visit_possible_values(visitor: *mut GCVisitor, data: *const u8, size: usize);pub fn gc_primitive_storage_allocate(diff --git a/Libraries/LibJS/Rust/src/gc/visitor.rs b/Libraries/LibJS/Rust/src/gc/visitor.rsindex 9ed111fd13c..6addf556a9e 100644--- a/Libraries/LibJS/Rust/src/gc/visitor.rs+++ b/Libraries/LibJS/Rust/src/gc/visitor.rs@@ -7,7 +7,7 @@use core::cell::Cell;use core::ptr::NonNull;-use super::capi::{GCVisitor, gc_visitor_visit_cell, gc_visitor_visit_values};+use super::capi::{GCVisitor, gc_visitor_visit_cell, gc_visitor_visit_ephemeron, gc_visitor_visit_values};use crate::layout::cell::Gc;use crate::layout::value::Value;@@ -36,6 +36,12 @@ impl Visitor {// SAFETY: The visitor is live, and Value is a NaN-boxed u64.unsafe { gc_visitor_visit_values(self.0.as_ptr(), values.as_ptr().cast(), values.len()) };}++ /// Visits a value that is reachable only while `key` is, such as a WeakMap entry's.+ pub fn visit_ephemeron<T>(&mut self, key: Gc<T>, value: &Value) {+ // SAFETY: The visitor is live, a Gc points to a live cell, and Value is a NaN-boxed u64.+ unsafe { gc_visitor_visit_ephemeron(self.0.as_ptr(), key.as_ptr().cast(), core::ptr::from_ref(value).cast()) };+ }}/// A value that can reach cells, which it reports to the visitor.diff --git a/Libraries/LibJS/Rust/src/runtime/weak_map.rs b/Libraries/LibJS/Rust/src/runtime/weak_map.rsindex d29552929e6..f0f3fcdc685 100644--- a/Libraries/LibJS/Rust/src/runtime/weak_map.rs+++ b/Libraries/LibJS/Rust/src/runtime/weak_map.rs@@ -27,11 +27,12 @@ use crate::runtime::realm::Realm;#[derive(Default)]struct WeakMapValues(HashMap<Gc<CellHeader>, Value, foldhash::fast::RandomState>);-// SAFETY: Visits every value. The keys are held weakly, and removed in remove_dead_cells() once they die.+// SAFETY: Visits every value as reachable only while its key is. The keys are held weakly, and removed in+// remove_dead_cells() once they die, together with their values.unsafe impl Trace for WeakMapValues {fn trace(&self, visitor: &mut Visitor) {- for value in self.0.values() {- value.trace(visitor);+ for (&key, value) in &self.0 {+ visitor.visit_ephemeron(key, value);}}}diff --git a/Tests/LibGC/CMakeLists.txt b/Tests/LibGC/CMakeLists.txtindex 5539e9e341a..9348c3d0c2a 100644--- a/Tests/LibGC/CMakeLists.txt+++ b/Tests/LibGC/CMakeLists.txt@@ -4,6 +4,7 @@ set(TEST_SOURCESTestBlockAllocator.cppTestExternalEntityTable.cppTestGCContainers.cpp+ TestGCEphemeron.cppTestGCFreeList.cppTestGCHeapGroup.cppTestGCIdleCollection.cppdiff --git a/Tests/LibGC/TestGCEphemeron.cpp b/Tests/LibGC/TestGCEphemeron.cppnew file mode 100644index 00000000000..eaa79ecfa53--- /dev/null+++ b/Tests/LibGC/TestGCEphemeron.cpp@@ -0,0 +1,228 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Vector.h>+#include <LibGC/Cell.h>+#include <LibGC/CellAllocator.h>+#include <LibGC/Heap.h>+#include <LibGC/NanBoxedValue.h>+#include <LibGC/Ptr.h>+#include <LibGC/Root.h>+#include <LibGC/Testing.h>+#include <LibGC/WeakContainer.h>+#include <LibGC/WeakInlines.h>+#include <LibTest/TestCase.h>++namespace {++class TestNanBox : public GC::NanBoxedValue {+public:+ static TestNanBox from_cell(GC::Cell& cell)+ {+ TestNanBox box;+ box.m_value.encoded = GC::SHIFTED_IS_CELL_PATTERN | GC::NanBoxedValue::encode_pointer_bits(&cell);+ return box;+ }++ static TestNanBox from_double(double value)+ {+ TestNanBox box;+ box.m_value.as_double = value;+ return box;+ }++ double as_double() const { return m_value.as_double; }+};++class TestCell final : public GC::Cell {+ GC_CELL(TestCell, GC::Cell);+ GC_DECLARE_ALLOCATOR(TestCell);++public:+ GC::Ptr<GC::Cell> edge;++private:+ TestCell() = default;++ virtual void visit_edges(Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ visitor.visit(edge);+ }+};++GC_DEFINE_ALLOCATOR(TestCell);++// Holds its values as ephemerons of their keys, and drops the entries whose key died, as WeakMap does.+class EphemeronTable final+ : public GC::Cell+ , public GC::WeakContainer {+ GC_CELL(EphemeronTable, GC::Cell);+ GC_DECLARE_ALLOCATOR(EphemeronTable);++public:+ struct Entry {+ GC::RawPtr<GC::Cell> key;+ TestNanBox value;+ };++ void add(GC::Cell& key, TestNanBox value) { entries.append({ &key, value }); }++ Vector<Entry> entries;++private:+ EphemeronTable()+ : GC::WeakContainer(heap())+ {+ }++ virtual void visit_edges(Visitor& visitor) override+ {+ Base::visit_edges(visitor);+ for (auto& entry : entries)+ visitor.visit_ephemeron(*entry.key, entry.value);+ }++ virtual GC::Cell const& owner_cell(Badge<GC::Heap>) const override { return *this; }++ virtual void remove_dead_cells(Badge<GC::Heap>) override+ {+ entries.remove_all_matching([](auto const& entry) { return !entry.key->is_marked(); });+ }+};++GC_DEFINE_ALLOCATOR(EphemeronTable);++struct Weaks {+ GC::Weak<TestCell> key;+ GC::Weak<TestCell> value;+};++NEVER_INLINE Weaks add_value_referring_to_its_key(GC::Heap& heap, EphemeronTable& table)+{+ auto key = heap.allocate<TestCell>();+ auto value = heap.allocate<TestCell>();+ value->edge = key.ptr();+ table.add(*key, TestNanBox::from_cell(*value));+ return { key.ptr(), value.ptr() };+}++// The entry of the second key comes first, so marking visits it before the entry of the first key marks the second.+NEVER_INLINE Weaks add_chain_from(GC::Heap& heap, EphemeronTable& table, TestCell& first_key)+{+ auto second_key = heap.allocate<TestCell>();+ auto value = heap.allocate<TestCell>();+ table.add(*second_key, TestNanBox::from_cell(*value));+ table.add(first_key, TestNanBox::from_cell(*second_key));+ return { second_key.ptr(), value.ptr() };+}++NEVER_INLINE GC::Weak<TestCell> add_value_of_foreign_key(GC::Heap& heap, GC::Heap& foreign_heap, EphemeronTable& table)+{+ auto key = foreign_heap.allocate<TestCell>();+ auto value = heap.allocate<TestCell>();+ table.add(*key, TestNanBox::from_cell(*value));+ return value.ptr();+}++NEVER_INLINE void add_double_of_dead_key(GC::Heap& heap, EphemeronTable& table)+{+ table.add(*heap.allocate<TestCell>(), TestNanBox::from_double(2.5));+}++}++static NEVER_INLINE void value_referring_to_its_key_dies_with_it()+{+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ heap.set_incremental_sweep_enabled(false);+ auto table = GC::make_root(heap.allocate<EphemeronTable>());++ auto weaks = add_value_referring_to_its_key(heap, *table);+ GC::scrub_stack_for_testing();+ heap.collect_garbage();++ EXPECT(!weaks.key);+ EXPECT(!weaks.value);+ EXPECT(table->entries.is_empty());+}++static NEVER_INLINE void value_survives_when_its_key_is_marked_later()+{+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ heap.set_incremental_sweep_enabled(false);+ auto table = GC::make_root(heap.allocate<EphemeronTable>());+ auto first_key = GC::make_root(heap.allocate<TestCell>());++ auto weaks = add_chain_from(heap, *table, *first_key);+ GC::scrub_stack_for_testing();+ heap.collect_garbage();++ EXPECT(weaks.key);+ EXPECT(weaks.value);+ EXPECT_EQ(table->entries.size(), 2u);+}++static NEVER_INLINE void value_of_key_outside_domain_survives_local_collection()+{+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ GC::Heap foreign_heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ heap.set_incremental_sweep_enabled(false);+ foreign_heap.set_incremental_sweep_enabled(false);+ auto table = GC::make_root(heap.allocate<EphemeronTable>());++ auto value = add_value_of_foreign_key(heap, foreign_heap, *table);+ GC::scrub_stack_for_testing();+ heap.collect_garbage();++ // NB: A collection of this heap alone never marks the key, so the table drops its entry.+ EXPECT(value);+ EXPECT(table->entries.is_empty());+}++static NEVER_INLINE void non_cell_value_is_ignored()+{+ GC::Heap heap([](auto&) { }, GC::Heap::BecomeProcessDefault::No);+ heap.set_incremental_sweep_enabled(false);+ auto table = GC::make_root(heap.allocate<EphemeronTable>());+ auto key = GC::make_root(heap.allocate<TestCell>());+ table->add(*key, TestNanBox::from_double(1.5));++ add_double_of_dead_key(heap, *table);+ GC::scrub_stack_for_testing();+ heap.collect_garbage();++ EXPECT_EQ(table->entries.size(), 1u);+ EXPECT_EQ(table->entries[0].value.as_double(), 1.5);+}++// Under ASan with detect_stack_use_after_return, a function's locals live on a fake stack, but its frame on the real+// stack still reserves room for them — room it never writes, so it keeps whatever earlier calls left there, and the+// conservative scan reads it. A stale pointer there can keep a dropped cell alive. So each case runs in a frame of its+// own, on stack that scrub_stack_for_testing() has just cleared.+TEST_CASE(value_referring_to_its_key_dies_with_it)+{+ GC::scrub_stack_for_testing();+ value_referring_to_its_key_dies_with_it();+}++TEST_CASE(value_survives_when_its_key_is_marked_later)+{+ GC::scrub_stack_for_testing();+ value_survives_when_its_key_is_marked_later();+}++TEST_CASE(value_of_key_outside_domain_survives_local_collection)+{+ GC::scrub_stack_for_testing();+ value_of_key_outside_domain_survives_local_collection();+}++TEST_CASE(non_cell_value_is_ignored)+{+ GC::scrub_stack_for_testing();+ non_cell_value_is_ignored();+}diff --git a/Tests/LibGC/TestGCVisitor.cpp b/Tests/LibGC/TestGCVisitor.cppindex 1efe9a8a669..10de44ab8bb 100644--- a/Tests/LibGC/TestGCVisitor.cpp+++ b/Tests/LibGC/TestGCVisitor.cpp@@ -131,6 +131,19 @@ TEST_CASE(visit_ptr_traces_cell)EXPECT(visitor.visited_cells.contains(cell.ptr()));}+TEST_CASE(visit_ephemeron_traces_value_but_not_key)+{+ auto& heap = test_heap();+ auto key = heap.allocate<TestCell>();+ auto value = heap.allocate<TestCell>();++ TestVisitor visitor;+ visitor.visit_ephemeron(*key, TestNanBox::from_cell(value.ptr()));++ EXPECT(visitor.visited_cells.contains(value.ptr()));+ EXPECT(!visitor.visited_cells.contains(key.ptr()));+}+TEST_CASE(visit_null_ptr_traces_nothing){GC::Ptr<TestCell> ptr;diff --git a/Tests/LibJS/Runtime/builtins/WeakMap/WeakMap.prototype.set.js b/Tests/LibJS/Runtime/builtins/WeakMap/WeakMap.prototype.set.jsindex 2d63f512e63..cec10be5c89 100644--- a/Tests/LibJS/Runtime/builtins/WeakMap/WeakMap.prototype.set.js+++ b/Tests/LibJS/Runtime/builtins/WeakMap/WeakMap.prototype.set.js@@ -45,3 +45,39 @@ test.xfail("automatic removal of garbage-collected values", () => {expect(getWeakMapSize(weakMap)).toBe(0);});++test("a value does not keep its own key alive", () => {+ // Fill the map in a function of its own, so that the JIT leaves none of the keys in this frame.+ const weakMap = (() => {+ const weakMap = new WeakMap();+ const key = {};+ weakMap.set(key, { key });++ // The first key's value is the second key, whose value refers back to the first.+ const first = {};+ const second = {};+ weakMap.set(first, second);+ weakMap.set(second, { first });+ return weakMap;+ })();+ expect(getWeakMapSize(weakMap)).toBe(3);++ gc();++ expect(getWeakMapSize(weakMap)).toBe(0);+});++test("a value stays alive while its key is reachable through another entry", () => {+ const weakMap = new WeakMap();+ const first = {};+ let second = {};+ weakMap.set(first, second);+ weakMap.set(second, { marker: 42 });+ (() => second)();++ markAsGarbage("second");+ gc();++ expect(getWeakMapSize(weakMap)).toBe(2);+ expect(weakMap.get(weakMap.get(first)).marker).toBe(42);+});