Truly independent web browser
LibJS: Build or trace the rest of what keeps cells in heap memory
Shannon Booth8528e160c695
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex 5eaaf4beeec..67a350c0a16 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -1065,7 +1065,7 @@ pub struct ObjectShapeCache {}/// The parts of an ObjectPropertyIteratorCacheData the interpreter does not read.-#[derive(Default)]+#[derive(Default, Trace)]pub struct ObjectPropertyIteratorCacheDataStorage {properties: Box<[PropertyKey]>,}@@ -1078,7 +1078,7 @@ unsafe impl Trace for ObjectPropertyIteratorCacheData {self.shape.trace(visitor);self.prototype_chain_validity.trace(visitor);self.property_values.trace(visitor);- self.storage.properties.trace(visitor);+ self.storage.trace(visitor);}}diff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex aeaa60ee596..0c2aaba7d21 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use core::cell::Cell;+use core::cell::{Cell, RefCell};use core::ffi::c_void;use core::mem::MaybeUninit;use core::num::NonZeroU64;@@ -847,7 +847,8 @@ pub struct ArrayBuffer {detach_key: Cell<Value>,/// The views that cache the offset of this buffer's data in the cage, which has to be invalidated once the data/// moves or goes away.- cached_views: GcRefCell<Vec<GcWeak<TypedArrayBase>>>,+ #[gc(untraced)]+ cached_views: RefCell<Vec<GcWeak<TypedArrayBase>>>,}define_cell!(@@ -893,7 +894,7 @@ impl ArrayBuffer {data_block: GcRefCell::new(DataBlock::new(buffer, is_shared)),max_byte_length: Cell::new(None),detach_key: Cell::new(Value::UNDEFINED),- cached_views: GcRefCell::new(Vec::new()),+ cached_views: RefCell::new(Vec::new()),}}@@ -903,7 +904,7 @@ impl ArrayBuffer {data_block: GcRefCell::new(DataBlock::empty(is_shared)),max_byte_length: Cell::new(None),detach_key: Cell::new(Value::UNDEFINED),- cached_views: GcRefCell::new(Vec::new()),+ cached_views: RefCell::new(Vec::new()),}}@@ -1263,7 +1264,7 @@ impl ArrayBuffer {pub fn register_cached_typed_array_view(&self, vm: &Vm, view: Gc<TypedArrayBase>) {let view = GcWeak::new(vm.heap(), view);- let mut cached_views = self.cached_views.borrow_mut(vm);+ let mut cached_views = self.cached_views.borrow_mut();// NB: Views that died stay in the list until it is full, which keeps registering amortized constant time.if cached_views.len() == cached_views.capacity() {cached_views.retain(|view| view.get().is_some());diff --git a/Libraries/LibJS/Rust/src/runtime/descriptor_array.rs b/Libraries/LibJS/Rust/src/runtime/descriptor_array.rsindex a1aeb2beb7b..4f1b134c350 100644--- a/Libraries/LibJS/Rust/src/runtime/descriptor_array.rs+++ b/Libraries/LibJS/Rust/src/runtime/descriptor_array.rs@@ -9,6 +9,7 @@ use core::hash::BuildHasher;use core::ops::ControlFlow;use crate::gc::class::{GcCell, define_cell};+use crate::gc::defer_gc::DeferGc;use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;@@ -124,7 +125,7 @@ fn set_entry(}impl DescriptorArray {- fn from_parts(entries: Vec<Entry>, entry_indices_by_enum_index: Vec<u32>) -> Self {+ fn from_parts(_: &DeferGc<'_>, entries: Vec<Entry>, entry_indices_by_enum_index: Vec<u32>) -> Self {Self {header: CellHeader::for_class(Self::CLASS),entries: GcRefCell::new(entries),@@ -133,31 +134,32 @@ impl DescriptorArray {}pub fn create(vm: &Vm) -> Gc<DescriptorArray> {- vm.heap().allocate(|_| Self::from_parts(Vec::new(), Vec::new()))+ vm.heap()+ .allocate(|defer_gc| Self::from_parts(defer_gc, Vec::new(), Vec::new()))}/// The first `descriptor_count` properties of `other`, in its insertion order.pub fn create_copy(vm: &Vm, other: &DescriptorArray, descriptor_count: u32) -> Gc<DescriptorArray> {assert!(descriptor_count <= MAX_DESCRIPTOR_COUNT);- let mut entries = Vec::with_capacity(descriptor_count as usize);- let mut entry_indices_by_enum_index = Vec::with_capacity(descriptor_count as usize);- other.for_each_in_insertion_order(- |property_key, metadata| {- let enum_index = entries.len() as u32;- set_entry(- &mut entries,- &mut entry_indices_by_enum_index,- property_key,- metadata,- enum_index,- );- ControlFlow::Continue(())- },- descriptor_count,- );- // The keys are clones of the keys `other` holds, which keeps their symbols alive while this allocates.- vm.heap()- .allocate(|_| Self::from_parts(entries, entry_indices_by_enum_index))+ vm.heap().allocate(|defer_gc| {+ let mut entries = Vec::with_capacity(descriptor_count as usize);+ let mut entry_indices_by_enum_index = Vec::with_capacity(descriptor_count as usize);+ other.for_each_in_insertion_order(+ |property_key, metadata| {+ let enum_index = entries.len() as u32;+ set_entry(+ &mut entries,+ &mut entry_indices_by_enum_index,+ property_key,+ metadata,+ enum_index,+ );+ ControlFlow::Continue(())+ },+ descriptor_count,+ );+ Self::from_parts(defer_gc, entries, entry_indices_by_enum_index)+ })}pub fn size(&self) -> u32 {diff --git a/Libraries/LibJS/Rust/src/runtime/native_function.rs b/Libraries/LibJS/Rust/src/runtime/native_function.rsindex 6e96a6f95fb..218f9c50b6b 100644--- a/Libraries/LibJS/Rust/src/runtime/native_function.rs+++ b/Libraries/LibJS/Rust/src/runtime/native_function.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use core::cell::{Cell, OnceCell};+use core::cell::Cell;use core::ops::Deref;use core::ptr::NonNull;@@ -481,7 +481,7 @@ where#[derive(Trace)]struct CapturingNativeFunction {base: NativeFunction,- native_function: OnceCell<Box<dyn NativeFunctionBehaviour>>,+ native_function: Box<dyn NativeFunctionBehaviour>,}static CAPTURING_NATIVE_FUNCTION_VIRTUAL_METHODS: NativeFunctionMethods = NativeFunctionMethods {@@ -515,14 +515,8 @@ impl CapturingNativeFunction {};let function = allocate_object(vm, |_| CapturingNativeFunction {base,- native_function: OnceCell::new(),+ native_function: Box::new(CapturingBehaviour { captures, behaviour }),});- // The captures stay on the stack, where the collector finds them, until the function that keeps them alive- // exists. Nothing allocates from the heap between allocating the function and storing them in it.- let behaviour: Box<dyn NativeFunctionBehaviour> = Box::new(CapturingBehaviour { captures, behaviour });- if function.native_function.set(behaviour).is_err() {- unreachable!("the behaviour is stored once");- }function.upcast()}@@ -530,11 +524,7 @@ impl CapturingNativeFunction {let function: &CapturingNativeFunction = cast_ref(function);// NB: The behaviour is borrowed for the whole call. That is sound: the function is the [[Function]] of the// running execution context, which keeps it and its behaviour alive, and the behaviour is never replaced.- function- .native_function- .get()- .expect("a capturing native function has its behaviour")- .call(vm)+ function.native_function.call(vm)}}diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rsindex a6fa1c2373e..efb47fcbabb 100644--- a/Libraries/LibJS/Rust/src/runtime/shape.rs+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs@@ -156,8 +156,16 @@ unsafe impl Trace for ShapeStorage {fn trace(&self, visitor: &mut Visitor) {self.previous.trace(visitor);self.special_property_cache.trace(visitor);+ self.property_storage.trace(visitor);+ self.forward_transitions.trace(visitor);+ self.rare_data.trace(visitor);+ }+}- match &*self.property_storage.borrow() {+// SAFETY: Visits the descriptor array or the keys of the property table.+unsafe impl Trace for PropertyStorage {+ fn trace(&self, visitor: &mut Visitor) {+ match self {PropertyStorage::Descriptors(descriptors) => descriptors.trace(visitor),// Descriptor arrays mark their own keys; dictionary tables are not cells, so Shape marks their keys directly.PropertyStorage::PropertyTable(property_table) => {@@ -166,9 +174,14 @@ unsafe impl Trace for ShapeStorage {}}}+ }+}+// SAFETY: Visits the keys. The shapes of transitions are weak.+unsafe impl Trace for ForwardTransitions {+ fn trace(&self, visitor: &mut Visitor) {// FIXME: The forward transition keys should be weak, but we have to mark them for now in case they go stale.- match &*self.forward_transitions.borrow() {+ match self {ForwardTransitions::Empty => {}ForwardTransitions::Single { property_key, .. } => property_key.trace(visitor),ForwardTransitions::Multiple(map) => {@@ -177,8 +190,6 @@ unsafe impl Trace for ShapeStorage {}}}-- self.rare_data.trace(visitor);}}@@ -490,6 +501,10 @@ impl Shape {let target = GcWeak::new(vm.heap(), shape);let mut forward_transitions = self.storage.forward_transitions.borrow_mut(vm);+ if let ForwardTransitions::Multiple(map) = &mut *forward_transitions {+ map.insert(key, target);+ return;+ }match core::mem::replace(&mut *forward_transitions, ForwardTransitions::Empty) {ForwardTransitions::Empty => {*forward_transitions = ForwardTransitions::Single {@@ -525,15 +540,12 @@ impl Shape {property_key,attributes: PropertyAttributes::new(attributes),};- let mut map = Box::new(ForwardTransitionMap::default());- map.insert(existing_key, existing_target);- map.insert(key, target);- *forward_transitions = ForwardTransitions::Multiple(map);- }- ForwardTransitions::Multiple(mut map) => {- map.insert(key, target);- *forward_transitions = ForwardTransitions::Multiple(map);+ *forward_transitions = ForwardTransitions::Multiple(Box::new(ForwardTransitionMap::from_iter([+ (existing_key, existing_target),+ (key, target),+ ])));}+ ForwardTransitions::Multiple(_) => unreachable!("the map takes the transition above"),}}diff --git a/Libraries/LibJS/Rust/src/runtime/synthetic_module.rs b/Libraries/LibJS/Rust/src/runtime/synthetic_module.rsindex accbcd6e44f..88b9acd3652 100644--- a/Libraries/LibJS/Rust/src/runtime/synthetic_module.rs+++ b/Libraries/LibJS/Rust/src/runtime/synthetic_module.rs@@ -4,7 +4,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-use core::cell::OnceCell;use core::ops::Deref;use ak::{ScopeGuard, Utf16FlyString};@@ -64,8 +63,8 @@ where#[derive(Trace)]pub struct SyntheticModule {base: Module,- export_names: Vec<Utf16FlyString>, // [[ExportNames]]- evaluation_steps: OnceCell<Box<dyn EvaluationSteps>>, // [[EvaluationSteps]]+ export_names: Vec<Utf16FlyString>, // [[ExportNames]]+ evaluation_steps: Box<dyn EvaluationSteps>, // [[EvaluationSteps]]}define_cell!(SyntheticModule, Other, extends: [Module]);@@ -115,21 +114,14 @@ impl SyntheticModule {"the evaluation steps capture their state through their captures");};- let module = vm.heap().allocate(|_| SyntheticModule {+ vm.heap().allocate(|_| SyntheticModule {base: Module::new(Self::CLASS, realm, filename, ForeignCellSlot::empty()),export_names,- evaluation_steps: OnceCell::new(),- });- // The captures stay on the stack, where the collector finds them, until the module that keeps them alive- // exists. Nothing allocates from the heap between allocating the module and storing them in it.- let steps: Box<dyn EvaluationSteps> = Box::new(CapturingEvaluationSteps {- captures,- steps: evaluation_steps,- });- if module.evaluation_steps.set(steps).is_err() {- unreachable!("the evaluation steps are stored once");- }- module+ evaluation_steps: Box::new(CapturingEvaluationSteps {+ captures,+ steps: evaluation_steps,+ }),+ })}// 16.2.1.8.1 CreateDefaultExportSyntheticModule ( defaultExport ), https://tc39.es/ecma262/#sec-create-default-export-synthetic-module@@ -286,11 +278,7 @@ impl SyntheticModule {// 9. Let steps be module.[[EvaluationSteps]].// 10. Let result be Completion(steps(module)).let module = self.as_synthetic_module_gc();- let result = module- .evaluation_steps- .get()- .expect("a synthetic module has its evaluation steps")- .call(vm, &module);+ let result = module.evaluation_steps.call(vm, &module);// 11. Suspend moduleContext and remove it from the execution context stack.// 12. Resume the context that is now on the top of the execution context stack as the running execution context.