Skip to content

Truly independent web browser

LibJS: Let embedders put their own values in GC cells

Aliaksandr Kalenik3b222294aff1
diff --git a/Libraries/LibJS/Rust/macros/src/lib.rs b/Libraries/LibJS/Rust/macros/src/lib.rs
index 1a4fb96abf7..8977d2e958d 100644
--- a/Libraries/LibJS/Rust/macros/src/lib.rs
+++ b/Libraries/LibJS/Rust/macros/src/lib.rs
@@ -13,13 +13,20 @@ use syn::{Data, DeriveInput, Fields, Index, parse_macro_input};
/// Implements Trace by tracing every field. A field marked #[gc(untraced)] is skipped; it has to hold no cells, or
/// cells something else keeps alive and the cell's owner clears once they die, like an inline cache's shapes.
+///
+/// The Trace trait is crate::gc::visitor::Trace, or path::gc::visitor::Trace for a type marked #[gc(crate = path)],
+/// such as a type that an embedder puts in cells of the runtime's heap from a crate of its own.
#[proc_macro_derive(Trace, attributes(gc))]
pub fn derive_trace(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
+ let gc = match gc_module_path(&input) {
+ Ok(path) => path,
+ Err(error) => return error.to_compile_error().into(),
+ };
let body = match &input.data {
- Data::Struct(data) => trace_fields(&data.fields, |member| quote!(&self.#member)),
+ Data::Struct(data) => trace_fields(&data.fields, &gc, |member| quote!(&self.#member)),
Data::Enum(data) => {
let arms = data.variants.iter().map(|variant| {
let variant_name = &variant.ident;
@@ -31,7 +38,7 @@ pub fn derive_trace(input: TokenStream) -> TokenStream {
.iter()
.zip(&bindings)
.filter(|(field, _)| !is_untraced(field))
- .map(|(_, binding)| quote!(crate::gc::visitor::Trace::trace(#binding, visitor);))
+ .map(|(_, binding)| quote!(#gc::visitor::Trace::trace(#binding, visitor);))
.collect();
match &variant.fields {
Fields::Named(fields) => {
@@ -52,9 +59,9 @@ pub fn derive_trace(input: TokenStream) -> TokenStream {
};
quote! {
// SAFETY: Traces every field that is not marked untraced.
- unsafe impl #impl_generics crate::gc::visitor::Trace for #name #type_generics #where_clause {
+ unsafe impl #impl_generics #gc::visitor::Trace for #name #type_generics #where_clause {
#[allow(unused_variables)]
- fn trace(&self, visitor: &mut crate::gc::visitor::Visitor) {
+ fn trace(&self, visitor: &mut #gc::visitor::Visitor) {
#body
}
}
@@ -62,7 +69,25 @@ pub fn derive_trace(input: TokenStream) -> TokenStream {
.into()
}
-fn trace_fields(fields: &Fields, access: impl Fn(TokenStream2) -> TokenStream2) -> TokenStream2 {
+/// The path of the module that has the visitor module, from the type's #[gc(crate = path)], or crate::gc.
+fn gc_module_path(input: &DeriveInput) -> syn::Result<TokenStream2> {
+ let mut crate_path: Option<syn::Path> = None;
+ for attribute in input.attrs.iter().filter(|attribute| attribute.path().is_ident("gc")) {
+ attribute.parse_nested_meta(|meta| {
+ if meta.path.is_ident("crate") {
+ crate_path = Some(meta.value()?.parse()?);
+ return Ok(());
+ }
+ Err(meta.error("expected `crate = path`"))
+ })?;
+ }
+ Ok(match crate_path {
+ Some(path) => quote!(#path::gc),
+ None => quote!(crate::gc),
+ })
+}
+
+fn trace_fields(fields: &Fields, gc: &TokenStream2, access: impl Fn(TokenStream2) -> TokenStream2) -> TokenStream2 {
let traced = fields
.iter()
.enumerate()
@@ -76,7 +101,7 @@ fn trace_fields(fields: &Fields, access: impl Fn(TokenStream2) -> TokenStream2)
}
};
let value = access(member);
- quote!(crate::gc::visitor::Trace::trace(#value, visitor);)
+ quote!(#gc::visitor::Trace::trace(#value, visitor);)
});
quote!(#(#traced)*)
}
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index a93bd7c4884..51c92a2069b 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -60,7 +60,7 @@ const _: () = {
};
/// LibGC hands out cells in the slots of fixed-size blocks, whose free list needs room for its own entry in each.
-const MIN_CELL_SIZE: usize = 24;
+pub(crate) const MIN_CELL_SIZE: usize = 24;
const MAX_CELL_ALIGNMENT: usize = 16;
impl Class {
diff --git a/Libraries/LibJS/Rust/src/gc/class_id.rs b/Libraries/LibJS/Rust/src/gc/class_id.rs
index 4e3a1a95056..656fbeb529f 100644
--- a/Libraries/LibJS/Rust/src/gc/class_id.rs
+++ b/Libraries/LibJS/Rust/src/gc/class_id.rs
@@ -341,4 +341,6 @@ define_class_ids! {
HostArray,
HostModule,
HostConsoleClient,
+ // The cells that hold values of an embedder's own types, which share this id and are told apart by their class.
+ EmbedderCell,
}
diff --git a/Libraries/LibJS/Rust/src/gc/embedder_cell.rs b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
new file mode 100644
index 00000000000..2c577a88ab7
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/gc/embedder_cell.rs
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Cells that hold values of an embedder's own types, which the embedder allocates from the heap of the VM and keeps
+//! alive through the host data slots of its host objects, or through any other traced place.
+//!
+//! The runtime does not know the embedder's types, so their cells have no class id of their own: every one has the
+//! id ClassId::EmbedderCell, and the class of a type, which the embedder defines once as a static, is told apart from
+//! every other class by its address. The heap keeps the allocator of such a class by that address.
+
+use core::ffi::c_void;
+use core::marker::PhantomData;
+use core::mem::{ManuallyDrop, MaybeUninit};
+use core::ops::Deref;
+use core::ptr::NonNull;
+
+use super::class::{Class, GcCell, MIN_CELL_SIZE, class_of};
+use super::class_id::ClassId;
+use super::visitor::{Trace, Visitor};
+use crate::interpreter::vm::Vm;
+use crate::layout::cell::{CellHeader, CellKind, Gc};
+
+/// A value of an embedder's type in a cell of its own, which derefs to the value.
+#[repr(C, align(8))]
+pub struct EmbedderCell<T> {
+ header: CellHeader,
+ value: ValueWithRoomForFreeListLink<T>,
+}
+
+/// LibGC keeps the link to the next free cell in the bytes after the header of a free cell, so a cell has at least
+/// MIN_CELL_SIZE bytes however small its value is.
+#[repr(C)]
+union ValueWithRoomForFreeListLink<T> {
+ value: ManuallyDrop<T>,
+ _room_for_free_list_link: [MaybeUninit<u8>; MIN_CELL_SIZE - size_of::<CellHeader>()],
+}
+
+const _: () = assert!(size_of::<EmbedderCell<()>>() == MIN_CELL_SIZE);
+const _: () = assert!(size_of::<EmbedderCell<u64>>() == 32);
+
+impl<T> Drop for EmbedderCell<T> {
+ fn drop(&mut self) {
+ // SAFETY: The union holds a value, which nothing has dropped: the cell is dropped once, by LibGC's destroy.
+ unsafe { ManuallyDrop::drop(&mut self.value.value) };
+ }
+}
+
+impl<T> Deref for EmbedderCell<T> {
+ type Target = T;
+
+ fn deref(&self) -> &T {
+ // SAFETY: The union holds a value for as long as the cell lives.
+ unsafe { &self.value.value }
+ }
+}
+
+// SAFETY: The value is all the cell holds.
+unsafe impl<T: Trace> Trace for EmbedderCell<T> {
+ fn trace(&self, visitor: &mut Visitor) {
+ (**self).trace(visitor);
+ }
+}
+
+/// The class of the cells that hold values of one of the embedder's types, which the embedder defines once per type
+/// as a static and names in the type's EmbedderValue implementation:
+///
+/// ```ignore
+/// static THING_CLASS: EmbedderClass<Thing> = EmbedderClass::new("Thing");
+///
+/// impl EmbedderValue for Thing {
+/// const CLASS: &'static EmbedderClass<Self> = &THING_CLASS;
+/// }
+/// ```
+///
+/// LibGC traces the cells of the class, and destroys those whose value has a destructor. It does not finalize them
+/// or count memory they own outside the heap: an embedder type that needs either has to opt in through its class,
+/// as the runtime's own cells do through theirs, which no embedder type does yet.
+pub struct EmbedderClass<T: 'static> {
+ class: Class,
+ _value: PhantomData<fn() -> T>,
+}
+
+impl<T: Trace + 'static> EmbedderClass<T> {
+ pub const fn new(name: &'static str) -> Self {
+ let mut class = Class::new::<EmbedderCell<T>>(name, ClassId::EmbedderCell, CellKind::Other, None, None, None);
+ // The cell drops its value, so Class::new sees a type that needs dropping whatever the value is. A value that
+ // has no destructor leaves the collector nothing to run when the cell dies.
+ if !core::mem::needs_drop::<T>() {
+ class.type_info.destroy = None;
+ }
+ Self {
+ class,
+ _value: PhantomData,
+ }
+ }
+
+ pub const fn class(&'static self) -> &'static Class {
+ &self.class
+ }
+}
+
+/// A type of the embedder whose values live in cells of their own.
+pub trait EmbedderValue: Trace + Sized + 'static {
+ const CLASS: &'static EmbedderClass<Self>;
+}
+
+// SAFETY: The cell is #[repr(C)] and starts with its header.
+unsafe impl<T: EmbedderValue> GcCell for EmbedderCell<T> {
+ const CLASS: &'static Class = T::CLASS.class();
+}
+
+impl<T: EmbedderValue> EmbedderClass<T> {
+ /// Moves `value` into a new cell of the class, from the allocator of the class, which the first allocation for
+ /// the class creates.
+ pub fn allocate(&'static self, vm: &Vm, value: T) -> Gc<EmbedderCell<T>> {
+ let allocator = vm.heap().embedder_class_allocator(&self.class);
+ vm.heap().allocate_in(
+ allocator,
+ EmbedderCell {
+ header: CellHeader::for_class(&self.class),
+ value: ValueWithRoomForFreeListLink {
+ value: ManuallyDrop::new(value),
+ },
+ },
+ )
+ }
+
+ /// The cell behind the pointer, if it is a cell of this class.
+ ///
+ /// # Safety
+ ///
+ /// `cell` must be a live cell that an embedder class allocated, such as the host data of a host object the
+ /// embedder created with such a cell, whose first word is therefore its class.
+ pub unsafe fn downcast(&'static self, cell: NonNull<c_void>) -> Option<Gc<EmbedderCell<T>>> {
+ // SAFETY: The caller passes a live cell of an embedder class.
+ let cell = unsafe { Gc::<EmbedderCell<T>>::from_non_null(cell.cast()) };
+ core::ptr::eq(class_of(cell), &raw const self.class).then_some(cell)
+ }
+}
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index 3a22a005514..48cfe91540e 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -12,7 +12,7 @@ use std::collections::HashMap;
use super::capi::{self, GCAllocator, GCGatherRootsCallback, GCHeap, GCLayout};
use super::class::{CellTypeInfo, Class, GcCell};
-use super::class_id::CLASS_COUNT;
+use super::class_id::{CLASS_COUNT, ClassId};
use super::weak::WEAK_IMPL_POINTER_OFFSET;
use crate::build_configuration::{HEAP_REGION_OFFSET_MASK, PRIMITIVE_STORAGE_CAGE_OFFSET_MASK};
use crate::layout::cell::{CellHeader, CellState, Gc};
@@ -24,7 +24,8 @@ use crate::layout::cell::{CellHeader, CellState, Gc};
pub struct Heap {
raw: NonNull<GCHeap>,
allocators: [Cell<Option<HeapAllocator>>; CLASS_COUNT],
- /// The allocators of the classes derived at run time, by the address of their class.
+ /// The allocators of the classes that have no id of their own, the classes derived at run time and the classes
+ /// of an embedder's cells, by the address of their class.
runtime_class_allocators: RefCell<HashMap<usize, HeapAllocator, foldhash::fast::RandomState>>,
/// The size classes of each class, by class id, out of line, as few classes have any.
size_class_tables: Box<[OnceCell<SizeClassTable>; CLASS_COUNT]>,
@@ -396,13 +397,33 @@ impl Heap {
"the cells of {} come from the allocator of its id",
class.name
);
- let allocator = *self
+ RuntimeClassAllocator {
+ class,
+ allocator: self.allocator_kept_by_class_address(class),
+ }
+ }
+
+ /// The allocator of `class`, the class of an embedder's cells, which the first call for the class creates. Such
+ /// classes all have ClassId::EmbedderCell, so each has an allocator of its own, kept by its address.
+ pub fn embedder_class_allocator(&self, class: &'static Class) -> RuntimeClassAllocator {
+ assert!(
+ class.id == ClassId::EmbedderCell && class.parent.is_none(),
+ "{} is not the class of an embedder's cells",
+ class.name
+ );
+ RuntimeClassAllocator {
+ class,
+ allocator: self.allocator_kept_by_class_address(class),
+ }
+ }
+
+ fn allocator_kept_by_class_address(&self, class: &'static Class) -> HeapAllocator {
+ *self
.runtime_class_allocators
.borrow_mut()
.entry(core::ptr::from_ref(class) as usize)
// SAFETY: The class and its name live as long as the process, so they outlive the allocator.
- .or_insert_with(|| unsafe { self.create_allocator(&raw const class.type_info, class.name) });
- RuntimeClassAllocator { class, allocator }
+ .or_insert_with(|| unsafe { self.create_allocator(&raw const class.type_info, class.name) })
}
/// The size classes of `class`, whose cells have `cell_sizes` bytes, in that order, which the first call for the
@@ -428,6 +449,11 @@ impl Heap {
"a class derived at run time shares the id of {}",
class.name
);
+ assert!(
+ class.id != ClassId::EmbedderCell,
+ "the class of an embedder's cells, {}, shares its id",
+ class.name
+ );
let type_infos: Box<[CellTypeInfo]> = cell_sizes
.iter()
.map(|&cell_size| {
@@ -463,6 +489,11 @@ impl Heap {
if let Some(allocator) = slot.get() {
return allocator;
}
+ assert!(
+ class.id != ClassId::EmbedderCell,
+ "the cells of an embedder class, {}, come from the allocator kept by its address",
+ class.name
+ );
// SAFETY: The class and its name are static, so they outlive the allocator.
let allocator = unsafe { self.create_allocator(&raw const class.type_info, class.name) };
slot.set(Some(allocator));
diff --git a/Libraries/LibJS/Rust/src/gc/mod.rs b/Libraries/LibJS/Rust/src/gc/mod.rs
index 4b0faddca1a..cae5c86f776 100644
--- a/Libraries/LibJS/Rust/src/gc/mod.rs
+++ b/Libraries/LibJS/Rust/src/gc/mod.rs
@@ -10,6 +10,7 @@
pub mod capi;
pub mod class;
pub mod class_id;
+pub mod embedder_cell;
pub mod foreign;
pub mod gc_ref_cell;
pub mod heap;