Truly independent web browser
LibJS: Keep the remaining temporary lists of cells in MarkedVecs
Shannon Booth85bf104f760b
diff --git a/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rsindex 5625b36ea18..597d8075efa 100644--- a/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rs+++ b/Libraries/LibJS/Rust/src/bytecode/bytecode_cache.rs@@ -132,21 +132,24 @@ pub fn functions_created_by() -> MarkedVec<'_, Gc<SharedFunctionInstanceData>> {let functions = MarkedVec::new(vm);let mut seen = HashSet::new();- let mut executables_to_visit: Vec<Gc<Executable>> = executable.into_iter().collect();- let mut add_function = |function: Gc<SharedFunctionInstanceData>,- executables_to_visit: &mut Vec<Gc<Executable>>| {- if seen.insert(function) {+ let executables_to_visit = MarkedVec::new(vm);+ if let Some(executable) = executable {+ executables_to_visit.push(executable);+ }+ let mut add_function = |function: Gc<SharedFunctionInstanceData>| {+ if seen.insert(function.as_ptr().addr()) {functions.push(function);- executables_to_visit.extend(function.executable());+ if let Some(executable) = function.executable() {+ executables_to_visit.push(executable);+ }}};for function in declared_functions {- add_function(function, &mut executables_to_visit);+ add_function(function);}while let Some(executable) = executables_to_visit.pop() {for index in 0..executable.shared_function_data_count() {- let function = executable.shared_function_data(u32::try_from(index).expect("the index fits in u32"));- add_function(function, &mut executables_to_visit);+ add_function(executable.shared_function_data(u32::try_from(index).expect("the index fits in u32")));}}functionsdiff --git a/Libraries/LibJS/Rust/src/embedding/compile.rs b/Libraries/LibJS/Rust/src/embedding/compile.rsindex 3879b4a07e7..97430692b0c 100644--- a/Libraries/LibJS/Rust/src/embedding/compile.rs+++ b/Libraries/LibJS/Rust/src/embedding/compile.rs@@ -32,7 +32,7 @@ use crate::compile::{use crate::embedding::abi_types::{JSRealm, JSSourceCode, JSUtf16View, cell_from_abi, cell_into_abi, vm_from_abi};use crate::embedding::script::{JSParserErrorSink, JSScript, append_to_parser_error_sink, host_defined_slot_from_abi};use crate::embedding::source_code::{shared_source_code_from_abi, source_code_into_abi};-use crate::gc::root::Root;+use crate::gc::root::{MarkedVec, Root};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::host_class::{JSModule, JSVM};@@ -590,18 +590,18 @@ const _: fn() = || {/// Has a worker compile copies of the ASTs of the functions, and installs the results on the VM's thread.fn compile_lazy_functions_off_thread(vm: &'static Vm,- functions: Vec<(Gc<SharedFunctionInstanceData>, Box<FunctionPayload>)>,+ shared_function_data: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,+ function_asts: impl IntoIterator<Item = Box<FunctionPayload>>,source_length_in_code_units: usize,callbacks: Arc<SharedOffThreadCompilationCallbacks>,) {- let (shared_function_data, function_asts): (Vec<_>, Vec<_>) = functions.into_iter().unzip();let awaiting_compilation = LazyFunctionsAwaitingCompilation {vm,- shared_function_data: Root::new(vm, shared_function_data),+ shared_function_data: Root::new(vm, shared_function_data.to_vec()),callbacks: callbacks.clone(),};let work = Box::new(LazyFunctionCompilation {- function_asts,+ function_asts: function_asts.into_iter().collect(),source_length_in_code_units,callbacks: callbacks.clone(),awaiting_compilation: OnlyForTheVmsThread(Box::new(awaiting_compilation)),@@ -663,8 +663,9 @@ fn compile_remaining_functions_of_executable_off_thread(executable: Gc<Executable>,callbacks: Arc<SharedOffThreadCompilationCallbacks>,) {- let functions = SharedFunctionInstanceData::uncompiled_functions_of(executable);- if functions.is_empty() {+ let shared_function_data = MarkedVec::new(vm);+ let function_asts = SharedFunctionInstanceData::uncompiled_functions_of(executable, &shared_function_data);+ if function_asts.is_empty() {return;}// NB: The frontend checks that nested functions lie within the source, which is unknown without a source code.@@ -672,7 +673,13 @@ fn compile_remaining_functions_of_executable_off_thread(.source_code.as_ref().map_or(usize::MAX, |source_code| source_code.length_in_code_units());- compile_lazy_functions_off_thread(vm, functions, source_length_in_code_units, callbacks);+ compile_lazy_functions_off_thread(+ vm,+ &shared_function_data,+ function_asts,+ source_length_in_code_units,+ callbacks,+ );}/// # Safetydiff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 4c1ec3f69bc..7b15571f463 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -1096,8 +1096,9 @@ impl Vm {self.update_dispatch_tables();// NB: Debuggers step through bytecode, so nothing enters JIT code while one is attached, not even JIT code// that runs already, which calls other JIT code only through the entries of executables.- let executables = self.executables.borrow().clone();- for executable in executables {+ let executables = MarkedVec::new(self);+ executables.extend_from_slice(&self.executables.borrow());+ for executable in executables.values().iter() {if executable.jit_compile_state() == crate::jit::code::CompileState::Installed {executable.discard_jit_code(self);}diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex 4ab16b7e178..ca9fd0c6919 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -811,12 +811,13 @@ pub unsafe extern "C" fn libjs_jit_call_forwarding_arguments(passed_argument_count,);}- // NB: The passed arguments stay alive in the frame while the call runs.- let arguments: Vec<Value> = frame_ref.arguments()[..passed_argument_count]- .iter()- .map(core::cell::Cell::get)- .collect();- call_from_jit_or_generic(vm, &site, function, this_argument, &arguments, 1).0+ let mut arguments = ArgumentStorage::new(+ vm,+ frame_ref.arguments()[..passed_argument_count]+ .iter()+ .map(core::cell::Cell::get),+ );+ call_from_jit_or_generic(vm, &site, function, this_argument, arguments.values(), 1).0}/// `i64 libjs_jit_finish_direct_call(VM*, ExecutionContext* frame, u32 pc, u64 status)`: finishes a direct call madediff --git a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs b/Libraries/LibJS/Rust/src/runtime/primitive_string.rsindex 682820584ac..530973c596d 100644--- a/Libraries/LibJS/Rust/src/runtime/primitive_string.rs+++ b/Libraries/LibJS/Rust/src/runtime/primitive_string.rs@@ -10,6 +10,7 @@ use ak::{Utf16FlyString, Utf16String};use libjs_runtime_macros::Trace;use crate::gc::class::{Class, ExternalMemorySize, GcCell, define_cell};+use crate::gc::root::MarkedVec;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::{StringToAtomCacheEntry, Vm};use crate::layout::cell::{CellHeader, Gc};@@ -778,15 +779,15 @@ impl RopeString {}fn concatenate_many_pieces(&self) -> Utf16String {- // This vector will hold all the pieces of the rope that need to be assembled+ let vm = Vm::of_cell(self);++ // This list will hold all the pieces of the rope that need to be assembled// into the resolved string.- // NB: Resolving takes no VM, so it cannot allocate cells or collect garbage while these vectors hold strings- // that only the rope keeps alive.- let mut pieces: Vec<Gc<PrimitiveString>> = Vec::with_capacity(2);+ let pieces = MarkedVec::with_capacity(vm, 2);// NOTE: We traverse the rope tree without using recursion, since we'd run out of// stack space quickly when handling a long sequence of unresolved concatenations.- let mut stack: Vec<Gc<PrimitiveString>> = Vec::with_capacity(2);+ let stack = MarkedVec::with_capacity(vm, 2);stack.push(self.rhs());stack.push(self.lhs());while let Some(current) = stack.pop() {@@ -800,6 +801,7 @@ impl RopeString {pieces.push(current);}+ let pieces = pieces.values();let views: Vec<Utf16View<'_>> = pieces.iter().map(|piece| piece.utf16_string_view()).collect();concatenate(&views)}diff --git a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rsindex c60eda89770..6d4728d0971 100644--- a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs+++ b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs@@ -37,6 +37,7 @@use core::cell::Cell;+use crate::gc::root::MarkedVec;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -225,15 +226,13 @@ fn watch_regexp_primordial_properties(vm: &Vm, realm: Gc<Realm>) -> Option<Gc<Wa}let regexp_prototype = realm.intrinsics().regexp_prototype(vm);let regexp_constructor: Gc<Object> = realm.intrinsics().regexp_constructor(vm).upcast();- let slots: Vec<_> = RegExpPrototype::primordial_property_keys(vm)- .map(|key| (regexp_prototype, key.clone()))- .into_iter()- .chain([- (regexp_prototype, PropertyKey::from(vm.well_known_symbols().match_)),- (regexp_constructor, PropertyKey::from(vm.well_known_symbols().species)),- ])- .collect();- watch_intrinsics(vm, &[regexp_prototype, regexp_constructor], &slots)+ let slots = MarkedVec::new(vm);+ for key in RegExpPrototype::primordial_property_keys(vm) {+ slots.push((regexp_prototype, key.clone()));+ }+ slots.push((regexp_prototype, PropertyKey::from(vm.well_known_symbols().match_)));+ slots.push((regexp_constructor, PropertyKey::from(vm.well_known_symbols().species)));+ watch_intrinsics(vm, &[regexp_prototype, regexp_constructor], &slots.values())}/// Whether ArraySpeciesCreate makes a plain array for an array of the realm that has no own constructor:diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rsindex a4931d54041..886df9a13c2 100644--- a/Libraries/LibJS/Rust/src/runtime/shape.rs+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs@@ -405,17 +405,25 @@ impl Shape {return 0;}*budget -= 1;- let targets: Vec<Gc<Shape>> = match &*self.storage.forward_transitions.borrow() {- ForwardTransitions::Empty => Vec::new(),- ForwardTransitions::Single { target, .. } => target.get().into_iter().collect(),- ForwardTransitions::Multiple(map) => map.values().filter_map(GcWeak::get).collect(),- };let mut longest = 0;- for target in targets {+ let mut reaches_depth_limit = |target: Gc<Shape>| {let length = 1 + target.longest_forward_transition_chain_within(depth_limit - 1, budget);longest = longest.max(length);- if longest >= depth_limit {- break;+ longest >= depth_limit+ };+ match &*self.storage.forward_transitions.borrow() {+ ForwardTransitions::Empty => {}+ ForwardTransitions::Single { target, .. } => {+ if let Some(target) = target.get() {+ reaches_depth_limit(target);+ }+ }+ ForwardTransitions::Multiple(map) => {+ for target in map.values().filter_map(GcWeak::get) {+ if reaches_depth_limit(target) {+ break;+ }+ }}}longest@@ -809,12 +817,13 @@ impl Shape {for (property_key, _) in &property_keys {keys.push(property_key.to_value(vm));}- let own_string_keys = OwnStringKeys {- generation,- keys: (*keys.values()).into(),- enumerable: property_keys.iter().map(|(_, enumerable)| *enumerable).collect(),- };- self.with_rare_data(|rare_data| rare_data.own_string_keys = Some(own_string_keys));+ self.with_rare_data(|rare_data| {+ rare_data.own_string_keys = Some(OwnStringKeys {+ generation,+ keys: keys.values().iter().copied().collect(),+ enumerable: property_keys.iter().map(|(_, enumerable)| *enumerable).collect(),+ });+ });}let rare_data = self.storage.rare_data.borrow();let own_string_keys = rare_data@@ -1152,7 +1161,7 @@ impl Shape {return;}self.flags.set(self.flags.get() & !shape_flag::HAS_WATCHED_SLOTS);- let mut watchpoint_sets = Vec::new();+ let watchpoint_sets = MarkedVec::new(vm);if let Some(rare_data) = self.storage.rare_data.borrow_mut().as_mut() {rare_data.watched_slots.retain(|_, watched_slot| match watched_slot {WatchedSlot::Watched(watchpoint_set) => {@@ -1162,7 +1171,7 @@ impl Shape {WatchedSlot::WrittenByCaches => true,});}- for watchpoint_set in watchpoint_sets {+ for watchpoint_set in watchpoint_sets.values().iter() {watchpoint_set.fire(vm);}}diff --git a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rsindex 06c4264ae53..ddc90b8729e 100644--- a/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs+++ b/Libraries/LibJS/Rust/src/runtime/shared_function_instance_data.rs@@ -21,6 +21,7 @@ use crate::compile::FunctionPrecompileMode;use crate::compile::SharedFunctionDescription;use crate::gc::class::{GcCell, define_cell};use crate::gc::gc_ref_cell::GcRefCell;+use crate::gc::root::MarkedVec;use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::run::should_dump_bytecode;use crate::interpreter::vm::Vm;@@ -596,22 +597,26 @@ impl SharedFunctionInstanceData {self.storage.cached_bytecode_executable.borrow().is_some()}- /// The functions that `executable` creates and that have not been compiled yet, with a copy of the AST of each, so- /// that they can be compiled elsewhere, such as on another thread, while their own ASTs stay in place for a first- /// call that comes sooner.+ /// Appends the functions that `executable` creates and that have not been compiled yet to `functions`, and returns+ /// a copy of the AST of each, so that they can be compiled elsewhere, such as on another thread, while their own+ /// ASTs stay in place for a first call that comes sooner.pub fn uncompiled_functions_of(executable: Gc<Executable>,- ) -> Vec<(Gc<SharedFunctionInstanceData>, Box<FunctionPayload>)> {- (0..executable.shared_function_data_count())- .filter_map(|index| {- let shared_data = executable.shared_function_data(u32::try_from(index).expect("the index fits in u32"));- if shared_data.executable().is_some() {- return None;- }- let function_ast = shared_data.storage.rust_function_ast.borrow().clone()?;- Some((shared_data, function_ast))- })- .collect()+ functions: &MarkedVec<'_, Gc<SharedFunctionInstanceData>>,+ ) -> Vec<Box<FunctionPayload>> {+ let mut function_asts = Vec::new();+ for index in 0..executable.shared_function_data_count() {+ let shared_data = executable.shared_function_data(u32::try_from(index).expect("the index fits in u32"));+ if shared_data.executable().is_some() {+ continue;+ }+ let Some(function_ast) = shared_data.storage.rust_function_ast.borrow().clone() else {+ continue;+ };+ functions.push(shared_data);+ function_asts.push(function_ast);+ }+ function_asts}/// Records what scope analysis found out about the function's body, as rust_sfd_set_metadata does.diff --git a/Libraries/LibJS/Rust/src/runtime/string_prototype.rs b/Libraries/LibJS/Rust/src/runtime/string_prototype.rsindex c0807beed5a..d5012dd99ee 100644--- a/Libraries/LibJS/Rust/src/runtime/string_prototype.rs+++ b/Libraries/LibJS/Rust/src/runtime/string_prototype.rs@@ -2199,12 +2199,9 @@ impl<'vm> SubstringList<'vm> {Array::create_from(vm, realm, &self.first_substrings[..self.length]).upcast::<Object>(),);}- // NB: The array is allocated before the first substrings are copied off the stack, so the collector still- // finds them there if the allocation collects.- let array = Array::create(vm, realm, 0, None).must();- let mut elements = self.first_substrings.to_vec();+ let elements = MarkedVec::with_capacity(vm, self.length);+ elements.extend_from_slice(&self.first_substrings);elements.extend_from_slice(&self.other_substrings.values());- array.set_indexed_property_elements(&elements);- Value::from_object(array.upcast::<Object>())+ Value::from_object(Array::create_from_list(vm, realm, &elements).upcast::<Object>())}}