Skip to content

Truly independent web browser

LibGC+LibJS: Let collections move cells held outside of cells

Andreas Kling64b7abc694af
diff --git a/Libraries/LibGC/BlockDescriptor.h b/Libraries/LibGC/BlockDescriptor.h
index 9d84107fe3b..a910f305e38 100644
--- a/Libraries/LibGC/BlockDescriptor.h
+++ b/Libraries/LibGC/BlockDescriptor.h
@@ -63,12 +63,6 @@ ALWAYS_INLINE void set_marked(void const* cell)
__atomic_fetch_or(&descriptor.marked[index / 64], cell_bit(index), __ATOMIC_RELAXED);
}
-ALWAYS_INLINE void clear_marks(FFI::BlockDescriptor& descriptor)
-{
- for (auto& word : descriptor.marked)
- __atomic_store_n(&word, 0, __ATOMIC_RELAXED);
-}
-
// A cell is allocated from when it is handed out until the sweep or a move frees its slot. While an allocator has taken
// 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.
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cpp
index 915837f4692..c6596bd8c86 100644
--- a/Libraries/LibGC/CAPI.cpp
+++ b/Libraries/LibGC/CAPI.cpp
@@ -159,6 +159,11 @@ struct CAPI {
auto* evacuation = cell.heap().m_evacuation;
return evacuation && FFI::rust_gc_evacuation_will_move(evacuation, &cell);
}
+ static void record_slot(Heap& heap, void const* slot, FFI::RecordedSlotKind kind)
+ {
+ if (heap.m_evacuation)
+ FFI::rust_gc_evacuation_record_slot(heap.m_evacuation, slot, kind);
+ }
};
}
@@ -418,6 +423,12 @@ bool gc_heap_is_moving_cells(GCHeap const* heap)
return as_heap(heap).is_moving_cells();
}
+void gc_heap_record_slot(GCHeap* heap, void const* slot, int kind)
+{
+ VERIFY(kind == GC_RECORDED_SLOT_VALUE || kind == GC_RECORDED_SLOT_CELL_POINTER);
+ CAPI::record_slot(as_heap(heap), slot, kind == GC_RECORDED_SLOT_VALUE ? FFI::RecordedSlotKind::Value : FFI::RecordedSlotKind::CellPointer);
+}
+
uint32_t gc_cell_identity_hash(GCCell const* cell)
{
return FFI::rust_gc_cell_identity_hash(heap_region_base(), cell);
@@ -494,6 +505,16 @@ void gc_marker_visit_values(GCMarker* marker, uint64_t const* values, size_t cou
FFI::rust_gc_marker_visit_values(reinterpret_cast<FFI::Marker*>(marker), values, count);
}
+void gc_marker_visit_owned_values(GCMarker* marker, uint64_t const* values, size_t count)
+{
+ FFI::rust_gc_marker_visit_owned_values(reinterpret_cast<FFI::Marker*>(marker), values, count);
+}
+
+void gc_marker_visit_ephemeron_without_pinning(GCMarker* marker, GCCell* key, GCCell* value)
+{
+ FFI::rust_gc_marker_visit_ephemeron_without_pinning(reinterpret_cast<FFI::Marker*>(marker), key, value);
+}
+
void gc_marker_visit_member(GCMarker* marker, uint32_t const* slot)
{
FFI::rust_gc_marker_visit_member(reinterpret_cast<FFI::Marker*>(marker), slot);
diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.h
index 5b1093ab907..f23b490ef4b 100644
--- a/Libraries/LibGC/CAPI.h
+++ b/Libraries/LibGC/CAPI.h
@@ -165,11 +165,11 @@ GC_API void gc_allocator_destroy(GCAllocator*);
GC_API void gc_allocator_set_traced_on_owner_thread_only(GCAllocator*);
// Lets collections move the cells of the allocator to other blocks of it, in collections that do not scan the stack. A
// cell moves as a bytewise copy, its old slot is freed without destroying it, and every slot that marking visited
-// through gc_marker_visit_member(), gc_marker_visit_values(), gc_marker_visit_interior_pointer() or
-// gc_marker_visit_self_pointer() is rewritten. A cell that something visits by value, through gc_marker_visit_cell() or
-// as a root, or that gc_marker_pin_cell() pins, stays where it is. So a type may only be movable if everything that
-// keeps its address without visiting it as a slot either pins it or forgets it (see gc_cell_will_move()). It must be
-// called before the allocator allocates a cell.
+// through gc_marker_visit_member(), gc_marker_visit_values(), gc_marker_visit_owned_values(),
+// gc_marker_visit_interior_pointer() or gc_marker_visit_self_pointer() is rewritten. A cell that something visits by
+// value, through gc_marker_visit_cell() or as a root, or that gc_marker_pin_cell() pins, stays where it is. So a type
+// may only be movable if everything that keeps its address without visiting it as a slot either pins it or forgets it
+// (see gc_cell_will_move()). It must be called before the allocator allocates a cell.
GC_API void gc_allocator_set_movable(GCAllocator*);
// Returns uninitialized storage for one cell.
@@ -213,6 +213,18 @@ GC_API bool gc_cell_is_marked(GCCell const*);
GC_API bool gc_cell_will_move(GCCell const*);
// Whether the collection in progress may move cells.
GC_API bool gc_heap_is_moving_cells(GCHeap const*);
+// What a slot handed to gc_heap_record_slot() holds.
+enum {
+ // A NaN-boxed value, which may hold a cell.
+ GC_RECORDED_SLOT_VALUE = 0,
+ // A raw pointer to the start of a cell, or null.
+ GC_RECORDED_SLOT_CELL_POINTER = 1,
+};
+// Has the collection in progress rewrite a slot that marking did not visit through it if its cell moves, as it rewrites
+// the slots marking visited. Holders that keep cells without keeping them alive or in place, like weak maps, hand over
+// the slots of the cells that survived from a sweep callback, once they forgot those that died. The cell must be marked,
+// and nothing may free, move or write the slot until the collection is over. Does nothing if no cell moves.
+GC_API void gc_heap_record_slot(GCHeap*, void const* slot, int kind);
// A 32-bit hash of the cell's identity, which stays the same while the cell lives, wherever the collector moves it.
// Hashing a cell for the first time sets the "hashed" bit of the byte at identity_hash_state_offset; while the "moved"
// bit is clear, the hash is the cell's compressed address, so code may compute it inline (see GC::identity_hash()) and
@@ -233,7 +245,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.
+// Visits a NaN-boxed value that is reachable only while key is, such as a WeakMap entry's. A collection that moves cells
+// keeps both where they are.
GC_API void gc_visitor_visit_ephemeron(GCVisitor*, GCCell* key, uint64_t const* value);
// The marker a marking GCVisitor points to (see GCLayout::visitor_marker_offset), which these hand cells to directly.
@@ -242,6 +255,10 @@ typedef struct GCMarker GCMarker;
GC_API void gc_marker_visit_cell(GCMarker*, GCCell*);
// Visits the values, whose slots a collection that moves cells rewrites if they are in a cell.
GC_API void gc_marker_visit_values(GCMarker*, uint64_t const*, size_t count);
+// Visits values in memory that the cell being visited owns outside the heap, whose slots a collection that moves cells
+// rewrites where they are, like those in cells. Nothing may free, move or write that memory until the collection is
+// over: no finalizer, destructor or sweep callback may touch it.
+GC_API void gc_marker_visit_owned_values(GCMarker*, uint64_t const*, size_t count);
// Visits the cell that the compressed pointer in the slot points to, if it is not null. A collection that moves cells
// rewrites the slot if it is in a cell, and keeps the cell where it is otherwise.
GC_API void gc_marker_visit_member(GCMarker*, uint32_t const* slot);
@@ -252,6 +269,9 @@ GC_API void gc_marker_visit_interior_pointer(GCMarker*, uintptr_t const* slot, G
GC_API void gc_marker_visit_self_pointer(GCMarker*, uintptr_t const* slot);
// Keeps the cell from moving without keeping it alive, for a weak reference that the collector cannot update.
GC_API void gc_marker_pin_cell(GCMarker*, GCCell const*);
+// Marks value once key is marked, like gc_visitor_visit_ephemeron(), without keeping either from moving. The holder must
+// hand the slots of both to gc_heap_record_slot() if the entry survives the collection.
+GC_API void gc_marker_visit_ephemeron_without_pinning(GCMarker*, GCCell* key, GCCell* value);
// Primitive storage holds byte buffers inside the cage that starts at gc_primitive_storage_cage_base(), so that the
// interpreter can reach any of their bytes as a cage offset masked with primitive_storage_cage_offset_mask. Like the
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index 79c93bc6cc4..34e074c9807 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -186,6 +186,7 @@ struct CompactionStats {
bool active { false };
size_t evacuated_blocks { 0 };
+ // The evacuated blocks that no cell stays in, which the sweep that follows lets go of.
size_t freed_blocks { 0 };
// What selection expected to recover and move, see rust_gc_compaction_select().
size_t recoverable_bytes { 0 };
@@ -197,7 +198,6 @@ struct CompactionStats {
size_t recorded_slots { 0 };
size_t rewritten_slots { 0 };
i64 select_us { 0 };
- i64 sweep_us { 0 };
i64 copy_us { 0 };
i64 fix_up_us { 0 };
i64 release_us { 0 };
@@ -311,11 +311,11 @@ thread_local bool g_recording_phase_timings { false };
void print_compaction_summary(CompactionStats const& stats)
{
auto pinned_bytes = [&](CompactionStats::PinReason reason) { return human_readable_size(stats.pinned[reason].bytes); };
- dbgln("Compaction: {} source blocks, {} freed; moved {} of {} expected; pinned {} by edge, {} by root, {} non-movable; {} recoverable before; {} slots recorded, {} rewritten; select {} us, sweep {} us, compaction {} us (copy {}, fix up {}, release {})",
+ dbgln("Compaction: {} source blocks, {} freed; moved {} of {} expected; pinned {} by edge, {} by root, {} non-movable; {} recoverable before; {} slots recorded, {} rewritten; select {} us, compaction {} us (copy {}, fix up {}, release {})",
stats.evacuated_blocks, stats.freed_blocks, human_readable_size(stats.moved.bytes), human_readable_size(stats.bytes_to_move),
pinned_bytes(CompactionStats::ByValueEdge), pinned_bytes(CompactionStats::ByValueRoot),
pinned_bytes(CompactionStats::NonMovableAllocator),
- human_readable_size(stats.recoverable_bytes), stats.recorded_slots, stats.rewritten_slots, stats.select_us, stats.sweep_us,
+ human_readable_size(stats.recoverable_bytes), stats.recorded_slots, stats.rewritten_slots, stats.select_us,
stats.select_us + stats.copy_us + stats.fix_up_us + stats.release_us, stats.copy_us, stats.fix_up_us, stats.release_us);
}
@@ -382,7 +382,6 @@ void print_gc_report(i64 total_us, size_t live_block_count, bool scan_stack, siz
dbgln(" recorded slots {:>10}", stats.recorded_slots);
dbgln(" rewritten slots {:>10}", stats.rewritten_slots);
dbgln(" select {:>10} us", stats.select_us);
- dbgln(" sweep for compaction {:>10} us", stats.sweep_us);
dbgln(" copy {:>10} us", stats.copy_us);
dbgln(" fix up {:>10} us", stats.fix_up_us);
dbgln(" release {:>10} us", stats.release_us);
@@ -1167,26 +1166,27 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
m_weak_pointers_to_dead_cells_are_cleared = false;
m_mark_duration_ns = MonotonicTime::now().nanoseconds() - mark_start_ns;
+ // NB: A collection that moves cells moves them before it sweeps, into slots that are free already. The sweep
+ // that follows frees the dead cells and lets go of the blocks that were emptied, as after any collection, so
+ // destructors run once the collection is over, where they may allocate, and the memory that they free is
+ // still there when the slots that marking recorded are rewritten. Only finalize() may reach other cells,
+ // and it runs before any cell moves. A destructor that reaches another cell may only reach one defined in
+ // C++, which never moves.
+ if (m_evacuation) {
+ evacuate();
+ end_evacuation();
+ if (libgc_log_level() >= 1)
+ print_compaction_summary(*m_compaction_stats);
+ }
+
// For CollectEverything we must finish sweeping synchronously so that
// every cell is collected before the Heap destructor returns. All
// other collection types defer sweeping to incremental work below,
// unless incremental sweeping is disabled (no event loop to run it).
- // NB: A collection that moves cells sweeps first as well, so that the dead cells are gone before any cell
- // moves, and their slots are free for the cells that move. Otherwise a dead cell's destructor could reach a
- // live cell through a pointer that no longer points at it.
- if (collection_type == CollectionType::CollectEverything || !m_incremental_sweep_enabled || m_evacuation) {
+ if (collection_type == CollectionType::CollectEverything || !m_incremental_sweep_enabled) {
ScopedPhaseTimer timer { report, g_phase_timings.sweep_dead_cells_us };
sweep_dead_cells(report, collection_measurement_timer);
}
- if (m_evacuation) {
- m_compaction_stats->sweep_us = g_phase_timings.sweep_dead_cells_us;
- evacuate();
- end_evacuation();
- // NB: The blocks this freed go back to the system once the decommit worker gets to them.
- BlockAllocator::wake_decommit_worker_async();
- if (libgc_log_level() >= 1)
- print_compaction_summary(*m_compaction_stats);
- }
if (report) {
size_t live_block_count = 0;
@@ -1205,7 +1205,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
// Arm incremental sweep before running post-GC tasks so any cells those
// tasks allocate get tagged as allocated-during-sweep and aren't freed
// by sweep_block before the next mark phase reaches them.
- if (collection_type != CollectionType::CollectEverything && m_incremental_sweep_enabled && !m_compaction_stats->active)
+ if (collection_type != CollectionType::CollectEverything && m_incremental_sweep_enabled)
start_incremental_sweep();
else
g_next_incremental_sweep_should_report = false;
@@ -1390,8 +1390,8 @@ Cell* Heap::allocate_destination_for_moved_cell(CellAllocator& allocator)
// Moves the live cells of the evacuated blocks that nothing pinned to free slots of other blocks of their allocator:
// takes their new slots, rewrites the slots that marking recorded and the weak pointers, copies the cells, and frees
-// the old slots without destroying their cells. The dead cells are swept already, so their slots are free to take, and
-// no destructor of a dead cell sees a cell that moved.
+// the old slots without destroying their cells. Nothing is swept yet, so the slots of dead cells are not free to take,
+// and the sweep that follows frees the dead cells of every block, the evacuated ones included.
void Heap::evacuate()
{
auto& stats = *m_compaction_stats;
@@ -1417,12 +1417,6 @@ void Heap::evacuate()
Vector<HeapBlock*> blocks_kept_by_pins;
auto copy_start_ns = MonotonicTime::now().nanoseconds();
- // NB: The sweep let go of the evacuated blocks whose cells all died, and a block it let go of may have come back
- // since, which publishes it again without an evacuation.
- m_evacuated_blocks.remove_all_matching([this](HeapBlock* block) {
- auto const& descriptor = block_descriptor_for(block);
- return descriptor.heap != this || !descriptor.evacuation;
- });
// NB: The blocks of an allocator come one after another, see begin_evacuation().
for (size_t first_block_of_allocator = 0; first_block_of_allocator < m_evacuated_blocks.size();) {
auto& allocator = m_evacuated_blocks[first_block_of_allocator]->cell_allocator();
@@ -1435,12 +1429,19 @@ void Heap::evacuate()
for (size_t i = exchange(first_block_of_allocator, end); i < end; ++i) {
auto& block = *m_evacuated_blocks[i];
auto& descriptor = block_descriptor_for(&block);
+ // NB: The cells that stay are the marked ones that do not move. The allocated cells that are not marked died,
+ // and the sweep frees them.
+ size_t staying_cells = 0;
if (count_by_type || !allocator.descriptor().is_movable()) {
for_each_allocated_cell(block, [&](Cell* cell) {
- if (!allocator.descriptor().is_movable())
+ if (!is_marked(descriptor, cell))
+ return;
+ 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)
+ ++staying_cells;
+ } else if (auto reason = FFI::rust_gc_evacuation_pin_reason(m_evacuation, cell); reason != FFI::PinReason::Unpinned) {
stats.pinned_by_type.ensure(class_name_of(*cell))[reason == FFI::PinReason::Root ? CompactionStats::ByValueRoot : CompactionStats::ByValueEdge].add(cell_size);
+ }
});
}
if (allocator.descriptor().is_movable()) {
@@ -1455,21 +1456,21 @@ void Heap::evacuate()
auto& by_root = stats.pinned[CompactionStats::ByValueRoot];
by_root.cells += pinned.by_root;
by_root.bytes += pinned.by_root * cell_size;
- if (pinned.by_edge + pinned.by_root > 0)
+ staying_cells = pinned.by_edge + pinned.by_root;
+ if (staying_cells > 0)
blocks_kept_by_pins.append(&block);
- // NB: Nothing allocates during a collection (see allocate_cell()), and the sweep freed every cell that
- // marking did not reach, so every cell left in the block is marked, and either moves or is pinned.
- // A cell allocated after marking would hold slots that marking never recorded.
- VERIFY(block.allocated_cell_count() == count + pinned.by_edge + pinned.by_root);
}
- clear_marks(descriptor);
+ if (staying_cells == 0)
+ ++stats.freed_blocks;
}
if (moves.is_empty())
continue;
- // NB: Every destination is taken before any cell moves, so no cell moves twice, and no old slot is free yet.
+ // NB: Every destination is taken before any cell moves, so no cell moves twice, and no old slot is free yet. A
+ // cell that moves is marked where it goes, so that the sweep that follows keeps it.
for (auto& cell_move : moves) {
cell_move.to = allocate_destination_for_moved_cell(allocator);
+ set_marked(cell_move.to);
stats.moved.add(cell_size);
}
FFI::rust_gc_evacuation_forward_cells(m_evacuation, moves.data(), moves.size(), cell_size);
@@ -1507,12 +1508,6 @@ void Heap::evacuate()
// rust_gc_compaction_select().
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;
- }
stats.release_us = (MonotonicTime::now().nanoseconds() - release_start_ns) / 1000;
}
@@ -2170,15 +2165,11 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure
{
ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.sweep_block_iteration_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.
- 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)) { }
+ while (FFI::rust_gc_allocator_sweep_next_block(rust_allocator, false, &stats)) { }
collected_cells += stats.collected_cells;
live_cells += stats.live_cells;
collected_cell_bytes += stats.collected_cells * allocator.cell_size();
diff --git a/Libraries/LibGC/Rust/src/allocator.rs b/Libraries/LibGC/Rust/src/allocator.rs
index 1eb535e8e6e..20a1852f5c7 100644
--- a/Libraries/LibGC/Rust/src/allocator.rs
+++ b/Libraries/LibGC/Rust/src/allocator.rs
@@ -427,17 +427,12 @@ impl Allocator {
}
// 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);
- }
+ self.clear_marks(block);
if live == 0 {
self.release_block(block, defer_decommit);
stats.freed_blocks += 1;
@@ -462,9 +457,13 @@ impl Allocator {
}
/// 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.
+ /// one of the cells left in it dies. The cells left are the marked ones that did not move: the others died, and the
+ /// sweep that follows frees them.
fn keep_cells_pinned(&self, block: usize) {
- let kept = *self.allocated(block);
+ let mut kept = *self.allocated(block);
+ for (word, kept_word) in kept.iter_mut().enumerate() {
+ *kept_word &= self.mark_word(block, word).load(Ordering::Relaxed);
+ }
self.lists.borrow_mut().kept_by_pins.insert(block, kept);
// SAFETY: As in make_usable().
unsafe { (*self.descriptor(block)).kept_by_pins = true };
@@ -478,8 +477,8 @@ impl Allocator {
.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.
+ /// Takes a free 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 the sweep that follows the collection lists them again.
fn allocate_destination(&self) -> usize {
loop {
let last = self.lists.borrow().usable.last().copied();
@@ -510,26 +509,6 @@ impl Allocator {
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 {
@@ -711,20 +690,6 @@ pub unsafe extern "C" fn rust_gc_allocator_release_moved_cell(allocator: *const
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.
@@ -982,35 +947,70 @@ mod tests {
}
#[test]
- fn evacuation_moves_cells_out_of_blocks_it_then_lets_go_of() {
+ fn evacuation_moves_cells_out_of_blocks_that_the_sweep_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.
+ // Half of each block survives a first collection, which leaves room for the cells that move.
let survivors: Vec<usize> = cells.iter().copied().step_by(2).collect();
heap.collect(&survivors);
+ heap.freed.borrow_mut().clear();
+
+ // The next collection marks half of the survivors, and evacuates the first block before it sweeps.
+ heap.allocator().give_back_local_free_cells();
+ let marked: Vec<usize> = survivors.iter().copied().step_by(2).collect();
+ for &cell in &marked {
+ heap.mark(cell);
+ }
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 mut destinations = Vec::new();
+ for &cell in marked.iter().filter(|&&cell| cell & !(BLOCK_SIZE - 1) == evacuated) {
let destination = heap.allocator().allocate_destination();
assert_ne!(destination & !(BLOCK_SIZE - 1), evacuated);
+ // NB: The dead cells are not swept yet, so their slots are not free to take.
+ assert!(!survivors.contains(&destination));
+ heap.mark(destination);
+ destinations.push(destination);
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));
+
+ // The sweep destroys the cells that died, in the evacuated block too, and lets go of the block.
+ heap.allocator().start_sweep();
+ let mut stats = SweepStats::default();
+ while heap.allocator().sweep_next_block(true, &mut stats) {}
+ assert_eq!(stats.freed_blocks, 1);
assert_eq!(heap.allocator().lists.borrow().blocks.len(), 1);
+ let freed = heap.freed.borrow();
+ let destroyed: Vec<usize> = freed
+ .iter()
+ .filter(|&&(_, destroy)| destroy)
+ .map(|&(cell, _)| cell)
+ .collect();
+ assert_eq!(destroyed.len(), survivors.len() - marked.len());
+ assert!(
+ destroyed
+ .iter()
+ .all(|cell| !marked.contains(cell) && !destinations.contains(cell))
+ );
+ assert_eq!(heap.allocated_count(), marked.len());
}
#[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);
+ // NB: A collection keeps the cells that pins left in a block it evacuated once they moved, before it sweeps.
+ for &cell in &cells {
+ heap.mark(cell);
+ }
heap.allocator().keep_cells_pinned(block);
+ heap.collect(&cells);
// 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());
diff --git a/Libraries/LibGC/Rust/src/evacuation.rs b/Libraries/LibGC/Rust/src/evacuation.rs
index 2b511d48d6d..48ec55c07f4 100644
--- a/Libraries/LibGC/Rust/src/evacuation.rs
+++ b/Libraries/LibGC/Rust/src/evacuation.rs
@@ -12,11 +12,16 @@
//! records the slots that point into evacuated blocks. After marking, a cell of an evacuated block moves if its
//! allocator is movable and nothing pinned it. Each cell that moves gets a free slot of another block first, then every
//! recorded slot that points at one is rewritten where it is, and only then is each cell copied bytewise to its new
-//! slot, with its slots rewritten already, and its old slot freed without being destroyed.
+//! slot, with its slots rewritten already, and its old slot freed without being destroyed. Cells move before the sweep,
+//! so a dead cell's slot is never taken, and the sweep that follows destroys the dead cells once the collection is
+//! over.
//!
-//! The collector finds slots only in cells, in the heap region: a slot elsewhere, like in malloc memory that a cell
-//! owns, could be freed or moved by the finalizers and destructors that run between marking and moving, so the visit
-//! of such a slot pins its target instead.
+//! The collector finds slots in cells, in the heap region: a slot elsewhere, like in malloc memory that a cell owns,
+//! could be freed or moved by the finalizers and sweep callbacks that run between marking and moving, so the visit of
+//! such a slot pins its target instead. The exception is memory that a live cell owns and that nothing frees, moves or
+//! writes until the collection is over, whose values the cell visits as owned values (see
+//! rust_gc_marker_visit_owned_values()). Holders of weak references, whose memory changes as they forget the cells that
+//! died, hand their slots over once they did, before cells move (see rust_gc_evacuation_record_slot()).
use core::ffi::c_void;
use core::ptr::NonNull;
@@ -134,10 +139,6 @@ impl RecordedSlots {
unsafe { ak::slice_from_raw_parts(chunk.pointer.as_ptr(), length) }
})
}
-
- fn len(&self) -> usize {
- self.slices().map(<[RecordedSlot]>::len).sum()
- }
}
/// Why a cell of an evacuated block stays where it is.
@@ -222,12 +223,16 @@ pub enum SlotKind {
const SLOT_KIND_MASK: usize = 3;
/// The address of a slot that marking recorded, with its kind in the low bits. Every slot is at least 4-aligned.
+///
+/// NB: The address is kept as an integer, so that a slot costs one word in the chunks that markers fill on several
+/// threads. Recording a slot exposes its provenance, which pointer() picks up again.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecordedSlot(usize);
impl RecordedSlot {
#[inline(always)]
- pub fn new(address: usize, kind: SlotKind) -> Self {
+ pub fn new(slot: *const u8, kind: SlotKind) -> Self {
+ let address = slot.expose_provenance();
debug_assert!(address & SLOT_KIND_MASK == 0, "slots are at least 4-aligned");
Self(address | kind as usize)
}
@@ -236,6 +241,11 @@ impl RecordedSlot {
self.0 & !SLOT_KIND_MASK
}
+ /// The slot, with the provenance that new() exposed.
+ fn pointer<T>(self) -> *mut T {
+ core::ptr::with_exposed_provenance_mut(self.address())
+ }
+
pub fn kind(self) -> SlotKind {
match self.0 & SLOT_KIND_MASK {
0 => SlotKind::Member,
@@ -266,6 +276,8 @@ pub struct EvacuationSet {
blocks: Vec<usize>,
evacuations: MappedArray<Evacuation>,
slots: Vec<RecordedSlots>,
+ /// The slots handed over after marking, see rust_gc_evacuation_record_slot().
+ slots_recorded_after_marking: RecordedSlots,
}
impl EvacuationSet {
@@ -280,6 +292,14 @@ impl EvacuationSet {
(address.wrapping_sub(self.layout.heap_region_base) as u64) <= self.layout.value_offset_mask
}
+ /// Every recorded slot, chunk by chunk.
+ fn all_slots(&self) -> impl Iterator<Item = &[RecordedSlot]> {
+ self.slots
+ .iter()
+ .chain(core::iter::once(&self.slots_recorded_after_marking))
+ .flat_map(RecordedSlots::slices)
+ }
+
/// The evacuation of the live block that `address` is in, with its descriptor.
#[inline(always)]
fn evacuation_of(&self, address: usize) -> Option<(&BlockDescriptor, &Evacuation)> {
@@ -296,6 +316,11 @@ impl EvacuationSet {
self.layout.heap_region_base + ((compressed.0 as usize) << COMPRESSED_POINTER_SHIFT)
}
+ /// A pointer to `address` in the heap region, whose provenance rust_gc_heap_region_init() exposed.
+ fn heap_region_pointer(address: usize) -> *mut u8 {
+ core::ptr::with_exposed_provenance_mut(address)
+ }
+
/// Where the cell that starts at `cell` moved to, if it moved.
#[inline(always)]
fn forwarding_address(&self, cell: usize) -> Option<usize> {
@@ -311,7 +336,8 @@ impl EvacuationSet {
///
/// # Safety
///
- /// The slot must be in a live cell that has not moved yet, and hold what its kind says.
+ /// The slot must be in a live cell that has not moved yet, or in memory that such a cell owns, and hold what its
+ /// kind says.
unsafe fn fix_up(&self, slot: RecordedSlot) -> bool {
let base = self.layout.heap_region_base;
let address = slot.address();
@@ -319,7 +345,7 @@ impl EvacuationSet {
unsafe {
match slot.kind() {
SlotKind::Member => {
- let slot = address as *mut u32;
+ let slot = slot.pointer::<u32>();
let compressed = slot.read();
if compressed == 0 {
return false;
@@ -330,7 +356,7 @@ impl EvacuationSet {
slot.write((to >> COMPRESSED_POINTER_SHIFT) as u32);
}
SlotKind::Value => {
- let slot = address as *mut u64;
+ let slot = slot.pointer::<u64>();
let value = slot.read();
if value & self.layout.value_is_cell_pattern != self.layout.value_is_cell_pattern {
return false;
@@ -342,8 +368,8 @@ impl EvacuationSet {
slot.write((value & !mask) | ((to - base) as u64 & mask));
}
SlotKind::InteriorPointer => {
- let slot = address as *mut usize;
- let pointer = slot.read();
+ let slot = slot.pointer::<*mut u8>();
+ let pointer = slot.read().addr();
let Some((descriptor, _)) = self.evacuation_of(pointer) else {
return false;
};
@@ -351,7 +377,7 @@ impl EvacuationSet {
let Some(to) = self.forwarding_address(cell) else {
return false;
};
- slot.write(to + (pointer - cell));
+ slot.write(Self::heap_region_pointer(to).wrapping_add(pointer - cell));
}
SlotKind::SelfPointer => {
let Some((descriptor, _)) = self.evacuation_of(address) else {
@@ -361,13 +387,13 @@ impl EvacuationSet {
let Some(to) = self.forwarding_address(holder) else {
return false;
};
- let slot = address as *mut usize;
- let pointer = slot.read();
+ let slot = slot.pointer::<*mut u8>();
+ let pointer = slot.read().addr();
// NB: The pointer may point one past the holder's fields, at the start of the next cell.
if pointer.wrapping_sub(holder) > descriptor.cell_size as usize {
return false;
}
- slot.write(to + (pointer - holder));
+ slot.write(Self::heap_region_pointer(to).wrapping_add(pointer - holder));
}
}
}
@@ -390,6 +416,7 @@ pub extern "C" fn rust_gc_evacuation_create(
// SAFETY: All zeros is an evacuation that pinned and moved nothing.
evacuations: unsafe { MappedArray::new_zeroed(block_count) },
slots: Vec::new(),
+ slots_recorded_after_marking: RecordedSlots::default(),
}))
}
@@ -577,9 +604,10 @@ pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet
// SAFETY: The caller passes a live set.
let set = unsafe { &*set };
let mut rewritten = 0;
- for slots in set.slots.iter().flat_map(RecordedSlots::slices) {
+ for slots in set.all_slots() {
for &slot in slots {
- // SAFETY: Marking recorded the slot in a live cell, which the caller makes sure is still live and where it was.
+ // SAFETY: The slot was recorded in a live cell or in memory that one owns, which the caller makes sure is
+ // still live and where it was.
if unsafe { set.fix_up(slot) } {
rewritten += 1;
}
@@ -597,7 +625,55 @@ pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_gc_evacuation_recorded_slot_count(set: *const EvacuationSet) -> usize {
// SAFETY: The caller passes a live set.
- unsafe { &*set }.slots.iter().map(RecordedSlots::len).sum()
+ unsafe { &*set }.all_slots().map(<[RecordedSlot]>::len).sum()
+}
+
+/// What a slot handed to rust_gc_evacuation_record_slot() holds.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RecordedSlotKind {
+ /// A NaN-boxed value, which may hold a cell.
+ Value = 0,
+ /// A raw pointer to the start of a cell, or null.
+ CellPointer = 1,
+}
+
+/// Records a slot that marking did not visit, which the collection then rewrites like the slots marking recorded, for
+/// holders that keep cells without keeping them alive or in place: the keys of weak maps, the targets of weak
+/// references. They hand over the slots of the cells that survived once they forgot those that died.
+///
+/// # Safety
+///
+/// `set` must be live, and its marking done. The slot must hold what `kind` says, in memory that nothing frees, moves or
+/// writes until the collection is over, and its cell, if it has one, must be marked.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_record_slot(
+ set: *mut EvacuationSet,
+ slot: *const c_void,
+ kind: RecordedSlotKind,
+) {
+ // SAFETY: The caller passes a live set, and a slot that holds what its kind says.
+ let set = unsafe { &mut *set };
+ let (target, kind) = match kind {
+ RecordedSlotKind::Value => {
+ // SAFETY: See above.
+ let value = unsafe { slot.cast::<u64>().read() };
+ if value & set.layout.value_is_cell_pattern != set.layout.value_is_cell_pattern {
+ return;
+ }
+ (
+ set.layout.heap_region_base + (value & set.layout.value_offset_mask) as usize,
+ SlotKind::Value,
+ )
+ }
+ // SAFETY: See above.
+ RecordedSlotKind::CellPointer => (unsafe { slot.cast::<usize>().read() }, SlotKind::InteriorPointer),
+ };
+ // NB: Only slots of cells that may move need rewriting.
+ if set.evacuation_of(target).is_some() {
+ set.slots_recorded_after_marking
+ .push(RecordedSlot::new(slot.cast(), kind));
+ }
}
/// Where the cell at `cell` moved to, or null if it did not move.
@@ -613,7 +689,7 @@ pub unsafe extern "C" fn rust_gc_evacuation_forwarding_address(
// SAFETY: The caller passes a live set.
let set = unsafe { &*set };
match set.forwarding_address(cell.addr()) {
- Some(address) => core::ptr::without_provenance_mut(address),
+ Some(address) => EvacuationSet::heap_region_pointer(address).cast(),
None => core::ptr::null_mut(),
}
}
@@ -622,22 +698,24 @@ pub unsafe extern "C" fn rust_gc_evacuation_forwarding_address(
///
/// # Safety
///
-/// `set` must be live, and nothing may use it after.
+/// `set` must be live, and nothing may use it after. Its blocks must all still be its heap's, which they are until
+/// the sweep that follows the collection, the only thing that lets go of a block.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_gc_evacuation_destroy(set: *mut EvacuationSet) {
// SAFETY: The caller passes a live set, which it gives up.
let set = unsafe { Box::from_raw(set) };
for (index, block) in set.blocks.iter().enumerate() {
- // SAFETY: Every block of the set was in the region, where descriptors stay backed by memory.
+ // SAFETY: The block is still the heap's, as the caller makes sure, so only this thread changes its descriptor.
let descriptor = unsafe { descriptor_for(set.layout.heap_region_base, *block) };
- // NB: A block that went away and came back since has a fresh descriptor, which may not be cleared.
- if descriptor
- .evacuation()
- .is_some_and(|current| core::ptr::eq(current, set.evacuations.get(index)))
- {
- // SAFETY: The block is in the region, and no marker runs.
- unsafe { set_evacuation_of_block(set.layout.heap_region_base, *block, core::ptr::null_mut()) };
- }
+ assert!(
+ descriptor.heap() == set.heap
+ && descriptor
+ .evacuation()
+ .is_some_and(|current| core::ptr::eq(current, set.evacuations.get(index))),
+ "an evacuated block stays its heap's until its evacuation ends"
+ );
+ // SAFETY: The block is the heap's, and no marker runs.
+ unsafe { set_evacuation_of_block(set.layout.heap_region_base, *block, core::ptr::null_mut()) };
}
}
diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rs
index f3646b10256..7fc48341186 100644
--- a/Libraries/LibGC/Rust/src/lib.rs
+++ b/Libraries/LibGC/Rust/src/lib.rs
@@ -30,10 +30,10 @@ mod sanitizer;
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,
+ rust_gc_allocator_create, rust_gc_allocator_destroy, 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::{
@@ -44,11 +44,11 @@ pub use block_pool::{
};
pub use compaction::{CompactionCandidate, CompactionSelection, rust_gc_compaction_select};
pub use evacuation::{
- CellMove, EvacuationLayout, EvacuationSet, PinReason, PinnedCells, rust_gc_evacuation_add_block,
+ CellMove, EvacuationLayout, EvacuationSet, PinReason, PinnedCells, RecordedSlotKind, rust_gc_evacuation_add_block,
rust_gc_evacuation_cells_to_move, rust_gc_evacuation_create, rust_gc_evacuation_destroy,
rust_gc_evacuation_fix_up_slots, rust_gc_evacuation_forward_cells, rust_gc_evacuation_forwarding_address,
- rust_gc_evacuation_move_cells, rust_gc_evacuation_pin_reason, rust_gc_evacuation_recorded_slot_count,
- rust_gc_evacuation_will_move,
+ rust_gc_evacuation_move_cells, rust_gc_evacuation_pin_reason, rust_gc_evacuation_record_slot,
+ rust_gc_evacuation_recorded_slot_count, rust_gc_evacuation_will_move,
};
pub use identity_hash::{
IDENTITY_HASH_HASHED, IDENTITY_HASH_MOVED, IDENTITY_HASH_STATE_OFFSET, IdentityHashes, rust_gc_cell_identity_hash,
@@ -57,6 +57,6 @@ pub use identity_hash::{
pub use marker::{
MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell,
rust_gc_marker_release_unused_helper_memory, 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,
+ rust_gc_marker_visit_ephemeron_without_pinning, rust_gc_marker_visit_interior_pointer, rust_gc_marker_visit_member,
+ rust_gc_marker_visit_owned_values, 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.rs
index b5e393d14dc..4db82ec048a 100644
--- a/Libraries/LibGC/Rust/src/marker.rs
+++ b/Libraries/LibGC/Rust/src/marker.rs
@@ -125,12 +125,21 @@ pub struct Marker {
visitor: Cell<*mut c_void>,
marked_cell_bytes: Box<[Cell<usize>]>,
marked_external_bytes: Box<[Cell<usize>]>,
- /// Ephemerons whose key was not marked yet when they were visited, as (key, value).
- pending_ephemerons: UnsafeCell<Vec<(u32, u32)>>,
+ /// Ephemerons whose key was not marked yet when they were visited.
+ pending_ephemerons: UnsafeCell<Vec<PendingEphemeron>>,
/// The slots that point into evacuated blocks, which a collection that moves cells rewrites.
recorded_slots: UnsafeCell<RecordedSlots>,
}
+/// An ephemeron whose key was not marked yet when it was visited, with compressed addresses.
+#[derive(Clone, Copy)]
+struct PendingEphemeron {
+ key: u32,
+ value: u32,
+ /// Whether marking the value pins it, see Marker::visit_ephemeron().
+ pins_value: bool,
+}
+
impl Job<'_> {
#[inline(always)]
fn compress(&self, address: usize) -> u32 {
@@ -207,6 +216,13 @@ impl Marker {
/// cell that is pinned already, as roots are before marking starts, stays where it is, so its slots are left out.
#[inline(always)]
fn mark_through_slot(&self, slot: RecordedSlot, address: usize) {
+ self.mark_through_slot_of::<false>(slot, address);
+ }
+
+ /// Like mark_through_slot(), and if `SLOT_IS_OWNED`, the slot is recorded even outside the heap region, as it is in
+ /// memory that a live cell owns and that stays where it is until the collection is over (see visit_owned_values()).
+ #[inline(always)]
+ fn mark_through_slot_of<const SLOT_IS_OWNED: bool>(&self, slot: RecordedSlot, address: usize) {
let job = self.job();
let Some((_, descriptor)) = job.descriptor_in_domain(address) else {
return;
@@ -214,7 +230,7 @@ impl Marker {
if let Some(evacuation) = descriptor.evacuation()
&& !evacuation.is_pinned(descriptor, address)
{
- if job.is_in_heap_region(slot.address()) {
+ if SLOT_IS_OWNED || job.is_in_heap_region(slot.address()) {
// SAFETY: Only this marker's thread touches its recorded slots while it marks.
unsafe { &mut *self.recorded_slots.get() }.push(slot);
} else {
@@ -236,16 +252,16 @@ impl Marker {
}
/// Records a slot that points into the cell that holds it, if that cell's block is evacuated.
- fn visit_self_pointer(&self, slot: usize) {
+ fn visit_self_pointer(&self, slot: *const usize) {
let job = self.job();
- if !job.is_in_heap_region(slot) {
+ if !job.is_in_heap_region(slot.addr()) {
return;
}
- if let Some((_, descriptor)) = job.descriptor_in_domain(slot)
+ if let Some((_, descriptor)) = job.descriptor_in_domain(slot.addr())
&& descriptor.evacuation().is_some()
{
// SAFETY: Only this marker's thread touches its recorded slots while it marks.
- unsafe { &mut *self.recorded_slots.get() }.push(RecordedSlot::new(slot, SlotKind::SelfPointer));
+ unsafe { &mut *self.recorded_slots.get() }.push(RecordedSlot::new(slot.cast(), SlotKind::SelfPointer));
}
}
@@ -281,12 +297,25 @@ impl Marker {
/// Marks the cells of the values in `values`, which are slots.
#[inline(always)]
fn visit_values(&self, values: &[u64]) {
+ self.visit_values_of::<false>(values);
+ }
+
+ /// Marks the cells of the values in `values`, which are slots in memory outside the heap region that the cell
+ /// being visited owns, and that nothing frees, moves or writes until the collection is over. A collection rewrites
+ /// them where they are, like slots in cells, rather than pinning their cells.
+ #[inline(always)]
+ fn visit_owned_values(&self, values: &[u64]) {
+ self.visit_values_of::<true>(values);
+ }
+
+ #[inline(always)]
+ fn visit_values_of<const SLOTS_ARE_OWNED: bool>(&self, values: &[u64]) {
let layout = &self.job().layout;
for value in values {
let bits = *value;
if bits & layout.value_is_cell_pattern == layout.value_is_cell_pattern {
- self.mark_through_slot(
- RecordedSlot::new(core::ptr::from_ref(value).addr(), SlotKind::Value),
+ self.mark_through_slot_of::<SLOTS_ARE_OWNED>(
+ RecordedSlot::new(core::ptr::from_ref(value).cast(), SlotKind::Value),
layout.heap_region_base + (bits & layout.value_offset_mask) as usize,
);
}
@@ -300,25 +329,44 @@ impl Marker {
let compressed = unsafe { slot.read() };
if compressed != 0 {
let address = self.job().decompress(compressed);
- self.mark_through_slot(RecordedSlot::new(slot.addr(), SlotKind::Member), address);
+ self.mark_through_slot(RecordedSlot::new(slot.cast(), SlotKind::Member), address);
}
}
- fn visit_ephemeron(&self, key: usize, value: usize) {
+ /// Marks `value` once `key` is marked. If `pins`, the key and the value stay where they are, as their holder visits
+ /// them by value. Otherwise the holder hands their slots to the collection once marking is done (see
+ /// rust_gc_evacuation_record_slot()), and only cells pinned by others stay where they are.
+ fn visit_ephemeron(&self, key: usize, value: usize, pins: bool) {
let job = self.job();
- // NB: The key of an ephemeron, like that of a WeakMap entry, is held weakly in a way the collector cannot
- // update, so it stays where it is.
- self.pin(key);
+ if pins {
+ self.pin(key);
+ }
// NB: Keys outside the heaps being collected are never marked here, so their values stay reachable.
if job
.descriptor_in_domain(key)
.is_none_or(|(_, descriptor)| descriptor.is_marked(key))
{
- self.mark(value);
+ self.mark_value_of_ephemeron(value, pins);
return;
}
// SAFETY: Only this marker's thread touches its pending ephemerons while it marks.
- unsafe { &mut *self.pending_ephemerons.get() }.push((job.compress(key), job.compress(value)));
+ unsafe { &mut *self.pending_ephemerons.get() }.push(PendingEphemeron {
+ key: job.compress(key),
+ value: job.compress(value),
+ pins_value: pins,
+ });
+ }
+
+ /// Marks the value of an ephemeron whose key is marked, and returns whether that was news.
+ fn mark_value_of_ephemeron(&self, value: usize, pins: bool) -> bool {
+ if pins {
+ return self.mark(value);
+ }
+ let job = self.job();
+ let Some((_, descriptor)) = job.descriptor_in_domain(value) else {
+ return false;
+ };
+ self.mark_in(descriptor, value)
}
fn find_work(&self) -> Option<u32> {
@@ -372,8 +420,10 @@ impl Marker {
job.owner_queue.push(compressed);
return;
}
+ // NB: Cell addresses are in the heap region, whose provenance rust_gc_heap_region_init() exposed.
+ let cell = core::ptr::with_exposed_provenance_mut::<c_void>(address);
// SAFETY: The cell is in a block of a heap being collected, which no thread changes meanwhile.
- if unsafe { ((address + layout.cell_state_offset as usize) as *const u8).read() } != layout.cell_state_live {
+ if unsafe { cell.cast::<u8>().add(layout.cell_state_offset as usize).read() } != layout.cell_state_live {
return;
}
let marked_cell_bytes = &self.marked_cell_bytes[heap_index];
@@ -394,13 +444,13 @@ impl Marker {
};
if let Some(external_memory_size) = external_memory_size {
// SAFETY: The cell is a live cell of the type whose function this is.
- let size = unsafe { external_memory_size(address as *const c_void) };
+ let size = unsafe { external_memory_size(cell) };
let marked_external_bytes = &self.marked_external_bytes[heap_index];
marked_external_bytes.set(marked_external_bytes.get().saturating_add(size));
}
// SAFETY: The cell is a live cell of the type whose function this is, which may be visited on this thread, and
// the visitor is this marker's.
- unsafe { visit_edges(address as *mut c_void, self.visitor.get()) };
+ unsafe { visit_edges(cell, self.visitor.get()) };
}
/// Visits the edges of at most `limit` cells, on this thread alone, and returns whether no cell was left.
@@ -456,12 +506,12 @@ impl Marker {
for marker in &job.markers {
// SAFETY: Every other marker waits at the barrier or is done.
let pending = unsafe { &mut *marker.pending_ephemerons.get() };
- pending.retain(|&(key, value)| {
- let key = job.decompress(key);
+ pending.retain(|ephemeron| {
+ let key = job.decompress(ephemeron.key);
if !job.descriptor(key).is_marked(key) {
return true;
}
- marked_a_value |= self.mark(job.decompress(value));
+ marked_a_value |= self.mark_value_of_ephemeron(job.decompress(ephemeron.value), ephemeron.pins_value);
false
});
}
@@ -540,6 +590,19 @@ pub unsafe extern "C" fn rust_gc_marker_visit_values(marker: *mut Marker, values
unsafe { &*marker }.visit_values(unsafe { ak::slice_from_raw_parts(values, count) });
}
+/// Marks the cells of the NaN-boxed values a visitor visits in memory that the cell being visited owns outside the heap
+/// region, as slots the collector can update.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_values(), and the values must be in memory that the cell being visited owns, which
+/// nothing frees, moves or writes until the collection is over: no finalizer, destructor or sweep callback touches it.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_owned_values(marker: *mut Marker, values: *const u64, count: usize) {
+ // SAFETY: The caller passes a live marker and count values.
+ unsafe { &*marker }.visit_owned_values(unsafe { ak::slice_from_raw_parts(values, count) });
+}
+
/// Marks the cell that the compressed pointer at `slot` points to, if it is not null, as a slot the collector can update.
///
/// # Safety
@@ -563,7 +626,7 @@ pub unsafe extern "C" fn rust_gc_marker_visit_interior_pointer(
cell: *const c_void,
) {
// SAFETY: The caller passes a live marker.
- unsafe { &*marker }.mark_through_slot(RecordedSlot::new(slot.addr(), SlotKind::InteriorPointer), cell.addr());
+ unsafe { &*marker }.mark_through_slot(RecordedSlot::new(slot.cast(), SlotKind::InteriorPointer), cell.addr());
}
/// Notes that the pointer at `slot` points into the cell that holds the slot, which keeps it right if that cell moves.
@@ -575,7 +638,7 @@ pub unsafe extern "C" fn rust_gc_marker_visit_interior_pointer(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_gc_marker_visit_self_pointer(marker: *mut Marker, slot: *const usize) {
// SAFETY: The caller passes a live marker.
- unsafe { &*marker }.visit_self_pointer(slot.addr());
+ unsafe { &*marker }.visit_self_pointer(slot);
}
/// Keeps `cell` from moving, without marking it, for a weak reference the collector cannot update.
@@ -589,7 +652,8 @@ pub unsafe extern "C" fn rust_gc_marker_pin_cell(marker: *mut Marker, cell: *con
unsafe { &*marker }.pin(cell.addr());
}
-/// Marks a cell that is reachable only while `key` is, such as a WeakMap entry's value, once the key is marked.
+/// Marks a cell that is reachable only while `key` is, such as a WeakMap entry's value, once the key is marked. Both
+/// stay where they are, as their holder visits them by value.
///
/// # Safety
///
@@ -597,7 +661,23 @@ pub unsafe extern "C" fn rust_gc_marker_pin_cell(marker: *mut Marker, cell: *con
#[unsafe(no_mangle)]
pub unsafe extern "C" fn rust_gc_marker_visit_ephemeron(marker: *mut Marker, key: *const c_void, value: *const c_void) {
// SAFETY: The caller passes a live marker.
- unsafe { &*marker }.visit_ephemeron(key.addr(), value.addr());
+ unsafe { &*marker }.visit_ephemeron(key.addr(), value.addr(), true);
+}
+
+/// Like rust_gc_marker_visit_ephemeron(), for a holder that keeps neither cell from moving: once marking is done, and
+/// before cells move, it hands the slots of the key and the value of each entry that survived to the collection.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_ephemeron().
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_ephemeron_without_pinning(
+ marker: *mut Marker,
+ key: *const c_void,
+ value: *const c_void,
+) {
+ // SAFETY: The caller passes a live marker.
+ unsafe { &*marker }.visit_ephemeron(key.addr(), value.addr(), false);
}
/// Has the threads that help mark give back the memory they no longer use, see Pool::release_unused_memory().
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 35f4aaac966..2943708f26f 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -1087,6 +1087,19 @@ impl<'a, 'z> GraphBuilder<'a, 'z> {
else {
return Ok(None);
};
+ // NB: The code embeds the bound values as constants, so it lists the cells among them, which keeps them
+ // where they are.
+ let bound_values = core::iter::once(forwarded.bound_this).chain(bound_arguments.iter().copied());
+ let (pattern, base, mask) = (
+ self.runtime.shifted_is_cell_pattern,
+ self.runtime.heap_region_base,
+ self.runtime.heap_region_offset_mask,
+ );
+ for bits in bound_values.filter(|bits| bits & pattern == pattern) {
+ if !self.graph.embedded_cells.contains(&CellId(base + (bits & mask))) {
+ self.graph.embedded_cells.push(CellId(base + (bits & mask)));
+ }
+ }
InlinedCallSite {
callee: Some(*callee),
expected_callee: Some(bound_function),
diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rs
index 5fe175ac313..65e80e2dc6c 100644
--- a/Libraries/LibJS/Rust/src/gc/capi.rs
+++ b/Libraries/LibJS/Rust/src/gc/capi.rs
@@ -6,7 +6,7 @@
//! Declarations of Libraries/LibGC/CAPI.h.
-use core::ffi::{c_char, c_void};
+use core::ffi::{c_char, c_int, c_void};
use super::class::CellTypeInfo;
@@ -46,6 +46,9 @@ pub struct GCWeakImpl {
pub const GC_COLLECTION_TYPE_COLLECT_GARBAGE: i32 = 0;
pub const GC_COLLECTION_TYPE_COLLECT_EVERYTHING: i32 = 1;
+pub const GC_RECORDED_SLOT_VALUE: c_int = 0;
+pub const GC_RECORDED_SLOT_CELL_POINTER: c_int = 1;
+
#[derive(Default)]
#[repr(C)]
pub struct GCLayout {
@@ -143,13 +146,16 @@ unsafe extern "C" {
pub fn gc_cell_is_marked(cell: *const c_void) -> bool;
pub fn gc_cell_will_move(cell: *const c_void) -> bool;
pub safe fn gc_heap_is_moving_cells(heap: &GCHeap) -> bool;
+ pub fn gc_heap_record_slot(heap: *mut GCHeap, slot: *const c_void, kind: c_int);
pub fn gc_cell_identity_hash(cell: *const c_void) -> u32;
pub fn gc_marker_visit_cell(marker: *mut GCMarker, cell: *mut c_void);
pub fn gc_marker_visit_values(marker: *mut GCMarker, values: *const u64, count: usize);
+ pub fn gc_marker_visit_owned_values(marker: *mut GCMarker, values: *const u64, count: usize);
pub fn gc_marker_visit_member(marker: *mut GCMarker, slot: *const u32);
pub fn gc_marker_visit_interior_pointer(marker: *mut GCMarker, slot: *const usize, cell: *mut c_void);
pub fn gc_marker_visit_self_pointer(marker: *mut GCMarker, slot: *const usize);
pub fn gc_marker_pin_cell(marker: *mut GCMarker, cell: *const c_void);
+ pub fn gc_marker_visit_ephemeron_without_pinning(marker: *mut GCMarker, key: *mut c_void, value: *mut c_void);
pub fn gc_root_create(cell: *mut c_void) -> *mut GCRoot;
pub fn gc_root_destroy(root: *mut GCRoot);
diff --git a/Libraries/LibJS/Rust/src/gc/sweep.rs b/Libraries/LibJS/Rust/src/gc/sweep.rs
index bdcf2ef39e0..621d2e7bdda 100644
--- a/Libraries/LibJS/Rust/src/gc/sweep.rs
+++ b/Libraries/LibJS/Rust/src/gc/sweep.rs
@@ -10,6 +10,7 @@
use crate::gc::capi;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, CellState, Gc};
+use crate::layout::value::Value;
use crate::runtime::finalization_registry::FinalizationRegistry;
/// What code can do while the sweep callback of a collection runs: tell which cells died, which only means anything
@@ -41,6 +42,46 @@ impl<'vm> Sweep<'vm> {
self.is_dead(cell) || unsafe { capi::gc_cell_will_move(cell.as_ptr().cast()) }
}
+ /// Whether the collection may move cells, which is when what holds cells without visiting their slots hands over
+ /// the slots of those that survived (see record_slot()).
+ pub fn moves_cells(&self) -> bool {
+ capi::gc_heap_is_moving_cells(self.0.heap().handle())
+ }
+
+ /// Has the collection rewrite `slot`, which holds a cell that survived it, if the cell moves, as it rewrites the slots
+ /// marking visited. For what holds cells without keeping them alive or in place, like the keys of a weak map, once
+ /// it forgot the cells that died.
+ ///
+ /// # Safety
+ ///
+ /// Nothing may free, move or write the slot until the collection is over.
+ pub unsafe fn record_slot<T>(&self, slot: &Gc<T>) {
+ // SAFETY: The slot holds a pointer to a cell that survived, and the caller vouches for its memory.
+ unsafe {
+ capi::gc_heap_record_slot(
+ self.0.heap().raw(),
+ core::ptr::from_ref(slot).cast(),
+ capi::GC_RECORDED_SLOT_CELL_POINTER,
+ );
+ }
+ }
+
+ /// Like record_slot(), for a slot that holds a value, which may be a cell that survived the collection.
+ ///
+ /// # Safety
+ ///
+ /// As for record_slot().
+ pub unsafe fn record_value_slot(&self, slot: &Value) {
+ // SAFETY: The slot holds a value, and the caller vouches for its memory.
+ unsafe {
+ capi::gc_heap_record_slot(
+ self.0.heap().raw(),
+ core::ptr::from_ref(slot).cast(),
+ capi::GC_RECORDED_SLOT_VALUE,
+ );
+ }
+ }
+
/// Hands `finalization_registry` to HostEnqueueFinalizationRegistryCleanupJob once the collection is over.
pub fn enqueue_finalization_registry_cleanup_job(&self, finalization_registry: Gc<FinalizationRegistry>) {
self.0
diff --git a/Libraries/LibJS/Rust/src/gc/visitor.rs b/Libraries/LibJS/Rust/src/gc/visitor.rs
index 33c4d3291df..32d0f26e76f 100644
--- a/Libraries/LibJS/Rust/src/gc/visitor.rs
+++ b/Libraries/LibJS/Rust/src/gc/visitor.rs
@@ -8,9 +8,10 @@ use core::cell::Cell;
use core::ptr::NonNull;
use super::capi::{
- GCMarker, GCVisitor, gc_marker_pin_cell, gc_marker_visit_cell, gc_marker_visit_interior_pointer,
- gc_marker_visit_member, gc_marker_visit_self_pointer, gc_marker_visit_values, gc_visitor_visit_cell,
- gc_visitor_visit_ephemeron, gc_visitor_visit_values,
+ GCMarker, GCVisitor, gc_marker_pin_cell, gc_marker_visit_cell, gc_marker_visit_ephemeron_without_pinning,
+ gc_marker_visit_interior_pointer, gc_marker_visit_member, gc_marker_visit_owned_values,
+ gc_marker_visit_self_pointer, gc_marker_visit_values, gc_visitor_visit_cell, gc_visitor_visit_ephemeron,
+ gc_visitor_visit_values,
};
use crate::layout::cell::Gc;
use crate::layout::member::{Member, NullableMember};
@@ -127,11 +128,54 @@ impl Visitor {
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.
+ /// Visits values in memory that the cell being visited owns outside the heap, such as malloc storage, which a
+ /// collection that moves cells rewrites where they are rather than keeping their cells where they are.
+ ///
+ /// # Safety
+ ///
+ /// Nothing may free, move or write the values until the collection is over: no finalizer, destructor or sweep
+ /// callback may touch them.
+ pub unsafe fn visit_owned_values(&mut self, values: &[Value]) {
+ if let Some(marker) = self.marker() {
+ if !values.is_empty() {
+ // SAFETY: The marker is the visitor's, Value is a NaN-boxed u64, and the caller vouches for the memory.
+ unsafe { gc_marker_visit_owned_values(marker.as_ptr(), values.as_ptr().cast(), values.len()) };
+ }
+ return;
+ }
+ // 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. A collection that moves cells keeps both where they are.
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()) };
}
+
+ /// Visits a value that is reachable only while `key` is, such as a WeakMap entry's, without keeping either from
+ /// moving.
+ ///
+ /// # Safety
+ ///
+ /// If the entry survives a collection that moves cells, its holder must hand the slots of the key and the value to
+ /// Sweep::record_slot() and Sweep::record_value_slot().
+ pub unsafe fn visit_ephemeron_without_pinning<T>(&mut self, key: Gc<T>, value: &Value) {
+ let Some(marker) = self.marker() else {
+ self.visit_ephemeron(key, value);
+ return;
+ };
+ if value.is_cell() {
+ // SAFETY: The marker is the visitor's, and both are live cells.
+ unsafe {
+ gc_marker_visit_ephemeron_without_pinning(
+ marker.as_ptr(),
+ key.as_ptr().cast(),
+ value.as_cell().as_ptr().cast(),
+ );
+ }
+ }
+ }
}
/// A value that can reach cells, which it reports to the visitor.
diff --git a/Libraries/LibJS/Rust/src/layout/environment.rs b/Libraries/LibJS/Rust/src/layout/environment.rs
index 80eac8efdfc..4220f6e7030 100644
--- a/Libraries/LibJS/Rust/src/layout/environment.rs
+++ b/Libraries/LibJS/Rust/src/layout/environment.rs
@@ -37,8 +37,7 @@ const _: () = assert!(size_of::<Environment>() == 16);
#[repr(C)]
pub struct DeclarativeEnvironment {
pub base: Environment,
- /// The first binding value, in the cell or in a malloc allocation that has its capacity in front of the first
- /// value.
+ /// The first binding value, in the cell or in value storage (see runtime::value_storage).
pub binding_values: Cell<*mut Value>,
pub binding_count: Cell<u32>,
pub rare_data: NullableMember<DeclarativeEnvironmentRareData>,
diff --git a/Libraries/LibJS/Rust/src/runtime/bound_function.rs b/Libraries/LibJS/Rust/src/runtime/bound_function.rs
index 0fc57fe5047..fb88d0b7dea 100644
--- a/Libraries/LibJS/Rust/src/runtime/bound_function.rs
+++ b/Libraries/LibJS/Rust/src/runtime/bound_function.rs
@@ -11,10 +11,12 @@ use ak::Utf16String;
use libjs_runtime_macros::Trace;
use crate::gc::class::{GcCell, cast_ref, define_cell};
+use crate::gc::visitor::{Trace, Visitor};
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::execution_context::ExecutionContext;
use crate::layout::function_object::FUNCTION_LENGTH_AND_NAME_SLOTS;
+use crate::layout::member::Member;
use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::runtime::completion::ThrowCompletionOr;
@@ -29,9 +31,23 @@ pub struct BoundFunction {
/// OPTIMIZATION: The named properties of bound functions are "length" and "name".
#[gc(untraced = "the object traces its inline named storage")]
inline_named_storage: [Cell<Value>; FUNCTION_LENGTH_AND_NAME_SLOTS],
- bound_target_function: Cell<Gc<FunctionObject>>, // [[BoundTargetFunction]]
- bound_this: Cell<Value>, // [[BoundThis]]
- bound_arguments: OnceCell<Box<[Value]>>, // [[BoundArguments]]
+ bound_target_function: Member<FunctionObject>, // [[BoundTargetFunction]]
+ bound_this: Cell<Value>, // [[BoundThis]]
+ bound_arguments: BoundArguments, // [[BoundArguments]]
+}
+
+/// The bound arguments of a bound function, which never change once they are set.
+struct BoundArguments(OnceCell<Box<[Value]>>);
+
+// SAFETY: Visits every bound argument.
+unsafe impl Trace for BoundArguments {
+ fn trace(&self, visitor: &mut Visitor) {
+ if let Some(arguments) = self.0.get() {
+ // SAFETY: The arguments are the function's own, which nothing changes once they are set, and only its
+ // destructor frees.
+ unsafe { visitor.visit_owned_values(arguments) };
+ }
+ }
}
pub static BOUND_FUNCTION_METHODS: ObjectMethods = ObjectMethods {
@@ -128,14 +144,15 @@ impl BoundFunction {
let object = allocate_object(vm, |_| BoundFunction {
base,
inline_named_storage: [const { Cell::new(Value::UNDEFINED) }; FUNCTION_LENGTH_AND_NAME_SLOTS],
- bound_target_function: Cell::new(target_function),
+ bound_target_function: Member::new(target_function),
bound_this: Cell::new(bound_this),
- bound_arguments: OnceCell::new(),
+ bound_arguments: BoundArguments(OnceCell::new()),
});
// The caller keeps the bound arguments alive until the function that does holds them, and nothing allocates
// from the heap in between.
if object
.bound_arguments
+ .0
.set(bound_arguments.to_vec().into_boxed_slice())
.is_err()
{
@@ -174,6 +191,7 @@ impl BoundFunction {
pub fn bound_arguments(&self) -> &[Value] {
self.bound_arguments
+ .0
.get()
.expect("a bound function has its bound arguments")
}
diff --git a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
index 86a99b43b90..3eb1c485bd4 100644
--- a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
@@ -11,7 +11,6 @@
use core::cell::{Cell, RefCell};
use core::ops::Deref;
-use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
use std::collections::HashMap;
use ak::Utf16FlyString;
@@ -37,6 +36,7 @@ use crate::runtime::environment_shape::{EnvironmentShape, EnvironmentShapeCache}
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::module_environment::ModuleEnvironment;
+use crate::runtime::value_storage;
#[derive(Clone)]
pub struct Binding {
@@ -186,11 +186,9 @@ fn padded_binding_capacity(capacity: usize) -> usize {
4 + capacity + capacity / 4
}
-fn owned_binding_values_layout(capacity: usize) -> Layout {
- Layout::array::<u64>(capacity + 1).expect("the binding values fit in memory")
-}
-
-/// The binding values of an environment, which it keeps in its cell or in a malloc allocation.
+/// The binding values of an environment, which it keeps in its cell or in value storage (see value_storage), which is
+/// a ValueStorage cell unless there are too many values for one. A collection can rewrite the values in a cell where they
+/// are, so the cells they name can move, as with the properties of objects.
struct BindingValues<'a> {
environment: &'a DeclarativeEnvironment,
}
@@ -208,8 +206,8 @@ impl BindingValues<'_> {
if data.is_null() {
return 0;
}
- // SAFETY: A malloc allocation has its capacity in front of the first value.
- unsafe { data.cast::<u64>().sub(1).read() as usize }
+ // SAFETY: Binding values that are not in the environment's cell are value storage.
+ unsafe { value_storage::capacity(data) as usize }
}
fn is_empty(&self) -> bool {
@@ -252,14 +250,14 @@ impl BindingValues<'_> {
}
}
- /// Removes every value and frees the malloc allocation, if there is one.
+ /// Removes every value and frees the storage, if it is malloc storage.
fn clear(&self) {
self.environment.binding_count.set(0);
self.reallocate(0);
}
- /// Moves the values from the cell to a malloc allocation, with room for at least `needed_capacity` values and as
- /// much more as append() would make.
+ /// Moves the values from the cell to value storage, with room for at least `needed_capacity` values and as much more
+ /// as append() would make.
fn move_to_owned_storage(&self, needed_capacity: usize) {
self.reallocate(needed_capacity.max(padded_binding_capacity(self.size())));
}
@@ -268,37 +266,23 @@ impl BindingValues<'_> {
let size = self.size();
assert!(new_capacity >= size);
let old_data = self.environment.binding_values.get();
- let old_capacity = self.capacity();
let was_inline = self.environment.binding_values_are_inline();
let new_data = if new_capacity == 0 {
core::ptr::null_mut()
} else {
- let layout = owned_binding_values_layout(new_capacity);
- // SAFETY: The layout has a non-zero size.
- let allocation = unsafe { alloc(layout) }.cast::<u64>();
- if allocation.is_null() {
- handle_alloc_error(layout);
- }
- // SAFETY: The allocation has room for the capacity and `new_capacity` values, of which `size` come from the
- // old storage, which is another one.
- unsafe {
- allocation.write(new_capacity as u64);
- let new_data = allocation.add(1).cast::<Value>();
- if size != 0 {
- core::ptr::copy_nonoverlapping(old_data, new_data, size);
- }
- new_data
+ let capacity = u32::try_from(new_capacity).expect("the binding count fits in u32");
+ // NB: Allocating value storage never collects garbage, so the old values stay where they are meanwhile.
+ let new_data = value_storage::allocate(Vm::of_cell(self.environment).heap(), capacity, Value::UNDEFINED);
+ if size != 0 {
+ // SAFETY: The new storage has room for `new_capacity` values, of which `size` come from the old storage,
+ // which is other memory.
+ unsafe { core::ptr::copy_nonoverlapping(old_data, new_data, size) };
}
+ new_data
};
if !old_data.is_null() && !was_inline {
- // SAFETY: The old storage is a malloc allocation that this method made with this layout, with the capacity
- // in front of the first value.
- unsafe {
- dealloc(
- old_data.cast::<u64>().sub(1).cast(),
- owned_binding_values_layout(old_capacity),
- );
- }
+ // SAFETY: The old storage is value storage that this method allocated, which nothing uses any more.
+ unsafe { value_storage::deallocate(old_data) };
}
self.environment.binding_values.set(new_data);
self.environment.inline_binding_capacity.set(0);
@@ -313,13 +297,26 @@ unsafe impl Trace for DeclarativeEnvironment {
fn trace(&self, visitor: &mut Visitor) {
self.base.trace(visitor);
self.rare_data.trace(visitor);
+ let binding_values = self.binding_values.get();
+ // SAFETY: The first `binding_count` values are initialized, and nothing writes them while they are visited.
+ let values = unsafe { ak::slice_from_raw_parts(binding_values, self.binding_count.get() as usize) };
if self.binding_values_are_inline() {
visitor.visit_self_pointer(&self.binding_values);
+ visitor.visit_values(values);
+ } else if !binding_values.is_null() {
+ // SAFETY: Binding values that are not in the environment's cell are value storage.
+ match unsafe { value_storage::cell(binding_values) } {
+ Some(storage) => {
+ // NB: The pointer to the storage is visited as a slot, so that a collection that moves the
+ // environment or its storage cell keeps it pointing into it.
+ visitor.visit_interior_pointer(&self.binding_values, storage);
+ visitor.visit_values(values);
+ }
+ // SAFETY: Malloc storage is the environment's own, which only its own methods change, and only its
+ // finalizer frees.
+ None => unsafe { visitor.visit_owned_values(values) },
+ }
}
- // SAFETY: The first `binding_count` values are initialized, and nothing writes them while they are visited.
- visitor.visit_values(unsafe {
- ak::slice_from_raw_parts(self.binding_values.get(), self.binding_count.get() as usize)
- });
}
}
@@ -332,7 +329,7 @@ impl Finalize for DeclarativeEnvironment {
}
/// How many binding values the size classes of an environment class have room for after the fields of the class.
-/// Environments with more bindings keep them in malloc storage.
+/// Environments with more bindings keep them in value storage.
pub const INLINE_BINDING_CAPACITIES: [u8; 8] = [1, 2, 3, 4, 6, 8, 12, 16];
/// The cell sizes of the size classes of an environment class whose cells are `cell_size` bytes.
diff --git a/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs b/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
index 4037d2acb08..0ffad921b2f 100644
--- a/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
+++ b/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
@@ -34,16 +34,12 @@ struct FinalizationRecord {
struct FinalizationRecords(Vec<FinalizationRecord>);
// SAFETY: Visits the held value and the unregister token of every record. The targets are held weakly, and cleared in
-// remove_dead_cells() once they die.
+// remove_dead_cells() once they die, which also hands the slots of those that survived to a collection that moves cells.
unsafe impl Trace for FinalizationRecords {
fn trace(&self, visitor: &mut Visitor) {
for record in &self.0 {
record.held_value.trace(visitor);
record.unregister_token.trace(visitor);
- // NB: The collector cannot update a weak reference, so the target stays where it is.
- if let Some(target) = record.target {
- visitor.pin(target);
- }
}
}
}
@@ -168,11 +164,17 @@ impl FinalizationRegistry {
.downcast::<FinalizationRegistry>()
.expect("the weak container is a FinalizationRegistry");
let mut any_cells_were_removed = false;
+ let moves_cells = sweep.moves_cells();
for record in &mut finalization_registry.records.borrow_mut_in_sweep(sweep).0 {
- let Some(target) = record.target else {
+ let Some(target) = &record.target else {
continue;
};
- if !sweep.is_dead(target) {
+ if !sweep.is_dead(*target) {
+ if moves_cells {
+ // SAFETY: Only the registry's own methods change its records, and none runs until the collection
+ // is over.
+ unsafe { sweep.record_slot(target) };
+ }
continue;
}
record.target = None;
diff --git a/Libraries/LibJS/Rust/src/runtime/map.rs b/Libraries/LibJS/Rust/src/runtime/map.rs
index 944f7fca23f..6a3cccee8ea 100644
--- a/Libraries/LibJS/Rust/src/runtime/map.rs
+++ b/Libraries/LibJS/Rust/src/runtime/map.rs
@@ -5,9 +5,10 @@
*/
use core::cell::Cell;
+use core::hash::BuildHasher;
use core::ops::Deref;
-use hashbrown::HashMap;
+use hashbrown::HashTable;
use libjs_runtime_macros::Trace;
use crate::gc::class::{ExternalMemorySize, Finalize, GcCell, define_cell};
@@ -23,24 +24,37 @@ use crate::runtime::realm::Realm;
use crate::runtime::value_traits::ValueTraitsKey;
/// What a keyed collection keeps with each of its keys: a Map keeps a value, and a Set keeps nothing.
-pub(crate) trait StoredValue: Copy + Trace {
+pub(crate) trait StoredValue: Copy {
/// What the entry of a removed key holds.
const REMOVED: Self;
+
+ /// Visits the stored value, which is in the entries of its collection, see Storage::trace().
+ ///
+ /// # Safety
+ ///
+ /// As for Visitor::visit_owned_values().
+ unsafe fn trace_owned(&self, visitor: &mut Visitor);
}
impl StoredValue for Value {
const REMOVED: Self = Value::UNDEFINED;
+
+ unsafe fn trace_owned(&self, visitor: &mut Visitor) {
+ // SAFETY: Forwarded from the caller.
+ unsafe { visitor.visit_owned_values(core::slice::from_ref(self)) };
+ }
}
/// What a Set keeps with each of its values.
-#[derive(Clone, Copy, Trace)]
+#[derive(Clone, Copy)]
pub(crate) struct NoValue;
impl StoredValue for NoValue {
const REMOVED: Self = NoValue;
+
+ unsafe fn trace_owned(&self, _: &mut Visitor) {}
}
-#[derive(Trace)]
struct StoredEntry<V: StoredValue> {
key: Value,
value: V,
@@ -58,7 +72,43 @@ impl<V: StoredValue> StoredEntry<V> {
/// memory than the entries themselves.
const MAX_ENTRY_COUNT_WITHOUT_INDICES: usize = 8;
-type Indices = HashMap<ValueTraitsKey, usize, foldhash::fast::RandomState>;
+/// The positions of the live entries of a collection, found by the hashes of their keys. The keys themselves are only in
+/// the entries, where a collection that moves cells rewrites them.
+#[derive(Default)]
+struct Indices {
+ positions: HashTable<usize>,
+ hasher: foldhash::fast::RandomState,
+}
+
+impl Indices {
+ fn hash(&self, key: Value) -> u64 {
+ self.hasher.hash_one(ValueTraitsKey(key))
+ }
+
+ fn find<V: StoredValue>(&self, entries: &[StoredEntry<V>], key: Value) -> Option<usize> {
+ let key = ValueTraitsKey(key);
+ self.positions
+ .find(self.hash(key.0), |&index| ValueTraitsKey(entries[index].key) == key)
+ .copied()
+ }
+
+ fn insert<V: StoredValue>(&mut self, entries: &[StoredEntry<V>], key: Value, index: usize) {
+ let hash = self.hash(key);
+ let hasher = &self.hasher;
+ self.positions.insert_unique(hash, index, |&index| {
+ hasher.hash_one(ValueTraitsKey(entries[index].key))
+ });
+ }
+
+ fn remove<V: StoredValue>(&mut self, entries: &[StoredEntry<V>], key: Value) -> Option<usize> {
+ let key = ValueTraitsKey(key);
+ let entry = self
+ .positions
+ .find_entry(self.hash(key.0), |&index| ValueTraitsKey(entries[index].key) == key)
+ .ok()?;
+ Some(entry.remove().0)
+ }
+}
/// The entries of a Map or a Set.
pub(crate) struct Storage<V: StoredValue> {
@@ -72,10 +122,19 @@ pub(crate) struct Storage<V: StoredValue> {
generation: u64,
}
-// SAFETY: Visits the key and value of every entry. The keys of the indices are the keys of the live entries.
+// SAFETY: Visits the key and value of every entry, which are all the cells the storage holds.
unsafe impl<V: StoredValue> Trace for Storage<V> {
fn trace(&self, visitor: &mut Visitor) {
- self.entries.trace(visitor);
+ // NB: The entries are visited as owned values, so that a collection that moves their cells rewrites them where
+ // they are. Only the collection's own methods change them, and no finalizer, destructor or sweep callback
+ // calls those.
+ for entry in &self.entries {
+ // SAFETY: See above.
+ unsafe {
+ visitor.visit_owned_values(core::slice::from_ref(&entry.key));
+ entry.value.trace_owned(visitor);
+ }
+ }
}
}
@@ -134,7 +193,7 @@ impl<V: StoredValue> Storage<V> {
pub(crate) fn external_memory_size(&self) -> usize {
let indices_size = self.indices.as_ref().map_or(0, |indices| {
- size_of::<Indices>().saturating_add(indices.allocation_size())
+ size_of::<Indices>().saturating_add(indices.positions.allocation_size())
});
(self.entries.capacity() * size_of::<StoredEntry<V>>()).saturating_add(indices_size)
}
@@ -152,7 +211,7 @@ impl<V: StoredValue> Storage<V> {
pub(crate) fn remove(&mut self, key: Value) -> bool {
let index = match &mut self.indices {
- Some(indices) => indices.remove(&ValueTraitsKey(key)),
+ Some(indices) => indices.remove(&self.entries, key),
None => self.index_of(key),
};
let Some(index) = index else {
@@ -185,12 +244,11 @@ impl<V: StoredValue> Storage<V> {
pub(crate) fn set(&mut self, key: Value, value: V) {
if let Some(indices) = &mut self.indices {
- let new_index = self.entries.len();
- let index = *indices.entry(ValueTraitsKey(key)).or_insert(new_index);
- if index != new_index {
+ if let Some(index) = indices.find(&self.entries, key) {
self.entries[index].value = value;
return;
}
+ indices.insert(&self.entries, key, self.entries.len());
} else {
if let Some(index) = self.index_of(key) {
self.entries[index].value = value;
@@ -205,7 +263,7 @@ impl<V: StoredValue> Storage<V> {
self.indices
.as_mut()
.expect("the indices were just built")
- .insert(ValueTraitsKey(key), new_index);
+ .insert(&self.entries, key, new_index);
}
}
}
@@ -222,7 +280,7 @@ impl<V: StoredValue> Storage<V> {
fn index_of(&self, key: Value) -> Option<usize> {
let key = ValueTraitsKey(key);
match &self.indices {
- Some(indices) => indices.get(&key).copied(),
+ Some(indices) => indices.find(&self.entries, key.0),
None => {
// NB: The key of a removed entry is the empty value, so an empty key would find a removed entry.
assert!(!key.0.is_empty());
@@ -252,16 +310,16 @@ impl<V: StoredValue> Storage<V> {
}
fn build_indices(&mut self) {
- // NB: The indices hold keys, so they are built in place, where the entries keep those keys alive.
- let indices = self.indices.insert(Box::new(Indices::with_capacity_and_hasher(
- self.entries.len() + 1,
- Default::default(),
- )));
+ let mut indices = Box::new(Indices::default());
+ indices
+ .positions
+ .reserve(self.entries.len() + 1, |_| unreachable!("the table is empty"));
for (index, entry) in self.entries.iter().enumerate() {
if !entry.is_removed() {
- indices.insert(ValueTraitsKey(entry.key), index);
+ indices.insert(&self.entries, entry.key, index);
}
}
+ self.indices = Some(indices);
}
fn index_of_first_entry_not_inserted_before(&self, insertion_id: u64) -> usize {
@@ -290,7 +348,7 @@ impl<V: StoredValue> Storage<V> {
new_entry_count += 1;
}
self.entries.truncate(new_entry_count);
- for index in indices.values_mut() {
+ for index in &mut indices.positions {
*index = new_indices[*index];
}
} else {
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 7d9fa5b288f..5aba45fc93d 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -333,7 +333,14 @@ unsafe impl Trace for Object {
debug_assert!(property_count <= self.named_storage_capacity() as usize);
// SAFETY: The storage holds at least one slot per property of the shape, and nothing writes it during
// a collection.
- visitor.visit_values(unsafe { ak::slice_from_raw_parts(named_properties, property_count) });
+ let values = unsafe { ak::slice_from_raw_parts(named_properties, property_count) };
+ if self.has_flag(object_flag::HAS_MALLOC_NAMED_STORAGE) {
+ // SAFETY: Malloc storage is the object's own, which only the object's own methods change, and only its
+ // destructor frees.
+ unsafe { visitor.visit_owned_values(values) };
+ } else {
+ visitor.visit_values(values);
+ }
}
// NB: The pointers to the storage are visited as slots, so that a collection that moves the object or its
// storage cell keeps them pointing into it.
@@ -4037,7 +4044,14 @@ impl Object {
return;
}
// SAFETY: The count is within the elements buffer, and nothing writes it during a collection.
- visitor.visit_values(unsafe { ak::slice_from_raw_parts(self.indexed_elements.get(), count as usize) });
+ let values = unsafe { ak::slice_from_raw_parts(self.indexed_elements.get(), count as usize) };
+ if self.has_flag(object_flag::HAS_MALLOC_INDEXED_STORAGE) {
+ // SAFETY: Malloc storage is the object's own, which only the object's own methods change, and only its
+ // destructor frees.
+ unsafe { visitor.visit_owned_values(values) };
+ } else {
+ visitor.visit_values(values);
+ }
}
/// Storage for at least `capacity` elements, all empty.
diff --git a/Libraries/LibJS/Rust/src/runtime/weak_map.rs b/Libraries/LibJS/Rust/src/runtime/weak_map.rs
index 6dd92577342..1eaec7c3f2c 100644
--- a/Libraries/LibJS/Rust/src/runtime/weak_map.rs
+++ b/Libraries/LibJS/Rust/src/runtime/weak_map.rs
@@ -28,11 +28,13 @@ use crate::runtime::realm::Realm;
struct WeakMapValues(HashMap<Gc<CellHeader>, Value, foldhash::fast::RandomState>);
// 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.
+// remove_dead_cells() once they die, together with their values, which then also hands the slots of the
+// surviving entries to a collection that moves cells.
unsafe impl Trace for WeakMapValues {
fn trace(&self, visitor: &mut Visitor) {
for (&key, value) in &self.0 {
- visitor.visit_ephemeron(key, value);
+ // SAFETY: See above.
+ unsafe { visitor.visit_ephemeron_without_pinning(key, value) };
}
}
}
@@ -135,10 +137,17 @@ impl WeakMap {
.as_gc()
.downcast::<WeakMap>()
.expect("the weak container is a WeakMap");
- weak_map
- .values
- .borrow_mut_in_sweep(sweep)
- .0
- .retain(|&key, _| !sweep.is_dead(key));
+ let mut values = weak_map.values.borrow_mut_in_sweep(sweep);
+ values.0.retain(|&key, _| !sweep.is_dead(key));
+ if sweep.moves_cells() {
+ // NB: The keys are hashed by their identity hash, which moves do not change, so the table stays as it is.
+ for (key, value) in &values.0 {
+ // SAFETY: Only the map's own methods change the table, and none runs until the collection is over.
+ unsafe {
+ sweep.record_slot(key);
+ sweep.record_value_slot(value);
+ }
+ }
+ }
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/weak_ref.rs b/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
index a6ca04a5964..ff7cc260661 100644
--- a/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
+++ b/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
@@ -31,7 +31,7 @@ pub struct WeakRef {
// SAFETY: Visits the target while the execution generation it was last used in is current, which keeps it alive for
// the rest of the job as AddToKeptObjects does. Otherwise it is held weakly, and remove_dead_cells() forgets it once
-// it dies.
+// it dies, or hands its slot to a collection that moves cells.
unsafe impl Trace for WeakRef {
fn trace(&self, visitor: &mut Visitor) {
self.base.trace(visitor);
@@ -40,9 +40,6 @@ unsafe impl Trace for WeakRef {
let execution_generation = unsafe { self.vm_execution_generation.as_ref() }.get();
if execution_generation == self.last_execution_generation.get() {
self.value.trace(visitor);
- } else if self.value.get().is_cell() {
- // NB: The collector cannot update a weak reference, so the target stays where it is.
- visitor.pin(self.value.get().as_cell());
}
}
}
@@ -98,10 +95,13 @@ impl WeakRef {
.expect("the weak container is a WeakRef");
let value = weak_ref.value.get();
let is_alive = value.is_empty() || !sweep.is_dead(value.as_cell());
- if is_alive {
+ if !is_alive {
+ weak_ref.value.set(Value::EMPTY);
return;
}
-
- weak_ref.value.set(Value::EMPTY);
+ if sweep.moves_cells() {
+ // SAFETY: The slot is in the WeakRef, which nothing changes until the collection is over.
+ unsafe { sweep.record_value_slot(&*weak_ref.value.as_ptr()) };
+ }
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/weak_set.rs b/Libraries/LibJS/Rust/src/runtime/weak_set.rs
index cd8c47c20bc..383c2db825a 100644
--- a/Libraries/LibJS/Rust/src/runtime/weak_set.rs
+++ b/Libraries/LibJS/Rust/src/runtime/weak_set.rs
@@ -26,14 +26,10 @@ use crate::runtime::realm::Realm;
#[derive(Default)]
struct WeakSetValues(HashSet<Gc<CellHeader>, foldhash::fast::RandomState>);
-// SAFETY: Visits nothing, since every value is held weakly and removed in remove_dead_cells() once it dies. The values
-// are hashed by address, so they are pinned.
+// SAFETY: Visits nothing, since every value is held weakly and removed in remove_dead_cells() once it dies, which then
+// also hands the slots of the surviving values to a collection that moves cells.
unsafe impl Trace for WeakSetValues {
- fn trace(&self, visitor: &mut Visitor) {
- for &value in &self.0 {
- visitor.pin(value);
- }
- }
+ fn trace(&self, _: &mut Visitor) {}
}
#[repr(C)]
@@ -130,10 +126,14 @@ impl WeakSet {
.as_gc()
.downcast::<WeakSet>()
.expect("the weak container is a WeakSet");
- weak_set
- .values
- .borrow_mut_in_sweep(sweep)
- .0
- .retain(|&cell| !sweep.is_dead(cell));
+ let mut values = weak_set.values.borrow_mut_in_sweep(sweep);
+ values.0.retain(|&cell| !sweep.is_dead(cell));
+ if sweep.moves_cells() {
+ // NB: The values are hashed by their identity hash, which moves do not change, so the table stays as it is.
+ for value in &values.0 {
+ // SAFETY: Only the set's own methods change the table, and none runs until the collection is over.
+ unsafe { sweep.record_slot(value) };
+ }
+ }
}
}
diff --git a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
index 7048fc53c60..a7263c05a35 100644
--- a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <LibGC/Heap.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentLoadEventDelayer.h>
@@ -46,26 +45,11 @@ DocumentLoadEventDelayer& DocumentLoadEventDelayer::operator=(DocumentLoadEventD
DocumentLoadEventDelayer::~DocumentLoadEventDelayer()
{
- if (!m_document)
- return;
- auto release = [](GC::Weak<Document> const& document, DocumentLoadEventDelayerReason reason) {
- if (!document || document->has_been_destroyed())
- return;
- if (reason == DocumentLoadEventDelayerReason::StyleSheetRequest)
- document->decrement_number_of_pending_style_sheet_requests({});
- document->decrement_number_of_things_delaying_the_load_event({});
- };
- // NB: Telling the document may allocate, see Document::schedule_html_parser_end_check(), which no destructor may
- // do while a collection is in progress, as a collection that moves cells destroys the cells that died before
- // it is over. Tell it once the collection is over.
- auto& heap = m_document->heap();
- if (heap.is_marking_for_collection()) {
- heap.enqueue_post_gc_task([release, document = m_document, reason = m_reason] {
- release(document, reason);
- });
- return;
+ if (m_document && !m_document->has_been_destroyed()) {
+ if (m_reason == DocumentLoadEventDelayerReason::StyleSheetRequest)
+ m_document->decrement_number_of_pending_style_sheet_requests({});
+ m_document->decrement_number_of_things_delaying_the_load_event({});
}
- release(m_document, m_reason);
}
}
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 0094494d21d..31883e52cea 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -210,20 +210,8 @@ struct HTMLMediaElement::RemoteFetchData {
if (stream)
stream->set_data_request_callback(nullptr);
- if (!fetch_controller)
- return;
- // NB: Stopping the fetch allocates, which no destructor may do while a collection is in progress, as a
- // collection that moves cells destroys the cells that died before it is over. Stop it once the
- // collection is over.
- auto& heap = fetch_controller->heap();
- if (heap.is_marking_for_collection()) {
- heap.enqueue_post_gc_task([fetch_controller = fetch_controller] {
- if (fetch_controller)
- fetch_controller->stop_fetch();
- });
- return;
- }
- fetch_controller->stop_fetch();
+ if (fetch_controller)
+ fetch_controller->stop_fetch();
}
};
diff --git a/Tests/LibJS/Runtime/gc-moving-cells.js b/Tests/LibJS/Runtime/gc-moving-cells.js
index 3a0abe31ac1..906c1afdc28 100644
--- a/Tests/LibJS/Runtime/gc-moving-cells.js
+++ b/Tests/LibJS/Runtime/gc-moving-cells.js
@@ -13,6 +13,12 @@ const holder = {
})(),
};
holder.counter();
+// An environment with this many bindings keeps their values outside its cell.
+const wideBindingCount = 40;
+holder.wide = new Function(
+ `let ${Array.from({ length: wideBindingCount }, (_, i) => `b${i} = { v: ${i} }`).join(", ")};` +
+ `return () => [${Array.from({ length: wideBindingCount }, (_, i) => `b${i}`).join(", ")}];`
+)();
holder.rope = "x".repeat(30) + "y".repeat(30);
holder.substring = holder.rope.substring(25, 35);
holder.flat = String(holder.rope.length) + "!";
@@ -26,12 +32,69 @@ const before = {
hashed: addressOf(holder.hashed),
hash: identityHashOf(holder.hashed),
counter: addressOf(holder.counter),
+ wideBinding: addressOf(holder.wide()[wideBindingCount - 1]),
rope: addressOf(holder.rope),
};
const map = new Map([[holder.mapKey, "map value"]]);
+
+// The entries of maps and sets, the elements of arrays too large for a storage cell, the values of environments with
+// more bindings than fit in one, and the target and arguments of bound functions are all slots the collector can
+// rewrite, so their cells move too.
+const entryCount = 40;
+const bigMap = new Map();
+const bigSet = new Set();
+for (let i = 0; i < entryCount; ++i) {
+ bigMap.set({ k: i }, { v: i });
+ bigSet.add({ s: i });
+}
+const smallSet = new Set([{ s: "only" }]);
+const hugeArray = Array.from({ length: 2000 }, (_, i) => ({ e: i }));
+const hugeBindingCount = 1500;
+const huge = new Function(
+ `let ${Array.from({ length: hugeBindingCount }, (_, i) => `h${i} = { v: ${i} }`).join(", ")};` +
+ `return () => h${hugeBindingCount - 1};`
+)();
+const bound = function (a, b) {
+ return [this.t, a.x, b];
+}.bind({ t: "this" }, { x: "argument" });
+const movedBefore = {
+ mapKey: addressOf(bigMap.keys().next().value),
+ mapValue: addressOf(bigMap.values().next().value),
+ setValue: addressOf(bigSet.values().next().value),
+ smallSetValue: addressOf(smallSet.values().next().value),
+ hugeElement: addressOf(hugeArray[1999]),
+ hugeBinding: addressOf(huge()),
+};
const weakMap = new WeakMap([[holder.weakMapKey, "weak map value"]]);
+// Weak collections hand the slots of the cells that survive to the collector once they forgot the dead ones, so their
+// keys, values and targets move too.
+const weakHolder = {
+ key: {},
+ primitiveKey: {},
+ setValue: {},
+ refTarget: {},
+ registryTarget: {},
+ registryToken: {},
+};
+const weakValueMap = new WeakMap([
+ [weakHolder.key, { value: "weak value" }],
+ [weakHolder.primitiveKey, 42],
+]);
+const weakSet = new WeakSet([weakHolder.setValue]);
+const weakRef = new WeakRef(weakHolder.refTarget);
+const registry = new FinalizationRegistry(() => {});
+registry.register(weakHolder.registryTarget, "held", weakHolder.registryToken);
+const weakBefore = {
+ key: addressOf(weakHolder.key),
+ primitiveKey: addressOf(weakHolder.primitiveKey),
+ value: addressOf(weakValueMap.get(weakHolder.key)),
+ setValue: addressOf(weakHolder.setValue),
+ refTarget: addressOf(weakHolder.refTarget),
+ registryTarget: addressOf(weakHolder.registryTarget),
+};
+
runAfterMovingCollection(() => {
test("objects with inline storage keep their properties when they move", () => {
expect(addressOf(holder.small)).not.toBe(before.small);
@@ -68,6 +131,12 @@ runAfterMovingCollection(() => {
expect(holder.counter()).toBe(3);
});
+ test("environments with many bindings keep their values when the values move", () => {
+ const values = holder.wide();
+ expect(addressOf(values[wideBindingCount - 1])).not.toBe(before.wideBinding);
+ expect(values.map(value => value.v)).toEqual(Array.from({ length: wideBindingCount }, (_, i) => i));
+ });
+
test("strings keep their contents when they move", () => {
expect(addressOf(holder.rope)).not.toBe(before.rope);
expect(holder.rope).toBe("x".repeat(30) + "y".repeat(30));
@@ -80,6 +149,55 @@ runAfterMovingCollection(() => {
expect(weakMap.get(holder.weakMapKey)).toBe("weak map value");
expect(map.has({})).toBeFalse();
});
+
+ test("map and set entries move, and keep their order and lookups", () => {
+ const keys = [...bigMap.keys()];
+ expect(addressOf(keys[0])).not.toBe(movedBefore.mapKey);
+ expect(addressOf(bigMap.get(keys[0]))).not.toBe(movedBefore.mapValue);
+ expect(keys.map(key => key.k)).toEqual(Array.from({ length: entryCount }, (_, i) => i));
+ for (const key of keys) expect(bigMap.get(key).v).toBe(key.k);
+ const values = [...bigSet];
+ expect(addressOf(values[0])).not.toBe(movedBefore.setValue);
+ for (const value of values) expect(bigSet.has(value)).toBeTrue();
+ expect(values.map(value => value.s)).toEqual(Array.from({ length: entryCount }, (_, i) => i));
+ bigMap.delete(keys[0]);
+ expect(bigMap.has(keys[0])).toBeFalse();
+ expect(bigMap.size).toBe(entryCount - 1);
+ const [only] = smallSet;
+ expect(addressOf(only)).not.toBe(movedBefore.smallSetValue);
+ expect(smallSet.has(only)).toBeTrue();
+ });
+
+ test("elements and bindings in storage too large for a cell move", () => {
+ expect(addressOf(hugeArray[1999])).not.toBe(movedBefore.hugeElement);
+ expect(hugeArray[1999].e).toBe(1999);
+ expect(addressOf(huge())).not.toBe(movedBefore.hugeBinding);
+ expect(huge().v).toBe(hugeBindingCount - 1);
+ });
+
+ test("bound functions keep their target, this and arguments", () => {
+ expect(bound(2)).toEqual(["this", "argument", 2]);
+ });
+
+ test("weak map keys and values move, and keep their lookups", () => {
+ expect(addressOf(weakHolder.key)).not.toBe(weakBefore.key);
+ expect(addressOf(weakHolder.primitiveKey)).not.toBe(weakBefore.primitiveKey);
+ expect(addressOf(weakValueMap.get(weakHolder.key))).not.toBe(weakBefore.value);
+ expect(weakValueMap.get(weakHolder.key).value).toBe("weak value");
+ expect(weakValueMap.get(weakHolder.primitiveKey)).toBe(42);
+ expect(weakValueMap.has({})).toBeFalse();
+ expect(weakValueMap.delete(weakHolder.primitiveKey)).toBeTrue();
+ expect(weakValueMap.has(weakHolder.primitiveKey)).toBeFalse();
+ });
+
+ test("weak set values, weak ref targets and finalization registry targets move", () => {
+ expect(addressOf(weakHolder.setValue)).not.toBe(weakBefore.setValue);
+ expect(weakSet.has(weakHolder.setValue)).toBeTrue();
+ expect(addressOf(weakHolder.refTarget)).not.toBe(weakBefore.refTarget);
+ expect(weakRef.deref()).toBe(weakHolder.refTarget);
+ expect(addressOf(weakHolder.registryTarget)).not.toBe(weakBefore.registryTarget);
+ expect(registry.unregister(weakHolder.registryToken)).toBeTrue();
+ });
});
runAfterMovingCollection(() => {