Skip to content

Truly independent web browser

LibGC+LibJS+LibWeb: Add identity hashes and a mover for Rust cells

Andreas Kling81790a02cb2e
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cpp
index 85b948cf2e2..bdd839d40ae 100644
--- a/Libraries/LibGC/CAPI.cpp
+++ b/Libraries/LibGC/CAPI.cpp
@@ -83,9 +83,13 @@ public:
struct CAPI {
static_assert(offsetof(ForeignCell, m_word_owned_by_the_foreign_implementation) == 0);
- static_assert(offsetof(ForeignCell, m_unused_header_byte) == offsetof(Cell, m_unused_header_byte));
+ static_assert(offsetof(ForeignCell, m_identity_hash_state) == offsetof(Cell, m_identity_hash_state));
static_assert(offsetof(ForeignCell, m_state) == offsetof(Cell, m_state));
static_assert(offsetof(ForeignCell, m_cell_kind) == offsetof(Cell, m_cell_kind));
+ static_assert(offsetof(Cell, m_identity_hash_state) == IdentityHashState::offset);
+ static_assert(IdentityHashState::offset == FFI::IDENTITY_HASH_STATE_OFFSET);
+ static_assert(IdentityHashState::hashed == FFI::IDENTITY_HASH_HASHED);
+ static_assert(IdentityHashState::moved == FFI::IDENTITY_HASH_MOVED);
static void get_layout(GCLayout& layout)
{
@@ -110,6 +114,9 @@ struct CAPI {
.heap_region_offset_mask = HEAP_REGION_OFFSET_MASK,
.primitive_storage_cage_offset_mask = PrimitiveStorage::cage_offset_mask,
.visitor_marker_offset = static_cast<uint32_t>(Cell::Visitor::marker_offset()),
+ .identity_hash_state_offset = FFI::IDENTITY_HASH_STATE_OFFSET,
+ .identity_hash_hashed = FFI::IDENTITY_HASH_HASHED,
+ .identity_hash_moved = FFI::IDENTITY_HASH_MOVED,
};
}
@@ -146,6 +153,12 @@ struct CAPI {
collect_when_deferrals_end = &heap.m_should_gc_when_deferral_ends;
}
static StackInfo const& stack_info(Heap const& heap) { return heap.m_stack_info; }
+ static FFI::IdentityHashes** identity_hashes(Heap& heap) { return &heap.m_identity_hashes; }
+ static bool will_move(Cell const& cell)
+ {
+ auto* evacuation = cell.heap().m_evacuation;
+ return evacuation && FFI::rust_gc_evacuation_will_move(evacuation, &cell);
+ }
};
}
@@ -190,6 +203,13 @@ static bool store_resized_primitive_storage(PrimitiveStorage const& storage, Err
extern "C" {
+// Where a heap keeps the identity hashes of the cells that moved, for LibGC's Rust core.
+void** gc_heap_identity_hashes(void* heap);
+void** gc_heap_identity_hashes(void* heap)
+{
+ return reinterpret_cast<void**>(CAPI::identity_hashes(*static_cast<Heap*>(heap)));
+}
+
void gc_get_layout(GCLayout* layout)
{
CAPI::get_layout(*layout);
@@ -230,6 +250,16 @@ void gc_heap_collect_garbage(GCHeap* heap, int collection_type, bool print_repor
as_heap(heap).collect_garbage(type, print_report);
}
+void gc_heap_collect_garbage_without_scanning_the_stack(GCHeap* heap)
+{
+ as_heap(heap).collect_garbage_without_scanning_the_stack();
+}
+
+bool gc_heap_moves_everything(void)
+{
+ return Heap::moves_everything();
+}
+
bool gc_heap_is_collecting_everything(GCHeap const* heap)
{
return as_heap(heap).is_collecting_everything();
@@ -328,6 +358,11 @@ void gc_allocator_set_traced_on_owner_thread_only(GCAllocator* allocator)
reinterpret_cast<CAPICellAllocator*>(allocator)->set_trace_thread(TraceThread::OwnerThreadOnly);
}
+void gc_allocator_set_movable(GCAllocator* allocator)
+{
+ reinterpret_cast<CAPICellAllocator*>(allocator)->set_movable();
+}
+
GCCell* gc_heap_allocate_cell(GCHeap* heap, GCAllocator* allocator)
{
auto& descriptor = *reinterpret_cast<CAPICellAllocator*>(allocator);
@@ -367,6 +402,21 @@ bool gc_cell_is_marked(GCCell const* cell)
return GC::is_marked(cell);
}
+bool gc_cell_will_move(GCCell const* cell)
+{
+ return CAPI::will_move(*reinterpret_cast<Cell const*>(cell));
+}
+
+bool gc_heap_is_moving_cells(GCHeap const* heap)
+{
+ return as_heap(heap).is_moving_cells();
+}
+
+uint32_t gc_cell_identity_hash(GCCell const* cell)
+{
+ return FFI::rust_gc_cell_identity_hash(heap_region_base(), cell);
+}
+
GCRoot* gc_root_create(GCCell* cell)
{
return reinterpret_cast<GCRoot*>(new Root<Cell>(from_gc_cell(cell)));
@@ -438,6 +488,26 @@ 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_member(GCMarker* marker, uint32_t const* slot)
+{
+ FFI::rust_gc_marker_visit_member(reinterpret_cast<FFI::Marker*>(marker), slot);
+}
+
+void gc_marker_visit_interior_pointer(GCMarker* marker, uintptr_t const* slot, GCCell* cell)
+{
+ FFI::rust_gc_marker_visit_interior_pointer(reinterpret_cast<FFI::Marker*>(marker), slot, cell);
+}
+
+void gc_marker_visit_self_pointer(GCMarker* marker, uintptr_t const* slot)
+{
+ FFI::rust_gc_marker_visit_self_pointer(reinterpret_cast<FFI::Marker*>(marker), slot);
+}
+
+void gc_marker_pin_cell(GCMarker* marker, GCCell const* cell)
+{
+ FFI::rust_gc_marker_pin_cell(reinterpret_cast<FFI::Marker*>(marker), cell);
+}
+
bool gc_primitive_storage_allocate(size_t size, bool zero_fill, GCPrimitiveStorageHandle* out_handle, GCPrimitiveStorageLayout* out_layout)
{
auto& storage = PrimitiveStorage::the();
diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.h
index 78b4342daca..1b7db05f32c 100644
--- a/Libraries/LibGC/CAPI.h
+++ b/Libraries/LibGC/CAPI.h
@@ -101,6 +101,10 @@ typedef struct GCLayout {
// Where a GCVisitor keeps a pointer to the marker it marks for, which is null in visitors that do not mark. Code that
// visits can hand cells to the marker directly, with gc_marker_visit_cell() and gc_marker_visit_values().
uint32_t visitor_marker_offset;
+ // Where a cell keeps the state of its identity hash, and the bits of that state (see gc_cell_identity_hash()).
+ uint32_t identity_hash_state_offset;
+ uint8_t identity_hash_hashed;
+ uint8_t identity_hash_moved;
} GCLayout;
GC_API void gc_get_layout(GCLayout*);
@@ -116,6 +120,11 @@ GC_API GCHeap* gc_heap_create(GCGatherRootsCallback, void* context, bool become_
// so their contexts must stay valid until this returns; nothing they allocate then is destroyed.
GC_API void gc_heap_destroy(GCHeap*);
GC_API void gc_heap_collect_garbage(GCHeap*, int collection_type, bool print_report);
+// Collects garbage without scanning the stack, so only the roots the heap knows of keep cells alive, and cells may move.
+// The caller must hold no cell that it did not root.
+GC_API void gc_heap_collect_garbage_without_scanning_the_stack(GCHeap*);
+// Whether LIBGC_MOVE_EVERYTHING is set, see Heap::moves_everything().
+GC_API bool gc_heap_moves_everything(void);
GC_API bool gc_heap_is_collecting_everything(GCHeap const*);
// Whether the heap gathers its roots and marks the live cells for a collection now, rather than for a graph dump.
GC_API bool gc_heap_is_marking_for_collection(GCHeap const*);
@@ -150,6 +159,14 @@ GC_API void gc_allocator_destroy(GCAllocator*);
// visit_edges() or external_memory_size() reach state that is not their own. It must be called before the allocator
// allocates a cell.
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.
+GC_API void gc_allocator_set_movable(GCAllocator*);
// Returns uninitialized storage for one cell.
GC_API GCCell* gc_heap_allocate_cell(GCHeap*, GCAllocator*);
@@ -187,6 +204,16 @@ GC_API GCCellTypeInfo const* gc_cell_type_info(GCCell const*);
// Whether the last collection marked the cell. Only meaningful from the end of marking until the cell is swept, as in a
// sweep callback.
GC_API bool gc_cell_is_marked(GCCell const*);
+// Whether the collection in progress moves the cell once marking is done, as a sweep callback may ask. A cache that keeps
+// cells by address without visiting them drops such a cell, as if it died.
+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*);
+// 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
+// call this only for cells whose "moved" bit is set.
+GC_API uint32_t gc_cell_identity_hash(GCCell const*);
GC_API GCRoot* gc_root_create(GCCell*);
GC_API void gc_root_destroy(GCRoot*);
@@ -207,8 +234,20 @@ GC_API void gc_visitor_visit_ephemeron(GCVisitor*, GCCell* key, uint64_t const*
// The marker a marking GCVisitor points to (see GCLayout::visitor_marker_offset), which these hand cells to directly.
typedef struct GCMarker GCMarker;
+// Visits the cell by value, which keeps it from moving.
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 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);
+// Visits a cell that the pointer in the slot points into, past its start, like the values of storage a cell keeps.
+GC_API void gc_marker_visit_interior_pointer(GCMarker*, uintptr_t const* slot, GCCell* cell);
+// Notes a pointer in the slot to somewhere in the cell that holds it, up to one past its end, which a collection that
+// moves the cell keeps pointing into the copy.
+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*);
// 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/Cell.cpp b/Libraries/LibGC/Cell.cpp
index 27490de2c0e..667aa77ea55 100644
--- a/Libraries/LibGC/Cell.cpp
+++ b/Libraries/LibGC/Cell.cpp
@@ -41,8 +41,14 @@ size_t Cell::Visitor::marker_offset()
void GC::Cell::Visitor::visit(NanBoxedValue const& value)
{
- if (value.is_cell())
- visit_cell(value.as_cell());
+ if (!value.is_cell())
+ return;
+ // NB: The value is visited through its slot, which a collection that moves cells rewrites if it is in a cell.
+ if (m_marker) {
+ gc_marker_visit_values(m_marker, reinterpret_cast<uint64_t const*>(&value), 1);
+ return;
+ }
+ visit_cell(value.as_cell());
}
void GC::Cell::Visitor::visit_ephemeron(Cell&, NanBoxedValue const& value)
diff --git a/Libraries/LibGC/Cell.h b/Libraries/LibGC/Cell.h
index d9703108f05..539ed06d5c2 100644
--- a/Libraries/LibGC/Cell.h
+++ b/Libraries/LibGC/Cell.h
@@ -128,11 +128,15 @@ public:
visit_cell(*as_cell(const_cast<RemoveConst<T>*>(cell.ptr())));
}
- // Members are visited through their slot, which a moving collector will update. For now this visits the cell
- // they point to.
+ // Members are visited through their slot, which a collection that moves cells rewrites.
template<typename T>
void visit(Member<T> const& slot)
{
+ static_assert(sizeof(slot) == sizeof(u32));
+ if (m_marker) {
+ gc_marker_visit_member(m_marker, reinterpret_cast<u32 const*>(&slot));
+ return;
+ }
if (slot)
visit_member_cell(slot.ptr());
}
@@ -140,6 +144,11 @@ public:
template<typename T>
void visit(NonnullMember<T> const& slot)
{
+ static_assert(sizeof(slot) == sizeof(u32));
+ if (m_marker) {
+ gc_marker_visit_member(m_marker, reinterpret_cast<u32 const*>(&slot));
+ return;
+ }
visit_member_cell(slot.ptr());
}
@@ -346,9 +355,8 @@ private:
void set_cell_kind(CellKind kind) { m_cell_kind = kind; }
- // NB: Unused since marks live in the descriptors of the blocks. The byte is free for later use, and stays so that no
- // cell layout changes.
- [[maybe_unused]] u8 m_unused_header_byte { 0 };
+ // NB: Holds the state of the cell's identity hash, see identity_hash().
+ [[maybe_unused]] u8 m_identity_hash_state { 0 };
State m_state { State::Live };
CellKind m_cell_kind { CellKind::Other };
};
@@ -378,7 +386,8 @@ private:
friend struct CAPI;
[[maybe_unused]] void const* m_word_owned_by_the_foreign_implementation;
- [[maybe_unused]] u8 m_unused_header_byte;
+ // NB: As in Cell.
+ [[maybe_unused]] u8 m_identity_hash_state;
Cell::State m_state;
CellKind m_cell_kind;
// The foreign implementation lays its fields out right after the header. Naming these bytes keeps GCC from
@@ -414,6 +423,40 @@ struct IsVisitable {
GC_API StringView class_name_of(Cell const&);
+// Where a cell keeps the state of its identity hash, and the bits of that state. CAPI.cpp checks them against the cell
+// header and the Rust side.
+namespace IdentityHashState {
+
+static constexpr size_t offset = 8;
+static constexpr u8 hashed = 1 << 0;
+static constexpr u8 moved = 1 << 1;
+
+}
+
+// The hash of a cell's identity, which stays the same while the cell lives, wherever the collector moves it. Tables that
+// are keyed by cells that may move hash them with this. See gc_cell_identity_hash().
+ALWAYS_INLINE u32 identity_hash(void const* cell)
+{
+ // NB: The fast path of gc_cell_identity_hash(), for cells that did not move since they were first hashed.
+ auto* state = static_cast<u8*>(const_cast<void*>(cell)) + IdentityHashState::offset;
+ if (!(*state & IdentityHashState::moved)) [[likely]] {
+ *state |= IdentityHashState::hashed;
+ return compress(cell);
+ }
+ return gc_cell_identity_hash(static_cast<GCCell const*>(cell));
+}
+
+// The hash of a cell that a table which holds it weakly keys by, or of null once the cell is gone. A cell defined
+// outside of C++ may move, which keeps its identity hash but not its address, see WeakBlock::update_moved_cells().
+template<typename T>
+ALWAYS_INLINE unsigned weak_key_hash(T const* cell)
+{
+ if constexpr (IsBaseOf<ForeignCell, T>)
+ return cell ? u32_hash(identity_hash(cell)) : 0;
+ else
+ return Traits<T const*>::hash(cell);
+}
+
inline StringView class_name_of(ForeignCell const& cell)
{
return class_name_of(*as_cell(&cell));
diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.h
index db330391645..d64e236241d 100644
--- a/Libraries/LibGC/CellAllocator.h
+++ b/Libraries/LibGC/CellAllocator.h
@@ -45,6 +45,11 @@ public:
TraceThread trace_thread() const { return m_trace_thread; }
void set_trace_thread(TraceThread trace_thread) { m_trace_thread = trace_thread; }
+ // Whether collections may move the cells to other blocks of their allocator, see gc_allocator_set_movable(). Only
+ // allocators of cells defined outside of C++ are ever movable.
+ bool is_movable() const { return m_movable; }
+ void set_movable() { m_movable = true; }
+
// Where each heap keeps its allocator for this descriptor, see Heap::cell_allocator_for().
size_t index() const { return m_index; }
@@ -64,6 +69,7 @@ private:
void const* m_foreign_type { nullptr };
size_t m_index { 0 };
TraceThread m_trace_thread { TraceThread::OwnerThreadOnly };
+ bool m_movable { false };
};
class GC_API CellAllocator {
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index 8f7cd70a20a..f6d2eb88812 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -17,6 +17,7 @@
#include <AK/LexicalPath.h>
#include <AK/NumberFormat.h>
#include <AK/Platform.h>
+#include <AK/QuickSort.h>
#include <AK/SaturatingMath.h>
#include <AK/ScopeGuard.h>
#include <AK/StackInfo.h>
@@ -124,6 +125,65 @@ i32 libgc_log_level()
return level;
}
+// LIBGC_MOVE_EVERYTHING=1 has every collection that may move cells (one that does not scan the stack) evacuate every
+// block of cells defined outside of C++, moving each cell that can move to another slot. This tests that moving cells
+// is safe, and its report tells what keeps cells from moving.
+bool read_libgc_move_everything()
+{
+ char const* env = getenv("LIBGC_MOVE_EVERYTHING");
+ return env && *env && atoi(env) != 0;
+}
+
+bool libgc_move_everything()
+{
+ static bool const value = read_libgc_move_everything();
+ return value;
+}
+
+// What a collection that moves cells did, for its report.
+struct CompactionStats {
+ enum PinReason : u8 {
+ ByValueEdge,
+ ByValueRoot,
+ NonMovableAllocator,
+ PinReasonCount,
+ };
+
+ struct Counts {
+ size_t cells { 0 };
+ size_t bytes { 0 };
+
+ void add(size_t cell_size)
+ {
+ ++cells;
+ bytes += cell_size;
+ }
+ };
+
+ bool active { false };
+ size_t evacuated_blocks { 0 };
+ size_t new_blocks { 0 };
+ size_t freed_blocks { 0 };
+ Counts moved;
+ Array<Counts, PinReasonCount> pinned;
+ size_t recorded_slots { 0 };
+ size_t rewritten_slots { 0 };
+ i64 sweep_us { 0 };
+ i64 copy_us { 0 };
+ i64 fix_up_us { 0 };
+ HashMap<ByteString, Array<Counts, PinReasonCount>> pinned_by_type;
+};
+
+CompactionStats& compaction_stats()
+{
+#ifdef AK_COMPILER_CLANG
+ AK_IGNORE_DIAGNOSTIC("-Wexit-time-destructors", static thread_local CompactionStats stats)
+#else
+ static thread_local CompactionStats stats;
+#endif
+ return stats;
+}
+
// Per-phase timings recorded during a single collect_garbage() call. We keep
// these per thread (instead of threading more parameters through the GC's
// internal helpers) since a heap only collects on its own thread, guarded by
@@ -248,6 +308,49 @@ void print_gc_report(i64 total_us, size_t live_block_count)
dbgln(" block reclassify {:>10} us ({:>5.1f}%)", t.sweep_block_reclassify_us, pct(t.sweep_block_reclassify_us));
dbgln(" update threshold {:>10} us ({:>5.1f}%)", t.sweep_update_threshold_us, pct(t.sweep_update_threshold_us));
}
+ auto const& c = compaction_stats();
+ if (c.active) {
+ auto print_counts = [](StringView label, CompactionStats::Counts const& counts) {
+ dbgln(" {:<27} {:>10} cells ({})", label, counts.cells, human_readable_size(counts.bytes));
+ };
+ dbgln("");
+ dbgln("Compaction:");
+ dbgln(" evacuated blocks {:>10}", c.evacuated_blocks);
+ dbgln(" new blocks {:>10}", c.new_blocks);
+ dbgln(" freed blocks {:>10}", c.freed_blocks);
+ print_counts("moved"sv, c.moved);
+ print_counts("pinned: by-value edge"sv, c.pinned[CompactionStats::ByValueEdge]);
+ print_counts("pinned: by-value root"sv, c.pinned[CompactionStats::ByValueRoot]);
+ print_counts("pinned: non-movable type"sv, c.pinned[CompactionStats::NonMovableAllocator]);
+ dbgln(" recorded slots {:>10}", c.recorded_slots);
+ dbgln(" rewritten slots {:>10}", c.rewritten_slots);
+ dbgln(" sweep for compaction {:>10} us", c.sweep_us);
+ dbgln(" copy {:>10} us", c.copy_us);
+ dbgln(" fix up {:>10} us", c.fix_up_us);
+ if (!c.pinned_by_type.is_empty()) {
+ struct Entry {
+ ByteString name;
+ Array<CompactionStats::Counts, CompactionStats::PinReasonCount> counts;
+ size_t bytes;
+ };
+ Vector<Entry> entries;
+ for (auto const& it : c.pinned_by_type) {
+ size_t bytes = 0;
+ for (auto const& counts : it.value)
+ bytes += counts.bytes;
+ entries.append({ it.key, it.value, bytes });
+ }
+ quick_sort(entries, [](auto const& a, auto const& b) { return a.bytes > b.bytes; });
+ dbgln(" top types by pinned bytes (edge / root / non-movable):");
+ for (size_t i = 0; i < min<size_t>(entries.size(), 25); ++i) {
+ auto const& entry = entries[i];
+ dbgln(" {:<40} {:>10} {:>10} {:>10}", entry.name,
+ human_readable_size(entry.counts[CompactionStats::ByValueEdge].bytes),
+ human_readable_size(entry.counts[CompactionStats::ByValueRoot].bytes),
+ human_readable_size(entry.counts[CompactionStats::NonMovableAllocator].bytes));
+ }
+ }
+ }
dbgln("=================================================================");
}
@@ -364,6 +467,9 @@ Heap::~Heap()
// A root that outlives its heap would reach into freed memory when it goes.
VERIFY(m_roots.is_empty());
+ FFI::rust_gc_identity_hashes_destroy(m_identity_hashes);
+ m_identity_hashes = nullptr;
+
free_weak_blocks();
while (auto* allocator = m_all_cell_allocators.first())
@@ -862,6 +968,9 @@ void Heap::clear_weak_pointers_to_dead_cells(bool report)
void Heap::run_post_mark_phases(bool report)
{
+ // NB: The side table keeps the identity hashes of cells by address, which other cells may take once these are swept.
+ FFI::rust_gc_identity_hashes_drop_dead(m_identity_hashes, heap_region_base());
+
{
ScopedPhaseTimer timer { report, g_phase_timings.finalize_unmarked_cells_us };
finalize_unmarked_cells();
@@ -962,12 +1071,15 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
m_stats->bytes_before = m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE;
m_stats->sweep_duration_ns = 0;
}
+ compaction_stats().active = false;
if (collection_type == CollectionType::CollectGarbage) {
HashMap<Cell*, HeapRoot> roots;
{
ScopedPhaseTimer timer { report, g_phase_timings.gather_roots_us };
gather_roots(origin, roots);
}
+ if (should_move_cells(collection_type, scan_stack))
+ begin_evacuation();
{
ScopedPhaseTimer timer { report, g_phase_timings.mark_live_cells_us };
mark_live_cells(roots);
@@ -985,10 +1097,18 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
// 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).
- if (collection_type == CollectionType::CollectEverything || !m_incremental_sweep_enabled) {
+ // 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) {
ScopedPhaseTimer timer { report, g_phase_timings.sweep_dead_cells_us };
sweep_dead_cells(report, collection_measurement_timer);
}
+ if (m_evacuation) {
+ compaction_stats().sweep_us = g_phase_timings.sweep_dead_cells_us;
+ evacuate();
+ end_evacuation();
+ }
if (report) {
size_t live_block_count = 0;
@@ -1007,7 +1127,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)
+ if (collection_type != CollectionType::CollectEverything && m_incremental_sweep_enabled && !compaction_stats().active)
start_incremental_sweep();
else
g_next_incremental_sweep_should_report = false;
@@ -1036,6 +1156,198 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
schedule_release_of_abandoned_object_graph_memory();
if (!m_incremental_sweep_active)
schedule_release_of_allocator_memory();
+
+ if (scan_stack && libgc_move_everything())
+ schedule_collection_that_moves_cells();
+}
+
+bool Heap::should_move_cells(CollectionType collection_type, bool scan_stack) const
+{
+ // NB: A cell that only the stack points to has to stay where it is, so only a collection that does not scan the
+ // stack moves cells.
+ if (collection_type != CollectionType::CollectGarbage || scan_stack)
+ return false;
+ // FIXME: Choose blocks worth evacuating. For now, only the stress mode moves cells.
+ return libgc_move_everything();
+}
+
+bool Heap::moves_everything()
+{
+ return libgc_move_everything();
+}
+
+void Heap::begin_evacuation()
+{
+ VERIFY(!m_evacuation);
+ auto& stats = compaction_stats();
+ stats = {};
+ stats.active = true;
+ m_evacuation = FFI::rust_gc_evacuation_create(
+ {
+ .heap_region_base = heap_region_base(),
+ .block_cells_offset = static_cast<u32>(HeapBlock::cells_offset()),
+ .value_is_cell_pattern = SHIFTED_IS_CELL_PATTERN,
+ .value_offset_mask = HEAP_REGION_OFFSET_MASK,
+ },
+ this);
+ for (auto& allocator : m_all_cell_allocators) {
+ // NB: Cells defined in C++ never move. Blocks of cells defined elsewhere are evacuated whether or not their
+ // allocator is movable, which tells what keeps cells from moving.
+ if (!allocator.foreign_type())
+ continue;
+ allocator.for_each_block([&](HeapBlock& block) {
+ FFI::rust_gc_evacuation_add_block(m_evacuation, &block);
+ ++stats.evacuated_blocks;
+ return IterationDecision::Continue;
+ });
+ }
+}
+
+Cell* Heap::allocate_destination_for_moved_cell(CellAllocator& allocator)
+{
+ for (;;) {
+ if (allocator.m_usable_blocks.is_empty()) {
+ auto block = HeapBlock::create(*this, allocator);
+ allocator.m_usable_blocks.append(*block.leak_ptr());
+ ++compaction_stats().new_blocks;
+ }
+ auto& block = *allocator.m_usable_blocks.first();
+ auto* cell = block.allocate();
+ if (block.is_full())
+ allocator.m_full_blocks.append(block);
+ if (cell)
+ return cell;
+ }
+}
+
+// Moves the live cells of the evacuated blocks that nothing pinned to free slots of their allocator, then rewrites the
+// slots that marking recorded and the weak pointers, 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.
+void Heap::evacuate()
+{
+ auto& stats = compaction_stats();
+ bool count_by_type = libgc_log_level() >= 2;
+ stats.recorded_slots = FFI::rust_gc_evacuation_recorded_slot_count(m_evacuation);
+
+ auto count_pinned = [&](Cell* cell, size_t cell_size, CompactionStats::PinReason reason) {
+ stats.pinned[reason].add(cell_size);
+ if (count_by_type)
+ stats.pinned_by_type.ensure(class_name_of(*cell))[reason].add(cell_size);
+ };
+
+ struct AllocatorMoves {
+ CellAllocator* allocator;
+ Vector<FFI::CellMove> moves;
+ };
+ Vector<AllocatorMoves> all_moves;
+
+ auto copy_start_ns = MonotonicTime::now().nanoseconds();
+ for (auto& allocator : m_all_cell_allocators) {
+ if (!allocator.foreign_type())
+ continue;
+ auto cell_size = allocator.cell_size();
+ Vector<Cell*> cells_to_move;
+ allocator.for_each_block([&](HeapBlock& block) {
+ if (!block_descriptor_for(&block).evacuation)
+ return IterationDecision::Continue;
+ block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
+ if (!allocator.descriptor().is_movable()) {
+ count_pinned(cell, cell_size, CompactionStats::NonMovableAllocator);
+ return;
+ }
+ switch (FFI::rust_gc_evacuation_pin_reason(m_evacuation, cell)) {
+ case FFI::PinReason::Root:
+ count_pinned(cell, cell_size, CompactionStats::ByValueRoot);
+ return;
+ case FFI::PinReason::Edge:
+ count_pinned(cell, cell_size, CompactionStats::ByValueEdge);
+ return;
+ case FFI::PinReason::Unpinned:
+ cells_to_move.append(cell);
+ return;
+ }
+ VERIFY_NOT_REACHED();
+ });
+ return IterationDecision::Continue;
+ });
+ if (cells_to_move.is_empty())
+ continue;
+
+ // NB: Every destination is taken before any cell moves, so no cell moves twice, and no old slot is free yet.
+ Vector<FFI::CellMove> moves;
+ moves.ensure_capacity(cells_to_move.size());
+ for (auto* cell : cells_to_move) {
+ moves.unchecked_append({ .from = cell, .to = allocate_destination_for_moved_cell(allocator) });
+ stats.moved.add(cell_size);
+ }
+ FFI::rust_gc_evacuation_move_cells(m_evacuation, moves.data(), moves.size(), cell_size);
+ all_moves.append({ &allocator, move(moves) });
+ }
+ auto fix_up_start_ns = MonotonicTime::now().nanoseconds();
+ stats.copy_us = (fix_up_start_ns - copy_start_ns) / 1000;
+
+ if (!all_moves.is_empty()) {
+ stats.rewritten_slots = FFI::rust_gc_evacuation_fix_up_slots(m_evacuation);
+ auto forwarding_address = [this](void* cell) {
+ return FFI::rust_gc_evacuation_forwarding_address(m_evacuation, cell);
+ };
+ for (auto& weak_block : m_usable_weak_blocks)
+ weak_block.update_moved_cells(forwarding_address);
+ for (auto& weak_block : m_full_weak_blocks)
+ weak_block.update_moved_cells(forwarding_address);
+ }
+ auto release_start_ns = MonotonicTime::now().nanoseconds();
+ stats.fix_up_us = (release_start_ns - fix_up_start_ns) / 1000;
+
+ for (auto& [allocator, moves] : all_moves) {
+ for (auto& cell_move : moves) {
+ auto* cell = static_cast<Cell*>(cell_move.from);
+ HeapBlock::from_cell(cell)->release_moved_cell(cell);
+ }
+
+ // Sorts the blocks of the allocator into full and usable ones again, and lets go of the empty ones.
+ Vector<HeapBlock*> blocks;
+ allocator->for_each_block([&](HeapBlock& block) {
+ blocks.append(&block);
+ return IterationDecision::Continue;
+ });
+ for (auto* block : blocks) {
+ bool has_live_cells = false;
+ block->for_each_cell_in_state<Cell::State::Live>([&](Cell*) { has_live_cells = true; });
+ if (!has_live_cells) {
+ allocator->block_did_become_empty({}, *block, DeferDecommit::No);
+ ++stats.freed_blocks;
+ } else if (block->is_full()) {
+ allocator->m_full_blocks.append(*block);
+ } else {
+ allocator->m_usable_blocks.append(*block);
+ }
+ }
+ }
+}
+
+void Heap::end_evacuation()
+{
+ FFI::rust_gc_evacuation_destroy(m_evacuation);
+ m_evacuation = nullptr;
+}
+
+void Heap::schedule_collection_that_moves_cells()
+{
+ // NB: The stress mode moves cells as often as it can: after each collection that scans the stack, the next turn of
+ // the event loop collects again without scanning it, if the embedder vouches that its outermost turns hold no
+ // cells.
+ if (!m_outermost_event_loop_turn_holds_no_cells)
+ return;
+ if (!m_moving_collection_timer) {
+ m_moving_collection_timer = Core::Timer::create_single_shot(AK::Duration::zero(), [this] {
+ if (is_gc_deferred() || Core::ThreadEventQueue::current().is_processing_nested())
+ return;
+ collect_garbage_from_timer();
+ });
+ }
+ if (!m_moving_collection_timer->is_active())
+ m_moving_collection_timer->start();
}
void Heap::update_allocation_rate()
@@ -1576,6 +1888,8 @@ void Heap::mark_live_cells_across(ReadonlySpan<Heap* const> heaps, HashMap<Cell*
.marked_cell_bytes = marked_cell_bytes.data(),
.marked_external_bytes = marked_external_bytes.data(),
.threads_used = 0,
+ // NB: Only a collection of one heap moves cells.
+ .evacuation = heaps.size() == 1 ? heaps[0]->m_evacuation : nullptr,
};
#pragma GCC diagnostic pop
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index 576a9014ff6..1804e97b1b5 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -36,6 +36,13 @@
namespace GC {
+namespace FFI {
+
+struct EvacuationSet;
+struct IdentityHashes;
+
+}
+
struct StackFrameInfo {
String label;
size_t size_bytes { 0 };
@@ -132,6 +139,13 @@ public:
// than it does in other collections.
bool is_returning_memory_to_system() const { return m_is_returning_memory_to_system; }
+ // Whether the collection in progress may move cells, which only a collection that does not scan the stack does.
+ bool is_moving_cells() const { return m_evacuation; }
+
+ // Whether LIBGC_MOVE_EVERYTHING has every collection that does not scan the stack move every cell it can, which
+ // test runners use to collect without scanning the stack where they safely can.
+ static bool moves_everything();
+
void set_incremental_sweep_enabled(bool enabled) { m_incremental_sweep_enabled = enabled; }
void set_should_collect_on_every_allocation(bool);
@@ -298,6 +312,12 @@ private:
NEVER_INLINE Vector<RetainingPath> build_retaining_paths(ReadonlySpan<FlatPtr> callee_saved_registers, AK::Function<bool(Cell&)> const& is_target, size_t max_paths);
void gather_roots(ConservativeScanOrigin const&, HashMap<Cell*, HeapRoot>&, Vector<StackFrameInfo>* out_stack_frames = nullptr, IncludeIncomingCrossHeapMembers = IncludeIncomingCrossHeapMembers::Yes);
+ bool should_move_cells(CollectionType, bool scan_stack) const;
+ void begin_evacuation();
+ void evacuate();
+ void end_evacuation();
+ Cell* allocate_destination_for_moved_cell(CellAllocator&);
+ void schedule_collection_that_moves_cells();
static void mark_live_cells_across(ReadonlySpan<Heap* const>, HashMap<Cell*, HeapRoot>& roots);
void clear_weak_pointers_to_dead_cells(bool report);
void run_post_mark_phases(bool report);
@@ -390,7 +410,13 @@ private:
RefPtr<Core::Timer> m_incremental_sweep_timer;
RefPtr<Core::Timer> m_idle_gc_timer;
+ RefPtr<Core::Timer> m_moving_collection_timer;
bool m_outermost_event_loop_turn_holds_no_cells { false };
+
+ // The blocks the collection in progress evacuates and the slots it found, while it may move cells.
+ FFI::EvacuationSet* m_evacuation { nullptr };
+ // The identity hashes of the cells that moved since they were hashed, see identity_hash().
+ FFI::IdentityHashes* m_identity_hashes { nullptr };
void collect_garbage_from_timer();
enum class AbandonedObjectGraphState : u8 {
None,
diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cpp
index bf0ef08bb13..aa843ac7f2c 100644
--- a/Libraries/LibGC/HeapBlock.cpp
+++ b/Libraries/LibGC/HeapBlock.cpp
@@ -32,11 +32,21 @@ void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator)
descriptor.cell_size = allocator.cell_size();
descriptor.cell_index_magic = static_cast<u32>(((static_cast<u64>(1) << 32) + descriptor.cell_size - 1) / descriptor.cell_size);
descriptor.traced_on_owner_thread_only = allocator.descriptor().trace_thread() == TraceThread::OwnerThreadOnly;
+ descriptor.movable = allocator.descriptor().is_movable();
+ descriptor.evacuation = nullptr;
clear_marks(descriptor);
// NB: Markers of other heaps read the heap of any block their cells point into, to leave it alone if it is not theirs.
__atomic_store_n(&descriptor.heap, static_cast<void*>(&block.heap()), __ATOMIC_RELEASE);
}
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Winvalid-offsetof"
+size_t HeapBlock::cells_offset()
+{
+ return offsetof(HeapBlock, m_storage);
+}
+#pragma GCC diagnostic pop
+
void retire_block_descriptor(HeapBlock& block)
{
__atomic_store_n(&block_descriptor_for(&block).heap, static_cast<void*>(nullptr), __ATOMIC_RELEASE);
@@ -110,6 +120,18 @@ void HeapBlock::deallocate(Cell* cell)
if (auto* destroy = type_info().destroy)
destroy(cell);
+ free_slot(cell);
+}
+
+void HeapBlock::release_moved_cell(Cell* cell)
+{
+ VERIFY(cell->state() == Cell::State::Live);
+ VERIFY(is_valid_cell_pointer(cell));
+ free_slot(cell);
+}
+
+void HeapBlock::free_slot(Cell* cell)
+{
auto* freelist_entry = new (cell) FreelistEntry();
freelist_entry->set_state(Cell::State::Dead);
freelist_entry->next = m_freelist;
@@ -120,7 +142,6 @@ void HeapBlock::deallocate(Cell* cell)
VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
VERIFY(m_cell_size >= sizeof(FreelistEntry));
VERIFY(m_cell_size >= FFI::MIN_CELL_SIZE);
- publish_block_descriptor(*this, cell_allocator);
// We can't poision the cell tracking data, nor the FreeListEntry's vtable or next pointer
// This means there's sizeof(FreelistEntry) data at the front of each cell that is always read/write
// On x86_64, this ends up being 24 bytes due to the size of the FreeListEntry's vtable, while on x86, it's only 12 bytes.
diff --git a/Libraries/LibGC/HeapBlock.h b/Libraries/LibGC/HeapBlock.h
index 855101feb6d..6429acc419c 100644
--- a/Libraries/LibGC/HeapBlock.h
+++ b/Libraries/LibGC/HeapBlock.h
@@ -56,6 +56,10 @@ public:
// found unmarked.
void deallocate(Cell*);
+ // Frees the slot of a live cell that moved to another slot, without
+ // destroying it, since its copy lives on.
+ void release_moved_cell(Cell*);
+
// The free cells of a block: the cells that were freed, as a list linked
// through freelist_next_offset, and the cells that were never allocated,
// which are the cells from lazy_start up to lazy_end.
@@ -78,6 +82,9 @@ public:
// The offset of the link to the next cell in a free cell.
static constexpr size_t freelist_next_offset();
+ // How far into a block its first cell is.
+ static size_t cells_offset();
+
// Free cells are in the heap region, where anything may have been
// corrupted, so a link read from a free cell must never lead out of its
// block: only the bits of the link under freelist_link_mask count, as
@@ -149,6 +156,7 @@ private:
HeapBlock(Heap&, CellAllocator&);
bool has_lazy_freelist() const { return m_next_lazy_freelist_index < cell_count(); }
+ void free_slot(Cell*);
struct FreelistEntry final : public Cell {
GC_CELL(FreelistEntry, Cell);
diff --git a/Libraries/LibGC/Rust/src/block.rs b/Libraries/LibGC/Rust/src/block.rs
index 31145c93c06..10e64e6b27c 100644
--- a/Libraries/LibGC/Rust/src/block.rs
+++ b/Libraries/LibGC/Rust/src/block.rs
@@ -18,6 +18,7 @@ use core::ptr::NonNull;
use core::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
use std::sync::OnceLock;
+use crate::evacuation::Evacuation;
use crate::os;
pub const BLOCK_SIZE: usize = 16 * 1024;
@@ -43,9 +44,13 @@ pub struct BlockDescriptor {
pub cell_index_magic: u32,
/// Whether the block's cells may only be traced on the thread that owns their heap, as C++ cells must.
pub traced_on_owner_thread_only: bool,
+ /// Whether a collection may move the block's cells to other blocks of their allocator.
+ pub movable: bool,
/// Rounds the descriptor up to 128 bytes, two whole cache lines in the table.
- pub reserved: [u8; 7],
- pub reserved_word: u64,
+ pub reserved: [u8; 6],
+ /// What a collection that evacuates the block knows about its cells, and null in every other collection. Marking
+ /// reads it for every cell it visits, to pin the cells of evacuated blocks that something visits by value.
+ pub evacuation: *mut Evacuation,
/// One bit for each cell, which marking sets atomically, see mark_word().
pub marked: [UnsafeCell<u64>; MARK_BITMAP_WORDS],
}
@@ -66,9 +71,38 @@ impl BlockDescriptor {
unsafe { AtomicU64::from_ptr(self.marked[word].get()) }
}
+ /// The evacuation state of the block, if a collection evacuates it.
+ #[inline(always)]
+ pub fn evacuation(&self) -> Option<&Evacuation> {
+ // SAFETY: The field is only accessed atomically while other threads may read it, only written while no marker
+ // runs, and the evacuation outlives the collection's use of it.
+ unsafe {
+ AtomicPtr::from_ptr((&raw const self.evacuation).cast_mut())
+ .load(Ordering::Relaxed)
+ .as_ref()
+ }
+ }
+
+ /// The index of the cell at `address` in the block, which is also the index of its mark bit. Cells are a cell size
+ /// apart, so the offsets of their starts divided by the cell size tell them apart.
+ #[inline(always)]
+ pub fn cell_index(&self, address: usize) -> CellIndex {
+ CellIndex((((address & (BLOCK_SIZE - 1)) as u64 * u64::from(self.cell_index_magic)) >> 32) as usize)
+ }
+
+ /// The start of the cell that `address` points into, for a block whose cells start `cells_offset` bytes into it.
+ pub fn cell_containing(&self, address: usize, cells_offset: usize) -> usize {
+ let block = address & !(BLOCK_SIZE - 1);
+ let offset_in_cells = (address & (BLOCK_SIZE - 1)) - cells_offset;
+ // NB: As for the mark bit index, multiplying by the magic and shifting right by 32 divides offsets below 2^14 by
+ // the cell size exactly.
+ let index = ((offset_in_cells as u64 * u64::from(self.cell_index_magic)) >> 32) as usize;
+ block + cells_offset + index * self.cell_size as usize
+ }
+
#[inline(always)]
pub fn mark_bit(&self, address: usize) -> (&AtomicU64, u64) {
- let index = (((address & (BLOCK_SIZE - 1)) as u64 * u64::from(self.cell_index_magic)) >> 32) as usize;
+ let index = self.cell_index(address).0;
(self.mark_word(index / 64), 1 << (index % 64))
}
@@ -102,6 +136,13 @@ impl BlockDescriptor {
}
}
+/// The index of a cell in its block, which marks and other per-cell bits of the block are indexed by.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct CellIndex(pub usize);
+
+/// The most cells a block has, and so the most bits that per-cell bitmaps of a block need.
+pub const MAX_CELLS_PER_BLOCK: usize = MARK_BITMAP_WORDS * 64;
+
struct Table {
descriptors: NonNull<BlockDescriptor>,
count: usize,
@@ -119,6 +160,40 @@ pub fn descriptor_table() -> NonNull<BlockDescriptor> {
TABLE.get().expect("the table of block descriptors exists").descriptors
}
+/// The descriptor of the block that `address` is in, for an address in the heap region at `heap_region_base`.
+///
+/// # Safety
+///
+/// `address` must be in a block of the region, whose descriptor is backed by memory.
+#[inline(always)]
+pub unsafe fn descriptor_for<'a>(heap_region_base: usize, address: usize) -> &'a BlockDescriptor {
+ // SAFETY: The caller passes an address in a block, whose descriptor is in the table.
+ unsafe {
+ descriptor_table()
+ .add((address - heap_region_base) / BLOCK_SIZE)
+ .as_ref()
+ }
+}
+
+/// Sets the evacuation state of the block that `address` is in, which only a collection that is not marking may do.
+///
+/// NB: This writes through a pointer from the table rather than through a reference to the descriptor, which would let
+/// the compiler assume that the descriptor does not change.
+///
+/// # Safety
+///
+/// As for descriptor_for().
+pub unsafe fn set_evacuation_of_block(heap_region_base: usize, address: usize, evacuation: *mut Evacuation) {
+ // SAFETY: The caller passes an address in a block, whose descriptor is in the table, and the field is only accessed
+ // atomically while other threads may read it.
+ unsafe {
+ let descriptor = descriptor_table()
+ .add((address - heap_region_base) / BLOCK_SIZE)
+ .as_ptr();
+ AtomicPtr::from_ptr(&raw mut (*descriptor).evacuation).store(evacuation, Ordering::Relaxed);
+ }
+}
+
/// The heap of a block, read without borrowing its descriptor. The thread of another heap may be filling in the other
/// fields of the descriptor of a block that it takes, which a reference to the descriptor would assume do not change.
///
@@ -132,6 +207,28 @@ pub unsafe fn heap_of_descriptor(descriptor: *const BlockDescriptor) -> *mut c_v
unsafe { AtomicPtr::from_ptr((&raw const (*descriptor).heap).cast_mut()) }.load(Ordering::Relaxed)
}
+/// The descriptor of the block that `address` is in, if that block belongs to `heap`, which only the calling thread
+/// changes, so nothing changes the descriptor while the reference is in use.
+///
+/// # Safety
+///
+/// As for descriptor_for().
+#[inline(always)]
+pub unsafe fn descriptor_of_heap<'a>(
+ heap_region_base: usize,
+ address: usize,
+ heap: *const c_void,
+) -> Option<&'a BlockDescriptor> {
+ // SAFETY: The caller passes an address in a block, whose descriptor is in the table.
+ let descriptor = unsafe { descriptor_table().add((address - heap_region_base) / BLOCK_SIZE) };
+ // SAFETY: As above.
+ if unsafe { heap_of_descriptor(descriptor.as_ptr()) }.cast_const() != heap {
+ return None;
+ }
+ // SAFETY: As above, and only the calling thread changes the descriptor of a block of the heap.
+ Some(unsafe { descriptor.as_ref() })
+}
+
/// Reserves the table of block descriptors for a heap region of `region_size` bytes, the first time it is called, and
/// returns it. The descriptor of the block at offset N of the region is at index N / BLOCK_SIZE.
#[unsafe(no_mangle)]
diff --git a/Libraries/LibGC/Rust/src/evacuation.rs b/Libraries/LibGC/Rust/src/evacuation.rs
new file mode 100644
index 00000000000..e1f72d57df4
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/evacuation.rs
@@ -0,0 +1,464 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Evacuation: a collection that does not scan the stack may move the live cells out of some blocks, into free slots of
+//! other blocks of the same allocator.
+//!
+//! An edge that marking visits through its slot can be updated once its target moves, while an edge visited by value
+//! pins its target. Marking pins the cells of evacuated blocks that something visits by value, or that are roots, and
+//! 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: it is copied bytewise to its new slot, and its old slot is freed without
+//! being destroyed. Then every recorded slot that points at a moved cell is rewritten, after the slot itself is found
+//! in the copy of its cell if that moved too.
+//!
+//! 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.
+
+use core::ffi::c_void;
+use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};
+
+use crate::block::{
+ BLOCK_SIZE, BlockDescriptor, CellIndex, MARK_BITMAP_WORDS, MAX_CELLS_PER_BLOCK, descriptor_for, descriptor_of_heap,
+ set_evacuation_of_block,
+};
+use crate::identity_hash::{CompressedAddress, IDENTITY_HASH_STATE_OFFSET, identity_hashes_of};
+use crate::marker::COMPRESSED_POINTER_SHIFT;
+use crate::rust_panic::abort_on_panic;
+
+/// Why a cell of an evacuated block stays where it is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum PinReason {
+ Unpinned = 0,
+ /// Something visited the cell by value rather than through a slot the collector can update.
+ Edge = 1,
+ /// The cell is a root, which roots hand over by value.
+ Root = 2,
+}
+
+/// What a collection that evacuates a block knows about the block's cells.
+pub struct Evacuation {
+ pinned_by_edge: [AtomicU64; MARK_BITMAP_WORDS],
+ pinned_by_root: [AtomicU64; MARK_BITMAP_WORDS],
+ /// The compressed address each cell that moved moved to, by cell index, and 0 for the cells that did not.
+ forwarding: [AtomicU32; MAX_CELLS_PER_BLOCK],
+}
+
+impl Evacuation {
+ fn new() -> Box<Self> {
+ Box::new(Self {
+ pinned_by_edge: [const { AtomicU64::new(0) }; MARK_BITMAP_WORDS],
+ pinned_by_root: [const { AtomicU64::new(0) }; MARK_BITMAP_WORDS],
+ forwarding: [const { AtomicU32::new(0) }; MAX_CELLS_PER_BLOCK],
+ })
+ }
+
+ /// Pins the cell at `address` of the block this evacuates, which markers may do from several threads at once.
+ #[inline(always)]
+ pub fn pin(&self, descriptor: &BlockDescriptor, address: usize, reason: PinReason) {
+ let index = descriptor.cell_index(address).0;
+ let bits = match reason {
+ PinReason::Root => &self.pinned_by_root,
+ _ => &self.pinned_by_edge,
+ };
+ let word = &bits[index / 64];
+ let bit = 1u64 << (index % 64);
+ // NB: As with mark bits, a bit that is set already costs no read-modify-write.
+ if word.load(Ordering::Relaxed) & bit == 0 {
+ word.fetch_or(bit, Ordering::Relaxed);
+ }
+ }
+
+ pub fn pin_reason(&self, index: CellIndex) -> PinReason {
+ let bit = 1u64 << (index.0 % 64);
+ if self.pinned_by_root[index.0 / 64].load(Ordering::Relaxed) & bit != 0 {
+ return PinReason::Root;
+ }
+ if self.pinned_by_edge[index.0 / 64].load(Ordering::Relaxed) & bit != 0 {
+ return PinReason::Edge;
+ }
+ PinReason::Unpinned
+ }
+
+ fn forwarding(&self, index: CellIndex) -> Option<CompressedAddress> {
+ let compressed = self.forwarding[index.0].load(Ordering::Relaxed);
+ (compressed != 0).then_some(CompressedAddress(compressed))
+ }
+}
+
+/// The kinds of slots that marking records, which differ in how they hold the address of their target.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(usize)]
+pub enum SlotKind {
+ /// A 32-bit compressed cell pointer, 0 for null, like GC::Member.
+ Member = 0,
+ /// A NaN-boxed value, which may hold a cell.
+ Value = 1,
+ /// A raw pointer into a cell, at the cell or past its start, as an object keeps to its property storage.
+ InteriorPointer = 2,
+ /// A raw pointer into the cell that holds it, as an object keeps to its inline property storage. It may point one
+ /// past the end of the cell's own fields, at the start of the next cell, which only its holder tells apart.
+ SelfPointer = 3,
+}
+
+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.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct RecordedSlot(usize);
+
+impl RecordedSlot {
+ #[inline(always)]
+ pub fn new(address: usize, kind: SlotKind) -> Self {
+ debug_assert!(address & SLOT_KIND_MASK == 0, "slots are at least 4-aligned");
+ Self(address | kind as usize)
+ }
+
+ pub fn address(self) -> usize {
+ self.0 & !SLOT_KIND_MASK
+ }
+
+ pub fn kind(self) -> SlotKind {
+ match self.0 & SLOT_KIND_MASK {
+ 0 => SlotKind::Member,
+ 1 => SlotKind::Value,
+ 2 => SlotKind::InteriorPointer,
+ _ => SlotKind::SelfPointer,
+ }
+ }
+}
+
+/// Where the collector finds what it needs to move cells and fix up slots.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct EvacuationLayout {
+ pub heap_region_base: usize,
+ /// How far into a block its first cell is.
+ pub block_cells_offset: u32,
+ /// As in MarkerLayout.
+ pub value_is_cell_pattern: u64,
+ pub value_offset_mask: u64,
+}
+
+/// The blocks a collection evacuates, and the slots its marking recorded.
+pub struct EvacuationSet {
+ layout: EvacuationLayout,
+ heap: *mut c_void,
+ blocks: Vec<(usize, Box<Evacuation>)>,
+ slots: Vec<Vec<RecordedSlot>>,
+}
+
+impl EvacuationSet {
+ pub(crate) fn add_recorded_slots(&mut self, slots: Vec<RecordedSlot>) {
+ if !slots.is_empty() {
+ self.slots.push(slots);
+ }
+ }
+
+ #[inline(always)]
+ fn is_in_heap_region(&self, address: usize) -> bool {
+ (address.wrapping_sub(self.layout.heap_region_base) as u64) <= self.layout.value_offset_mask
+ }
+
+ /// The evacuation of the live block that `address` is in, with its descriptor.
+ #[inline(always)]
+ fn evacuation_of(&self, address: usize) -> Option<(&BlockDescriptor, &Evacuation)> {
+ if !self.is_in_heap_region(address) {
+ return None;
+ }
+ // SAFETY: The address is in the region, whose descriptors are backed by memory wherever a block ever was, and
+ // read as zero elsewhere.
+ let descriptor = unsafe { descriptor_of_heap(self.layout.heap_region_base, address, self.heap) }?;
+ Some((descriptor, descriptor.evacuation()?))
+ }
+
+ fn decompress(&self, compressed: CompressedAddress) -> usize {
+ self.layout.heap_region_base + ((compressed.0 as usize) << COMPRESSED_POINTER_SHIFT)
+ }
+
+ /// Where the cell that starts at `cell` moved to, if it moved.
+ #[inline(always)]
+ fn forwarding_address(&self, cell: usize) -> Option<usize> {
+ let (descriptor, evacuation) = self.evacuation_of(cell)?;
+ evacuation
+ .forwarding(descriptor.cell_index(cell))
+ .map(|to| self.decompress(to))
+ }
+
+ /// Where the byte at `address` is now: in the copy of its cell if that moved.
+ #[inline(always)]
+ fn relocate(&self, address: usize) -> usize {
+ let Some((descriptor, evacuation)) = self.evacuation_of(address) else {
+ return address;
+ };
+ let cell = descriptor.cell_containing(address, self.layout.block_cells_offset as usize);
+ match evacuation.forwarding(descriptor.cell_index(cell)) {
+ Some(to) => self.decompress(to) + (address - cell),
+ None => address,
+ }
+ }
+
+ /// Rewrites a slot that marking recorded to point where its target moved, and returns whether it did.
+ ///
+ /// # Safety
+ ///
+ /// The slot must be in a live cell, and hold what its kind says.
+ unsafe fn fix_up(&self, slot: RecordedSlot) -> bool {
+ let base = self.layout.heap_region_base;
+ let address = self.relocate(slot.address());
+ // SAFETY: The caller passes a slot of a live cell, which is now at `address`.
+ unsafe {
+ match slot.kind() {
+ SlotKind::Member => {
+ let slot = address as *mut u32;
+ let compressed = slot.read();
+ if compressed == 0 {
+ return false;
+ }
+ let Some(to) = self.forwarding_address(self.decompress(CompressedAddress(compressed))) else {
+ return false;
+ };
+ slot.write((to >> COMPRESSED_POINTER_SHIFT) as u32);
+ }
+ SlotKind::Value => {
+ let slot = address as *mut u64;
+ let value = slot.read();
+ if value & self.layout.value_is_cell_pattern != self.layout.value_is_cell_pattern {
+ return false;
+ }
+ let mask = self.layout.value_offset_mask;
+ let Some(to) = self.forwarding_address(base + (value & mask) as usize) else {
+ return false;
+ };
+ slot.write((value & !mask) | ((to - base) as u64 & mask));
+ }
+ SlotKind::InteriorPointer => {
+ let slot = address as *mut usize;
+ let pointer = slot.read();
+ let Some((descriptor, _)) = self.evacuation_of(pointer) else {
+ return false;
+ };
+ let cell = descriptor.cell_containing(pointer, self.layout.block_cells_offset as usize);
+ let Some(to) = self.forwarding_address(cell) else {
+ return false;
+ };
+ slot.write(to + (pointer - cell));
+ }
+ SlotKind::SelfPointer => {
+ let Some((descriptor, _)) = self.evacuation_of(slot.address()) else {
+ return false;
+ };
+ let holder = descriptor.cell_containing(slot.address(), self.layout.block_cells_offset as usize);
+ let Some(to) = self.forwarding_address(holder) else {
+ return false;
+ };
+ let slot = address as *mut usize;
+ let pointer = slot.read();
+ // 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));
+ }
+ }
+ }
+ true
+ }
+}
+
+/// Starts the evacuation state of a collection of `heap`, which owns the evacuations of the blocks it adds.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_gc_evacuation_create(layout: EvacuationLayout, heap: *mut c_void) -> *mut EvacuationSet {
+ Box::into_raw(Box::new(EvacuationSet {
+ layout,
+ heap,
+ blocks: Vec::new(),
+ slots: Vec::new(),
+ }))
+}
+
+/// Has the collection evacuate the block at `block`, which must belong to the set's heap. Must be called before marking.
+///
+/// # Safety
+///
+/// `set` must be live, and `block` a live block of its heap that the set does not have yet.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_add_block(set: *mut EvacuationSet, block: *mut c_void) {
+ // SAFETY: The caller passes a live set.
+ let set = unsafe { &mut *set };
+ let address = block.addr();
+ debug_assert!(address & (BLOCK_SIZE - 1) == 0);
+ // SAFETY: The caller passes a live block.
+ let descriptor = unsafe { descriptor_for(set.layout.heap_region_base, address) };
+ debug_assert!(descriptor.heap() == set.heap && descriptor.evacuation().is_none());
+ let evacuation = Evacuation::new();
+ // SAFETY: The caller passes a live block, and no marker runs yet.
+ unsafe {
+ set_evacuation_of_block(
+ set.layout.heap_region_base,
+ address,
+ core::ptr::from_ref(&*evacuation).cast_mut(),
+ );
+ }
+ set.blocks.push((address, evacuation));
+}
+
+/// Why a live cell of an evacuated block was pinned.
+///
+/// # Safety
+///
+/// `set` must be live, and `cell` a cell of one of its blocks.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_pin_reason(set: *const EvacuationSet, cell: *const c_void) -> PinReason {
+ // SAFETY: The caller passes a live set.
+ let set = unsafe { &*set };
+ let (descriptor, evacuation) = set
+ .evacuation_of(cell.addr())
+ .expect("the cell is in an evacuated block");
+ evacuation.pin_reason(descriptor.cell_index(cell.addr()))
+}
+
+/// A cell to move, from its slot to a free slot of another block of its allocator.
+#[repr(C)]
+pub struct CellMove {
+ pub from: *mut c_void,
+ pub to: *mut c_void,
+}
+
+/// Copies each cell to its new slot, and notes where it went. Both slots are `cell_size` bytes.
+///
+/// # Safety
+///
+/// `set` must be live, and the moves name live, unpinned cells of its blocks and free slots of the same allocators,
+/// each once.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_move_cells(
+ set: *mut EvacuationSet,
+ moves: *const CellMove,
+ count: usize,
+ cell_size: usize,
+) {
+ abort_on_panic(|| {
+ // SAFETY: The caller passes a live set, and count moves.
+ let (set, moves) = unsafe { (&mut *set, ak::slice_from_raw_parts(moves, count)) };
+ let mut identity_hashes = None;
+ for cell_move in moves {
+ let (from, to) = (cell_move.from.addr(), cell_move.to.addr());
+ let (descriptor, evacuation) = set.evacuation_of(from).expect("the cell is in an evacuated block");
+ debug_assert!(descriptor.cell_size as usize == cell_size);
+ let index = descriptor.cell_index(from);
+ debug_assert!(evacuation.forwarding(index).is_none());
+ // SAFETY: The caller passes a live cell and a free slot of the same size, which do not overlap.
+ unsafe {
+ core::ptr::copy_nonoverlapping(cell_move.from.cast::<u8>(), cell_move.to.cast::<u8>(), cell_size);
+ let state = cell_move.to.cast::<u8>().add(IDENTITY_HASH_STATE_OFFSET);
+ if state.read() != 0 {
+ let table = identity_hashes.get_or_insert_with(|| identity_hashes_of(set.heap));
+ state.write(table.did_move(
+ state.read(),
+ CompressedAddress((from >> COMPRESSED_POINTER_SHIFT) as u32),
+ CompressedAddress((to >> COMPRESSED_POINTER_SHIFT) as u32),
+ ));
+ }
+ }
+ evacuation.forwarding[index.0].store((to >> COMPRESSED_POINTER_SHIFT) as u32, Ordering::Relaxed);
+ }
+ });
+}
+
+/// Rewrites every slot that marking recorded and that points at a cell that moved, and returns how many it rewrote.
+///
+/// # Safety
+///
+/// `set` must be live, every cell has to be moved already, and the cells that held recorded slots must still be live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_fix_up_slots(set: *mut EvacuationSet) -> usize {
+ abort_on_panic(|| {
+ // SAFETY: The caller passes a live set.
+ let set = unsafe { &*set };
+ let mut rewritten = 0;
+ for slots in &set.slots {
+ for &slot in slots {
+ // SAFETY: Marking recorded the slot in a live cell, as the caller makes sure it still is.
+ if unsafe { set.fix_up(slot) } {
+ rewritten += 1;
+ }
+ }
+ }
+ rewritten
+ })
+}
+
+/// How many slots marking recorded.
+///
+/// # Safety
+///
+/// `set` must be live.
+#[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(Vec::len).sum()
+}
+
+/// Where the cell at `cell` moved to, or null if it did not move.
+///
+/// # Safety
+///
+/// `set` must be live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_forwarding_address(
+ set: *const EvacuationSet,
+ cell: *const c_void,
+) -> *mut c_void {
+ // 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),
+ None => core::ptr::null_mut(),
+ }
+}
+
+/// Ends the evacuation state of a collection: its blocks are no longer evacuated.
+///
+/// # Safety
+///
+/// `set` must be live, and nothing may use it after.
+#[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 (block, evacuation) in &set.blocks {
+ // SAFETY: Every block of the set was in the region, where descriptors stay backed by memory.
+ 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, &raw const **evacuation))
+ {
+ // 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()) };
+ }
+ }
+}
+
+/// Whether the collection will move the cell at `cell`: once marking is done, a live cell of an evacuated block moves if
+/// its allocator is movable and nothing pinned it. Caches that hold cells weakly drop such a cell as if it died.
+///
+/// # Safety
+///
+/// `set` must be live, and its marking done.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_evacuation_will_move(set: *const EvacuationSet, cell: *const c_void) -> bool {
+ // SAFETY: The caller passes a live set.
+ let set = unsafe { &*set };
+ let Some((descriptor, evacuation)) = set.evacuation_of(cell.addr()) else {
+ return false;
+ };
+ descriptor.movable
+ && descriptor.is_marked(cell.addr())
+ && evacuation.pin_reason(descriptor.cell_index(cell.addr())) == PinReason::Unpinned
+}
diff --git a/Libraries/LibGC/Rust/src/identity_hash.rs b/Libraries/LibGC/Rust/src/identity_hash.rs
new file mode 100644
index 00000000000..aa3b5c88c13
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/identity_hash.rs
@@ -0,0 +1,195 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Identity hashes: a 32-bit hash of each cell that stays the same for as long as the cell lives, wherever the
+//! collector moves it.
+//!
+//! A cell's identity hash is its compressed address at the time it is first hashed. Two bits of the header byte that
+//! LibGC leaves free tell where the hash is: in an unhashed cell nowhere yet, in a hashed cell in the cell's address, and
+//! in a cell that was hashed and then moved in the side table of its heap. Hashing an unhashed cell sets "hashed", so
+//! that the collector knows to keep its hash when it moves the cell: under the copy's address in the side table, with
+//! "moved" set on the copy. A copy that moves again has its entry rekeyed, and the entries of cells that died are
+//! dropped after marking.
+//!
+//! Every hash of a cell's identity goes through identity_hash(), or through the inline copies of its fast path in C++
+//! (GC::identity_hash()) and in LibJS's runtime, which hand the cells that moved to it.
+
+use core::ffi::c_void;
+use core::hash::{BuildHasherDefault, Hasher};
+use std::collections::HashMap;
+
+use crate::block::{BLOCK_SIZE, descriptor_for};
+use crate::marker::COMPRESSED_POINTER_SHIFT;
+
+/// Where a cell keeps its identity hash state, the header byte that LibGC leaves free.
+pub const IDENTITY_HASH_STATE_OFFSET: usize = 8;
+/// Set once the cell has been hashed, so its identity hash must survive moves.
+pub const IDENTITY_HASH_HASHED: u8 = 1 << 0;
+/// Set on a hashed cell that moved since it was hashed, whose hash is then in the side table of its heap.
+pub const IDENTITY_HASH_MOVED: u8 = 1 << 1;
+
+/// A cell's compressed address, which keys the side table.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct CompressedAddress(pub u32);
+
+/// An identity hash.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct IdentityHash(pub u32);
+
+/// OPTIMIZATION: The keys are compressed addresses, whose low bits differ the most, so a multiplication spreads them
+/// well enough for the table.
+#[derive(Default)]
+struct CompressedAddressHasher(u64);
+
+impl Hasher for CompressedAddressHasher {
+ fn finish(&self) -> u64 {
+ self.0
+ }
+
+ fn write(&mut self, bytes: &[u8]) {
+ for &byte in bytes {
+ self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ }
+ }
+
+ fn write_u32(&mut self, value: u32) {
+ self.0 = u64::from(value).wrapping_mul(0x9e37_79b9_7f4a_7c15).rotate_left(32);
+ }
+}
+
+/// The side table of a heap: the identity hashes of the hashed cells that moved, by their current address.
+#[derive(Default)]
+pub struct IdentityHashes {
+ hashes: HashMap<CompressedAddress, IdentityHash, BuildHasherDefault<CompressedAddressHasher>>,
+}
+
+impl IdentityHashes {
+ pub fn len(&self) -> usize {
+ self.hashes.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.hashes.is_empty()
+ }
+
+ /// Notes that a cell with identity hash state `state` moved from `from` to `to`, and returns the state of the copy.
+ pub fn did_move(&mut self, state: u8, from: CompressedAddress, to: CompressedAddress) -> u8 {
+ if state & IDENTITY_HASH_HASHED == 0 {
+ return state;
+ }
+ let hash = if state & IDENTITY_HASH_MOVED != 0 {
+ self.hashes
+ .remove(&from)
+ .expect("a cell that moved since it was hashed has an entry")
+ } else {
+ IdentityHash(from.0)
+ };
+ self.hashes.insert(to, hash);
+ state | IDENTITY_HASH_MOVED
+ }
+
+ /// Drops the entries of the cells that `is_live` says died.
+ pub fn retain_live(&mut self, mut is_live: impl FnMut(CompressedAddress) -> bool) {
+ self.hashes.retain(|&address, _| is_live(address));
+ }
+
+ fn get(&self, address: CompressedAddress) -> IdentityHash {
+ *self
+ .hashes
+ .get(&address)
+ .expect("a cell that moved since it was hashed has an entry")
+ }
+}
+
+unsafe extern "C" {
+ /// Where a LibGC heap keeps its side table, which CAPI.cpp defines.
+ fn gc_heap_identity_hashes(heap: *mut c_void) -> *mut *mut c_void;
+}
+
+/// The side table of `heap`, which this creates if it has none yet.
+///
+/// # Safety
+///
+/// `heap` must be a live LibGC heap, used on this thread.
+pub unsafe fn identity_hashes_of<'a>(heap: *mut c_void) -> &'a mut IdentityHashes {
+ // SAFETY: The caller passes a live heap, whose table only its thread uses.
+ unsafe {
+ let slot = gc_heap_identity_hashes(heap).cast::<*mut IdentityHashes>();
+ if (*slot).is_null() {
+ *slot = Box::into_raw(Box::default());
+ }
+ &mut **slot
+ }
+}
+
+/// Destroys a side table that rust_gc_identity_hash() or the mover created.
+///
+/// # Safety
+///
+/// `table` must be null or a table that nothing uses any more.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_identity_hashes_destroy(table: *mut IdentityHashes) {
+ if !table.is_null() {
+ // SAFETY: The caller passes a table this crate created and nothing uses.
+ drop(unsafe { Box::from_raw(table) });
+ }
+}
+
+/// The identity hash of the cell at `cell`.
+///
+/// # Safety
+///
+/// `cell` must be a live cell, of a heap that this thread uses.
+#[inline]
+pub unsafe fn identity_hash(heap_region_base: usize, cell: usize) -> IdentityHash {
+ let state = (cell + IDENTITY_HASH_STATE_OFFSET) as *mut u8;
+ let compressed = CompressedAddress((cell >> COMPRESSED_POINTER_SHIFT) as u32);
+ // SAFETY: The caller passes a live cell, whose header has the state byte, and which only this thread touches.
+ unsafe {
+ let value = state.read();
+ if value & IDENTITY_HASH_MOVED == 0 {
+ if value & IDENTITY_HASH_HASHED == 0 {
+ state.write(value | IDENTITY_HASH_HASHED);
+ }
+ return IdentityHash(compressed.0);
+ }
+ let heap = descriptor_for(heap_region_base, cell).heap();
+ identity_hashes_of(heap).get(compressed)
+ }
+}
+
+/// identity_hash(), for C++ and for LibJS's runtime, whose inline fast paths hand it the cells that moved.
+///
+/// # Safety
+///
+/// As for identity_hash().
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_cell_identity_hash(heap_region_base: usize, cell: *const c_void) -> u32 {
+ debug_assert!(
+ cell.addr() & (BLOCK_SIZE - 1) != 0,
+ "a cell is never at the start of its block"
+ );
+ // SAFETY: The caller passes a live cell.
+ unsafe { identity_hash(heap_region_base, cell.addr()) }.0
+}
+
+/// Drops the entries of the cells that the collection that just marked found dead, from a heap's side table.
+///
+/// # Safety
+///
+/// `table` must be null or the side table of the heap that just marked, while its marks are valid.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_identity_hashes_drop_dead(table: *mut IdentityHashes, heap_region_base: usize) {
+ // SAFETY: The caller passes null or a live table.
+ let Some(table) = (unsafe { table.as_mut() }) else {
+ return;
+ };
+ table.retain_live(|address| {
+ let cell = heap_region_base + ((address.0 as usize) << COMPRESSED_POINTER_SHIFT);
+ // SAFETY: Every entry is of a cell of the heap that marked, whose block is live until the cell is swept.
+ unsafe { descriptor_for(heap_region_base, cell) }.is_marked(cell)
+ });
+}
diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rs
index 0114b7c2bfe..249c18b4fc2 100644
--- a/Libraries/LibGC/Rust/src/lib.rs
+++ b/Libraries/LibGC/Rust/src/lib.rs
@@ -16,12 +16,25 @@ mod rust_demangle;
mod rust_panic;
mod block;
+mod evacuation;
+mod identity_hash;
mod marker;
mod os;
mod pool;
pub use block::{BlockDescriptor, rust_gc_block_descriptor_commit, rust_gc_block_descriptor_table};
+pub use evacuation::{
+ CellMove, EvacuationLayout, EvacuationSet, PinReason, rust_gc_evacuation_add_block, rust_gc_evacuation_create,
+ rust_gc_evacuation_destroy, rust_gc_evacuation_fix_up_slots, 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,
+};
+pub use identity_hash::{
+ IDENTITY_HASH_HASHED, IDENTITY_HASH_MOVED, IDENTITY_HASH_STATE_OFFSET, IdentityHashes, rust_gc_cell_identity_hash,
+ rust_gc_identity_hashes_destroy, rust_gc_identity_hashes_drop_dead,
+};
pub use marker::{
- MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_thread_count, rust_gc_marker_visit_cell,
- rust_gc_marker_visit_ephemeron, rust_gc_marker_visit_values,
+ MarkRequest, Marker, MarkerLayout, rust_gc_marker_mark, rust_gc_marker_pin_cell, rust_gc_marker_thread_count,
+ rust_gc_marker_visit_cell, rust_gc_marker_visit_ephemeron, rust_gc_marker_visit_interior_pointer,
+ rust_gc_marker_visit_member, rust_gc_marker_visit_self_pointer, rust_gc_marker_visit_values,
};
diff --git a/Libraries/LibGC/Rust/src/marker.rs b/Libraries/LibGC/Rust/src/marker.rs
index 02c248d1714..a4b81df84cc 100644
--- a/Libraries/LibGC/Rust/src/marker.rs
+++ b/Libraries/LibGC/Rust/src/marker.rs
@@ -25,10 +25,11 @@ use std::sync::Barrier;
use crossbeam_deque::{Injector, Steal, Stealer, Worker};
use crate::block::{BLOCK_SIZE, BlockDescriptor, descriptor_table, heap_of_descriptor};
+use crate::evacuation::{EvacuationSet, PinReason, RecordedSlot, SlotKind};
use crate::pool::{Pool, PoolGuard, thread_count};
use crate::rust_panic::abort_on_panic;
-const COMPRESSED_POINTER_SHIFT: u32 = 3;
+pub(crate) const COMPRESSED_POINTER_SHIFT: u32 = 3;
/// How many cells the thread that collects marks alone before the helpers join in, which takes about as long as waking
/// them. Collections that mark fewer are done before then.
@@ -76,6 +77,8 @@ pub struct MarkRequest {
pub marked_external_bytes: *mut usize,
/// Set to the number of threads that marked.
pub threads_used: usize,
+ /// The evacuation state of a collection that moves cells, which gets the slots marking records, or null.
+ pub evacuation: *mut EvacuationSet,
}
type VisitEdges = unsafe extern "C" fn(cell: *mut c_void, visitor: *mut c_void);
@@ -124,6 +127,8 @@ pub struct Marker {
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)>>,
+ /// The slots that point into evacuated blocks, which a collection that moves cells rewrites.
+ recorded_slots: UnsafeCell<Vec<RecordedSlot>>,
}
impl Job<'_> {
@@ -164,6 +169,12 @@ impl Job<'_> {
// the mark bits, which are atomic.
Some((heap_index, unsafe { descriptor.as_ref() }))
}
+
+ /// Whether `address` is in the heap region, and so in a cell, since the collector only records slots in cells.
+ #[inline(always)]
+ fn is_in_heap_region(&self, address: usize) -> bool {
+ (address.wrapping_sub(self.layout.heap_region_base) as u64) <= self.layout.value_offset_mask
+ }
}
impl Marker {
@@ -173,13 +184,71 @@ impl Marker {
}
/// Sets the mark bit of the cell at `address` if it is in one of the heaps being collected, and queues the cell if
- /// that was news, which this returns.
+ /// that was news, which this returns. This is a visit by value, which pins the cell if its block is evacuated.
#[inline(always)]
fn mark(&self, address: usize) -> bool {
+ self.mark_pinned(address, PinReason::Edge)
+ }
+
+ #[inline(always)]
+ fn mark_pinned(&self, address: usize, reason: PinReason) -> bool {
let job = self.job();
let Some((_, descriptor)) = job.descriptor_in_domain(address) else {
return false;
};
+ if let Some(evacuation) = descriptor.evacuation() {
+ evacuation.pin(descriptor, address, reason);
+ }
+ self.mark_in(descriptor, address)
+ }
+
+ /// Marks the cell at `address`, which a slot at `slot` points to. If the cell's block is evacuated, the slot is
+ /// recorded, so that it can be rewritten once the cell moves, or the cell pinned if the slot is not in a cell.
+ #[inline(always)]
+ fn mark_through_slot(&self, slot: RecordedSlot, address: usize) {
+ let job = self.job();
+ let Some((_, descriptor)) = job.descriptor_in_domain(address) else {
+ return;
+ };
+ if let Some(evacuation) = descriptor.evacuation() {
+ if 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 {
+ evacuation.pin(descriptor, address, PinReason::Edge);
+ }
+ }
+ self.mark_in(descriptor, address);
+ }
+
+ /// Pins the cell at `address` without marking it, for a weak reference that the collector cannot update.
+ fn pin(&self, address: usize) {
+ let job = self.job();
+ let Some((_, descriptor)) = job.descriptor_in_domain(address) else {
+ return;
+ };
+ if let Some(evacuation) = descriptor.evacuation() {
+ evacuation.pin(descriptor, address, PinReason::Edge);
+ }
+ }
+
+ /// 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) {
+ let job = self.job();
+ if !job.is_in_heap_region(slot) {
+ return;
+ }
+ if let Some((_, descriptor)) = job.descriptor_in_domain(slot)
+ && 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));
+ }
+ }
+
+ #[inline(always)]
+ fn mark_in(&self, descriptor: &BlockDescriptor, address: usize) -> bool {
+ let job = self.job();
let newly_marked = if self.shared.get() {
descriptor.mark(address)
} else {
@@ -206,18 +275,37 @@ impl Marker {
newly_marked
}
+ /// Marks the cells of the values in `values`, which are slots.
#[inline(always)]
fn visit_values(&self, values: &[u64]) {
let layout = &self.job().layout;
- for &value in values {
- if value & layout.value_is_cell_pattern == layout.value_is_cell_pattern {
- self.mark(layout.heap_region_base + (value & layout.value_offset_mask) as usize);
+ 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),
+ layout.heap_region_base + (bits & layout.value_offset_mask) as usize,
+ );
}
}
}
+ /// Marks the cell a compressed pointer at `slot` points to, if it is not null.
+ #[inline(always)]
+ fn visit_member(&self, slot: *const u32) {
+ // SAFETY: The caller passes a live slot.
+ 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);
+ }
+ }
+
fn visit_ephemeron(&self, key: usize, value: usize) {
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);
// NB: Keys outside the heaps being collected are never marked here, so their values stay reachable.
if job
.descriptor_in_domain(key)
@@ -449,6 +537,55 @@ 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 cell that the compressed pointer at `slot` points to, if it is not null, as a slot the collector can update.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell(), and `slot` must hold a compressed cell pointer or 0.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_member(marker: *mut Marker, slot: *const u32) {
+ // SAFETY: The caller passes a live marker and slot.
+ unsafe { &*marker }.visit_member(slot);
+}
+
+/// Marks `cell`, which the pointer at `slot` points into, as a slot the collector can update.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell(), and `slot` must hold a pointer into `cell`, past its start.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_interior_pointer(
+ marker: *mut Marker,
+ slot: *const usize,
+ cell: *const c_void,
+) {
+ // SAFETY: The caller passes a live marker.
+ unsafe { &*marker }.mark_through_slot(RecordedSlot::new(slot.addr(), 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.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell(), and `slot` must be in a cell being visited, and point into it, up to one past
+/// its end.
+#[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());
+}
+
+/// Keeps `cell` from moving, without marking it, for a weak reference the collector cannot update.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell().
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_pin_cell(marker: *mut Marker, cell: *const c_void) {
+ // SAFETY: The caller passes a live marker.
+ 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.
///
/// # Safety
@@ -515,6 +652,7 @@ fn mark(request: &mut MarkRequest, heaps: &[*const c_void], roots: &[*const c_vo
marked_cell_bytes: (0..heaps.len()).map(|_| Cell::new(0)).collect(),
marked_external_bytes: (0..heaps.len()).map(|_| Cell::new(0)).collect(),
pending_ephemerons: UnsafeCell::new(Vec::new()),
+ recorded_slots: UnsafeCell::new(Vec::new()),
});
}
// NB: The job lives on this stack until every marker is done with it, so the markers may point at it as if it lived
@@ -528,7 +666,7 @@ fn mark(request: &mut MarkRequest, heaps: &[*const c_void], roots: &[*const c_vo
let owner = &job.markers[0];
owner.create_visitor();
for &root in roots {
- owner.mark(root.addr());
+ owner.mark_pinned(root.addr(), PinReason::Root);
}
// NB: Collections that mark few cells are done before helpers could have started.
@@ -580,4 +718,12 @@ fn mark(request: &mut MarkRequest, heaps: &[*const c_void], roots: &[*const c_vo
}
}
request.threads_used = threads_used;
+
+ // SAFETY: The caller passes null or a live evacuation set, which nothing else uses meanwhile.
+ if let Some(evacuation) = unsafe { request.evacuation.as_mut() } {
+ for marker in &job.markers {
+ // SAFETY: Every marker is done.
+ evacuation.add_recorded_slots(core::mem::take(unsafe { &mut *marker.recorded_slots.get() }));
+ }
+ }
}
diff --git a/Libraries/LibGC/WeakBlock.h b/Libraries/LibGC/WeakBlock.h
index 384ab576ad0..86a890d0d08 100644
--- a/Libraries/LibGC/WeakBlock.h
+++ b/Libraries/LibGC/WeakBlock.h
@@ -27,6 +27,19 @@ public:
void sweep();
+ // Points every weak pointer at the cell that its cell moved to, which forwarding_address returns, or null if the
+ // cell did not move.
+ template<typename Callback>
+ void update_moved_cells(Callback forwarding_address)
+ {
+ for (auto& impl : m_impls) {
+ if (impl.state() != WeakImpl::State::Allocated || !impl.ptr())
+ continue;
+ if (auto* moved_to = forwarding_address(impl.ptr()))
+ impl.set_ptr({}, moved_to);
+ }
+ }
+
private:
WeakBlock();
~WeakBlock();
diff --git a/Libraries/LibGC/WeakHashMap.h b/Libraries/LibGC/WeakHashMap.h
index 21b8c85e4d9..e64f1f3a03e 100644
--- a/Libraries/LibGC/WeakHashMap.h
+++ b/Libraries/LibGC/WeakHashMap.h
@@ -28,7 +28,7 @@ class WeakHashMap {
static unsigned hash(KeyStorage const& value)
{
if constexpr (key_is_cell)
- return Traits<K const*>::hash(value.ptr().ptr());
+ return weak_key_hash(value.ptr().ptr());
else
return Traits<K>::hash(value);
}
@@ -187,7 +187,7 @@ private:
auto find_iterator(K const& key) const -> typename TableType::ConstIteratorType
{
if constexpr (key_is_cell) {
- return m_table.find(Traits<K const*>::hash(&key), [&](auto& entry) {
+ return m_table.find(weak_key_hash(&key), [&](auto& entry) {
return entry.key.ptr().ptr() == &key;
});
} else {
@@ -198,7 +198,7 @@ private:
auto find_iterator(K const& key) -> typename TableType::IteratorType
{
if constexpr (key_is_cell) {
- return m_table.find(Traits<K const*>::hash(&key), [&](auto& entry) {
+ return m_table.find(weak_key_hash(&key), [&](auto& entry) {
return entry.key.ptr().ptr() == &key;
});
} else {
diff --git a/Libraries/LibGC/WeakHashSet.h b/Libraries/LibGC/WeakHashSet.h
index 2890cb2a167..29b907eda14 100644
--- a/Libraries/LibGC/WeakHashSet.h
+++ b/Libraries/LibGC/WeakHashSet.h
@@ -16,7 +16,7 @@ class WeakHashSet {
struct InternalTraits : public DefaultTraits<Weak<T>> {
static unsigned hash(Weak<T> const& value)
{
- return Traits<T*>::hash(value.ptr().ptr());
+ return weak_key_hash(value.ptr().ptr());
}
};
@@ -34,7 +34,7 @@ public:
bool remove(T& value)
{
maybe_prune();
- auto it = m_table.find(Traits<T*>::hash(&value), [&](auto& entry) { return entry.ptr().ptr() == &value; });
+ auto it = m_table.find(weak_key_hash(&value), [&](auto& entry) { return entry.ptr().ptr() == &value; });
if (it == m_table.end())
return false;
m_table.remove(it);
@@ -43,7 +43,7 @@ public:
bool contains(T& value) const
{
- auto it = m_table.find(Traits<T*>::hash(&value), [&](auto& entry) { return entry.ptr().ptr() == &value; });
+ auto it = m_table.find(weak_key_hash(&value), [&](auto& entry) { return entry.ptr().ptr() == &value; });
return it != m_table.end();
}
diff --git a/Libraries/LibJS/Rust/generate/layout_forward.rs b/Libraries/LibJS/Rust/generate/layout_forward.rs
index 8577647aa60..9e7f50e8054 100644
--- a/Libraries/LibJS/Rust/generate/layout_forward.rs
+++ b/Libraries/LibJS/Rust/generate/layout_forward.rs
@@ -51,6 +51,15 @@ pub struct Utf16StringDataHeader {
pub flags: u32,
}
+/// The crate's tests never dereference cells, so they hash the compressed address, as cells that never moved do.
+///
+/// # Safety
+///
+/// None, unlike the real one.
+pub unsafe fn cell_identity_hash(cell: *const core::ffi::c_void) -> u32 {
+ (cell.addr() >> 3) as u32
+}
+
/// The build script never decodes compressed pointers. The crate's tests decode them against this base, which is
/// aligned like LibGC aligns the real one, and where nothing is mapped.
pub fn heap_region_base() -> usize {
diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rs
index d271b477ccb..780d6af4d26 100644
--- a/Libraries/LibJS/Rust/src/gc/capi.rs
+++ b/Libraries/LibJS/Rust/src/gc/capi.rs
@@ -69,6 +69,9 @@ pub struct GCLayout {
pub heap_region_offset_mask: u64,
pub primitive_storage_cage_offset_mask: u64,
pub visitor_marker_offset: u32,
+ pub identity_hash_state_offset: u32,
+ pub identity_hash_hashed: u8,
+ pub identity_hash_moved: u8,
}
/// The generation of the storage's table entry in the high 32 bits and the entry's index in the low 32 bits.
@@ -100,6 +103,9 @@ unsafe extern "C" {
pub fn gc_heap_destroy(heap: *mut GCHeap);
// NB: The functions that take a reference to the heap have no other preconditions.
pub safe fn gc_heap_collect_garbage(heap: &GCHeap, collection_type: i32, print_report: bool);
+ // NB: A collection that does not scan the stack may collect or move the cells that only the stack holds.
+ pub fn gc_heap_collect_garbage_without_scanning_the_stack(heap: &GCHeap);
+ pub safe fn gc_heap_moves_everything() -> bool;
pub safe fn gc_heap_is_collecting_everything(heap: &GCHeap) -> bool;
pub safe fn gc_heap_is_marking_for_collection(heap: &GCHeap) -> bool;
pub safe fn gc_heap_is_returning_memory_to_system(heap: &GCHeap) -> bool;
@@ -127,14 +133,22 @@ unsafe extern "C" {
) -> *mut GCAllocator;
pub fn gc_allocator_destroy(allocator: *mut GCAllocator);
pub fn gc_allocator_set_traced_on_owner_thread_only(allocator: *mut GCAllocator);
+ pub fn gc_allocator_set_movable(allocator: *mut GCAllocator);
pub fn gc_heap_allocate_cell(heap: *mut GCHeap, allocator: *mut GCAllocator) -> *mut c_void;
pub fn gc_heap_allocate_storage_cell(heap: *mut GCHeap, allocator: *mut GCAllocator) -> *mut c_void;
pub fn gc_heap_allocator_local_free_list(heap: *mut GCHeap, allocator: *mut GCAllocator) -> *mut *mut c_void;
pub fn gc_cell_heap_context(cell: *const c_void) -> *mut c_void;
pub fn gc_cell_type_info(cell: *const c_void) -> *const CellTypeInfo;
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_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_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_root_create(cell: *mut c_void) -> *mut GCRoot;
pub fn gc_root_destroy(root: *mut GCRoot);
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index 8443d0a043a..0df4007beee 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -122,6 +122,16 @@ impl Class {
self.owner_thread_only
}
+ /// Whether collections that do not scan the stack may move the cells of this class, see gc_allocator_set_movable().
+ /// A class may only be movable if everything that keeps the address of its cells visits it through a slot, pins
+ /// the cell, or forgets the address when the cell moves. Classes derived at run time, such as an embedder's host
+ /// objects, never are, as the embedder keeps their addresses.
+ pub fn is_movable(&self) -> bool {
+ // FIXME: No class is movable yet.
+ let _ = self;
+ false
+ }
+
/// What Cell::class_name() returns for the cells of this class, which printing and messages show. It is the name
/// of the class unless the Rust type is spelled differently.
pub fn class_name(&self) -> &'static str {
@@ -418,7 +428,7 @@ impl CellHeaderTail {
/// The header of a cell of `class` that keeps fields of its own in the first word, like `CellHeader::for_class()`.
pub fn for_class(class: &'static Class) -> Self {
Self {
- unused_byte: 0,
+ identity_hash_state: core::cell::Cell::new(0),
state: CellState::Live.into(),
kind: class.kind(),
}
@@ -430,7 +440,7 @@ impl CellHeader {
pub fn for_class(class: &'static Class) -> Self {
Self {
unused: [0; 8],
- unused_byte: 0,
+ identity_hash_state: core::cell::Cell::new(0),
state: CellState::Live.into(),
kind: class.kind(),
}
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index 1522f2730fa..6d6081bd851 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -524,6 +524,11 @@ impl Heap {
// SAFETY: The allocator is live and has not allocated yet.
unsafe { capi::gc_allocator_set_traced_on_owner_thread_only(raw.as_ptr()) };
}
+ // NB: The classes derived at run time that share an allocator are never movable.
+ if class.is_movable() && !class_in_tail {
+ // SAFETY: The allocator is live and has not allocated yet.
+ unsafe { capi::gc_allocator_set_movable(raw.as_ptr()) };
+ }
// SAFETY: The heap and the allocator are live.
let local_free_list = unsafe { capi::gc_heap_allocator_local_free_list(self.raw.as_ptr(), raw.as_ptr()) };
HeapAllocator { raw, local_free_list }
@@ -691,6 +696,23 @@ impl Heap {
capi::gc_heap_collect_garbage(self.handle(), capi::GC_COLLECTION_TYPE_COLLECT_GARBAGE, false);
}
+ /// Collects garbage without scanning the stack, so that only roots keep cells alive, and cells may move.
+ ///
+ /// # Safety
+ ///
+ /// The caller, and every frame above it, must hold no cell that is not rooted, since such a cell may be collected
+ /// or moved.
+ pub unsafe fn collect_garbage_without_scanning_the_stack(&self) {
+ // SAFETY: The caller vouches that the stack holds no cell that is not rooted.
+ unsafe { capi::gc_heap_collect_garbage_without_scanning_the_stack(self.handle()) };
+ }
+
+ /// Whether LIBGC_MOVE_EVERYTHING has collections that do not scan the stack move every cell they can, which test
+ /// runners use to collect that way where they safely can.
+ pub fn moves_everything() -> bool {
+ capi::gc_heap_moves_everything()
+ }
+
/// Calls `callback` with `context` during every collection, after marking and finalization and before dead cells
/// are swept, so that weak holders can drop the cells whose mark is clear.
///
@@ -812,6 +834,22 @@ fn check_layout() -> GCLayout {
offset_of!(CellHeader, kind) as u64,
);
expect("block size", layout.block_size.into(), BLOCK_SIZE as u64);
+ expect(
+ "identity hash state offset",
+ layout.identity_hash_state_offset.into(),
+ crate::layout_forward::IDENTITY_HASH_STATE_OFFSET as u64,
+ );
+ expect(
+ "identity hash state offset in the cell header",
+ layout.identity_hash_state_offset.into(),
+ offset_of!(CellHeader, identity_hash_state) as u64,
+ );
+ expect(
+ "identity hash bits",
+ u64::from(layout.identity_hash_hashed) | (u64::from(layout.identity_hash_moved) << 8),
+ u64::from(crate::layout_forward::IDENTITY_HASH_HASHED)
+ | (u64::from(crate::layout_forward::IDENTITY_HASH_MOVED) << 8),
+ );
expect(
"block foreign type offset",
layout.block_foreign_type_offset.into(),
diff --git a/Libraries/LibJS/Rust/src/gc/visitor.rs b/Libraries/LibJS/Rust/src/gc/visitor.rs
index 161f997c957..33c4d3291df 100644
--- a/Libraries/LibJS/Rust/src/gc/visitor.rs
+++ b/Libraries/LibJS/Rust/src/gc/visitor.rs
@@ -8,7 +8,8 @@ use core::cell::Cell;
use core::ptr::NonNull;
use super::capi::{
- GCMarker, GCVisitor, gc_marker_visit_cell, gc_marker_visit_values, gc_visitor_visit_cell,
+ 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,
};
use crate::layout::cell::Gc;
@@ -49,6 +50,9 @@ impl Visitor {
self.0.as_ptr()
}
+ /// Visits a cell by value, which keeps it where it is in a collection that moves cells, since the collector cannot
+ /// update the copy of the pointer that the caller keeps. Edges that live in a cell should be visited through their
+ /// slot instead, with visit_member(), visit_nullable_member() or visit_values().
pub fn visit<T>(&mut self, cell: Gc<T>) {
if let Some(marker) = self.marker() {
// SAFETY: The marker is the visitor's, and a Gc points to a live cell.
@@ -59,19 +63,58 @@ impl Visitor {
unsafe { gc_visitor_visit_cell(self.0.as_ptr(), cell.as_ptr().cast()) };
}
- /// Visits the cell a member names. It takes the slot so that a collector that moves cells can update it.
+ /// Visits the cell a member names. It takes the slot, which a collection that moves the cell rewrites if the slot
+ /// is in a cell. A slot elsewhere keeps the cell where it is.
pub fn visit_member<T>(&mut self, slot: &Member<T>) {
+ if let Some(marker) = self.marker() {
+ // SAFETY: The marker is the visitor's, and the slot holds a compressed pointer to a live cell.
+ unsafe { gc_marker_visit_member(marker.as_ptr(), core::ptr::from_ref(slot).cast()) };
+ return;
+ }
self.visit(slot.get());
}
- /// Visits the cell a member names, if it is not null. It takes the slot so that a collector that moves cells can
- /// update it.
+ /// Visits the cell a member names, if it is not null, like visit_member().
pub fn visit_nullable_member<T>(&mut self, slot: &NullableMember<T>) {
+ if let Some(marker) = self.marker() {
+ // SAFETY: The marker is the visitor's, and the slot holds 0 or a compressed pointer to a live cell.
+ unsafe { gc_marker_visit_member(marker.as_ptr(), core::ptr::from_ref(slot).cast()) };
+ return;
+ }
if let Some(cell) = slot.get() {
self.visit(cell);
}
}
+ /// Visits `cell`, which the raw pointer in `slot` points into, past its start, as an object points into the cell
+ /// that holds its property storage. A collection that moves the cell rewrites the slot if it is in a cell.
+ pub fn visit_interior_pointer<T, U>(&mut self, slot: &Cell<*mut T>, cell: Gc<U>) {
+ if let Some(marker) = self.marker() {
+ // SAFETY: The marker is the visitor's, the slot holds a pointer, and the cell is live.
+ unsafe { gc_marker_visit_interior_pointer(marker.as_ptr(), slot.as_ptr().cast(), cell.as_ptr().cast()) };
+ return;
+ }
+ self.visit(cell);
+ }
+
+ /// Notes that the raw pointer in `slot` points into the cell that holds the slot, up to one past its end, as an
+ /// object points to its inline property storage. A collection that moves the cell points the slot into the copy.
+ pub fn visit_self_pointer<T>(&mut self, slot: &Cell<*mut T>) {
+ if let Some(marker) = self.marker() {
+ // SAFETY: The marker is the visitor's, and the slot is in the cell being visited.
+ unsafe { gc_marker_visit_self_pointer(marker.as_ptr(), slot.as_ptr().cast()) };
+ }
+ }
+
+ /// Keeps `cell` where it is in a collection that moves cells, without keeping it alive, for a weak reference that
+ /// the collector cannot update.
+ pub fn pin<T: ?Sized>(&mut self, cell: Gc<T>) {
+ if let Some(marker) = self.marker() {
+ // SAFETY: The marker is the visitor's, and the cell is live.
+ unsafe { gc_marker_pin_cell(marker.as_ptr(), cell.as_ptr().cast()) };
+ }
+ }
+
pub fn visit_values(&mut self, values: &[Value]) {
if let Some(marker) = self.marker() {
if !values.is_empty() {
@@ -285,9 +328,10 @@ unsafe impl Trace for Value {
}
}
-// SAFETY: Forwards to the current value.
+// SAFETY: Forwards to the current value, in place, so that a collection that moves cells can update a slot in it.
unsafe impl<T: Copy + Trace> Trace for Cell<T> {
fn trace(&self, visitor: &mut Visitor) {
- self.get().trace(visitor);
+ // SAFETY: Nothing writes the value while it is traced, since the mutator waits for tracing to end.
+ unsafe { &*self.as_ptr() }.trace(visitor);
}
}
diff --git a/Libraries/LibJS/Rust/src/layout/cell.rs b/Libraries/LibJS/Rust/src/layout/cell.rs
index 42b1c382804..5364581053c 100644
--- a/Libraries/LibJS/Rust/src/layout/cell.rs
+++ b/Libraries/LibJS/Rust/src/layout/cell.rs
@@ -45,10 +45,11 @@ impl<T: ?Sized> PartialEq for Gc<T> {
impl<T: ?Sized> Eq for Gc<T> {}
-/// Hashes the address, like the pointer traits of AK's hash tables.
+/// Hashes the identity of the cell, which stays the same wherever the collector moves it.
impl<T: ?Sized> core::hash::Hash for Gc<T> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
- self.0.as_ptr().cast::<()>().addr().hash(state);
+ // SAFETY: A Gc points at a live cell.
+ state.write_u32(unsafe { crate::layout_forward::cell_identity_hash(self.0.as_ptr().cast()) });
}
}
@@ -84,8 +85,8 @@ pub enum CellState {
#[repr(C, packed)]
pub struct CellHeader {
pub unused: [u8; 8],
- /// Free for later use: LibGC keeps the marks of cells in the descriptors of their blocks.
- pub unused_byte: u8,
+ /// The state of the cell's identity hash, which LibGC keeps here, see `cell_identity_hash()`.
+ pub identity_hash_state: Cell<u8>,
pub state: Cell<CellState>,
pub kind: CellKind,
}
@@ -95,7 +96,7 @@ const _: () = assert!(size_of::<CellHeader>() == 11);
/// The header of a cell that keeps fields of its own in the first word, which comes right after those fields.
#[repr(C, packed)]
pub struct CellHeaderTail {
- pub unused_byte: u8,
+ pub identity_hash_state: Cell<u8>,
pub state: Cell<CellState>,
pub kind: CellKind,
}
diff --git a/Libraries/LibJS/Rust/src/layout/object.rs b/Libraries/LibJS/Rust/src/layout/object.rs
index 91dbd7ccb69..b445c8108a9 100644
--- a/Libraries/LibJS/Rust/src/layout/object.rs
+++ b/Libraries/LibJS/Rust/src/layout/object.rs
@@ -58,8 +58,8 @@ pub const INDEXED_ELEMENTS_HEADER_SIZE: usize = 8;
pub struct Object {
pub shape: Member<Shape>,
pub indexed_array_like_size: Cell<u32>,
- /// Free for later use, see CellHeader::unused_byte.
- pub unused_byte: u8,
+ /// See CellHeader::identity_hash_state.
+ pub identity_hash_state: Cell<u8>,
pub state: Cell<CellState>,
pub kind: CellKind,
pub indexed_storage_kind: Cell<IndexedStorageKind>,
@@ -82,7 +82,7 @@ pub struct Object {
const _: () = {
use core::mem::offset_of;
- assert!(offset_of!(Object, unused_byte) == offset_of!(CellHeader, unused_byte));
+ assert!(offset_of!(Object, identity_hash_state) == offset_of!(CellHeader, identity_hash_state));
assert!(offset_of!(Object, state) == offset_of!(CellHeader, state));
assert!(offset_of!(Object, kind) == offset_of!(CellHeader, kind));
};
diff --git a/Libraries/LibJS/Rust/src/layout_forward.rs b/Libraries/LibJS/Rust/src/layout_forward.rs
index 51091ee7cf3..43466113f5e 100644
--- a/Libraries/LibJS/Rust/src/layout_forward.rs
+++ b/Libraries/LibJS/Rust/src/layout_forward.rs
@@ -112,5 +112,32 @@ pub fn initialize_heap_region_base() {
});
}
+/// Where a cell keeps the state of its identity hash, and its bits, which the startup layout check compares with LibGC's.
+pub const IDENTITY_HASH_STATE_OFFSET: usize = 8;
+pub const IDENTITY_HASH_HASHED: u8 = 1 << 0;
+pub const IDENTITY_HASH_MOVED: u8 = 1 << 1;
+
+/// The identity hash of the cell at `cell`, which stays the same while the cell lives, wherever the collector moves it.
+/// This is the fast path of LibGC's gc_cell_identity_hash(), which it calls only for cells that moved since they were
+/// first hashed.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of a heap of this thread.
+#[inline(always)]
+pub unsafe fn cell_identity_hash(cell: *const c_void) -> u32 {
+ // SAFETY: The caller passes a live cell, whose header has the state byte, which only this thread touches.
+ let state = unsafe { &*cell.byte_add(IDENTITY_HASH_STATE_OFFSET).cast::<Cell<u8>>() };
+ let bits = state.get();
+ if bits & IDENTITY_HASH_MOVED == 0 {
+ if bits & IDENTITY_HASH_HASHED == 0 {
+ state.set(bits | IDENTITY_HASH_HASHED);
+ }
+ return (cell.addr() >> crate::layout::member::COMPRESSED_POINTER_SHIFT) as u32;
+ }
+ // SAFETY: The caller passes a live cell.
+ unsafe { crate::gc::capi::gc_cell_identity_hash(cell) }
+}
+
const _: () =
assert!(crate::layout::member::COMPRESSED_POINTER_RANGE == crate::build_configuration::HEAP_REGION_OFFSET_MASK + 1);
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 7b834952c7c..e31b2d39833 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -325,12 +325,17 @@ unsafe impl Trace for Object {
// a collection.
visitor.visit_values(unsafe { ak::slice_from_raw_parts(named_properties, property_count) });
}
- if !named_properties.is_null()
- && !self.named_storage_is_inline()
- // SAFETY: Out-of-line named storage is storage value_storage::allocate() returned.
- && let Some(storage) = unsafe { value_storage::cell(named_properties) }
- {
- visitor.visit(storage);
+ // 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.
+ if !named_properties.is_null() {
+ if self.named_storage_is_inline() {
+ visitor.visit_self_pointer(&self.named_properties);
+ } else if let Some(storage) =
+ // SAFETY: Out-of-line named storage is storage value_storage::allocate() returned.
+ unsafe { value_storage::cell(named_properties) }
+ {
+ visitor.visit_interior_pointer(&self.named_properties, storage);
+ }
}
match self.indexed_storage_kind() {
@@ -350,7 +355,7 @@ unsafe impl Trace for Object {
// SAFETY: Packed and holey indexed storage is storage value_storage::allocate() returned.
&& let Some(storage) = unsafe { value_storage::cell(indexed_elements) }
{
- visitor.visit(storage);
+ visitor.visit_interior_pointer(&self.indexed_elements, storage);
}
}
}
@@ -579,7 +584,7 @@ impl Object {
let object = Object {
shape: Member::new(shape),
indexed_array_like_size: Cell::new(0),
- unused_byte: 0,
+ identity_hash_state: Cell::new(0),
state: Cell::new(CellState::Live),
kind: CellKind::Object,
indexed_storage_kind: Cell::new(IndexedStorageKind::None),
diff --git a/Libraries/LibJS/Rust/src/runtime/value_traits.rs b/Libraries/LibJS/Rust/src/runtime/value_traits.rs
index 3fbddb5adcc..956a253a077 100644
--- a/Libraries/LibJS/Rust/src/runtime/value_traits.rs
+++ b/Libraries/LibJS/Rust/src/runtime/value_traits.rs
@@ -40,7 +40,13 @@ impl Hash for ValueTraitsKey {
value = Value::from_f64(f64::NAN);
}
- // FIXME: Is this the best way to hash pointers, doubles & ints?
+ // NB: A cell may move, so it is hashed by its identity, not its address.
+ if value.is_cell() {
+ value.as_cell().hash(state);
+ return;
+ }
+
+ // FIXME: Is this the best way to hash doubles & ints?
state.write_u64(value.0);
}
}
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
index 670ac80ff4a..42545b82d05 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
@@ -19,6 +19,8 @@ use super::test_runner::{
get_time_in_ms, iterate_directory_recursively, print_modifiers, set_currently_running_test,
};
use crate::gc::class::{GcCell, define_cell};
+use crate::gc::heap::Heap;
+use crate::gc::root::Root;
use crate::hash_table::HashTable;
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
@@ -391,6 +393,17 @@ impl TestRunner {
let top_level_result = vm.run_script(file_script, None);
vm.pop_execution_context();
+ // NB: With LIBGC_MOVE_EVERYTHING, the objects the test left behind move before their results are read. Nothing
+ // on the stack holds a cell then but the error of the script, which this roots, and the realm, which the
+ // global execution context keeps.
+ let top_level_error = top_level_result.err().map(|throw| Root::new(vm, throw.value()));
+ if Heap::moves_everything() {
+ vm.push_execution_context(global_execution_context);
+ // SAFETY: Every cell the runner holds is rooted, see above, and test-js holds none further up.
+ unsafe { vm.heap().collect_garbage_without_scanning_the_stack() };
+ vm.pop_execution_context();
+ }
+
vm.push_execution_context(global_execution_context);
let test_json = get_test_results(vm, realm);
vm.pop_execution_context();
@@ -492,7 +505,7 @@ impl TestRunner {
file_result.suites.push(suite);
}
- if let Err(throw) = top_level_result {
+ if let Some(throw) = top_level_error {
let mut suite = Suite::new(test_path, b"<top-level>".to_vec());
suite.most_severe_test_result = TestResult::Crashed;
diff --git a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
index a7263c05a35..7048fc53c60 100644
--- a/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
+++ b/Libraries/LibWeb/DOM/DocumentLoadEventDelayer.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGC/Heap.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/DocumentLoadEventDelayer.h>
@@ -45,11 +46,26 @@ DocumentLoadEventDelayer& DocumentLoadEventDelayer::operator=(DocumentLoadEventD
DocumentLoadEventDelayer::~DocumentLoadEventDelayer()
{
- 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({});
+ 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;
}
+ release(m_document, m_reason);
}
}
diff --git a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
index 31883e52cea..0094494d21d 100644
--- a/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLMediaElement.cpp
@@ -210,8 +210,20 @@ struct HTMLMediaElement::RemoteFetchData {
if (stream)
stream->set_data_request_callback(nullptr);
- if (fetch_controller)
- fetch_controller->stop_fetch();
+ 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();
}
};