Skip to content

Truly independent web browser

LibGC: Mark cells in parallel, with marks in block descriptors

Andreas Klingc3a2d9189dbc
diff --git a/Cargo.lock b/Cargo.lock
index 8c5fc99be68..a121c6f4653 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1876,6 +1876,19 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "libgc_rust"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "cbindgen",
+ "crossbeam-deque",
+ "ladybird_allocator",
+ "libc",
+ "rustc-demangle",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "libgfx_rust"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 2557a323347..c470fd63316 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,6 +4,7 @@ members = [
"Libraries/LibCompositing/Rust",
"Libraries/LibCompress/Rust",
"Libraries/LibCrypto/Rust",
+ "Libraries/LibGC/Rust",
"Libraries/LibGfx/Rust",
"Libraries/LibHTTP/Rust",
"Libraries/LibImageDecoders/Rust",
diff --git a/Libraries/LibGC/BlockDescriptor.h b/Libraries/LibGC/BlockDescriptor.h
new file mode 100644
index 00000000000..03612639261
--- /dev/null
+++ b/Libraries/LibGC/BlockDescriptor.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/BitCast.h>
+#include <AK/Platform.h>
+#include <AK/Types.h>
+#include <LibGC/HeapRegion.h>
+#include <LibGC/Internals.h>
+#include <RustFFI.h>
+
+// NB: Only LibGC's own sources include this, since RustFFI.h is generated in its build directory.
+
+namespace GC {
+
+static_assert(FFI::BLOCK_SIZE == HeapBlockBase::BLOCK_SIZE);
+
+// What the heap knows about each block lives in the block's descriptor, outside the heap region, so that nothing in a
+// block can change it: the heap and the type of the block, and the mark bits of its cells. The descriptor of a block
+// is at the index of the block in the region, in a table that LibGC's Rust core reserves once.
+extern GC_API FFI::BlockDescriptor* const g_block_descriptors;
+
+ALWAYS_INLINE FFI::BlockDescriptor& block_descriptor_for(void const* address)
+{
+ return g_block_descriptors[(bit_cast<FlatPtr>(address) - heap_region_base()) / HeapBlockBase::BLOCK_SIZE];
+}
+
+// A cell's mark bit is its offset in its block divided by the cell size, which tells the cells apart since they are a
+// cell size apart.
+// OPTIMIZATION: Dividing by the cell size is slow, so the offset is multiplied by 2^32 / cell size, rounded up, and
+// shifted right by 32. For offsets and cell sizes up to 2^14, the rounding error never reaches the next
+// whole number.
+ALWAYS_INLINE size_t mark_bit_index(FFI::BlockDescriptor const& descriptor, void const* cell)
+{
+ auto offset = static_cast<u64>(bit_cast<FlatPtr>(cell) & (HeapBlockBase::BLOCK_SIZE - 1));
+ return static_cast<size_t>((offset * descriptor.cell_index_magic) >> 32);
+}
+
+// Marking sets mark bits from several threads at once, so every access is atomic. Outside of marking, nothing else
+// writes them, so relaxed accesses are enough.
+ALWAYS_INLINE bool is_marked(FFI::BlockDescriptor const& descriptor, void const* cell)
+{
+ auto index = mark_bit_index(descriptor, cell);
+ return __atomic_load_n(&descriptor.marked[index / 64], __ATOMIC_RELAXED) & (static_cast<u64>(1) << (index % 64));
+}
+
+ALWAYS_INLINE bool is_marked(void const* cell)
+{
+ return is_marked(block_descriptor_for(cell), cell);
+}
+
+ALWAYS_INLINE void set_marked(void const* cell)
+{
+ auto& descriptor = block_descriptor_for(cell);
+ auto index = mark_bit_index(descriptor, cell);
+ __atomic_fetch_or(&descriptor.marked[index / 64], static_cast<u64>(1) << (index % 64), __ATOMIC_RELAXED);
+}
+
+ALWAYS_INLINE void clear_marks(FFI::BlockDescriptor& descriptor)
+{
+ for (auto& word : descriptor.marked)
+ __atomic_store_n(&word, 0, __ATOMIC_RELAXED);
+}
+
+// Fills in the descriptor of a block that is about to hold cells, and empties it once the block goes away.
+void publish_block_descriptor(HeapBlock&, CellAllocator&);
+void retire_block_descriptor(HeapBlock&);
+
+}
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cpp
index 6e99931e187..85b948cf2e2 100644
--- a/Libraries/LibGC/CAPI.cpp
+++ b/Libraries/LibGC/CAPI.cpp
@@ -7,6 +7,7 @@
#include <AK/StdLibExtras.h>
#include <LibCore/System.h>
#include <LibGC/BlockAllocator.h>
+#include <LibGC/BlockDescriptor.h>
#include <LibGC/CAPI.h>
#include <LibGC/Heap.h>
#include <LibGC/HeapBlock.h>
@@ -69,6 +70,7 @@ public:
CAPICellAllocator(CellTypeInfo const& type_info, StringView class_name, void const* foreign_type)
: CellAllocatorDescriptorBase(type_info, class_name, foreign_type)
{
+ set_trace_thread(TraceThread::AnyThread);
}
~CAPICellAllocator()
@@ -81,14 +83,13 @@ public:
struct CAPI {
static_assert(offsetof(ForeignCell, m_word_owned_by_the_foreign_implementation) == 0);
- static_assert(offsetof(ForeignCell, m_mark) == offsetof(Cell, m_mark));
+ static_assert(offsetof(ForeignCell, m_unused_header_byte) == offsetof(Cell, m_unused_header_byte));
static_assert(offsetof(ForeignCell, m_state) == offsetof(Cell, m_state));
static_assert(offsetof(ForeignCell, m_cell_kind) == offsetof(Cell, m_cell_kind));
static void get_layout(GCLayout& layout)
{
layout = {
- .cell_mark_offset = offsetof(Cell, m_mark),
.cell_state_offset = offsetof(Cell, m_state),
.cell_kind_offset = offsetof(Cell, m_cell_kind),
.min_cell_size = HeapBlock::min_possible_cell_size,
@@ -108,20 +109,21 @@ struct CAPI {
.block_foreign_type_offset = offsetof(HeapBlockBase, m_foreign_type),
.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()),
};
}
- static Cell* allocate_cell(Heap& heap, CellAllocatorDescriptorBase& descriptor, bool& must_mark)
+ static Cell* allocate_cell(Heap& heap, CellAllocatorDescriptorBase& descriptor)
{
auto* cell = heap.allocate_cell(descriptor);
- must_mark = heap.mark_if_allocated_during_incremental_sweep(*cell);
+ heap.mark_if_allocated_during_incremental_sweep(*cell);
return cell;
}
- static Cell* allocate_storage_cell(Heap& heap, CellAllocatorDescriptorBase& descriptor, bool& must_mark)
+ static Cell* allocate_storage_cell(Heap& heap, CellAllocatorDescriptorBase& descriptor)
{
auto* cell = heap.allocate_cell(descriptor, Heap::TriggersCollection::No);
- must_mark = heap.mark_if_allocated_during_incremental_sweep(*cell);
+ heap.mark_if_allocated_during_incremental_sweep(*cell);
return cell;
}
@@ -321,16 +323,21 @@ void gc_allocator_destroy(GCAllocator* allocator)
delete reinterpret_cast<CAPICellAllocator*>(allocator);
}
-GCCell* gc_heap_allocate_cell(GCHeap* heap, GCAllocator* allocator, bool* must_mark)
+void gc_allocator_set_traced_on_owner_thread_only(GCAllocator* allocator)
+{
+ reinterpret_cast<CAPICellAllocator*>(allocator)->set_trace_thread(TraceThread::OwnerThreadOnly);
+}
+
+GCCell* gc_heap_allocate_cell(GCHeap* heap, GCAllocator* allocator)
{
auto& descriptor = *reinterpret_cast<CAPICellAllocator*>(allocator);
- return as_gc_cell(CAPI::allocate_cell(as_heap(heap), descriptor, *must_mark));
+ return as_gc_cell(CAPI::allocate_cell(as_heap(heap), descriptor));
}
-GCCell* gc_heap_allocate_storage_cell(GCHeap* heap, GCAllocator* allocator, bool* must_mark)
+GCCell* gc_heap_allocate_storage_cell(GCHeap* heap, GCAllocator* allocator)
{
auto& descriptor = *reinterpret_cast<CAPICellAllocator*>(allocator);
- return as_gc_cell(CAPI::allocate_storage_cell(as_heap(heap), descriptor, *must_mark));
+ return as_gc_cell(CAPI::allocate_storage_cell(as_heap(heap), descriptor));
}
GCCell** gc_heap_allocator_local_free_list(GCHeap* heap, GCAllocator* allocator)
@@ -355,6 +362,11 @@ GCCellTypeInfo const* gc_cell_type_info(GCCell const* cell)
return reinterpret_cast<GCCellTypeInfo const*>(&reinterpret_cast<Cell const*>(cell)->type_info());
}
+bool gc_cell_is_marked(GCCell const* cell)
+{
+ return GC::is_marked(cell);
+}
+
GCRoot* gc_root_create(GCCell* cell)
{
return reinterpret_cast<GCRoot*>(new Root<Cell>(from_gc_cell(cell)));
@@ -416,6 +428,16 @@ void gc_visitor_visit_ephemeron(GCVisitor* visitor, GCCell* key, uint64_t const*
as_visitor(visitor).visit_ephemeron(*from_gc_cell(key), *reinterpret_cast<NanBoxedValue const*>(value));
}
+void gc_marker_visit_cell(GCMarker* marker, GCCell* cell)
+{
+ FFI::rust_gc_marker_visit_cell(reinterpret_cast<FFI::Marker*>(marker), cell);
+}
+
+void gc_marker_visit_values(GCMarker* marker, uint64_t const* values, size_t count)
+{
+ FFI::rust_gc_marker_visit_values(reinterpret_cast<FFI::Marker*>(marker), values, count);
+}
+
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 0bfb74d9d0f..78b4342daca 100644
--- a/Libraries/LibGC/CAPI.h
+++ b/Libraries/LibGC/CAPI.h
@@ -74,7 +74,6 @@ typedef struct GCCellTypeInfo {
// Everything a foreign implementation of cells needs to agree on with this build of LibGC.
typedef struct GCLayout {
- uint32_t cell_mark_offset;
uint32_t cell_state_offset;
uint32_t cell_kind_offset;
uint32_t min_cell_size;
@@ -99,6 +98,9 @@ typedef struct GCLayout {
uint32_t block_foreign_type_offset;
uint64_t heap_region_offset_mask;
uint64_t primitive_storage_cage_offset_mask;
+ // 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;
} GCLayout;
GC_API void gc_get_layout(GCLayout*);
@@ -143,15 +145,19 @@ GC_API void gc_heap_did_free_external_memory(GCHeap*, size_t);
// be destroyed.
GC_API GCAllocator* gc_allocator_create(GCCellTypeInfo const*, char const* name, size_t name_length, void const* foreign_type);
GC_API void gc_allocator_destroy(GCAllocator*);
+// Cells of allocators created here may be traced on any thread while the collector marks, as long as the thread that
+// owns their heap is stopped. This has the cells of an allocator traced only on that thread instead, for types whose
+// 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*);
-// Returns uninitialized storage for one cell. *must_mark tells the caller what to store as the cell's mark: cells that
-// are allocated while an incremental sweep is in progress have to start out marked.
-GC_API GCCell* gc_heap_allocate_cell(GCHeap*, GCAllocator*, bool* must_mark);
+// Returns uninitialized storage for one cell.
+GC_API GCCell* gc_heap_allocate_cell(GCHeap*, GCAllocator*);
// Like gc_heap_allocate_cell(), for cells that other cells keep their storage in instead of malloc memory: it never
// collects garbage, so storage can grow while its owner is between states nothing may observe, and callers can hold on
// to anything across the growth. It still counts towards the next collection, which the next allocation that may
// collect starts.
-GC_API GCCell* gc_heap_allocate_storage_cell(GCHeap*, GCAllocator*, bool* must_mark);
+GC_API GCCell* gc_heap_allocate_storage_cell(GCHeap*, GCAllocator*);
// Each allocator takes the free cells of one block at a time into the heap, as a local free list of the cells that were
// freed and a range of cells that were never allocated, so that allocating is usually popping that list or bumping
// the cursor of that range, and code that allocates cells itself (like the Rust heap) does either inline:
@@ -164,13 +170,12 @@ GC_API GCCell* gc_heap_allocate_storage_cell(GCHeap*, GCAllocator*, bool* must_m
// at local_cursor_offset, local_end_offset and local_cell_size_offset from the head of the list. While the cursor is
// below the end, the cell at the cursor is free, and taking it advances the cursor by the cell size. These words are
// outside the heap region.
-// - Cells from the list or the range never need marking.
// - Before taking a cell of N bytes (the cell size of the allocator), such code checks that the heap's
// allocated_bytes_since_last_gc + N stays within its gc_bytes_threshold, and allocates through the heap otherwise
// (which may collect garbage). After taking it, it adds N to allocated_bytes_since_last_gc and total_allocated_bytes;
// storage cells (see gc_heap_allocate_storage_cell()) skip the check but add N to both as well. These
// are size_t fields of the heap, at the offsets gc_get_layout() reports.
-// - It then writes every byte of the cell, as after gc_heap_allocate_cell(), with a clear mark.
+// - It then writes every byte of the cell, as after gc_heap_allocate_cell().
// Returns where the head of the allocator's list in the heap is, which stays valid as long as the heap. The list and
// the range are always empty while the heap collects on every allocation. Returns null if cells must always be
// allocated through the heap, as in builds that poison free cells for AddressSanitizer.
@@ -179,6 +184,9 @@ GC_API GCCell** gc_heap_allocator_local_free_list(GCHeap*, GCAllocator*);
GC_API void* gc_cell_heap_context(GCCell const*);
// The type info the cell's block was allocated with.
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*);
GC_API GCRoot* gc_root_create(GCCell*);
GC_API void gc_root_destroy(GCRoot*);
@@ -197,6 +205,11 @@ GC_API void gc_visitor_visit_values(GCVisitor*, uint64_t const*, size_t count);
// Visits a NaN-boxed value that is reachable only while key is, such as a WeakMap entry's.
GC_API void gc_visitor_visit_ephemeron(GCVisitor*, GCCell* key, uint64_t const* value);
+// The marker a marking GCVisitor points to (see GCLayout::visitor_marker_offset), which these hand cells to directly.
+typedef struct GCMarker GCMarker;
+GC_API void gc_marker_visit_cell(GCMarker*, GCCell*);
+GC_API void gc_marker_visit_values(GCMarker*, uint64_t const*, size_t count);
+
// 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
// heap, primitive storage is not thread-safe, and every call must come from the thread that uses the heap.
diff --git a/Libraries/LibGC/CMakeLists.txt b/Libraries/LibGC/CMakeLists.txt
index 2efa3551bad..1eb571996cf 100644
--- a/Libraries/LibGC/CMakeLists.txt
+++ b/Libraries/LibGC/CMakeLists.txt
@@ -22,6 +22,12 @@ ladybird_lib(LibGC gc EXPLICIT_SYMBOL_EXPORT)
target_link_libraries(LibGC PRIVATE LibCore)
target_link_libraries(LibGC PUBLIC LibThreading)
+# The collector's core: the descriptors of blocks, and marking.
+import_rust_crate(MANIFEST_PATH Rust/Cargo.toml CRATE_NAME libgc_rust FEATURES allocator FFI_HEADER RustFFI.h)
+target_link_libraries(LibGC PRIVATE libgc_rust)
+get_target_property(_libgc_rust_lib libgc_rust IMPORTED_LOCATION)
+set_property(SOURCE CAPI.cpp Cell.cpp Heap.cpp HeapBlock.cpp WeakBlock.cpp APPEND PROPERTY OBJECT_DEPENDS ${_libgc_rust_lib})
+
# The first word of a GC::ForeignCell belongs to its foreign implementation rather than holding a vtable pointer, so
# UBSan's vptr checks misfire whenever LibGC handles such a cell as a GC::Cell.
if (ENABLE_UNDEFINED_SANITIZER)
diff --git a/Libraries/LibGC/Cell.cpp b/Libraries/LibGC/Cell.cpp
index 1381e7f8a8a..27490de2c0e 100644
--- a/Libraries/LibGC/Cell.cpp
+++ b/Libraries/LibGC/Cell.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGC/BlockDescriptor.h>
#include <LibGC/Cell.h>
#include <LibGC/CellAllocator.h>
#include <LibGC/CellTypeInfo.h>
@@ -25,10 +26,23 @@ StringView class_name_of(Cell const& cell)
return HeapBlock::from_cell(&cell)->cell_allocator().class_name().value_or("Cell"sv);
}
+bool Cell::is_marked() const
+{
+ return GC::is_marked(this);
+}
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Winvalid-offsetof"
+size_t Cell::Visitor::marker_offset()
+{
+ return offsetof(Visitor, m_marker);
+}
+#pragma GCC diagnostic pop
+
void GC::Cell::Visitor::visit(NanBoxedValue const& value)
{
if (value.is_cell())
- visit_impl(value.as_cell());
+ 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 48a85ddb483..d9703108f05 100644
--- a/Libraries/LibGC/Cell.h
+++ b/Libraries/LibGC/Cell.h
@@ -12,6 +12,7 @@
#include <AK/Noncopyable.h>
#include <AK/Platform.h>
#include <AK/StringView.h>
+#include <LibGC/CAPI.h>
#include <LibGC/Forward.h>
#include <LibGC/Internals.h>
#include <LibGC/Member.h>
@@ -72,8 +73,9 @@ public:
CellKind cell_kind() const { return m_cell_kind; }
- bool is_marked() const { return m_mark; }
- void set_marked(bool b) { m_mark = b; }
+ // Whether the last collection marked the cell, which it keeps in the descriptor of the cell's block. Only meaningful
+ // from the end of marking until the cell's block is swept.
+ bool is_marked() const;
enum class State : bool {
Live,
@@ -90,12 +92,12 @@ public:
void visit(Cell* cell)
{
if (cell)
- visit_impl(*cell);
+ visit_cell(*cell);
}
void visit(Cell& cell)
{
- visit_impl(cell);
+ visit_cell(cell);
}
void visit(Cell const* cell)
@@ -117,13 +119,13 @@ public:
void visit(Ptr<T> cell)
{
if (cell)
- visit_impl(*as_cell(const_cast<RemoveConst<T>*>(cell.ptr())));
+ visit_cell(*as_cell(const_cast<RemoveConst<T>*>(cell.ptr())));
}
template<typename T>
void visit(Ref<T> cell)
{
- visit_impl(*as_cell(const_cast<RemoveConst<T>*>(cell.ptr())));
+ 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
@@ -153,7 +155,7 @@ public:
void visit(ReadonlySpan<T> span)
requires(IsBaseOf<NanBoxedValue, T>)
{
- visit_impl(ReadonlySpan<NanBoxedValue>(span.data(), span.size()));
+ visit_values(ReadonlySpan<NanBoxedValue>(span.data(), span.size()));
}
template<typename T>
@@ -168,7 +170,7 @@ public:
void visit(Span<T> span)
requires(IsBaseOf<NanBoxedValue, T>)
{
- visit_impl(ReadonlySpan<NanBoxedValue>(span.data(), span.size()));
+ visit_values(ReadonlySpan<NanBoxedValue>(span.data(), span.size()));
}
template<typename T, size_t inline_capacity>
@@ -183,7 +185,7 @@ public:
void visit(Vector<T, inline_capacity> const& vector)
requires(IsBaseOf<NanBoxedValue, T>)
{
- visit_impl(ReadonlySpan<NanBoxedValue>(vector.span().data(), vector.size()));
+ visit_values(ReadonlySpan<NanBoxedValue>(vector.span().data(), vector.size()));
}
template<typename T, size_t size>
@@ -284,6 +286,8 @@ public:
// The caller must drop its entries whose key died, or the next collection reads a freed key.
virtual void visit_ephemeron(Cell& key, NanBoxedValue const& value);
+ static size_t marker_offset();
+
protected:
template<typename T>
ALWAYS_INLINE void visit_member_cell(T* cell)
@@ -291,9 +295,33 @@ public:
auto* mutable_cell = as_cell(const_cast<RemoveConst<T>*>(cell));
// A compressed pointer must name the start of its cell.
ASSERT(static_cast<void const*>(mutable_cell) == static_cast<void const*>(cell));
- visit_impl(*mutable_cell);
+ visit_cell(*mutable_cell);
+ }
+
+ // NB: A marking visitor hands edges to its marker directly, rather than through its own visit_impl().
+ ALWAYS_INLINE void visit_cell(Cell& cell)
+ {
+ if (m_marker) {
+ gc_marker_visit_cell(m_marker, reinterpret_cast<GCCell*>(&cell));
+ return;
+ }
+ visit_impl(cell);
+ }
+
+ ALWAYS_INLINE void visit_values(ReadonlySpan<NanBoxedValue> values)
+ {
+ if (m_marker) {
+ if (!values.is_empty())
+ gc_marker_visit_values(m_marker, reinterpret_cast<uint64_t const*>(values.data()), values.size());
+ return;
+ }
+ visit_impl(values);
}
+ // The marker of the collection that a marking visitor marks for, and null in every other visitor. Foreign
+ // implementations find it at GCLayout::visitor_marker_offset.
+ GCMarker* m_marker { nullptr };
+
virtual void visit_impl(Cell&) = 0;
virtual void visit_impl(ReadonlySpan<NanBoxedValue>) = 0;
virtual ~Visitor() = default;
@@ -318,7 +346,9 @@ private:
void set_cell_kind(CellKind kind) { m_cell_kind = kind; }
- bool m_mark { false };
+ // 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 };
State m_state { State::Live };
CellKind m_cell_kind { CellKind::Other };
};
@@ -338,7 +368,7 @@ public:
~ForeignCell() = delete;
CellKind cell_kind() const { return m_cell_kind; }
- bool is_marked() const { return m_mark; }
+ bool is_marked() const { return as_cell(this)->is_marked(); }
Cell::State state() const { return m_state; }
ALWAYS_INLINE Heap& heap() const { return HeapBlockBase::from_cell(as_cell(this))->heap(); }
@@ -348,12 +378,12 @@ private:
friend struct CAPI;
[[maybe_unused]] void const* m_word_owned_by_the_foreign_implementation;
- bool m_mark;
+ [[maybe_unused]] u8 m_unused_header_byte;
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
// placing a field of a derived type in the tail padding, where it would overlap them without changing the size.
- [[maybe_unused]] u8 m_tail_owned_by_the_foreign_implementation[sizeof(void*) - sizeof(bool) - sizeof(Cell::State) - sizeof(CellKind)];
+ [[maybe_unused]] u8 m_tail_owned_by_the_foreign_implementation[sizeof(void*) - sizeof(u8) - sizeof(Cell::State) - sizeof(CellKind)];
};
inline void Cell::Visitor::visit(ForeignCell* cell)
diff --git a/Libraries/LibGC/CellAllocator.h b/Libraries/LibGC/CellAllocator.h
index 93bf7301501..db330391645 100644
--- a/Libraries/LibGC/CellAllocator.h
+++ b/Libraries/LibGC/CellAllocator.h
@@ -24,6 +24,13 @@
namespace GC {
+// Which threads may trace the cells of an allocator while the collector marks. C++ cells are only traced on the thread
+// that owns their heap.
+enum class TraceThread : u8 {
+ OwnerThreadOnly,
+ AnyThread,
+};
+
class GC_API CellAllocatorDescriptorBase {
AK_MAKE_NONCOPYABLE(CellAllocatorDescriptorBase);
AK_MAKE_NONMOVABLE(CellAllocatorDescriptorBase);
@@ -35,6 +42,8 @@ public:
CellTypeInfo const& type_info() const { return m_type_info; }
size_t cell_size() const { return m_type_info.cell_size; }
void const* foreign_type() const { return m_foreign_type; }
+ TraceThread trace_thread() const { return m_trace_thread; }
+ void set_trace_thread(TraceThread trace_thread) { m_trace_thread = trace_thread; }
// Where each heap keeps its allocator for this descriptor, see Heap::cell_allocator_for().
size_t index() const { return m_index; }
@@ -54,6 +63,7 @@ private:
Optional<StringView> m_class_name;
void const* m_foreign_type { nullptr };
size_t m_index { 0 };
+ TraceThread m_trace_thread { TraceThread::OwnerThreadOnly };
};
class GC_API CellAllocator {
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index a88624cf9b7..8f7cd70a20a 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -30,6 +30,7 @@
#include <LibCore/ThreadEventQueue.h>
#include <LibCore/Timer.h>
#include <LibGC/BlockAllocator.h>
+#include <LibGC/BlockDescriptor.h>
#include <LibGC/CellAllocator.h>
#include <LibGC/CompressedPointer.h>
#include <LibGC/Heap.h>
@@ -151,6 +152,7 @@ struct PhaseTimings {
i64 mark_initial_visit_us { 0 };
i64 mark_bfs_us { 0 };
i64 mark_clear_uprooted_us { 0 };
+ size_t mark_threads { 0 };
// sweep_dead_cells() subphases. Only populated for CollectEverything;
// normal collections defer sweep to the incremental sweeper.
@@ -235,6 +237,7 @@ void print_gc_report(i64 total_us, size_t live_block_count)
dbgln(" clear uprooted {:>10} us ({:>5.1f}%)", t.mark_clear_uprooted_us, pct(t.mark_clear_uprooted_us));
dbgln(" initial visit {:>10} us ({:>5.1f}%)", t.mark_initial_visit_us, pct(t.mark_initial_visit_us));
dbgln(" BFS marking {:>10} us ({:>5.1f}%)", t.mark_bfs_us, pct(t.mark_bfs_us));
+ dbgln(" marking threads {:>10}", t.mark_threads);
dbgln(" finalize_unmarked_cells {:>10} us ({:>5.1f}%)", t.finalize_unmarked_cells_us, pct(t.finalize_unmarked_cells_us));
dbgln(" sweep_weak_blocks {:>10} us ({:>5.1f}%)", t.sweep_weak_blocks_us, pct(t.sweep_weak_blocks_us));
dbgln(" prune_weak_containers {:>10} us ({:>5.1f}%)", t.prune_weak_containers_us, pct(t.prune_weak_containers_us));
@@ -1477,111 +1480,35 @@ NO_SANITIZE_ADDRESS void Heap::gather_conservative_roots(ConservativeScanOrigin
}
}
+// The visitor of one marker of a collection, which hands everything it visits straight to the marker.
class MarkingVisitor final : public Cell::Visitor {
-public:
- // The domain is a set of heaps whose cells this mark phase is responsible for; cells outside the domain are not visited.
- explicit MarkingVisitor(ReadonlySpan<Heap* const> domain, HashMap<Cell*, HeapRoot> const& roots)
- : m_domain(domain)
- {
- for (auto* root : roots.keys()) {
- visit(root);
- }
- }
+ AK_ALLOC_WITH_KMALLOC;
- bool cell_is_in_domain(Cell const& cell) const
+public:
+ explicit MarkingVisitor(FFI::Marker* marker)
{
- auto& heap = HeapBlockBase::from_cell(&cell)->heap();
- if (m_domain.size() == 1) [[likely]]
- return m_domain.data()[0] == &heap;
- for (auto* domain_heap : m_domain) {
- if (domain_heap == &heap)
- return true;
- }
- return false;
+ m_marker = reinterpret_cast<GCMarker*>(marker);
}
virtual void visit_impl(Cell& cell) override
{
- if (cell.is_marked())
- return;
- if (!cell_is_in_domain(cell))
- return;
- dbgln_if(HEAP_DEBUG, " ! {}", &cell);
-
- cell.set_marked(true);
- m_work_queue.append(cell);
+ FFI::rust_gc_marker_visit_cell(marker(), &cell);
}
virtual void visit_impl(ReadonlySpan<NanBoxedValue> values) override
{
- m_work_queue.grow_capacity(m_work_queue.size() + values.size());
-
- for (auto value : values) {
- if (!value.is_cell())
- continue;
- auto& cell = value.as_cell();
- if (cell.is_marked())
- continue;
- if (!cell_is_in_domain(cell))
- continue;
- dbgln_if(HEAP_DEBUG, " ! {}", &cell);
-
- cell.set_marked(true);
- m_work_queue.unchecked_append(cell);
- }
+ FFI::rust_gc_marker_visit_values(marker(), reinterpret_cast<u64 const*>(values.data()), values.size());
}
virtual void visit_ephemeron(Cell& key, NanBoxedValue const& value) override
{
if (!value.is_cell())
return;
- // NB: This phase does not mark keys outside the domain, so their values stay reachable.
- if (key.is_marked() || !cell_is_in_domain(key)) {
- visit(value);
- return;
- }
- m_pending_ephemerons.append({ &key, &value.as_cell() });
- }
-
- void mark_all_live_cells()
- {
- // Marking can reach the key of a pending ephemeron, so repeat until no more values get marked.
- for (;;) {
- while (!m_work_queue.is_empty()) {
- auto cell = m_work_queue.take_last();
- if (cell->state() != Cell::State::Live)
- continue;
- auto* block = HeapBlock::from_cell(cell.ptr());
- auto& heap = block->heap();
- auto const& type_info = block->type_info();
- heap.m_marked_cell_bytes += block->cell_size();
- if (type_info.external_memory_size)
- heap.m_marked_external_bytes = saturating_add(heap.m_marked_external_bytes, type_info.external_memory_size(cell.ptr()));
- type_info.visit_edges(cell.ptr(), this);
- }
-
- bool marked_a_value = false;
- m_pending_ephemerons.remove_all_matching([&](auto const& ephemeron) {
- if (!ephemeron.key->is_marked())
- return false;
- visit(*ephemeron.value);
- marked_a_value = true;
- return true;
- });
- if (!marked_a_value)
- break;
- }
+ FFI::rust_gc_marker_visit_ephemeron(marker(), &key, &value.as_cell());
}
private:
- struct Ephemeron {
- Cell* key { nullptr };
- Cell* value { nullptr };
- };
-
- ReadonlySpan<Heap* const> m_domain;
- Vector<Ref<Cell>> m_work_queue;
- Vector<Ephemeron> m_pending_ephemerons;
+ FFI::Marker* marker() const { return reinterpret_cast<FFI::Marker*>(m_marker); }
};
void Heap::mark_live_cells(HashMap<Cell*, HeapRoot>& roots)
@@ -1590,6 +1517,10 @@ void Heap::mark_live_cells(HashMap<Cell*, HeapRoot>& roots)
mark_live_cells_across(domain, roots);
}
+// OPTIMIZATION: Marking starts helper threads only once the heaps it marks are this large, and the collecting thread did
+// not finish alone soon.
+static constexpr size_t GC_PARALLEL_MARKING_MIN_HEAP_BYTES = 8 * MiB;
+
void Heap::mark_live_cells_across(ReadonlySpan<Heap* const> heaps, HashMap<Cell*, HeapRoot>& roots)
{
dbgln_if(HEAP_DEBUG, "mark_live_cells:");
@@ -1604,31 +1535,78 @@ void Heap::mark_live_cells_across(ReadonlySpan<Heap* const> heaps, HashMap<Cell*
}
}
- for (auto* heap : heaps) {
- heap->m_marked_cell_bytes = 0;
- heap->m_marked_external_bytes = 0;
- }
-
- Optional<MarkingVisitor> visitor;
+ Vector<void const*> root_cells;
+ size_t heap_bytes = 0;
{
ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.mark_initial_visit_us };
- visitor.emplace(heaps, roots);
- }
+ root_cells.ensure_capacity(roots.size());
+ for (auto* root : roots.keys())
+ root_cells.unchecked_append(root);
+ for (auto* heap : heaps)
+ heap_bytes += heap->m_live_heap_blocks.size() * HeapBlock::BLOCK_SIZE;
+ }
+
+ Vector<size_t, 1> marked_cell_bytes;
+ Vector<size_t, 1> marked_external_bytes;
+ marked_cell_bytes.resize(heaps.size());
+ marked_external_bytes.resize(heaps.size());
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Winvalid-offsetof"
+ FFI::MarkRequest request {
+ .layout = {
+ .heap_region_base = heap_region_base(),
+ .cell_state_offset = static_cast<u32>(offsetof(Cell, m_state)),
+ .cell_state_live = to_underlying(Cell::State::Live),
+ .type_info_visit_edges_offset = static_cast<u32>(offsetof(CellTypeInfo, visit_edges)),
+ .type_info_external_memory_size_offset = static_cast<u32>(offsetof(CellTypeInfo, external_memory_size)),
+ .value_is_cell_pattern = SHIFTED_IS_CELL_PATTERN,
+ .value_offset_mask = HEAP_REGION_OFFSET_MASK,
+ },
+ .heaps = reinterpret_cast<void const* const*>(heaps.data()),
+ .heap_count = heaps.size(),
+ .roots = root_cells.data(),
+ .root_count = root_cells.size(),
+ .parallel = heap_bytes >= GC_PARALLEL_MARKING_MIN_HEAP_BYTES,
+ .context = nullptr,
+ .create_visitor = [](void*, FFI::Marker* marker) -> void* {
+ return static_cast<Cell::Visitor*>(new MarkingVisitor(marker));
+ },
+ .destroy_visitor = [](void*, void* visitor) { delete static_cast<MarkingVisitor*>(static_cast<Cell::Visitor*>(visitor)); },
+ .marked_cell_bytes = marked_cell_bytes.data(),
+ .marked_external_bytes = marked_external_bytes.data(),
+ .threads_used = 0,
+ };
+#pragma GCC diagnostic pop
{
ScopedPhaseTimer timer { g_recording_phase_timings, g_phase_timings.mark_bfs_us };
- visitor->mark_all_live_cells();
+ FFI::rust_gc_marker_mark(&request);
+ }
+ g_phase_timings.mark_threads = request.threads_used;
+
+ for (size_t i = 0; i < heaps.size(); ++i) {
+ heaps[i]->m_marked_cell_bytes = marked_cell_bytes[i];
+ heaps[i]->m_marked_external_bytes = marked_external_bytes[i];
}
}
+void Heap::mark_cell_allocated_during_incremental_sweep(Cell& cell)
+{
+ auto* block = HeapBlock::from_cell(&cell);
+ if (block->is_pending_sweep() || block->is_being_swept())
+ set_marked(&cell);
+}
+
void Heap::finalize_unmarked_cells()
{
for_each_block([&](auto& block) {
auto* finalize = block.type_info().finalize;
if (!finalize)
return IterationDecision::Continue;
+ auto& descriptor = block_descriptor_for(&block);
block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
- if (!cell->is_marked())
+ if (!is_marked(descriptor, cell))
finalize(cell);
});
return IterationDecision::Continue;
@@ -1668,19 +1646,20 @@ void Heap::sweep_dead_cells(bool print_report, Core::ElapsedTimer const& measure
for_each_block([&](auto& block) {
bool block_has_live_cells = false;
bool block_was_full = block.is_full();
+ auto& descriptor = block_descriptor_for(&block);
block.template for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
- if (!cell->is_marked()) {
+ if (!is_marked(descriptor, cell)) {
dbgln_if(HEAP_DEBUG, " ~ {}", cell);
block.deallocate(cell);
++collected_cells;
collected_cell_bytes += block.cell_size();
} else {
- cell->set_marked(false);
block_has_live_cells = true;
++live_cells;
live_cell_bytes += block.cell_size();
}
});
+ clear_marks(descriptor);
if (!block_has_live_cells)
empty_blocks.append(&block);
else if (block_was_full != block.is_full())
@@ -1758,18 +1737,20 @@ void Heap::sweep_block(HeapBlock& block)
size_t collected_cells = 0;
size_t live_cells = 0;
+ auto& descriptor = block_descriptor_for(&block);
block.for_each_cell_in_state<Cell::State::Live>([&](Cell* cell) {
- if (!cell->is_marked()) {
+ if (!is_marked(descriptor, cell)) {
dbgln_if(HEAP_DEBUG, " ~ {}", cell);
block.deallocate(cell);
++collected_cells;
} else {
- cell->set_marked(false);
block_has_live_cells = true;
++live_cells;
}
});
block.set_being_swept(false);
+ // NB: This also clears the marks of the cells that were allocated in the block while it was swept.
+ clear_marks(descriptor);
if (!block_has_live_cells) {
dbgln_if(HEAP_DEBUG, " - HeapBlock empty @ {}: cell_size={}", &block, block.cell_size());
@@ -1860,12 +1841,6 @@ void Heap::finish_incremental_sweep()
dbgln_if(INCREMENTAL_SWEEP_DEBUG, "[sweep] Next GC threshold: {} ({} KiB)", m_gc_bytes_threshold, m_gc_bytes_threshold / KiB);
print_incremental_sweep_report(m_marked_cell_bytes, m_marked_external_bytes, m_gc_bytes_threshold);
- // Clear marks on cells allocated during sweep. Sweep already cleared
- // marks on cells it visited, so only these remain marked.
- for (auto cell : m_cells_allocated_during_sweep)
- cell->set_marked(false);
- m_cells_allocated_during_sweep.clear();
-
m_incremental_sweep_active = false;
if (m_stats)
finish_stats_collection();
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index 2bfe445563f..576a9014ff6 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -257,27 +257,14 @@ private:
return cell_allocator_for(descriptor).allocate_cell(*this);
}
- // Cells allocated during incremental sweep in a block that the sweep has
- // yet to finish must be marked so that it keeps them. The sweep clears the
- // marks of the blocks it has yet to sweep; cells in the block it is
- // sweeping right now are remembered so their marks get cleared when the
- // sweep finishes. Swept and new blocks need nothing.
- bool mark_if_allocated_during_incremental_sweep(Cell& cell)
+ // Cells allocated during incremental sweep in a block that the sweep has yet to finish must be marked so that it
+ // keeps them. Sweeping a block clears its marks once it is done, so swept and new blocks need nothing.
+ void mark_if_allocated_during_incremental_sweep(Cell& cell)
{
- if (!m_incremental_sweep_active)
- return false;
- auto* block = HeapBlock::from_cell(&cell);
- if (block->is_pending_sweep()) {
- cell.set_marked(true);
- return true;
- }
- if (block->is_being_swept()) {
- cell.set_marked(true);
- m_cells_allocated_during_sweep.append(&cell);
- return true;
- }
- return false;
+ if (m_incremental_sweep_active) [[unlikely]]
+ mark_cell_allocated_during_incremental_sweep(cell);
}
+ void mark_cell_allocated_during_incremental_sweep(Cell&);
// Marking makes every block pending sweep again, which local free lists
// must never be in, so every collection does this once it has finished the
@@ -399,7 +386,6 @@ private:
size_t m_blocks_swept { 0 };
size_t m_marked_cell_bytes { 0 };
size_t m_marked_external_bytes { 0 };
- Vector<GC::Ptr<Cell>> m_cells_allocated_during_sweep;
CellAllocator::SweepList m_allocators_to_sweep;
RefPtr<Core::Timer> m_incremental_sweep_timer;
diff --git a/Libraries/LibGC/HeapBlock.cpp b/Libraries/LibGC/HeapBlock.cpp
index cf2e1494e81..bf0ef08bb13 100644
--- a/Libraries/LibGC/HeapBlock.cpp
+++ b/Libraries/LibGC/HeapBlock.cpp
@@ -7,6 +7,7 @@
#include <AK/Assertions.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/Platform.h>
+#include <LibGC/BlockDescriptor.h>
#include <LibGC/CellAllocator.h>
#include <LibGC/Forward.h>
#include <LibGC/Heap.h>
@@ -18,6 +19,29 @@
namespace GC {
+static_assert(HeapBlock::min_possible_cell_size >= FFI::MIN_CELL_SIZE);
+
+FFI::BlockDescriptor* const g_block_descriptors = FFI::rust_gc_block_descriptor_table(HEAP_REGION_SIZE);
+
+void publish_block_descriptor(HeapBlock& block, CellAllocator& allocator)
+{
+ auto index = (bit_cast<FlatPtr>(&block) - heap_region_base()) / HeapBlockBase::BLOCK_SIZE;
+ FFI::rust_gc_block_descriptor_commit(index);
+ auto& descriptor = g_block_descriptors[index];
+ descriptor.type_info = &allocator.type_info();
+ descriptor.cell_size = allocator.cell_size();
+ descriptor.cell_index_magic = static_cast<u32>(((static_cast<u64>(1) << 32) + descriptor.cell_size - 1) / descriptor.cell_size);
+ descriptor.traced_on_owner_thread_only = allocator.descriptor().trace_thread() == TraceThread::OwnerThreadOnly;
+ 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);
+}
+
+void retire_block_descriptor(HeapBlock& block)
+{
+ __atomic_store_n(&block_descriptor_for(&block).heap, static_cast<void*>(nullptr), __ATOMIC_RELEASE);
+}
+
NonnullOwnPtr<HeapBlock> HeapBlock::create(Heap& heap, CellAllocator& cell_allocator)
{
char const* name = nullptr;
@@ -34,9 +58,16 @@ HeapBlock::HeapBlock(Heap& heap, CellAllocator& cell_allocator)
, m_cell_count((BLOCK_SIZE - sizeof(HeapBlock)) / m_cell_size)
{
VERIFY(m_cell_size >= sizeof(FreelistEntry));
+ VERIFY(m_cell_size >= FFI::MIN_CELL_SIZE);
+ publish_block_descriptor(*this, cell_allocator);
ASAN_POISON_MEMORY_REGION(m_storage, BLOCK_SIZE - sizeof(HeapBlock));
}
+HeapBlock::~HeapBlock()
+{
+ retire_block_descriptor(*this);
+}
+
HeapBlock::FreeCells HeapBlock::take_free_cells()
{
FreeCells free_cells {
@@ -75,7 +106,7 @@ void HeapBlock::deallocate(Cell* cell)
// NB: The cell is one of this block's, since for_each_cell() found it, and the free list only ever holds cells
// that this function or give_back_free_cells() put there.
VERIFY(cell->state() == Cell::State::Live);
- VERIFY(!cell->is_marked());
+ VERIFY(!GC::is_marked(cell));
if (auto* destroy = type_info().destroy)
destroy(cell);
@@ -88,6 +119,8 @@ void HeapBlock::deallocate(Cell* cell)
auto dword_after_freelist = round_up_to_power_of_two(reinterpret_cast<uintptr_t>(freelist_entry) + sizeof(FreelistEntry), 8);
VERIFY((dword_after_freelist - reinterpret_cast<uintptr_t>(freelist_entry)) <= m_cell_size);
VERIFY(m_cell_size >= sizeof(FreelistEntry));
+ VERIFY(m_cell_size >= FFI::MIN_CELL_SIZE);
+ 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 5e734b286e4..855101feb6d 100644
--- a/Libraries/LibGC/HeapBlock.h
+++ b/Libraries/LibGC/HeapBlock.h
@@ -29,6 +29,7 @@ class GC_API HeapBlock : public HeapBlockBase {
public:
using HeapBlockBase::BLOCK_SIZE;
static NonnullOwnPtr<HeapBlock> create(Heap&, CellAllocator&);
+ ~HeapBlock();
size_t cell_size() const { return m_cell_size; }
size_t cell_count() const { return m_cell_count; }
diff --git a/Libraries/LibGC/Rust/Cargo.toml b/Libraries/LibGC/Rust/Cargo.toml
new file mode 100644
index 00000000000..e2b01ec8125
--- /dev/null
+++ b/Libraries/LibGC/Rust/Cargo.toml
@@ -0,0 +1,30 @@
+[package]
+name = "libgc_rust"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["staticlib", "rlib"]
+
+[features]
+allocator = ["dep:ladybird_allocator"]
+
+# After changing dependencies, regenerate the Flatpak sources:
+# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[dependencies]
+ak = { path = "../../../AK/Rust" }
+crossbeam-deque = "0.8"
+ladybird_allocator = { path = "../../RustAllocator", optional = true }
+rustc-demangle = "0.1"
+
+[target.'cfg(unix)'.dependencies]
+libc = "0.2"
+
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = ["Win32_System_Memory"] }
+
+[build-dependencies]
+cbindgen = "0.29"
+
+[lints]
+workspace = true
diff --git a/Libraries/LibGC/Rust/build.rs b/Libraries/LibGC/Rust/build.rs
new file mode 100644
index 00000000000..5c6f8f8c952
--- /dev/null
+++ b/Libraries/LibGC/Rust/build.rs
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::env;
+use std::error::Error;
+use std::path::PathBuf;
+
+fn main() -> Result<(), Box<dyn Error>> {
+ let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?);
+ let out_dir = PathBuf::from(env::var("OUT_DIR")?);
+
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-changed=cbindgen.toml");
+ println!("cargo:rerun-if-changed=src");
+
+ cbindgen::generate(manifest_dir).map_or_else(
+ |error| match error {
+ cbindgen::Error::ParseSyntaxError { .. } => {}
+ e => panic!("{e:?}"),
+ },
+ |bindings| {
+ let header_path = out_dir.join("RustFFI.h");
+ bindings.write_to_file(&header_path);
+ },
+ );
+
+ Ok(())
+}
diff --git a/Libraries/LibGC/Rust/cbindgen.toml b/Libraries/LibGC/Rust/cbindgen.toml
new file mode 100644
index 00000000000..618968671eb
--- /dev/null
+++ b/Libraries/LibGC/Rust/cbindgen.toml
@@ -0,0 +1,17 @@
+language = "C++"
+header = """/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */"""
+pragma_once = true
+include_version = true
+namespaces = ["GC", "FFI"]
+line_length = 120
+tab_width = 4
+no_includes = true
+sys_includes = ["stdint.h", "stddef.h"]
+usize_is_size_t = true
+
+[export.mangle]
+rename_types = "PascalCase"
diff --git a/Libraries/LibGC/Rust/src/block.rs b/Libraries/LibGC/Rust/src/block.rs
new file mode 100644
index 00000000000..31145c93c06
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/block.rs
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The descriptors of the heap's blocks.
+//!
+//! A block holds cells of one type and one size. What the collector knows about a block is in its descriptor, which
+//! lives outside the heap region: the heap and the type of the block, and which of its cells are marked. So nothing that
+//! writes to a cell, or past it, can change what the collector does with the block. The descriptor of a block is at the
+//! block's index in the region in a table of descriptors, which is reserved once for the whole region and only backed
+//! by memory where blocks are.
+
+use core::cell::UnsafeCell;
+use core::ffi::c_void;
+use core::ptr::NonNull;
+use core::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
+use std::sync::OnceLock;
+
+use crate::os;
+
+pub const BLOCK_SIZE: usize = 16 * 1024;
+
+/// The smallest cell, which has room for the link of a free cell after the header of a cell.
+pub const MIN_CELL_SIZE: usize = 24;
+
+/// A cell's mark bit is its offset in its block divided by its size, which the smallest cells take the most bits for.
+pub const MARK_BITMAP_WORDS: usize = 11;
+
+const _: () = assert!(MARK_BITMAP_WORDS == (BLOCK_SIZE / MIN_CELL_SIZE + 1).div_ceil(64));
+
+/// What the collector knows about a block. LibGC's C++ side fills it in when it creates the block, and empties it when
+/// the block goes away.
+#[repr(C)]
+pub struct BlockDescriptor {
+ /// The heap the block belongs to, or null while there is no block.
+ pub heap: *mut c_void,
+ /// The CellTypeInfo of the block's cells.
+ pub type_info: *const c_void,
+ pub cell_size: u32,
+ /// ceil(2^32 / cell_size): the offset of a cell in its block times this, shifted right by 32, is its mark bit.
+ 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,
+ /// Rounds the descriptor up to 128 bytes, two whole cache lines in the table.
+ pub reserved: [u8; 7],
+ pub reserved_word: u64,
+ /// One bit for each cell, which marking sets atomically, see mark_word().
+ pub marked: [UnsafeCell<u64>; MARK_BITMAP_WORDS],
+}
+
+const _: () = assert!(size_of::<BlockDescriptor>() == 128);
+
+impl BlockDescriptor {
+ pub fn heap(&self) -> *mut c_void {
+ // SAFETY: A reference is a valid pointer.
+ unsafe { heap_of_descriptor(self) }
+ }
+
+ /// A word of the mark bits, which other threads may set while marking runs.
+ #[inline(always)]
+ pub fn mark_word(&self, word: usize) -> &AtomicU64 {
+ // SAFETY: The word is in an UnsafeCell, so writing to it through a shared reference is fine, and it is only
+ // ever accessed atomically while other threads may access it.
+ unsafe { AtomicU64::from_ptr(self.marked[word].get()) }
+ }
+
+ #[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;
+ (self.mark_word(index / 64), 1 << (index % 64))
+ }
+
+ pub fn is_marked(&self, address: usize) -> bool {
+ let (word, bit) = self.mark_bit(address);
+ word.load(Ordering::Relaxed) & bit != 0
+ }
+
+ /// Sets the mark bit of the cell at `address`, and returns whether it was clear.
+ #[inline(always)]
+ pub fn mark(&self, address: usize) -> bool {
+ let (word, bit) = self.mark_bit(address);
+ // NB: A bit that is set already costs no atomic read-modify-write, which would take the word's cache line from
+ // the other threads that set bits in it.
+ if word.load(Ordering::Relaxed) & bit != 0 {
+ return false;
+ }
+ word.fetch_or(bit, Ordering::Relaxed) & bit == 0
+ }
+
+ /// Like mark(), for a thread that no other thread sets mark bits concurrently with.
+ #[inline(always)]
+ pub fn mark_exclusive(&self, address: usize) -> bool {
+ let (word, bit) = self.mark_bit(address);
+ let value = word.load(Ordering::Relaxed);
+ if value & bit != 0 {
+ return false;
+ }
+ word.store(value | bit, Ordering::Relaxed);
+ true
+ }
+}
+
+struct Table {
+ descriptors: NonNull<BlockDescriptor>,
+ count: usize,
+}
+
+// SAFETY: The table is only ever read through, and its descriptors are accessed atomically where threads share them.
+unsafe impl Send for Table {}
+// SAFETY: As above.
+unsafe impl Sync for Table {}
+
+static TABLE: OnceLock<Table> = OnceLock::new();
+
+/// The table of block descriptors, which this reserves for a region of `region_size` bytes on first use.
+pub fn descriptor_table() -> NonNull<BlockDescriptor> {
+ TABLE.get().expect("the table of block descriptors exists").descriptors
+}
+
+/// 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.
+///
+/// # Safety
+///
+/// `descriptor` must point to a descriptor in the table that is backed by memory.
+#[inline(always)]
+pub unsafe fn heap_of_descriptor(descriptor: *const BlockDescriptor) -> *mut c_void {
+ // SAFETY: The caller passes a valid descriptor, and the field is only ever accessed atomically while other threads
+ // may read it.
+ unsafe { AtomicPtr::from_ptr((&raw const (*descriptor).heap).cast_mut()) }.load(Ordering::Relaxed)
+}
+
+/// 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)]
+pub extern "C" fn rust_gc_block_descriptor_table(region_size: usize) -> *mut BlockDescriptor {
+ TABLE
+ .get_or_init(|| {
+ let count = region_size / BLOCK_SIZE;
+ let descriptors = os::reserve_zeroed(count * size_of::<BlockDescriptor>())
+ .expect("reserve the table of block descriptors");
+ Table {
+ descriptors: descriptors.cast(),
+ count,
+ }
+ })
+ .descriptors
+ .as_ptr()
+}
+
+/// Makes sure that the descriptor at `index` is backed by memory, before a block is created there.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_gc_block_descriptor_commit(index: usize) {
+ let table = TABLE.get().expect("the table of block descriptors exists");
+ assert!(index < table.count, "a block is within the heap region");
+ // SAFETY: The descriptor is within the reserved table.
+ unsafe { os::commit_reserved_zeroed(table.descriptors.add(index).cast(), size_of::<BlockDescriptor>()) };
+}
diff --git a/Libraries/LibGC/Rust/src/lib.rs b/Libraries/LibGC/Rust/src/lib.rs
new file mode 100644
index 00000000000..0114b7c2bfe
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/lib.rs
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The parts of LibGC's collector that are written in Rust.
+
+#[cfg(feature = "allocator")]
+extern crate ladybird_allocator;
+
+#[path = "../../../RustDemangle.rs"]
+mod rust_demangle;
+
+#[path = "../../../RustPanic.rs"]
+mod rust_panic;
+
+mod block;
+mod marker;
+mod os;
+mod pool;
+
+pub use block::{BlockDescriptor, rust_gc_block_descriptor_commit, rust_gc_block_descriptor_table};
+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,
+};
diff --git a/Libraries/LibGC/Rust/src/marker.rs b/Libraries/LibGC/Rust/src/marker.rs
new file mode 100644
index 00000000000..02c248d1714
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/marker.rs
@@ -0,0 +1,583 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Marking: from the roots, every cell of the heaps being collected that can be reached gets its mark bit set, and its
+//! edges visited.
+//!
+//! The thread that collects marks alone at first. If cells are left after a few thousand, the helper threads of the
+//! pool join in, each with a marker of its own: a cell's mark bit is set atomically, so the marker that sets it is the
+//! one that visits its edges, and markers that run out of cells steal them from the others. The cells that markers have
+//! yet to visit are kept as 32-bit compressed pointers.
+//!
+//! A cell's edges are visited through the visit_edges() of the type its block was created for, which gets the visitor
+//! of the marker, which hands the cells it finds straight back to the marker. The cells of some blocks may only be
+//! visited on the thread that collects, as C++ cells must, so helpers hand those to it.
+
+use core::cell::{Cell, UnsafeCell};
+use core::ffi::c_void;
+use core::ptr::NonNull;
+use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::Barrier;
+
+use crossbeam_deque::{Injector, Steal, Stealer, Worker};
+
+use crate::block::{BLOCK_SIZE, BlockDescriptor, descriptor_table, heap_of_descriptor};
+use crate::pool::{Pool, PoolGuard, thread_count};
+use crate::rust_panic::abort_on_panic;
+
+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.
+const CELLS_TO_MARK_BEFORE_HELPERS: usize = 4096;
+
+/// Where the marker finds what it needs in LibGC's cells, type infos and NaN-boxed values.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct MarkerLayout {
+ pub heap_region_base: usize,
+ /// The state of a cell, a u8 that is cell_state_live while the cell is live.
+ pub cell_state_offset: u32,
+ pub cell_state_live: u8,
+ /// `void (*)(Cell*, Visitor*)`.
+ pub type_info_visit_edges_offset: u32,
+ /// `size_t (*)(Cell const*)`, which may be null.
+ pub type_info_external_memory_size_offset: u32,
+ /// The bits that are all set in a NaN-boxed value that holds a cell, whose bits under value_offset_mask are then the
+ /// cell's offset into the heap region.
+ pub value_is_cell_pattern: u64,
+ pub value_offset_mask: u64,
+}
+
+/// Creates the visitor of a marker, a Cell::Visitor that hands what it visits to the marker, on the marker's thread.
+pub type CreateVisitor = unsafe extern "C" fn(context: *mut c_void, marker: *mut Marker) -> *mut c_void;
+pub type DestroyVisitor = unsafe extern "C" fn(context: *mut c_void, visitor: *mut c_void);
+
+#[repr(C)]
+pub struct MarkRequest {
+ pub layout: MarkerLayout,
+ /// The heaps whose cells this marks. Cells of other heaps are neither marked nor visited.
+ pub heaps: *const *const c_void,
+ pub heap_count: usize,
+ pub roots: *const *const c_void,
+ pub root_count: usize,
+ /// Whether the heaps are large enough for helpers to be worth waking, should the collecting thread not finish
+ /// alone soon.
+ pub parallel: bool,
+ pub context: *mut c_void,
+ pub create_visitor: CreateVisitor,
+ pub destroy_visitor: DestroyVisitor,
+ /// Arrays of heap_count entries, which this sets to the bytes of the cells it marked in each heap, and the bytes
+ /// that they own outside the heap.
+ pub marked_cell_bytes: *mut usize,
+ pub marked_external_bytes: *mut usize,
+ /// Set to the number of threads that marked.
+ pub threads_used: usize,
+}
+
+type VisitEdges = unsafe extern "C" fn(cell: *mut c_void, visitor: *mut c_void);
+type ExternalMemorySize = unsafe extern "C" fn(cell: *const c_void) -> usize;
+
+/// What every marker of one collection shares.
+struct Job<'a> {
+ layout: MarkerLayout,
+ descriptors: NonNull<BlockDescriptor>,
+ heaps: &'a [*const c_void],
+ markers: Vec<Marker>,
+ stealers: Vec<Stealer<u32>>,
+ /// The cells that only the thread that collects may visit the edges of.
+ owner_queue: Injector<u32>,
+ /// How many markers mark in this round; 1 until the helpers join in.
+ participants: AtomicUsize,
+ /// The markers that found no work, see Marker::run_round().
+ idle_markers: AtomicUsize,
+ round_done: Barrier,
+ /// Whether the markers go for another round, which the owner decides once a round is done.
+ another_round: AtomicBool,
+ context: *mut c_void,
+ create_visitor: CreateVisitor,
+ destroy_visitor: DestroyVisitor,
+}
+
+// SAFETY: Each marker is only used by its own thread while markers run. The thread that collects reads all of them
+// while every other marker waits at a barrier or is done. The rest is either immutable or synchronized.
+unsafe impl Sync for Job<'_> {}
+
+/// One thread's marker. The first is the one of the thread that collects (the owner).
+///
+/// Marking reenters the marker: a cell's visit_edges() hands the cells it finds back to the marker that visits it. So
+/// a marker is only ever used through shared references.
+pub struct Marker {
+ job: Cell<*const Job<'static>>,
+ is_owner: bool,
+ /// Whether other markers may set mark bits at the same time.
+ shared: Cell<bool>,
+ queue: Worker<u32>,
+ /// The owner's cells that only it may visit, which no other marker can steal. Once helpers mark too, the owner
+ /// visits these first: they are what only it can do, while the other markers take the rest.
+ owner_only_queue: Worker<u32>,
+ visitor: Cell<*mut c_void>,
+ marked_cell_bytes: Box<[Cell<usize>]>,
+ marked_external_bytes: Box<[Cell<usize>]>,
+ /// Ephemerons whose key was not marked yet when they were visited, as (key, value).
+ pending_ephemerons: UnsafeCell<Vec<(u32, u32)>>,
+}
+
+impl Job<'_> {
+ #[inline(always)]
+ fn compress(&self, address: usize) -> u32 {
+ ((address - self.layout.heap_region_base) >> COMPRESSED_POINTER_SHIFT) as u32
+ }
+
+ #[inline(always)]
+ fn decompress(&self, compressed: u32) -> usize {
+ self.layout.heap_region_base + ((compressed as usize) << COMPRESSED_POINTER_SHIFT)
+ }
+
+ /// The descriptor of the block of a cell of the heaps being collected.
+ #[inline(always)]
+ fn descriptor(&self, address: usize) -> &BlockDescriptor {
+ self.descriptor_in_domain(address)
+ .expect("the cell is in a heap being collected")
+ .1
+ }
+
+ /// The index among the heaps being collected of the heap of the block that `address` is in, and the block's
+ /// descriptor, if it is one of them. Only then is the descriptor borrowed, as the descriptor of a block of another
+ /// heap may change meanwhile, see heap_of_descriptor().
+ #[inline(always)]
+ fn descriptor_in_domain(&self, address: usize) -> Option<(usize, &BlockDescriptor)> {
+ let index = (address - self.layout.heap_region_base) / BLOCK_SIZE;
+ // SAFETY: Every cell is in a block of the region, whose descriptor is in the table.
+ let descriptor = unsafe { self.descriptors.add(index) };
+ // SAFETY: As above.
+ let heap = unsafe { heap_of_descriptor(descriptor.as_ptr()) }.cast_const();
+ let heap_index = if self.heaps.len() == 1 {
+ (self.heaps[0] == heap).then_some(0)
+ } else {
+ self.heaps.iter().position(|&candidate| candidate == heap)
+ }?;
+ // SAFETY: The block belongs to a heap being collected, which is stopped, so nothing changes its descriptor but
+ // the mark bits, which are atomic.
+ Some((heap_index, unsafe { descriptor.as_ref() }))
+ }
+}
+
+impl Marker {
+ fn job(&self) -> &Job<'static> {
+ // SAFETY: The job outlives its markers' use.
+ unsafe { &*self.job.get() }
+ }
+
+ /// 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.
+ #[inline(always)]
+ fn mark(&self, address: usize) -> bool {
+ let job = self.job();
+ let Some((_, descriptor)) = job.descriptor_in_domain(address) else {
+ return false;
+ };
+ let newly_marked = if self.shared.get() {
+ descriptor.mark(address)
+ } else {
+ descriptor.mark_exclusive(address)
+ };
+ if newly_marked {
+ // NB: The cell's edges are visited soon, as the queue is a stack.
+ #[cfg(target_arch = "x86_64")]
+ // SAFETY: Prefetching has no effect on memory.
+ unsafe {
+ core::arch::x86_64::_mm_prefetch(address as *const i8, core::arch::x86_64::_MM_HINT_T0);
+ }
+ let compressed = job.compress(address);
+ if descriptor.traced_on_owner_thread_only && self.shared.get() {
+ if self.is_owner {
+ self.owner_only_queue.push(compressed);
+ } else {
+ job.owner_queue.push(compressed);
+ }
+ } else {
+ self.queue.push(compressed);
+ }
+ }
+ newly_marked
+ }
+
+ #[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);
+ }
+ }
+ }
+
+ fn visit_ephemeron(&self, key: usize, value: usize) {
+ let job = self.job();
+ // NB: Keys outside the heaps being collected are never marked here, so their values stay reachable.
+ if job
+ .descriptor_in_domain(key)
+ .is_none_or(|(_, descriptor)| descriptor.is_marked(key))
+ {
+ self.mark(value);
+ return;
+ }
+ // SAFETY: Only this marker's thread touches its pending ephemerons while it marks.
+ unsafe { &mut *self.pending_ephemerons.get() }.push((job.compress(key), job.compress(value)));
+ }
+
+ fn find_work(&self) -> Option<u32> {
+ let job = self.job();
+ if self.is_owner
+ && let Some(cell) = self.owner_only_queue.pop()
+ {
+ return Some(cell);
+ }
+ loop {
+ let mut retry = false;
+ if self.is_owner {
+ match job.owner_queue.steal_batch_and_pop(&self.owner_only_queue) {
+ Steal::Success(cell) => return Some(cell),
+ Steal::Retry => retry = true,
+ Steal::Empty => {}
+ }
+ }
+ if let Some(cell) = self.queue.pop() {
+ return Some(cell);
+ }
+ if self.shared.get() {
+ for stealer in &job.stealers {
+ match stealer.steal_batch_and_pop(&self.queue) {
+ Steal::Success(cell) => return Some(cell),
+ Steal::Retry => retry = true,
+ Steal::Empty => {}
+ }
+ }
+ }
+ if !retry {
+ return None;
+ }
+ }
+ }
+
+ fn has_visible_work(&self) -> bool {
+ let job = self.job();
+ (self.is_owner && !job.owner_queue.is_empty()) || job.stealers.iter().any(|stealer| !stealer.is_empty())
+ }
+
+ /// Visits the edges of a marked cell, and counts the cell and the memory it owns outside the heap.
+ fn visit_edges_of(&self, compressed: u32) {
+ let job = self.job();
+ let layout = &job.layout;
+ let address = job.decompress(compressed);
+ let (heap_index, descriptor) = job
+ .descriptor_in_domain(address)
+ .expect("only cells of the heaps being collected are marked");
+ if !self.is_owner && descriptor.traced_on_owner_thread_only {
+ job.owner_queue.push(compressed);
+ return;
+ }
+ // SAFETY: The cell is in a block of a heap being collected, which no thread changes meanwhile.
+ if unsafe { ((address + layout.cell_state_offset as usize) as *const u8).read() } != layout.cell_state_live {
+ return;
+ }
+ let marked_cell_bytes = &self.marked_cell_bytes[heap_index];
+ marked_cell_bytes.set(marked_cell_bytes.get() + descriptor.cell_size as usize);
+ let type_info = descriptor.type_info.cast::<u8>();
+ // SAFETY: The type info of a block outlives it, and the layout says where its functions are.
+ let (external_memory_size, visit_edges) = unsafe {
+ (
+ type_info
+ .add(layout.type_info_external_memory_size_offset as usize)
+ .cast::<Option<ExternalMemorySize>>()
+ .read(),
+ type_info
+ .add(layout.type_info_visit_edges_offset as usize)
+ .cast::<VisitEdges>()
+ .read(),
+ )
+ };
+ if let Some(external_memory_size) = external_memory_size {
+ // SAFETY: The cell is a live cell of the type whose function this is.
+ let size = unsafe { external_memory_size(address as *const c_void) };
+ let marked_external_bytes = &self.marked_external_bytes[heap_index];
+ marked_external_bytes.set(marked_external_bytes.get().saturating_add(size));
+ }
+ // SAFETY: The cell is a live cell of the type whose function this is, which may be visited on this thread, and
+ // the visitor is this marker's.
+ unsafe { visit_edges(address as *mut c_void, self.visitor.get()) };
+ }
+
+ /// Visits the edges of at most `limit` cells, on this thread alone, and returns whether no cell was left.
+ fn drain_alone(&self, mut limit: usize) -> bool {
+ while limit != 0 {
+ let Some(cell) = self.find_work() else {
+ return true;
+ };
+ self.visit_edges_of(cell);
+ limit -= 1;
+ }
+ self.queue.is_empty() && self.owner_only_queue.is_empty() && self.job().owner_queue.is_empty()
+ }
+
+ /// Visits edges until no marker has cells left.
+ fn run_round(&self) {
+ let job = self.job();
+ loop {
+ while let Some(cell) = self.find_work() {
+ self.visit_edges_of(cell);
+ }
+
+ // NB: A marker only queues cells while it is not idle, and only the owner takes from the owner queue. So
+ // once every marker is idle and the owner queue is empty, no cell is left anywhere.
+ job.idle_markers.fetch_add(1, Ordering::SeqCst);
+ let mut waits = 0u32;
+ loop {
+ if self.has_visible_work() {
+ job.idle_markers.fetch_sub(1, Ordering::SeqCst);
+ break;
+ }
+ if job.idle_markers.load(Ordering::SeqCst) == job.participants.load(Ordering::Relaxed)
+ && job.owner_queue.is_empty()
+ {
+ return;
+ }
+ // NB: A marker that waits long yields, rather than take the time of a thread it shares a core with.
+ waits += 1;
+ if waits < 1024 {
+ core::hint::spin_loop();
+ } else {
+ std::thread::yield_now();
+ }
+ }
+ }
+ }
+
+ /// Marks the values of the pending ephemerons of every marker whose key was marked since, into this marker, which
+ /// must be the owner's. Returns whether that marked any.
+ fn mark_values_of_reached_ephemerons(&self) -> bool {
+ let job = self.job();
+ let mut marked_a_value = false;
+ for marker in &job.markers {
+ // SAFETY: Every other marker waits at the barrier or is done.
+ let pending = unsafe { &mut *marker.pending_ephemerons.get() };
+ pending.retain(|&(key, value)| {
+ let key = job.decompress(key);
+ if !job.descriptor(key).is_marked(key) {
+ return true;
+ }
+ marked_a_value |= self.mark(job.decompress(value));
+ false
+ });
+ }
+ marked_a_value
+ }
+
+ fn create_visitor(&self) {
+ let job = self.job();
+ // SAFETY: The marker outlives its visitor.
+ let visitor = unsafe { (job.create_visitor)(job.context, core::ptr::from_ref(self).cast_mut()) };
+ self.visitor.set(visitor);
+ }
+
+ fn destroy_visitor(&self) {
+ let job = self.job();
+ // SAFETY: The visitor was created for this marker, which is done with it.
+ unsafe { (job.destroy_visitor)(job.context, self.visitor.get()) };
+ }
+}
+
+/// What every marker runs once the helpers joined in, with its index; the owner's is 0.
+fn mark_in_parallel(job: &Job<'static>, index: usize) {
+ let marker = &job.markers[index];
+ marker.shared.set(true);
+ if index != 0 {
+ marker.create_visitor();
+ }
+ loop {
+ marker.run_round();
+ job.round_done.wait();
+ // NB: Marking can reach the key of a pending ephemeron, so the owner looks at those between rounds, and the
+ // markers go again while that marks more.
+ if index == 0 {
+ job.idle_markers.store(0, Ordering::SeqCst);
+ let another_round = marker.mark_values_of_reached_ephemerons();
+ job.another_round.store(another_round, Ordering::SeqCst);
+ }
+ job.round_done.wait();
+ if !job.another_round.load(Ordering::SeqCst) {
+ break;
+ }
+ }
+ if index != 0 {
+ marker.destroy_visitor();
+ }
+}
+
+/// # Safety
+///
+/// `data` must be a live Job, and `index` a marker of it that runs nowhere else.
+unsafe fn mark_in_parallel_from_pool(data: *const (), index: usize) {
+ // SAFETY: The caller passes a live job.
+ let job = unsafe { &*data.cast::<Job<'static>>() };
+ abort_on_panic(|| mark_in_parallel(job, index));
+}
+
+/// Marks the cell a visitor visits, which must be the start of a cell.
+///
+/// # Safety
+///
+/// `marker` must be the marker the visitor was created for, on its thread, and `cell` a cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_cell(marker: *mut Marker, cell: *const c_void) {
+ // SAFETY: The caller passes a live marker.
+ unsafe { &*marker }.mark(cell.addr());
+}
+
+/// Marks the cells of the NaN-boxed values a visitor visits.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell(), with `count` values at `values`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_values(marker: *mut Marker, values: *const u64, count: usize) {
+ // SAFETY: The caller passes a live marker and count values.
+ unsafe { &*marker }.visit_values(unsafe { ak::slice_from_raw_parts(values, count) });
+}
+
+/// Marks a cell that is reachable only while `key` is, such as a WeakMap entry's value, once the key is marked.
+///
+/// # Safety
+///
+/// As for rust_gc_marker_visit_cell(), and `key` and `value` must be cells.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_visit_ephemeron(marker: *mut Marker, key: *const c_void, value: *const c_void) {
+ // SAFETY: The caller passes a live marker.
+ unsafe { &*marker }.visit_ephemeron(key.addr(), value.addr());
+}
+
+/// The most threads that mark a heap, the thread that collects included.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_gc_marker_thread_count() -> usize {
+ thread_count()
+}
+
+/// Marks every cell of the heaps that the roots reach, and adds up the bytes they take.
+///
+/// # Safety
+///
+/// The request must be valid as its fields describe. Nothing else may use the heaps until this returns.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_gc_marker_mark(request: *mut MarkRequest) {
+ abort_on_panic(|| {
+ // SAFETY: The caller passes a valid request.
+ let request = unsafe { &mut *request };
+ // SAFETY: The caller passes heap_count heaps.
+ let heaps = unsafe { ak::slice_from_raw_parts(request.heaps, request.heap_count) };
+ // SAFETY: The caller passes root_count roots.
+ let roots = unsafe { ak::slice_from_raw_parts(request.roots, request.root_count) };
+ mark(request, heaps, roots);
+ });
+}
+
+fn mark(request: &mut MarkRequest, heaps: &[*const c_void], roots: &[*const c_void]) {
+ let pool = if request.parallel { Pool::the() } else { None };
+ let marker_count = pool.map_or(0, Pool::helper_count) + 1;
+ let mut job = Job {
+ layout: request.layout,
+ descriptors: descriptor_table(),
+ heaps,
+ markers: Vec::with_capacity(marker_count),
+ stealers: Vec::with_capacity(marker_count),
+ owner_queue: Injector::new(),
+ participants: AtomicUsize::new(1),
+ idle_markers: AtomicUsize::new(0),
+ round_done: Barrier::new(marker_count),
+ another_round: AtomicBool::new(false),
+ context: request.context,
+ create_visitor: request.create_visitor,
+ destroy_visitor: request.destroy_visitor,
+ };
+ for index in 0..marker_count {
+ let queue = Worker::new_lifo();
+ job.stealers.push(queue.stealer());
+ job.markers.push(Marker {
+ job: Cell::new(core::ptr::null()),
+ is_owner: index == 0,
+ shared: Cell::new(false),
+ queue,
+ owner_only_queue: Worker::new_lifo(),
+ visitor: Cell::new(core::ptr::null_mut()),
+ 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()),
+ });
+ }
+ // 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
+ // forever.
+ let job_pointer = (&raw const job).cast::<Job<'static>>();
+ for marker in &job.markers {
+ marker.job.set(job_pointer);
+ }
+ // SAFETY: See job_pointer.
+ let job = unsafe { &*job_pointer };
+ let owner = &job.markers[0];
+ owner.create_visitor();
+ for &root in roots {
+ owner.mark(root.addr());
+ }
+
+ // NB: Collections that mark few cells are done before helpers could have started.
+ let mut threads_used = 1;
+ let mut done_alone = owner.drain_alone(CELLS_TO_MARK_BEFORE_HELPERS);
+ let helpers: Option<PoolGuard> = if done_alone {
+ None
+ } else {
+ pool.and_then(Pool::try_acquire)
+ };
+ match helpers {
+ Some(helpers) => {
+ threads_used = marker_count;
+ job.participants.store(marker_count, Ordering::SeqCst);
+ // SAFETY: mark_in_parallel_from_pool() takes the job and the index of a helper's marker, which runs nowhere
+ // else.
+ unsafe {
+ helpers.run(mark_in_parallel_from_pool, job_pointer.cast(), || {
+ mark_in_parallel(job, 0);
+ });
+ };
+ }
+ None => {
+ // NB: Another heap may be using the helpers, so this one marks alone.
+ loop {
+ if !done_alone {
+ owner.drain_alone(usize::MAX);
+ }
+ if !owner.mark_values_of_reached_ephemerons() {
+ break;
+ }
+ done_alone = false;
+ }
+ }
+ }
+ owner.destroy_visitor();
+
+ for heap_index in 0..heaps.len() {
+ let mut cell_bytes = 0usize;
+ let mut external_bytes = 0usize;
+ for marker in &job.markers {
+ cell_bytes += marker.marked_cell_bytes[heap_index].get();
+ external_bytes = external_bytes.saturating_add(marker.marked_external_bytes[heap_index].get());
+ }
+ // SAFETY: The caller passes arrays of heap_count entries.
+ unsafe {
+ request.marked_cell_bytes.add(heap_index).write(cell_bytes);
+ request.marked_external_bytes.add(heap_index).write(external_bytes);
+ }
+ }
+ request.threads_used = threads_used;
+}
diff --git a/Libraries/LibGC/Rust/src/os.rs b/Libraries/LibGC/Rust/src/os.rs
new file mode 100644
index 00000000000..1011d2f64a3
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/os.rs
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The virtual memory operations the collector needs: reserving zero-filled address space that is only backed by
+//! memory where it is touched.
+
+use core::ptr::NonNull;
+
+#[cfg(unix)]
+mod platform {
+ use core::ptr::NonNull;
+
+ // Tags the heap's memory on macOS, as Core::System does, so that tools like vmmap show it apart from malloc.
+ #[cfg(target_os = "macos")]
+ const MEMORY_TAG: i32 = 241 << 24;
+ #[cfg(not(target_os = "macos"))]
+ const MEMORY_TAG: i32 = -1;
+
+ pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {
+ // SAFETY: An anonymous mapping that the kernel places anywhere touches no existing memory.
+ let address = unsafe {
+ libc::mmap(
+ core::ptr::null_mut(),
+ size,
+ libc::PROT_READ | libc::PROT_WRITE,
+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
+ MEMORY_TAG,
+ 0,
+ )
+ };
+ if address == libc::MAP_FAILED {
+ return None;
+ }
+ NonNull::new(address.cast())
+ }
+
+ /// # Safety
+ ///
+ /// The range must be within memory that reserve_zeroed() returned.
+ pub unsafe fn commit_reserved_zeroed(_address: NonNull<u8>, _size: usize) {
+ // NB: Anonymous mappings are backed by zeroed pages as they are first touched.
+ }
+}
+
+#[cfg(windows)]
+mod platform {
+ use core::ptr::NonNull;
+ use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc};
+
+ pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {
+ // NB: Windows has no lazily committed memory that does not count towards the commit limit, so this reserves
+ // only, and commit_reserved_zeroed() commits what is used.
+ // SAFETY: Reserving address space that the system places anywhere touches no existing memory.
+ let address = unsafe { VirtualAlloc(core::ptr::null(), size, MEM_RESERVE, PAGE_NOACCESS) };
+ NonNull::new(address.cast())
+ }
+
+ /// # Safety
+ ///
+ /// The range must be within memory that reserve_zeroed() returned.
+ pub unsafe fn commit_reserved_zeroed(address: NonNull<u8>, size: usize) {
+ // NB: Committing pages that are committed already leaves their contents alone.
+ // SAFETY: The caller guarantees the range is reserved.
+ let committed = unsafe { VirtualAlloc(address.as_ptr().cast(), size, MEM_COMMIT, PAGE_READWRITE) };
+ assert!(!committed.is_null(), "commit the table of block descriptors");
+ }
+}
+
+pub fn reserve_zeroed(size: usize) -> Option<NonNull<u8>> {
+ platform::reserve_zeroed(size)
+}
+
+/// Backs a range of memory that reserve_zeroed() returned with memory, if it was not already.
+///
+/// # Safety
+///
+/// The range must be within memory that reserve_zeroed() returned.
+pub unsafe fn commit_reserved_zeroed(address: NonNull<u8>, size: usize) {
+ // SAFETY: The caller's guarantee is the platform's.
+ unsafe { platform::commit_reserved_zeroed(address, size) }
+}
diff --git a/Libraries/LibGC/Rust/src/pool.rs b/Libraries/LibGC/Rust/src/pool.rs
new file mode 100644
index 00000000000..dfd6c671418
--- /dev/null
+++ b/Libraries/LibGC/Rust/src/pool.rs
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The threads that help the thread that owns a heap mark it. They live as long as the process, and wait for the next
+//! collection in between, so a collection does not pay for creating them.
+
+use core::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Condvar, Mutex, MutexGuard, OnceLock, PoisonError};
+
+/// The most threads that mark a heap, the thread that owns it included, unless LIBGC_MARKER_THREADS asks for another
+/// number. Marking is bound by memory accesses, so more threads than this gain little.
+const DEFAULT_MAX_THREADS: usize = 8;
+
+/// The threads that mark a heap, the thread that owns it included.
+pub(crate) fn thread_count() -> usize {
+ static COUNT: OnceLock<usize> = OnceLock::new();
+ *COUNT.get_or_init(|| {
+ if let Some(count) = std::env::var("LIBGC_MARKER_THREADS")
+ .ok()
+ .and_then(|value| value.trim().parse::<usize>().ok())
+ {
+ return count.clamp(1, 64);
+ }
+ std::thread::available_parallelism()
+ .map_or(1, usize::from)
+ .min(DEFAULT_MAX_THREADS)
+ })
+}
+
+/// What a collection hands the helpers: a function they each call with the data and their index, from 1 up.
+#[derive(Clone, Copy)]
+struct Task {
+ run: unsafe fn(data: *const (), index: usize),
+ data: *const (),
+}
+
+// SAFETY: The thread that hands out a task keeps its data alive and waits for every helper to be done with it.
+unsafe impl Send for Task {}
+
+struct State {
+ /// Goes up by one for every task, which tells the helpers that a new one is there.
+ generation: u64,
+ task: Option<Task>,
+ /// The helpers that have yet to finish the current task.
+ helpers_left: usize,
+}
+
+pub(crate) struct Pool {
+ /// The helpers that started, which is set once before the pool is used.
+ helper_count: AtomicUsize,
+ state: Mutex<State>,
+ task_available: Condvar,
+ helpers_done: Condvar,
+ /// Held while a collection uses the helpers. Heaps of other threads collect on their own meanwhile.
+ in_use: Mutex<()>,
+}
+
+fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
+ mutex.lock().unwrap_or_else(PoisonError::into_inner)
+}
+
+impl Pool {
+ /// The pool of the process, which is created on first use. There is none if only one thread marks.
+ pub(crate) fn the() -> Option<&'static Pool> {
+ static POOL: OnceLock<Option<&'static Pool>> = OnceLock::new();
+ *POOL.get_or_init(|| {
+ let helper_count = thread_count() - 1;
+ if helper_count == 0 {
+ return None;
+ }
+ let pool: &'static Pool = Box::leak(Box::new(Pool {
+ helper_count: AtomicUsize::new(0),
+ state: Mutex::new(State {
+ generation: 0,
+ task: None,
+ helpers_left: 0,
+ }),
+ task_available: Condvar::new(),
+ helpers_done: Condvar::new(),
+ in_use: Mutex::new(()),
+ }));
+ // NB: A helper that cannot start, as when the process has as many threads as it may, leaves marking to the
+ // ones that did, or to the thread that owns the heap alone.
+ let started = (1..=helper_count)
+ .take_while(|&index| {
+ std::thread::Builder::new()
+ .name("GC marker".into())
+ .spawn(move || pool.run_helper(index))
+ .is_ok()
+ })
+ .count();
+ if started == 0 {
+ return None;
+ }
+ pool.helper_count.store(started, Ordering::Relaxed);
+ Some(pool)
+ })
+ }
+
+ pub(crate) fn helper_count(&self) -> usize {
+ self.helper_count.load(Ordering::Relaxed)
+ }
+
+ /// Takes the helpers for one collection, unless another thread uses them.
+ pub(crate) fn try_acquire(&'static self) -> Option<PoolGuard> {
+ let guard = self.in_use.try_lock().ok()?;
+ Some(PoolGuard {
+ pool: self,
+ _in_use: guard,
+ })
+ }
+
+ fn run_helper(&self, index: usize) {
+ // NB: The pool starts at generation 0, so a helper that starts after the first task was handed out still sees it.
+ let mut seen_generation = 0;
+ loop {
+ let task = {
+ let mut state = lock(&self.state);
+ while state.generation == seen_generation {
+ state = self.task_available.wait(state).unwrap_or_else(PoisonError::into_inner);
+ }
+ seen_generation = state.generation;
+ state.task.expect("a new generation has a task")
+ };
+ // SAFETY: The thread that handed out the task keeps its data alive until every helper is done with it.
+ unsafe { (task.run)(task.data, index) };
+ let mut state = lock(&self.state);
+ state.helpers_left -= 1;
+ if state.helpers_left == 0 {
+ self.helpers_done.notify_one();
+ }
+ }
+ }
+}
+
+/// The helpers, taken for one collection.
+pub(crate) struct PoolGuard {
+ pool: &'static Pool,
+ _in_use: MutexGuard<'static, ()>,
+}
+
+impl PoolGuard {
+ /// Has every helper call `run` with `data` and its index while the calling thread calls `owner`, and returns once
+ /// all are done.
+ ///
+ /// # Safety
+ ///
+ /// `run` must be safe to call with `data` and each index from 1 to helper_count(), on any thread, at the same time
+ /// as `owner` runs.
+ pub(crate) unsafe fn run(
+ &self,
+ run: unsafe fn(data: *const (), index: usize),
+ data: *const (),
+ owner: impl FnOnce(),
+ ) {
+ let pool = self.pool;
+ {
+ let mut state = lock(&pool.state);
+ state.generation += 1;
+ state.task = Some(Task { run, data });
+ state.helpers_left = pool.helper_count();
+ pool.task_available.notify_all();
+ }
+ owner();
+ let mut state = lock(&pool.state);
+ while state.helpers_left > 0 {
+ state = pool.helpers_done.wait(state).unwrap_or_else(PoisonError::into_inner);
+ }
+ state.task = None;
+ }
+}
diff --git a/Libraries/LibGC/WeakBlock.cpp b/Libraries/LibGC/WeakBlock.cpp
index 53b8651ca9e..c83ce6a688f 100644
--- a/Libraries/LibGC/WeakBlock.cpp
+++ b/Libraries/LibGC/WeakBlock.cpp
@@ -5,6 +5,7 @@
*/
#include <LibCore/System.h>
+#include <LibGC/BlockDescriptor.h>
#include <LibGC/Cell.h>
#include <LibGC/WeakBlock.h>
@@ -71,7 +72,7 @@ void WeakBlock::sweep()
if (impl.state() == WeakImpl::State::Freelist)
continue;
auto* cell = static_cast<Cell*>(impl.ptr());
- if (!cell || !cell->is_marked())
+ if (!cell || !GC::is_marked(cell))
impl.set_ptr({}, nullptr);
if (impl.ref_count() == 0)
deallocate(&impl);
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 953a4365a27..4f9d6d778e9 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -639,8 +639,8 @@ pub struct LexicalEnvironmentTemplateSnapshot {
/// `ECMAScriptFunctionObject::inline_call_environment()`), with its final
/// shape and room for its binding values in the cell, as JIT code allocates
/// it: from the local free list at `allocator` (like
-/// `ObjectSizeClass::allocator`), with `words` (the cell's bytes, with a
-/// clear mark), then the pointer to its binding values, which start right
+/// `ObjectSizeClass::allocator`), with `words` (the cell's bytes), then the
+/// pointer to its binding values, which start right
/// after `words`, at `binding_values_offset`, and the `this` value the call
/// binds at `this_value_offset` if `binds_this`. The binding values need no
/// initialization: the environment has none yet.
diff --git a/Libraries/LibJS/Rust/generate/layout_header.rs b/Libraries/LibJS/Rust/generate/layout_header.rs
index 1b7df13e499..95b088cc75b 100644
--- a/Libraries/LibJS/Rust/generate/layout_header.rs
+++ b/Libraries/LibJS/Rust/generate/layout_header.rs
@@ -281,7 +281,6 @@ pub fn generate() -> LayoutHeader {
let mut w = HeaderWriter::new();
w.section("Cell header, at the start of every cell");
- offset!(w, "CELL_MARK", CellHeader, mark);
offset!(w, "CELL_STATE", CellHeader, state);
offset!(w, "CELL_KIND", CellHeader, kind);
for kind in [CellKind::Other, CellKind::Object, CellKind::PrimitiveString, CellKind::Symbol, CellKind::BigInt, CellKind::Accessor] {
diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rs
index 28e44ef5b36..d271b477ccb 100644
--- a/Libraries/LibJS/Rust/src/gc/capi.rs
+++ b/Libraries/LibJS/Rust/src/gc/capi.rs
@@ -28,6 +28,11 @@ pub struct GCAllocator {
_private: [u8; 0],
}
+#[repr(C)]
+pub struct GCMarker {
+ _private: [u8; 0],
+}
+
#[repr(C)]
pub struct GCRoot {
_private: [u8; 0],
@@ -44,7 +49,6 @@ pub const GC_COLLECTION_TYPE_COLLECT_EVERYTHING: i32 = 1;
#[derive(Default)]
#[repr(C)]
pub struct GCLayout {
- pub cell_mark_offset: u32,
pub cell_state_offset: u32,
pub cell_kind_offset: u32,
pub min_cell_size: u32,
@@ -64,6 +68,7 @@ pub struct GCLayout {
pub block_foreign_type_offset: u32,
pub heap_region_offset_mask: u64,
pub primitive_storage_cage_offset_mask: u64,
+ pub visitor_marker_offset: u32,
}
/// The generation of the storage's table entry in the high 32 bits and the entry's index in the low 32 bits.
@@ -121,15 +126,15 @@ unsafe extern "C" {
foreign_type: *const c_void,
) -> *mut GCAllocator;
pub fn gc_allocator_destroy(allocator: *mut GCAllocator);
- pub fn gc_heap_allocate_cell(heap: *mut GCHeap, allocator: *mut GCAllocator, must_mark: *mut bool) -> *mut c_void;
- pub fn gc_heap_allocate_storage_cell(
- heap: *mut GCHeap,
- allocator: *mut GCAllocator,
- must_mark: *mut bool,
- ) -> *mut c_void;
+ pub fn gc_allocator_set_traced_on_owner_thread_only(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_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_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 4bd1b46dce2..8443d0a043a 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -44,6 +44,9 @@ pub struct Class {
pub object_methods: Option<&'static ObjectMethods>,
/// The kind of the cells of this class, which type_info also holds for LibGC.
kind: CellKind,
+ /// Whether LibGC may only trace the cells of this class on the thread that owns their heap, see
+ /// traced_on_owner_thread_only().
+ owner_thread_only: bool,
}
// The layout module's mirror of the class, through which Layout.h tells an embedder where a class keeps its id and
@@ -99,6 +102,7 @@ impl Class {
parent,
object_methods,
kind,
+ owner_thread_only: false,
}
}
@@ -106,6 +110,18 @@ impl Class {
self.kind
}
+ /// LibGC traces cells on several threads at once while the thread that owns their heap is stopped. This has it
+ /// trace the cells of this class on the owner only, for classes whose trace() or external_memory_size() read
+ /// state of the owner thread, or state that other cells share without synchronization.
+ pub const fn traced_on_owner_thread_only(mut self) -> Self {
+ self.owner_thread_only = true;
+ self
+ }
+
+ pub fn is_traced_on_owner_thread_only(&self) -> bool {
+ self.owner_thread_only
+ }
+
/// 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 {
@@ -207,6 +223,7 @@ impl Class {
parent: Some(parent),
object_methods,
kind: parent.kind,
+ owner_thread_only: parent.owner_thread_only,
}));
#[cfg(feature = "address-sanitizer")]
// SAFETY: The class is a live allocation, which the process keeps for as long as it runs.
@@ -401,7 +418,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 {
- mark: false.into(),
+ unused_byte: 0,
state: CellState::Live.into(),
kind: class.kind(),
}
@@ -413,7 +430,7 @@ impl CellHeader {
pub fn for_class(class: &'static Class) -> Self {
Self {
unused: [0; 8],
- mark: false.into(),
+ unused_byte: 0,
state: CellState::Live.into(),
kind: class.kind(),
}
@@ -432,17 +449,21 @@ impl CellHeader {
/// of them inherits them from the class it extends, as C++ subclasses inherit virtual methods, so the Finalize
/// implementation of a subclass has to finalize its base as well.
macro_rules! define_cell {
- ($type:ident, $kind:ident $(, extends: [$parent:ident $(, $ancestor:ident)*])? $(, methods: $methods:path)? $(, finalize: $finalize:ident)? $(, external_memory_size: $external_memory_size:ident)?) => {
+ ($type:ident, $kind:ident $(, extends: [$parent:ident $(, $ancestor:ident)*])? $(, methods: $methods:path)? $(, finalize: $finalize:ident)? $(, external_memory_size: $external_memory_size:ident)? $(, traced_on: $traced_on:ident)?) => {
const _: () = {
- static CLASS: $crate::gc::class::Class = $crate::gc::class::Class::new::<$type>(
- stringify!($type),
- $crate::gc::class_id::ClassId::$type,
- $crate::layout::cell::CellKind::$kind,
- define_cell!(@parent $($parent)?),
- define_cell!(@methods [$($parent)?] [$($methods)?]),
- define_cell!(@finalize $type [$($parent)?] [$($finalize)?]),
- )
- .with_external_memory_size(define_cell!(@external_memory_size $type [$($parent)?] [$($external_memory_size)?]));
+ static CLASS: $crate::gc::class::Class = {
+ let class = $crate::gc::class::Class::new::<$type>(
+ stringify!($type),
+ $crate::gc::class_id::ClassId::$type,
+ $crate::layout::cell::CellKind::$kind,
+ define_cell!(@parent $($parent)?),
+ define_cell!(@methods [$($parent)?] [$($methods)?]),
+ define_cell!(@finalize $type [$($parent)?] [$($finalize)?]),
+ )
+ .with_external_memory_size(define_cell!(@external_memory_size $type [$($parent)?] [$($external_memory_size)?]));
+ $(let class = define_cell!(@traced_on $traced_on class);)?
+ class
+ };
// SAFETY: Checked by the asserts in Class::new and the cell's #[repr(C)] layout.
unsafe impl $crate::gc::class::GcCell for $type {
@@ -456,6 +477,7 @@ macro_rules! define_cell {
)?
};
};
+ (@traced_on owner_thread_only $class:ident) => { $class.traced_on_owner_thread_only() };
(@parent) => { None };
(@parent $parent:ident) => { Some(<$parent as $crate::gc::class::GcCell>::CLASS) };
(@methods [] []) => { None };
diff --git a/Libraries/LibJS/Rust/src/gc/embedder_cell.rs b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
index 73156063ffb..ad1cdc8b910 100644
--- a/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
+++ b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
@@ -108,6 +108,12 @@ impl<T: Trace + 'static> EmbedderClass<T> {
self.class.type_info.finalize = Some(finalize);
self
}
+
+ /// The class with its cells traced on the thread that owns their heap only, see Class::traced_on_owner_thread_only().
+ pub const fn traced_on_owner_thread_only(mut self) -> Self {
+ self.class = self.class.traced_on_owner_thread_only();
+ self
+ }
}
impl<T: Trace + ExternalMemorySize + 'static> EmbedderClass<T> {
diff --git a/Libraries/LibJS/Rust/src/gc/gc_ref_cell.rs b/Libraries/LibJS/Rust/src/gc/gc_ref_cell.rs
index b011ea234ed..354acd78ae1 100644
--- a/Libraries/LibJS/Rust/src/gc/gc_ref_cell.rs
+++ b/Libraries/LibJS/Rust/src/gc/gc_ref_cell.rs
@@ -60,7 +60,11 @@ impl<T: Default> Default for GcRefCell<T> {
// SAFETY: Traces the current value.
unsafe impl<T: Trace> Trace for GcRefCell<T> {
fn trace(&self, visitor: &mut Visitor) {
- let Ok(value) = self.0.try_borrow() else {
+ // NB: Marking may trace the cell on a thread other than the one that owns the heap, so this only reads the
+ // borrow state, rather than borrow the value.
+ // SAFETY: The thread that owns the heap is stopped while its collection marks, and it holds no mutable borrow,
+ // which this checks, so nothing changes the value while it is traced.
+ let Ok(value) = (unsafe { self.0.try_borrow_unguarded() }) else {
eprintln!("libjs_rust: garbage collection while a GcRefCell is mutably borrowed");
std::process::abort();
};
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index c6418e811a9..1522f2730fa 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -387,7 +387,7 @@ impl Heap {
// SAFETY: The allocator belongs to this heap and hands out cells of cell_size bytes.
let cell = match unsafe { self.take_from_local_free_list(allocator, cell_size, kind) } {
// SAFETY: The storage is a cell of the allocator, so it has the size and the alignment the caller guarantees.
- Some(storage) => unsafe { Self::write_cell(storage.cast(), cell, initialize_tail, false) },
+ Some(storage) => unsafe { Self::write_cell(storage.cast(), cell, initialize_tail) },
// SAFETY: The caller's guarantees about the allocator and the tail pass on.
None => unsafe { self.allocate_from_heap(&defer_gc, allocator, kind, cell, initialize_tail) },
};
@@ -409,35 +409,27 @@ impl Heap {
cell: T,
initialize_tail: impl FnOnce(*mut u8),
) -> Gc<T> {
- let mut must_mark = false;
let raw = allocator.raw.as_ptr();
// SAFETY: The heap and the allocator are live.
let storage = unsafe {
match kind {
- AllocationKind::Cell => capi::gc_heap_allocate_cell(self.raw.as_ptr(), raw, &raw mut must_mark),
- AllocationKind::Storage => {
- capi::gc_heap_allocate_storage_cell(self.raw.as_ptr(), raw, &raw mut must_mark)
- }
+ AllocationKind::Cell => capi::gc_heap_allocate_cell(self.raw.as_ptr(), raw),
+ AllocationKind::Storage => capi::gc_heap_allocate_storage_cell(self.raw.as_ptr(), raw),
}
};
let storage = NonNull::new(storage).expect("LibGC allocates the cell").cast::<T>();
// SAFETY: LibGC returned uninitialized storage of at least the size and the alignment of a T, as the caller
// guarantees.
- unsafe { Self::write_cell(storage, cell, initialize_tail, must_mark) }
+ unsafe { Self::write_cell(storage, cell, initialize_tail) }
}
- /// Writes `cell` to `storage` and has `initialize_tail` write the rest of the cell, with `must_mark` as its mark.
+ /// Writes `cell` to `storage` and has `initialize_tail` write the rest of the cell.
///
/// # Safety
///
/// `storage` must be uninitialized storage of at least the size and the alignment of a T, which nothing can collect
/// garbage before it is written, and `initialize_tail` must write every byte beyond the T.
- unsafe fn write_cell<T: GcCell>(
- storage: NonNull<T>,
- cell: T,
- initialize_tail: impl FnOnce(*mut u8),
- must_mark: bool,
- ) -> Gc<T> {
+ unsafe fn write_cell<T: GcCell>(storage: NonNull<T>, cell: T, initialize_tail: impl FnOnce(*mut u8)) -> Gc<T> {
// SAFETY: The caller passes storage for a T with room for the tail.
unsafe {
storage.write(cell);
@@ -447,14 +439,13 @@ impl Heap {
// SAFETY: Every cell starts with its header.
unsafe {
debug_assert!((*header.as_ptr()).class().is_subclass_of(T::CLASS));
- (*header.as_ptr()).mark.set(must_mark);
Gc::from_non_null(storage)
}
}
/// Takes a cell from the allocator's local free list, or else from its never-allocated cells, unless LibGC has to
/// collect garbage first or there is no local free cell, with the bookkeeping gc_heap_allocator_local_free_list()
- /// describes. These cells never need marking.
+ /// describes. These cells are in blocks that are swept already, so they never need marking.
///
/// # Safety
///
@@ -529,6 +520,10 @@ impl Heap {
let raw =
unsafe { capi::gc_allocator_create(type_info, name.as_ptr().cast(), name.len(), foreign_type.cast()) };
let raw = NonNull::new(raw).expect("LibGC creates the allocator");
+ if class.is_traced_on_owner_thread_only() {
+ // SAFETY: The allocator is live and has not allocated yet.
+ unsafe { capi::gc_allocator_set_traced_on_owner_thread_only(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 }
@@ -564,6 +559,12 @@ impl Heap {
class.name,
allocating_class.name
);
+ assert!(
+ !class.is_traced_on_owner_thread_only() || allocating_class.is_traced_on_owner_thread_only(),
+ "{} is traced on the owner thread only, unlike the allocator of {} it shares",
+ class.name,
+ allocating_class.name
+ );
let allocator = self
.shared_class_allocators
.borrow_mut()
@@ -796,9 +797,9 @@ fn check_layout() -> GCLayout {
);
};
expect(
- "cell mark offset",
- layout.cell_mark_offset.into(),
- offset_of!(CellHeader, mark) as u64,
+ "visitor marker offset",
+ layout.visitor_marker_offset.into(),
+ super::visitor::VISITOR_MARKER_OFFSET as u64,
);
expect(
"cell state offset",
diff --git a/Libraries/LibJS/Rust/src/gc/sweep.rs b/Libraries/LibJS/Rust/src/gc/sweep.rs
index 6527158b196..884181e6383 100644
--- a/Libraries/LibJS/Rust/src/gc/sweep.rs
+++ b/Libraries/LibJS/Rust/src/gc/sweep.rs
@@ -7,6 +7,7 @@
//! The sweep callback of a collection, which runs once the marks are final and before the cells that died are swept,
//! and has what holds cells without keeping them alive forget the ones that died.
+use crate::gc::capi;
use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, CellState, Gc};
use crate::runtime::finalization_registry::FinalizationRegistry;
@@ -28,7 +29,8 @@ impl<'vm> Sweep<'vm> {
pub fn is_dead<T>(&self, cell: Gc<T>) -> bool {
// SAFETY: Every cell starts with its header, and a cell that died is intact until the sweep that follows.
let header = unsafe { &*cell.as_ptr().cast::<CellHeader>() };
- header.state.get() != CellState::Live || !header.mark.get()
+ // SAFETY: The cell is a cell.
+ header.state.get() != CellState::Live || !unsafe { capi::gc_cell_is_marked(cell.as_ptr().cast()) }
}
/// Hands `finalization_registry` to HostEnqueueFinalizationRegistryCleanupJob once the collection is over.
diff --git a/Libraries/LibJS/Rust/src/gc/visitor.rs b/Libraries/LibJS/Rust/src/gc/visitor.rs
index dc3b9514b10..161f997c957 100644
--- a/Libraries/LibJS/Rust/src/gc/visitor.rs
+++ b/Libraries/LibJS/Rust/src/gc/visitor.rs
@@ -7,7 +7,10 @@
use core::cell::Cell;
use core::ptr::NonNull;
-use super::capi::{GCVisitor, gc_visitor_visit_cell, gc_visitor_visit_ephemeron, gc_visitor_visit_values};
+use super::capi::{
+ GCMarker, GCVisitor, gc_marker_visit_cell, gc_marker_visit_values, gc_visitor_visit_cell,
+ gc_visitor_visit_ephemeron, gc_visitor_visit_values,
+};
use crate::layout::cell::Gc;
use crate::layout::member::{Member, NullableMember};
use crate::layout::value::Value;
@@ -15,7 +18,25 @@ use crate::layout::value::Value;
/// A LibGC visitor, which marks what it visits during a collection and roots it while roots are gathered.
pub struct Visitor(NonNull<GCVisitor>);
+/// Where a visitor keeps the marker it marks for, right after the vtable pointer of the C++ Cell::Visitor, which
+/// check_layout() checks against GCLayout::visitor_marker_offset.
+pub(crate) const VISITOR_MARKER_OFFSET: usize = size_of::<usize>();
+
impl Visitor {
+ /// The marker of a visitor that marks for a collection, which takes the cells it visits directly.
+ #[inline(always)]
+ fn marker(&self) -> Option<NonNull<GCMarker>> {
+ // SAFETY: The visitor is a live Cell::Visitor, which keeps a marker pointer at this offset.
+ NonNull::new(unsafe {
+ self.0
+ .as_ptr()
+ .cast::<u8>()
+ .add(VISITOR_MARKER_OFFSET)
+ .cast::<*mut GCMarker>()
+ .read()
+ })
+ }
+
/// # Safety
///
/// `visitor` must be a visitor LibGC passed in, and outlive the returned value.
@@ -29,6 +50,11 @@ impl Visitor {
}
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.
+ unsafe { gc_marker_visit_cell(marker.as_ptr(), cell.as_ptr().cast()) };
+ return;
+ }
// SAFETY: The visitor is live, and a Gc points to a live cell.
unsafe { gc_visitor_visit_cell(self.0.as_ptr(), cell.as_ptr().cast()) };
}
@@ -47,6 +73,13 @@ impl Visitor {
}
pub fn visit_values(&mut self, values: &[Value]) {
+ if let Some(marker) = self.marker() {
+ if !values.is_empty() {
+ // SAFETY: The marker is the visitor's, and Value is a NaN-boxed u64.
+ unsafe { gc_marker_visit_values(marker.as_ptr(), values.as_ptr().cast(), values.len()) };
+ }
+ return;
+ }
// SAFETY: The visitor is live, and Value is a NaN-boxed u64.
unsafe { gc_visitor_visit_values(self.0.as_ptr(), values.as_ptr().cast(), values.len()) };
}
diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rs
index 575a3c41c81..db280b73ab5 100644
--- a/Libraries/LibJS/Rust/src/jit/allocation.rs
+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs
@@ -60,18 +60,13 @@ fn address(local_free_list: Option<NonNull<*mut core::ffi::c_void>>) -> u64 {
local_free_list.map_or(0, |list| list.as_ptr() as u64)
}
-/// Gives `word` the bytes of `cell` (of `size` bytes) as u64 words, first to last, with a clear mark: cells allocated
-/// while the incremental sweep is active start out marked, but cells from local free lists never need marking.
+/// Gives `word` the bytes of `cell` (of `size` bytes) as u64 words, first to last.
fn for_each_cell_word<T>(cell: Gc<T>, size: usize, mut word: impl FnMut(u64)) {
- let mark = core::mem::offset_of!(CellHeader, mark);
for start in (0..size).step_by(8) {
let mut bytes = [0u8; 8];
let len = (size - start).min(8);
// SAFETY: The cell is live and has `size` bytes, of which these `len` are some, and `bytes` has room for 8.
unsafe { core::ptr::copy_nonoverlapping(cell.as_ptr().cast::<u8>().add(start), bytes.as_mut_ptr(), len) };
- if let Some(byte) = mark.checked_sub(start).and_then(|index| bytes.get_mut(index)) {
- *byte = 0;
- }
word(u64::from_ne_bytes(bytes));
}
}
diff --git a/Libraries/LibJS/Rust/src/layout/cell.rs b/Libraries/LibJS/Rust/src/layout/cell.rs
index bb6703c52a6..42b1c382804 100644
--- a/Libraries/LibJS/Rust/src/layout/cell.rs
+++ b/Libraries/LibJS/Rust/src/layout/cell.rs
@@ -84,7 +84,8 @@ pub enum CellState {
#[repr(C, packed)]
pub struct CellHeader {
pub unused: [u8; 8],
- pub mark: Cell<bool>,
+ /// Free for later use: LibGC keeps the marks of cells in the descriptors of their blocks.
+ pub unused_byte: u8,
pub state: Cell<CellState>,
pub kind: CellKind,
}
@@ -94,7 +95,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 mark: Cell<bool>,
+ pub unused_byte: 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 27d7509f2db..91dbd7ccb69 100644
--- a/Libraries/LibJS/Rust/src/layout/object.rs
+++ b/Libraries/LibJS/Rust/src/layout/object.rs
@@ -58,7 +58,8 @@ pub const INDEXED_ELEMENTS_HEADER_SIZE: usize = 8;
pub struct Object {
pub shape: Member<Shape>,
pub indexed_array_like_size: Cell<u32>,
- pub mark: Cell<bool>,
+ /// Free for later use, see CellHeader::unused_byte.
+ pub unused_byte: u8,
pub state: Cell<CellState>,
pub kind: CellKind,
pub indexed_storage_kind: Cell<IndexedStorageKind>,
@@ -81,7 +82,7 @@ pub struct Object {
const _: () = {
use core::mem::offset_of;
- assert!(offset_of!(Object, mark) == offset_of!(CellHeader, mark));
+ assert!(offset_of!(Object, unused_byte) == offset_of!(CellHeader, unused_byte));
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/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index cec368297f3..7b834952c7c 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -579,7 +579,7 @@ impl Object {
let object = Object {
shape: Member::new(shape),
indexed_array_like_size: Cell::new(0),
- mark: Cell::new(false),
+ unused_byte: 0,
state: Cell::new(CellState::Live),
kind: CellKind::Object,
indexed_storage_kind: Cell::new(IndexedStorageKind::None),
@@ -3940,10 +3940,13 @@ impl Object {
fn indexed_dictionary_pointer(&self) -> *mut IndexedDictionary {
if self.is_ecmascript_function_object() {
- return *self
- .vm()
- .function_indexed_dictionaries
- .borrow()
+ // NB: Marker threads read the dictionaries of functions while they trace them, all at once, so this reads
+ // the map without touching its borrow count.
+ // SAFETY: Only the thread that owns the heap changes the map, and never while the map is read here: not
+ // while its collections mark, nor while the map is borrowed mutably, which this checks.
+ let dictionaries = unsafe { self.vm().function_indexed_dictionaries.try_borrow_unguarded() }
+ .expect("the indexed dictionaries of functions are not being changed");
+ return *dictionaries
.get(&core::ptr::from_ref(self).addr())
.expect("a function in dictionary mode has a dictionary");
}
diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
index 63feab8889b..13d68a590a4 100644
--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs
@@ -219,7 +219,8 @@ const MAX_CONSTRUCT_RESERVE_UPDATES: u32 = 1024;
const _: () = assert!(MAX_CONSTRUCT_RESERVE <= u8::MAX as u32);
const _: () = assert!(MAX_CONSTRUCT_RESERVE_UPDATES as u64 <= asm_call_metadata::CONSTRUCT_COUNT_MASK);
-define_cell!(SharedFunctionInstanceData, Other);
+// NB: Tracing considers the bytecode for flushing, with state of the thread that owns the heap.
+define_cell!(SharedFunctionInstanceData, Other, traced_on: owner_thread_only);
// SAFETY: Visits the executable, the call environment template and every cell the storage holds. While a collection
// flushes code, an executable that idled long enough is left to what else holds it, and the cells that outlive
diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rs
index 0676c4ddb6a..a1cb83ca1a4 100644
--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs
@@ -35,7 +35,6 @@ pub struct CellTypeInfo {
#[derive(Default, Clone, Copy)]
#[repr(C)]
pub struct GcLayout {
- pub cell_mark_offset: u32,
pub cell_state_offset: u32,
pub cell_kind_offset: u32,
pub min_cell_size: u32,
@@ -55,6 +54,7 @@ pub struct GcLayout {
pub block_foreign_type_offset: u32,
pub heap_region_offset_mask: u64,
pub primitive_storage_cage_offset_mask: u64,
+ pub visitor_marker_offset: u32,
}
/// Mirrors GCPrimitiveStorageLayout.
@@ -79,8 +79,8 @@ pub struct GcInterface {
name_length: usize,
foreign_type: *const c_void,
) -> *mut c_void,
- pub gc_heap_allocate_cell:
- unsafe extern "C" fn(heap: *mut c_void, allocator: *mut c_void, must_mark: *mut bool) -> *mut c_void,
+ pub gc_allocator_set_traced_on_owner_thread_only: unsafe extern "C" fn(allocator: *mut c_void),
+ pub gc_heap_allocate_cell: unsafe extern "C" fn(heap: *mut c_void, allocator: *mut c_void) -> *mut c_void,
pub gc_heap_defer_gc: unsafe extern "C" fn(heap: *mut c_void),
pub gc_heap_undefer_gc: unsafe extern "C" fn(heap: *mut c_void),
pub gc_heap_collect_garbage: unsafe extern "C" fn(heap: *mut c_void, collection_type: i32, print_report: bool),
@@ -283,7 +283,12 @@ impl Allocators {
fn new(interface: &GcInterface) -> Self {
let create = |cell_type: CellType| {
let (info, name) = type_info(cell_type);
- unsafe { (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len(), core::ptr::null()) }
+ let allocator =
+ unsafe { (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len(), core::ptr::null()) };
+ // NB: Tracing reaches the host objects of the thread that owns the heap (see HOST_OBJECTS), and the
+ // embedder's visit callbacks, so the cells of these allocators are only traced on that thread.
+ unsafe { (interface.gc_allocator_set_traced_on_owner_thread_only)(allocator) };
+ allocator
};
Self {
objects: (0..OBJECT_CELL_SIZE_CLASSES.len())
@@ -343,17 +348,13 @@ impl Heap {
let mut layout = GcLayout::default();
unsafe { (interface.gc_get_layout)(&raw mut layout) };
assert!(
- layout.cell_mark_offset as usize >= 8 && (layout.cell_kind_offset as usize) < CELL_HEADER_SIZE,
+ layout.cell_state_offset as usize >= 8 && (layout.cell_kind_offset as usize) < CELL_HEADER_SIZE,
"LibGC keeps its cell header in the second word"
);
assert!(
- [
- layout.cell_mark_offset,
- layout.cell_state_offset,
- layout.cell_kind_offset
- ]
- .iter()
- .all(|&offset| (offset as usize) < CELL_FLAGS_OFFSET),
+ [layout.cell_state_offset, layout.cell_kind_offset]
+ .iter()
+ .all(|&offset| (offset as usize) < CELL_FLAGS_OFFSET),
"the runtime's flags follow LibGC's cell header"
);
let allocators = ALLOCATORS.get_or_init(|| Allocators::new(&interface));
@@ -388,16 +389,10 @@ impl Heap {
cell
}
Self::Gc(heap) => unsafe {
- let mut must_mark = false;
- let cell: *mut u8 = (heap.interface.gc_heap_allocate_cell)(
- heap.interface.heap,
- heap.allocators.of(cell_type),
- &raw mut must_mark,
- )
- .cast();
+ let cell: *mut u8 =
+ (heap.interface.gc_heap_allocate_cell)(heap.interface.heap, heap.allocators.of(cell_type)).cast();
assert!(!cell.is_null(), "LibGC allocates the cell");
core::ptr::write_bytes(cell, 0, size);
- *cell.add(heap.layout.cell_mark_offset as usize) = u8::from(must_mark);
*cell.add(heap.layout.cell_state_offset as usize) = CELL_STATE_LIVE;
*cell.add(heap.layout.cell_kind_offset as usize) = CELL_KIND_OTHER;
cell
diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cpp
index 90bdb8a01cb..3e0d9d14015 100644
--- a/Libraries/LibWasm/Runtime.cpp
+++ b/Libraries/LibWasm/Runtime.cpp
@@ -160,6 +160,7 @@ static FFI::GcInterface gc_interface(GC::Heap& heap)
.heap = &heap,
.gc_get_layout = function_cast<decltype(Interface::gc_get_layout)>(gc_get_layout),
.gc_allocator_create = function_cast<decltype(Interface::gc_allocator_create)>(gc_allocator_create),
+ .gc_allocator_set_traced_on_owner_thread_only = function_cast<decltype(Interface::gc_allocator_set_traced_on_owner_thread_only)>(gc_allocator_set_traced_on_owner_thread_only),
.gc_heap_allocate_cell = function_cast<decltype(Interface::gc_heap_allocate_cell)>(gc_heap_allocate_cell),
.gc_heap_defer_gc = function_cast<decltype(Interface::gc_heap_defer_gc)>(gc_heap_defer_gc),
.gc_heap_undefer_gc = function_cast<decltype(Interface::gc_heap_undefer_gc)>(gc_heap_undefer_gc),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
index 5be548f5052..ce3b2c9aada 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
@@ -298,6 +298,7 @@ unsafe impl Trace for Animation {
}
impl Wrappable for Animation {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
Some(self.realm)
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
index f25386e68d4..c60eddd0663 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs
@@ -101,6 +101,7 @@ unsafe impl Trace for AnimationEffect {
}
impl Wrappable for AnimationEffect {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
self.relevant_realm()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
index a1b083448e8..65409b3c402 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs
@@ -50,7 +50,9 @@ unsafe impl Trace for AnimationTimeline {
}
}
-impl Wrappable for AnimationTimeline {}
+impl Wrappable for AnimationTimeline {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
+}
impl AnimationTimeline {
/// The timeline's state, which lives as long as the timeline.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs
index db754b099f7..59109ab5cdd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs
@@ -51,6 +51,7 @@ impl Inherits<AnimationTimeline> for DocumentTimeline {
}
impl Wrappable for DocumentTimeline {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const FINALIZES: bool = true;
fn finalize(object: Ref<Self>) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
index 8a4d71a5a23..65e2117b5bb 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs
@@ -863,6 +863,7 @@ impl Inherits<AnimationEffect> for KeyframeEffect {
}
impl Wrappable for KeyframeEffect {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
self.effect.relevant_realm()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
index 7f4358b6eba..13fa145fbf1 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs
@@ -72,6 +72,7 @@ impl Inherits<AnimationTimeline> for ScrollTimeline {
}
impl Wrappable for ScrollTimeline {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const FINALIZES: bool = true;
fn finalize(object: Ref<Self>) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
index ffdf2d7dfad..82757b63b74 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs
@@ -83,6 +83,7 @@ impl Inherits<ScrollTimeline> for ViewTimeline {
}
impl Wrappable for ViewTimeline {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const FINALIZES: bool = true;
fn finalize(object: Ref<Self>) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index c3dfb4fe76e..6997f4376d8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -64,6 +64,12 @@ pub(crate) trait Wrappable {
0
}
+ /// Whether LibGC may only trace the object, and ask for its external_memory_size(), on the thread that owns its heap,
+ /// as it does C++ objects. LibGC traces other objects on several threads at once while that thread is stopped, so
+ /// this must be true for an object whose tracing reaches C++ objects, thread-local state, or state that it shares
+ /// with other objects without synchronization.
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = false;
+
/// Whether LibGC finalizes the object before it destroys it, which it does through finalize(), as it does a C++
/// implementation object that overrides Cell::finalize().
const FINALIZES: bool = false;
@@ -147,6 +153,11 @@ pub(crate) const fn cell_class<T: Wrappable + Trace + 'static>(name: &'static st
} else {
EmbedderClass::new(name)
};
+ let class = if T::TRACED_ON_OWNER_THREAD_ONLY {
+ class.traced_on_owner_thread_only()
+ } else {
+ class
+ };
if T::FINALIZES {
class.with_finalize(finalize_object::<T>)
} else {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
index 494381c7fd8..c8d78af3f37 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs
@@ -89,6 +89,7 @@ pub(crate) struct AnimationEvent {
}
impl Wrappable for AnimationEvent {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.event.as_cpp_parent()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs
index 0c437245b82..5bc2fb0ecd4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs
@@ -37,6 +37,7 @@ impl Inherits<Animation> for CSSAnimation {
}
impl Wrappable for CSSAnimation {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
self.animation.relevant_realm()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
index 50b49e2d877..e53a5c42ada 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule.rs
@@ -85,6 +85,8 @@ pub(crate) fn native_rules_of_sheet(sheet: &CppCell) -> Rc<NativeRuleList> {
macro_rules! impl_rule_wrappable {
($type:ty) => {
impl crate::bindings::interface::Wrappable for $type {
+ // NB: The native rules and their lists share state with the whole document's style without synchronization.
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const OWNS_EXTERNAL_MEMORY: bool = true;
fn external_memory_size(&self) -> usize {
@@ -112,7 +114,9 @@ pub(crate) struct CSSRule {
declarations: GcRefCell<Option<CppCell>>,
}
-impl Wrappable for CSSRule {}
+impl Wrappable for CSSRule {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
+}
impl CSSRule {
pub(crate) fn new(native_rule: Rc<NativeRule>) -> Self {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs
index 5b626baf799..96ff3280a6e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_rule_list.rs
@@ -53,6 +53,7 @@ pub(crate) struct CSSRuleList {
}
impl Wrappable for CSSRuleList {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const OWNS_EXTERNAL_MEMORY: bool = true;
fn external_memory_size(&self) -> usize {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs
index a4f712a300e..342776a0675 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_style_sheet.rs
@@ -66,6 +66,7 @@ pub(crate) struct CSSStyleSheet {
}
impl Wrappable for CSSStyleSheet {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const OWNS_EXTERNAL_MEMORY: bool = true;
fn external_memory_size(&self) -> usize {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs
index 6b03bb9c4bb..6810feef8f5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs
@@ -38,6 +38,7 @@ impl Inherits<Animation> for CSSTransition {
}
impl Wrappable for CSSTransition {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
self.animation.relevant_realm()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
index 839f9001838..06cfe0cf52d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
@@ -201,6 +201,7 @@ pub(crate) struct FontFaceSet {
}
impl Wrappable for FontFaceSet {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn relevant_realm(&self) -> Option<Gc<Realm>> {
Some(self.realm)
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
index b62bd447f57..ed171731c59 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs
@@ -44,6 +44,7 @@ pub(crate) struct TransitionEvent {
}
impl Wrappable for TransitionEvent {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.event.as_cpp_parent()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
index 42a7bbdf3ce..1babc92c389 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs
@@ -36,6 +36,7 @@ impl Inherits<AnimationTimeline> for InternalAnimationTimeline {
}
impl Wrappable for InternalAnimationTimeline {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
const FINALIZES: bool = true;
fn finalize(object: Ref<Self>) {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
index 8fd98daee2b..2ee759e5da3 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
@@ -73,7 +73,8 @@ unsafe extern "C" {
name_length: usize,
foreign_type: *const c_void,
) -> *mut c_void;
- fn gc_heap_allocate_cell(heap: *mut c_void, allocator: *mut c_void, must_mark: *mut bool) -> *mut c_void;
+ fn gc_allocator_set_traced_on_owner_thread_only(allocator: *mut c_void);
+ fn gc_heap_allocate_cell(heap: *mut c_void, allocator: *mut c_void) -> *mut c_void;
fn gc_heap_defer_gc(heap: *mut c_void);
fn gc_heap_undefer_gc(heap: *mut c_void);
fn gc_heap_collect_garbage(heap: *mut c_void, collection_type: i32, print_report: bool);
@@ -104,6 +105,7 @@ fn gc_interface(heap: *mut c_void) -> GcInterface {
heap,
gc_get_layout,
gc_allocator_create,
+ gc_allocator_set_traced_on_owner_thread_only,
gc_heap_allocate_cell,
gc_heap_defer_gc,
gc_heap_undefer_gc,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
index 095bf21b458..b8600aa27da 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/audio_context.rs
@@ -80,6 +80,7 @@ impl Inherits<BaseAudioContext> for AudioContext {
}
impl Wrappable for AudioContext {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.context.cpp_parent()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
index e3a59899787..f81ab840ae7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/base_audio_context.rs
@@ -157,6 +157,7 @@ unsafe impl Trace for BaseAudioContext {
}
impl Wrappable for BaseAudioContext {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.event_target.as_cpp_parent()
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
index fbc71f33b3d..9f7b824eb12 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_audio/offline_audio_context.rs
@@ -63,6 +63,7 @@ impl Inherits<BaseAudioContext> for OfflineAudioContext {
}
impl Wrappable for OfflineAudioContext {
+ const TRACED_ON_OWNER_THREAD_ONLY: bool = true;
fn cpp_parent(&self) -> Option<NonNull<c_void>> {
self.context.cpp_parent()
}