Skip to content

Truly independent web browser

LibGC+LibJS+LibWeb: Let collections move common LibJS cell types

Andreas Klinga3e64318b6f3
diff --git a/Libraries/LibGC/CAPI.cpp b/Libraries/LibGC/CAPI.cpp
index bdd839d40ae..cc0a581c219 100644
--- a/Libraries/LibGC/CAPI.cpp
+++ b/Libraries/LibGC/CAPI.cpp
@@ -260,6 +260,11 @@ bool gc_heap_moves_everything(void)
return Heap::moves_everything();
}
+void gc_heap_set_moves_everything_for_testing(GCHeap* heap, bool moves_everything)
+{
+ as_heap(heap).set_moves_everything_for_testing(moves_everything);
+}
+
bool gc_heap_is_collecting_everything(GCHeap const* heap)
{
return as_heap(heap).is_collecting_everything();
diff --git a/Libraries/LibGC/CAPI.h b/Libraries/LibGC/CAPI.h
index 1b7db05f32c..2e16a000e5a 100644
--- a/Libraries/LibGC/CAPI.h
+++ b/Libraries/LibGC/CAPI.h
@@ -125,6 +125,8 @@ GC_API void gc_heap_collect_garbage(GCHeap*, int collection_type, bool print_rep
GC_API void gc_heap_collect_garbage_without_scanning_the_stack(GCHeap*);
// Whether LIBGC_MOVE_EVERYTHING is set, see Heap::moves_everything().
GC_API bool gc_heap_moves_everything(void);
+// See Heap::set_moves_everything_for_testing().
+GC_API void gc_heap_set_moves_everything_for_testing(GCHeap*, bool);
GC_API bool gc_heap_is_collecting_everything(GCHeap const*);
// Whether the heap gathers its roots and marks the live cells for a collection now, rather than for a graph dump.
GC_API bool gc_heap_is_marking_for_collection(GCHeap const*);
diff --git a/Libraries/LibGC/Heap.cpp b/Libraries/LibGC/Heap.cpp
index f6d2eb88812..5ab12bb9bbf 100644
--- a/Libraries/LibGC/Heap.cpp
+++ b/Libraries/LibGC/Heap.cpp
@@ -1157,7 +1157,7 @@ void Heap::run_collection(ReadonlySpan<FlatPtr> callee_saved_registers, Collecti
if (!m_incremental_sweep_active)
schedule_release_of_allocator_memory();
- if (scan_stack && libgc_move_everything())
+ if (scan_stack && m_moves_everything)
schedule_collection_that_moves_cells();
}
@@ -1168,7 +1168,7 @@ bool Heap::should_move_cells(CollectionType collection_type, bool scan_stack) co
if (collection_type != CollectionType::CollectGarbage || scan_stack)
return false;
// FIXME: Choose blocks worth evacuating. For now, only the stress mode moves cells.
- return libgc_move_everything();
+ return m_moves_everything;
}
bool Heap::moves_everything()
diff --git a/Libraries/LibGC/Heap.h b/Libraries/LibGC/Heap.h
index 1804e97b1b5..8d0c7aa7f42 100644
--- a/Libraries/LibGC/Heap.h
+++ b/Libraries/LibGC/Heap.h
@@ -145,6 +145,9 @@ public:
// Whether LIBGC_MOVE_EVERYTHING has every collection that does not scan the stack move every cell it can, which
// test runners use to collect without scanning the stack where they safely can.
static bool moves_everything();
+ // Has the collections of this heap that do not scan the stack move every cell they can, or not, as
+ // LIBGC_MOVE_EVERYTHING does for every heap, for tests of moving cells.
+ void set_moves_everything_for_testing(bool moves_everything) { m_moves_everything = moves_everything; }
void set_incremental_sweep_enabled(bool enabled) { m_incremental_sweep_enabled = enabled; }
void set_should_collect_on_every_allocation(bool);
@@ -417,6 +420,7 @@ private:
FFI::EvacuationSet* m_evacuation { nullptr };
// The identity hashes of the cells that moved since they were hashed, see identity_hash().
FFI::IdentityHashes* m_identity_hashes { nullptr };
+ bool m_moves_everything { moves_everything() };
void collect_garbage_from_timer();
enum class AbandonedObjectGraphState : u8 {
None,
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index 487bfe9ae85..138a304711f 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -123,13 +123,15 @@ impl PropertyLookupCacheEntryData {
}
fn has_dead_cell(&self, sweep: &Sweep<'_>) -> bool {
- (self.key != 0 && sweep.is_dead(Value::from_bits(self.key).as_cell()))
- || self.new_shape.is_some_and(|shape| sweep.is_dead(shape))
- || self.shape.is_some_and(|key| sweep.is_dead(key.shape))
- || self.prototype.is_some_and(|prototype| sweep.is_dead(prototype))
+ (self.key != 0 && sweep.is_dead_or_moving(Value::from_bits(self.key).as_cell()))
+ || self.new_shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
+ || self.shape.is_some_and(|key| sweep.is_dead_or_moving(key.shape))
+ || self
+ .prototype
+ .is_some_and(|prototype| sweep.is_dead_or_moving(prototype))
|| self
.prototype_chain_validity
- .is_some_and(|validity| sweep.is_dead(validity))
+ .is_some_and(|validity| sweep.is_dead_or_moving(validity))
}
}
@@ -209,7 +211,7 @@ impl PropertyLookupCacheEntry {
if self.get().has_dead_cell(sweep) {
self.set(PropertyLookupCacheEntryData::default());
}
- if self.getter.get().is_some_and(|getter| sweep.is_dead(getter)) {
+ if self.getter.get().is_some_and(|getter| sweep.is_dead_or_moving(getter)) {
self.getter.set(None);
}
}
@@ -1094,12 +1096,14 @@ impl KeyedPropertyLookupCache {
for entry in self.entries.borrow_mut().iter_mut() {
let lookup = &entry.lookup;
// NB: Entries of the keyed property store cache for puts it does not make have a shape but no type.
- if lookup.shape.is_some_and(|shape| sweep.is_dead(shape))
- || lookup.prototype.is_some_and(|prototype| sweep.is_dead(prototype))
+ if lookup.shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
+ || lookup
+ .prototype
+ .is_some_and(|prototype| sweep.is_dead_or_moving(prototype))
|| lookup
.prototype_chain_validity
- .is_some_and(|validity| sweep.is_dead(validity))
- || lookup.new_shape.is_some_and(|shape| sweep.is_dead(shape))
+ .is_some_and(|validity| sweep.is_dead_or_moving(validity))
+ || lookup.new_shape.is_some_and(|shape| sweep.is_dead_or_moving(shape))
{
*entry = KeyedPropertyLookupCacheEntry::default();
}
@@ -1459,7 +1463,7 @@ impl Executable {
cache.entry.clear_if_it_has_a_dead_cell(sweep);
}
for cache in &self.object_shape_caches {
- if cache.shape.get().is_some_and(|shape| sweep.is_dead(shape)) {
+ if cache.shape.get().is_some_and(|shape| sweep.is_dead_or_moving(shape)) {
cache.shape.set(None);
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/feedback.rs b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
index abdaca1c93d..f5e331376b6 100644
--- a/Libraries/LibJS/Rust/src/bytecode/feedback.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/feedback.rs
@@ -201,7 +201,7 @@ impl ExecutableFeedback {
pub fn remove_dead_cells(&self, sweep: &Sweep<'_>) {
self.update_value_feedback();
let clear_if_dead = |cell: &Cell<Option<Gc<CellHeader>>>| {
- if decode_weak_reference(cell).is_some_and(|cell| sweep.is_dead(cell)) {
+ if decode_weak_reference(cell).is_some_and(|cell| sweep.is_dead_or_moving(cell)) {
cell.set(None);
}
};
diff --git a/Libraries/LibJS/Rust/src/gc/capi.rs b/Libraries/LibJS/Rust/src/gc/capi.rs
index 780d6af4d26..c75ac7bbbed 100644
--- a/Libraries/LibJS/Rust/src/gc/capi.rs
+++ b/Libraries/LibJS/Rust/src/gc/capi.rs
@@ -106,6 +106,7 @@ unsafe extern "C" {
// NB: A collection that does not scan the stack may collect or move the cells that only the stack holds.
pub fn gc_heap_collect_garbage_without_scanning_the_stack(heap: &GCHeap);
pub safe fn gc_heap_moves_everything() -> bool;
+ pub safe fn gc_heap_set_moves_everything_for_testing(heap: &GCHeap, moves_everything: bool);
pub safe fn gc_heap_is_collecting_everything(heap: &GCHeap) -> bool;
pub safe fn gc_heap_is_marking_for_collection(heap: &GCHeap) -> bool;
pub safe fn gc_heap_is_returning_memory_to_system(heap: &GCHeap) -> bool;
diff --git a/Libraries/LibJS/Rust/src/gc/class.rs b/Libraries/LibJS/Rust/src/gc/class.rs
index 0df4007beee..b483290cf00 100644
--- a/Libraries/LibJS/Rust/src/gc/class.rs
+++ b/Libraries/LibJS/Rust/src/gc/class.rs
@@ -127,9 +127,39 @@ impl Class {
/// the cell, or forgets the address when the cell moves. Classes derived at run time, such as an embedder's host
/// objects, never are, as the embedder keeps their addresses.
pub fn is_movable(&self) -> bool {
- // FIXME: No class is movable yet.
- let _ = self;
- false
+ if self.is_derived_at_run_time() {
+ return false;
+ }
+ matches!(
+ self.id,
+ ClassId::ValueStorage
+ | ClassId::Object
+ | ClassId::Array
+ | ClassId::EcmascriptFunctionObject
+ | ClassId::EcmascriptFunctionObjectWithRareData
+ | ClassId::DeclarativeEnvironment
+ | ClassId::FunctionEnvironment
+ | ClassId::PrimitiveString
+ | ClassId::RopeString
+ | ClassId::Substring
+ | ClassId::InlineString
+ | ClassId::Shape
+ | ClassId::DescriptorArray
+ | ClassId::DictionaryPropertyTable
+ | ClassId::BigInt
+ | ClassId::Accessor
+ | ClassId::BoundFunction
+ | ClassId::ArgumentsObject
+ | ClassId::RegExpObject
+ | ClassId::Date
+ | ClassId::ArrayIterator
+ | ClassId::StringIterator
+ | ClassId::Map
+ | ClassId::MapIterator
+ | ClassId::Set
+ | ClassId::SetIterator
+ | ClassId::Promise
+ )
}
/// What Cell::class_name() returns for the cells of this class, which printing and messages show. It is the name
@@ -379,7 +409,8 @@ impl<T: GcCell> core::ops::Deref for crate::layout::cell::Gc<T> {
type Target = T;
fn deref(&self) -> &T {
- // SAFETY: A Gc points to a live cell, which never moves.
+ // SAFETY: A Gc points to a live cell. Cells only move in collections that do not scan the stack, while no
+ // reference to a cell is on it.
unsafe { self.as_non_null().as_ref() }
}
}
diff --git a/Libraries/LibJS/Rust/src/gc/heap.rs b/Libraries/LibJS/Rust/src/gc/heap.rs
index 6d6081bd851..3094788cad4 100644
--- a/Libraries/LibJS/Rust/src/gc/heap.rs
+++ b/Libraries/LibJS/Rust/src/gc/heap.rs
@@ -713,6 +713,11 @@ impl Heap {
capi::gc_heap_moves_everything()
}
+ /// Has the collections of this heap that do not scan the stack move every cell they can, or not, for tests.
+ pub fn set_moves_everything_for_testing(&self, moves_everything: bool) {
+ capi::gc_heap_set_moves_everything_for_testing(self.handle(), moves_everything);
+ }
+
/// Calls `callback` with `context` during every collection, after marking and finalization and before dead cells
/// are swept, so that weak holders can drop the cells whose mark is clear.
///
diff --git a/Libraries/LibJS/Rust/src/gc/sweep.rs b/Libraries/LibJS/Rust/src/gc/sweep.rs
index 884181e6383..bdcf2ef39e0 100644
--- a/Libraries/LibJS/Rust/src/gc/sweep.rs
+++ b/Libraries/LibJS/Rust/src/gc/sweep.rs
@@ -33,6 +33,14 @@ impl<'vm> Sweep<'vm> {
header.state.get() != CellState::Live || !unsafe { capi::gc_cell_is_marked(cell.as_ptr().cast()) }
}
+ /// Whether `cell`, which a cache held without keeping it alive, did not survive the collection, or moves in it. A
+ /// cache that keeps the address of a cell without visiting it forgets the cell either way, while what holds cells
+ /// weakly by identity pins them as it is traced (see Visitor::pin()).
+ pub fn is_dead_or_moving<T>(&self, cell: Gc<T>) -> bool {
+ // SAFETY: The cell is a cell, intact until the sweep that follows.
+ self.is_dead(cell) || unsafe { capi::gc_cell_will_move(cell.as_ptr().cast()) }
+ }
+
/// Hands `finalization_registry` to HostEnqueueFinalizationRegistryCleanupJob once the collection is over.
pub fn enqueue_finalization_registry_cleanup_job(&self, finalization_registry: Gc<FinalizationRegistry>) {
self.0
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index 79249ae3bff..43cb0dcd6a6 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -1619,7 +1619,8 @@ impl Vm {
/// Drops the weak cache entries of strings that died in this collection, and every entry of the caches that each
/// collection empties.
fn remove_dead_strings_from_weak_caches(&self, sweep: &Sweep<'_>) {
- let is_dead = |string: Gc<PrimitiveString>| sweep.is_dead(string);
+ // NB: The caches forget strings that move. The interned strings do not move.
+ let is_dead = |string: Gc<PrimitiveString>| sweep.is_dead_or_moving(string);
for cache_slot in self.fly_string_cache.iter() {
if cache_slot.get().is_some_and(is_dead) {
cache_slot.set(None);
@@ -1630,7 +1631,9 @@ impl Vm {
*entry = StringToAtomCacheEntry::default();
}
}
- self.interned_strings.borrow_mut().retain(|_, string| !is_dead(*string));
+ self.interned_strings
+ .borrow_mut()
+ .retain(|_, string| !sweep.is_dead(*string));
self.characters_to_atom_cache
.borrow_mut()
.fill_with(CharactersToAtomCacheEntry::default);
diff --git a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
index a5262933642..86a99b43b90 100644
--- a/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
+++ b/Libraries/LibJS/Rust/src/runtime/declarative_environment.rs
@@ -313,6 +313,9 @@ unsafe impl Trace for DeclarativeEnvironment {
fn trace(&self, visitor: &mut Visitor) {
self.base.trace(visitor);
self.rare_data.trace(visitor);
+ if self.binding_values_are_inline() {
+ visitor.visit_self_pointer(&self.binding_values);
+ }
// SAFETY: The first `binding_count` values are initialized, and nothing writes them while they are visited.
visitor.visit_values(unsafe {
ak::slice_from_raw_parts(self.binding_values.get(), self.binding_count.get() as usize)
diff --git a/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs b/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
index 71f99f14dab..4037d2acb08 100644
--- a/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
+++ b/Libraries/LibJS/Rust/src/runtime/finalization_registry.rs
@@ -40,6 +40,10 @@ unsafe impl Trace for FinalizationRecords {
for record in &self.0 {
record.held_value.trace(visitor);
record.unregister_token.trace(visitor);
+ // NB: The collector cannot update a weak reference, so the target stays where it is.
+ if let Some(target) = record.target {
+ visitor.pin(target);
+ }
}
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index e31b2d39833..7d9fa5b288f 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -316,6 +316,16 @@ impl ExternalMemorySize for Object {
// cells an object reaches.
unsafe impl Trace for Object {
fn trace(&self, visitor: &mut Visitor) {
+ // NB: The VM keeps the intrinsic accessors and unimplemented properties of objects by their address, and
+ // compiled code depends on the slots of global objects by theirs, so such objects stay where they are.
+ if self.flags.get()
+ & (object_flag::HAS_INTRINSIC_ACCESSORS
+ | object_flag::HAS_UNIMPLEMENTED_PROPERTIES
+ | object_flag::IS_GLOBAL_OBJECT)
+ != 0
+ {
+ visitor.pin(self.as_gc());
+ }
self.shape.trace(visitor);
let property_count = self.shape().property_count() as usize;
let named_properties = self.named_properties.get();
@@ -345,7 +355,14 @@ unsafe impl Trace for Object {
self.indexed_array_like_size().min(self.indexed_elements_capacity()),
visitor,
),
- IndexedStorageKind::Dictionary => self.indexed_dictionary().trace(visitor),
+ IndexedStorageKind::Dictionary => {
+ // NB: The VM keeps the indexed dictionaries of ECMAScript function objects by the address of the
+ // function, so such a function stays where it is.
+ if self.is_ecmascript_function_object() {
+ visitor.pin(self.as_gc());
+ }
+ self.indexed_dictionary().trace(visitor);
+ }
}
let indexed_elements = self.indexed_elements.get();
if matches!(
diff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
index ac069a0a892..397d44c1456 100644
--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs
@@ -45,7 +45,13 @@ impl ExternalMemorySize for PrimitiveString {
// SAFETY: A string's own data holds no cells. The deferred kinds trace the strings they are made of.
unsafe impl Trace for PrimitiveString {
- fn trace(&self, _: &mut Visitor) {}
+ fn trace(&self, visitor: &mut Visitor) {
+ // NB: The VM's table of interned strings holds them weakly, and there may only be one interned string with the
+ // same contents, so an interned string stays where it is rather than being forgotten.
+ if self.is_interned() {
+ visitor.pin(Gc::from_ref(self));
+ }
+ }
}
#[repr(C)]
@@ -79,7 +85,9 @@ const _: () = assert!(size_of::<Substring>() == 32);
// SAFETY: The characters hold no cells.
unsafe impl Trace for InlineString {
- fn trace(&self, _: &mut Visitor) {}
+ fn trace(&self, visitor: &mut Visitor) {
+ self.base.trace(visitor);
+ }
}
/// OPTIMIZATION: Copies the at most INLINE_STRING_CAPACITY bytes of `source` to the start of `destination` with two
diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rs
index c63463a5c42..ae8d378c57d 100644
--- a/Libraries/LibJS/Rust/src/runtime/shape.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs
@@ -323,6 +323,11 @@ define_cell!(Shape, Other);
// the storage owns.
unsafe impl Trace for Shape {
fn trace(&self, visitor: &mut Visitor) {
+ // NB: The VM keeps the compiled code that depends on a shape by the address of the shape, so such a shape
+ // stays where it is.
+ if self.flags.get() & shape_flag::HAS_DEPENDENT_CODE != 0 {
+ visitor.pin(Gc::from_ref(self));
+ }
self.realm.trace(visitor);
self.prototype.trace(visitor);
self.prototype_chain_validity.trace(visitor);
@@ -403,11 +408,15 @@ impl ConstructShapeCache {
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
for entry in &self.entries {
let construct_shape = entry.get();
- if construct_shape.constructor.is_some_and(|cell| sweep.is_dead(cell))
+ if construct_shape
+ .constructor
+ .is_some_and(|cell| sweep.is_dead_or_moving(cell))
|| construct_shape
.constructor_shape
- .is_some_and(|cell| sweep.is_dead(cell))
- || construct_shape.this_shape.is_some_and(|cell| sweep.is_dead(cell))
+ .is_some_and(|cell| sweep.is_dead_or_moving(cell))
+ || construct_shape
+ .this_shape
+ .is_some_and(|cell| sweep.is_dead_or_moving(cell))
{
entry.set(ConstructShape::default());
}
@@ -467,8 +476,16 @@ impl PrototypeTransitionCache {
pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
for entry in &self.entries {
let transition = entry.get();
- let is_dead = |shape| sweep.is_dead(shape);
- if transition.from.is_some_and(is_dead) || transition.target.is_some_and(is_dead) {
+ // NB: The entry is found by the addresses of the shape and the prototype, which change if they move.
+ let is_dead = |shape| sweep.is_dead_or_moving(shape);
+ if transition.from.is_some_and(is_dead)
+ || transition.target.is_some_and(|target| {
+ is_dead(target)
+ || target
+ .prototype()
+ .is_some_and(|prototype| sweep.is_dead_or_moving(prototype))
+ })
+ {
entry.set(PrototypeTransition::default());
}
}
@@ -769,7 +786,9 @@ impl Shape {
let key = prototype_address(prototype);
self.with_existing_rare_data(vm, |rare_data| {
let target = rare_data.prototype_transitions.get(&key)?;
- let Some(shape) = target.get() else {
+ // NB: The entry is keyed by the address of a prototype, which may have moved since, and another object
+ // may be at that address now.
+ let Some(shape) = target.get().filter(|shape| shape.prototype() == prototype) else {
// The cached prototype transition has gone stale (from garbage collection). Prune it.
rare_data.prototype_transitions.remove(&key);
return None;
diff --git a/Libraries/LibJS/Rust/src/runtime/weak_ref.rs b/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
index f3cca0a921b..a6ca04a5964 100644
--- a/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
+++ b/Libraries/LibJS/Rust/src/runtime/weak_ref.rs
@@ -39,7 +39,10 @@ unsafe impl Trace for WeakRef {
// SAFETY: The VM owns the heap and destroys it before anything else, so it outlives every WeakRef.
let execution_generation = unsafe { self.vm_execution_generation.as_ref() }.get();
if execution_generation == self.last_execution_generation.get() {
- self.value.get().trace(visitor);
+ self.value.trace(visitor);
+ } else if self.value.get().is_cell() {
+ // NB: The collector cannot update a weak reference, so the target stays where it is.
+ visitor.pin(self.value.get().as_cell());
}
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/weak_set.rs b/Libraries/LibJS/Rust/src/runtime/weak_set.rs
index 6aad72a3662..cd8c47c20bc 100644
--- a/Libraries/LibJS/Rust/src/runtime/weak_set.rs
+++ b/Libraries/LibJS/Rust/src/runtime/weak_set.rs
@@ -26,9 +26,14 @@ use crate::runtime::realm::Realm;
#[derive(Default)]
struct WeakSetValues(HashSet<Gc<CellHeader>, foldhash::fast::RandomState>);
-// SAFETY: Visits nothing, since every value is held weakly and removed in remove_dead_cells() once it dies.
+// SAFETY: Visits nothing, since every value is held weakly and removed in remove_dead_cells() once it dies. The values
+// are hashed by address, so they are pinned.
unsafe impl Trace for WeakSetValues {
- fn trace(&self, _: &mut Visitor) {}
+ fn trace(&self, visitor: &mut Visitor) {
+ for &value in &self.0 {
+ visitor.pin(value);
+ }
+ }
}
#[repr(C)]
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
index 42545b82d05..1f432d83a8f 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/javascript_test_runner.rs
@@ -13,7 +13,9 @@ use ak::{Utf16FlyString, Utf16String};
use libjs_runtime_macros::Trace;
use super::json::{JsonParser, JsonValue};
-use super::test_js_functions::{EXPOSED_GLOBAL_FUNCTIONS, RunFileHookResult, run_file};
+use super::test_js_functions::{
+ EXPOSED_GLOBAL_FUNCTIONS, RunFileHookResult, run_file, take_callbacks_after_moving_collection,
+};
use super::test_runner::{
COUNTS, Case, Modifier, Suite, TOP_LEVEL_TEST_NAME, TestResult, TestRunner, cleanup_and_exit, format_file_time,
get_time_in_ms, iterate_directory_recursively, print_modifiers, set_currently_running_test,
@@ -27,6 +29,7 @@ use crate::layout::cell::Gc;
use crate::layout::object::Object;
use crate::layout::value::Value;
use crate::parser_error::ParserError;
+use crate::runtime::abstract_operations::call;
use crate::runtime::array::Array;
use crate::runtime::completion::{Must, ThrowCompletionOr};
use crate::runtime::error::Error;
@@ -376,6 +379,12 @@ impl TestRunner {
vm.push_execution_context(global_execution_context);
vm.run_script(test_script, None).must();
+ // NB: With LIBGC_MOVE_EVERYTHING, what test-common.js made moves before the test uses it. Nothing on the stack
+ // holds a cell that the test needs, and the global execution context keeps the realm.
+ if Heap::moves_everything() {
+ // SAFETY: The runner holds no cell it uses after this but the realm, see above.
+ unsafe { vm.heap().collect_garbage_without_scanning_the_stack() };
+ }
vm.pop_execution_context();
let file_script = match parse_script(vm, test_path, realm) {
@@ -396,11 +405,34 @@ impl TestRunner {
// NB: With LIBGC_MOVE_EVERYTHING, the objects the test left behind move before their results are read. Nothing
// on the stack holds a cell then but the error of the script, which this roots, and the realm, which the
// global execution context keeps.
- let top_level_error = top_level_result.err().map(|throw| Root::new(vm, throw.value()));
- if Heap::moves_everything() {
+ let mut top_level_error = top_level_result.err().map(|throw| Root::new(vm, throw.value()));
+ let mut callbacks_after_moving_collection = take_callbacks_after_moving_collection();
+ if Heap::moves_everything() || !callbacks_after_moving_collection.is_empty() {
vm.push_execution_context(global_execution_context);
- // SAFETY: Every cell the runner holds is rooted, see above, and test-js holds none further up.
- unsafe { vm.heap().collect_garbage_without_scanning_the_stack() };
+ // NB: The callbacks may ask for more, which run after another collection that moves cells.
+ loop {
+ vm.heap().set_moves_everything_for_testing(true);
+ // SAFETY: Every cell the runner holds is rooted, see above, and test-js holds none further up.
+ unsafe { vm.heap().collect_garbage_without_scanning_the_stack() };
+ vm.heap().set_moves_everything_for_testing(Heap::moves_everything());
+ for callback in &callbacks_after_moving_collection {
+ // NB: A callback that throws fails the file as if its top level threw, and the others still run.
+ if let Err(throw) = call(vm, Value::from_object(callback.cell()), Value::UNDEFINED, &[]) {
+ if top_level_error.is_none() {
+ top_level_error = Some(Root::new(vm, throw.value()));
+ continue;
+ }
+ eprintln!(
+ "{test_path}: a callback of runAfterMovingCollection() threw: {}",
+ String::from_utf8_lossy(&wtf8_of(&throw.value().to_utf16_string_without_side_effects()))
+ );
+ }
+ }
+ callbacks_after_moving_collection = take_callbacks_after_moving_collection();
+ if callbacks_after_moving_collection.is_empty() {
+ break;
+ }
+ }
vm.pop_execution_context();
}
diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
index 89f3f128e6d..010ef5f4468 100644
--- a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
+++ b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs
@@ -7,6 +7,7 @@
//! The global functions the runtime tests call besides the harness, and the hook that runs the test262 parser tests
//! instead of the runtime tests.
+use core::cell::RefCell;
use core::ops::ControlFlow;
use std::ffi::{CStr, CString};
@@ -17,6 +18,7 @@ use super::test_runner::{Case, Suite, TestResult, get_time_in_ms, relative_path}
use crate::bytecode::flushing::{ALL_FLUSH_LAYERS, FlushLayer};
use crate::bytecode::property_access::Strict;
use crate::gc::class::{Extends, ExternalMemorySize, GcCell};
+use crate::gc::root::CellRoot;
use crate::interpreter::vm::Vm;
use crate::layout::cell::Gc;
use crate::layout::object::Object;
@@ -80,8 +82,52 @@ pub const EXPOSED_GLOBAL_FUNCTIONS: &[(&str, RawNativeFunctionPointer)] = &[
("setTimeZone", raw_native!(set_time_zone)),
("toUTF8Bytes", raw_native!(to_utf8_bytes)),
("createDefaultTypedArray", raw_native!(create_default_typed_array)),
+ ("runAfterMovingCollection", raw_native!(run_after_moving_collection)),
+ ("addressOf", raw_native!(address_of)),
+ ("identityHashOf", raw_native!(identity_hash_of)),
];
+thread_local! {
+ /// The functions runAfterMovingCollection() was called with, which the runner calls after a test file ran.
+ static CALLBACKS_AFTER_MOVING_COLLECTION: RefCell<Vec<CellRoot<Object>>> = const { RefCell::new(Vec::new()) };
+}
+
+/// Calls `callback` once the test file has run, after a collection that moves every cell it can, so that tests can
+/// see what they made after it moved.
+fn run_after_moving_collection(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let callback = vm.argument(0);
+ if !callback.is_function() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAFunction, &[&callback]);
+ }
+ CALLBACKS_AFTER_MOVING_COLLECTION.with_borrow_mut(|callbacks| callbacks.push(CellRoot::new(callback.as_object())));
+ Ok(Value::UNDEFINED)
+}
+
+/// The functions runAfterMovingCollection() was called with since the last call.
+pub fn take_callbacks_after_moving_collection() -> Vec<CellRoot<Object>> {
+ CALLBACKS_AFTER_MOVING_COLLECTION.take()
+}
+
+/// The address of the cell `value` holds, which changes when the cell moves.
+fn address_of(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let value = vm.argument(0);
+ if !value.is_cell() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);
+ }
+ Ok(Value::from_f64(value.as_cell().as_ptr().addr() as f64))
+}
+
+/// The identity hash of the cell `value` holds, which stays the same when the cell moves.
+fn identity_hash_of(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let value = vm.argument(0);
+ if !value.is_cell() {
+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObject, &[&value]);
+ }
+ // SAFETY: The value holds a live cell.
+ let hash = unsafe { crate::layout_forward::cell_identity_hash(value.as_cell().as_ptr().cast()) };
+ Ok(Value::from_f64(f64::from(hash)))
+}
+
/// Value::as_if<T>(): the object `value` is, if it is a T.
fn as_if<T: GcCell + Extends<Object>>(value: Value) -> Option<Gc<T>> {
if !value.is_object() {
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index 5ba1a83579f..e413f957133 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -405,28 +405,38 @@ u32 Internals::worker_agent_count() const
return Bindings::worker_agent_count();
}
-static void collect_garbage_from_the_outermost_event_loop_turn(GC::Root<WebIDL::Promise>);
+enum class MoveCells {
+ No,
+ Yes,
+};
+
+static void collect_garbage_from_the_outermost_event_loop_turn(MoveCells, GC::Root<WebIDL::Promise>);
-void Internals::gc_async(GC::Ref<WebIDL::Promise> promise)
+void Internals::gc_async(bool move_cells, GC::Ref<WebIDL::Promise> promise)
{
- collect_garbage_from_the_outermost_event_loop_turn(GC::make_root(promise));
+ collect_garbage_from_the_outermost_event_loop_turn(move_cells ? MoveCells::Yes : MoveCells::No, GC::make_root(promise));
}
-static void collect_garbage_from_the_outermost_event_loop_turn(GC::Root<WebIDL::Promise> promise)
+static void collect_garbage_from_the_outermost_event_loop_turn(MoveCells move_cells, GC::Root<WebIDL::Promise> promise)
{
// Queue a LibCore event to run the collection, so that it runs outside the JS execution context. Nothing on the stack
// of the outermost event loop turn refers to a cell that is not rooted some other way, so the collection leaves the
// stack out. A word there that only looks like a cell pointer would otherwise keep that cell alive, and one in a
// frame of the event loop itself would keep it alive for every later collection too.
- Core::deferred_invoke([promise = move(promise)]() mutable {
+ Core::deferred_invoke([move_cells, promise = move(promise)]() mutable {
// A nested event loop has script waiting further up the stack, so wait for it to finish.
if (Core::ThreadEventQueue::current().is_processing_nested()) {
- collect_garbage_from_the_outermost_event_loop_turn(move(promise));
+ collect_garbage_from_the_outermost_event_loop_turn(move_cells, move(promise));
return;
}
auto& realm = WebIDL::promise_realm(*promise);
HTML::TemporaryExecutionContext execution_context { realm };
- realm.vm().heap().collect_garbage_without_scanning_the_stack();
+ auto& heap = realm.vm().heap();
+ if (move_cells == MoveCells::Yes)
+ heap.set_moves_everything_for_testing(true);
+ heap.collect_garbage_without_scanning_the_stack();
+ if (move_cells == MoveCells::Yes)
+ heap.set_moves_everything_for_testing(GC::Heap::moves_everything());
WebIDL::resolve_promise(*promise);
});
}
diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.h
index 4cce231e30b..754e3d418d8 100644
--- a/Libraries/LibWeb/Internals/Internals.h
+++ b/Libraries/LibWeb/Internals/Internals.h
@@ -71,7 +71,7 @@ public:
void gc();
u32 worker_agent_count() const;
- void gc_async(GC::Ref<WebIDL::Promise>);
+ void gc_async(bool move_cells, GC::Ref<WebIDL::Promise>);
WebIDL::UnsignedLongLong discard_decoded_image_frames();
WebIDL::ExceptionOr<void> mark_as_garbage(Utf16String const& variable_name);
bool wrapper_is_preserved(JS::Object&);
diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idl
index f3566d31575..8670827ac15 100644
--- a/Libraries/LibWeb/Internals/Internals.idl
+++ b/Libraries/LibWeb/Internals/Internals.idl
@@ -36,7 +36,8 @@ interface Internals {
// How many worker agents are alive in this process. One that a worker's owner let go of still counts until its
// thread has shut it down.
unsigned long workerAgentCount();
- [CreatesPromise] Promise<undefined> gcAsync();
+ // Collects garbage once the current task is over. With moveCells, the collection moves every cell it can.
+ [CreatesPromise] Promise<undefined> gcAsync(optional boolean moveCells = false);
// Discards every decoded image frame that can be decoded again, and returns how many were discarded.
unsigned long long discardDecodedImageFrames();
// Clears a named environment binding and forces its current cell to be treated as garbage.
diff --git a/Tests/LibJS/Runtime/gc-moving-cells.js b/Tests/LibJS/Runtime/gc-moving-cells.js
new file mode 100644
index 00000000000..3a0abe31ac1
--- /dev/null
+++ b/Tests/LibJS/Runtime/gc-moving-cells.js
@@ -0,0 +1,93 @@
+// The objects below are only reachable through the properties of `holder`, which the collector can rewrite, so a
+// collection that moves cells moves them.
+const holder = {
+ small: { a: 1, b: "two" },
+ large: {},
+ array: [1, 2, 3, { x: 4 }],
+ hashed: {},
+ mapKey: {},
+ weakMapKey: {},
+ counter: (() => {
+ let count = 0;
+ return () => ++count;
+ })(),
+};
+holder.counter();
+holder.rope = "x".repeat(30) + "y".repeat(30);
+holder.substring = holder.rope.substring(25, 35);
+holder.flat = String(holder.rope.length) + "!";
+for (let i = 0; i < 40; ++i) holder.large["property" + i] = i;
+holder.large.nested = { y: 5 };
+
+const before = {
+ small: addressOf(holder.small),
+ large: addressOf(holder.large),
+ array: addressOf(holder.array),
+ hashed: addressOf(holder.hashed),
+ hash: identityHashOf(holder.hashed),
+ counter: addressOf(holder.counter),
+ rope: addressOf(holder.rope),
+};
+
+const map = new Map([[holder.mapKey, "map value"]]);
+const weakMap = new WeakMap([[holder.weakMapKey, "weak map value"]]);
+
+runAfterMovingCollection(() => {
+ test("objects with inline storage keep their properties when they move", () => {
+ expect(addressOf(holder.small)).not.toBe(before.small);
+ expect(holder.small.a).toBe(1);
+ expect(holder.small.b).toBe("two");
+ holder.small.c = 3;
+ expect(Object.keys(holder.small)).toEqual(["a", "b", "c"]);
+ });
+
+ test("objects with out-of-line storage keep their properties when they move", () => {
+ expect(addressOf(holder.large)).not.toBe(before.large);
+ for (let i = 0; i < 40; ++i) expect(holder.large["property" + i]).toBe(i);
+ expect(holder.large.nested.y).toBe(5);
+ });
+
+ test("arrays keep their elements when they move", () => {
+ expect(addressOf(holder.array)).not.toBe(before.array);
+ expect(holder.array.length).toBe(4);
+ expect(holder.array[3].x).toBe(4);
+ holder.array.push(5);
+ expect(holder.array).toEqual([1, 2, 3, { x: 4 }, 5]);
+ });
+
+ test("identity hashes stay the same when cells move", () => {
+ expect(addressOf(holder.hashed)).not.toBe(before.hashed);
+ expect(identityHashOf(holder.hashed)).toBe(before.hash);
+ const set = new Set([holder.hashed]);
+ expect(set.has(holder.hashed)).toBeTrue();
+ });
+
+ test("closures keep their environments when they move", () => {
+ expect(addressOf(holder.counter)).not.toBe(before.counter);
+ expect(holder.counter()).toBe(2);
+ expect(holder.counter()).toBe(3);
+ });
+
+ test("strings keep their contents when they move", () => {
+ expect(addressOf(holder.rope)).not.toBe(before.rope);
+ expect(holder.rope).toBe("x".repeat(30) + "y".repeat(30));
+ expect(holder.substring).toBe("xxxxxyyyyy");
+ expect(holder.flat).toBe("60!");
+ });
+
+ test("maps and weak maps find their keys after the collection", () => {
+ expect(map.get(holder.mapKey)).toBe("map value");
+ expect(weakMap.get(holder.weakMapKey)).toBe("weak map value");
+ expect(map.has({})).toBeFalse();
+ });
+});
+
+runAfterMovingCollection(() => {
+ const addressAfterFirstMove = addressOf(holder.small);
+ runAfterMovingCollection(() => {
+ test("callbacks that a callback asks for run after another collection that moves cells", () => {
+ expect(addressOf(holder.small)).not.toBe(addressAfterFirstMove);
+ expect(holder.small.c).toBe(3);
+ });
+ });
+});
diff --git a/Tests/LibWeb/Text/input/rejectionhandled-after-promise-moved.html b/Tests/LibWeb/Text/input/rejectionhandled-after-promise-moved.html
index 8ab02b31019..f91339085bb 100644
--- a/Tests/LibWeb/Text/input/rejectionhandled-after-promise-moved.html
+++ b/Tests/LibWeb/Text/input/rejectionhandled-after-promise-moved.html
@@ -11,12 +11,12 @@
events.push(`rejectionhandled: ${event.reason}`);
});
- // NB: Only the property of the holder refers to the promise, so a collection that moves cells can move it while
+ // NB: Only the property of the holder refers to the promise, so a collection that moves cells moves it while
// it is in the outstanding rejected promises weak set.
const holder = { promise: Promise.reject("moved") };
await waitForCondition(() => events.length === 1);
- await internals.gcAsync();
+ await internals.gcAsync(true);
holder.promise.catch(() => {});
await waitForCondition(() => events.length === 2);