Truly independent web browser
LibJS: Keep cells that JIT code embeds alive only with their realms
Andreas Kling0c05e1fbb8bd
diff --git a/Libraries/LibJS/Rust/src/gc/visitor.rs b/Libraries/LibJS/Rust/src/gc/visitor.rsindex 32d0f26e76f..96e4e49cfd5 100644--- a/Libraries/LibJS/Rust/src/gc/visitor.rs+++ b/Libraries/LibJS/Rust/src/gc/visitor.rs@@ -153,6 +153,22 @@ impl Visitor {unsafe { gc_visitor_visit_ephemeron(self.0.as_ptr(), key.as_ptr().cast(), core::ptr::from_ref(value).cast()) };}+ /// Visits `value`, a cell that is reachable only while `key` is, by value: it stays where it is in a collection+ /// that moves cells, even if it dies. Visitors that do not mark see the value as reachable.+ pub fn visit_ephemeron_cell<K, V>(&mut self, key: Gc<K>, value: Gc<V>) {+ let Some(marker) = self.marker() else {+ self.visit(value);+ return;+ };+ // SAFETY: The marker is the visitor's, and both are live cells. The value is pinned, so no slot needs to be+ // handed to the collection. The key is only looked at, and moves of it change nothing the caller+ // holds.+ unsafe {+ gc_marker_pin_cell(marker.as_ptr(), value.as_ptr().cast());+ gc_marker_visit_ephemeron_without_pinning(marker.as_ptr(), key.as_ptr().cast(), value.as_ptr().cast());+ }+ }+/// Visits a value that is reachable only while `key` is, such as a WeakMap entry's, without keeping either from/// moving.///diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 80d235ee212..7aacfd9d02c 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -1257,6 +1257,7 @@ impl Vm {fn gather_roots(&self, visitor: &mut Visitor) {self.code_flushing.begin_pass(self);self.jit.trace(visitor);+ self.trace_embedded_cells_of_running_jit_code(visitor);self.for_each_execution_context_top_to_bottom(|context| {context.trace(visitor);ControlFlow::Continue(())@@ -1610,6 +1611,22 @@ impl Vm {});}+ /// Keeps the cells that the JIT code which frames run embeds alive. Other JIT code holds them weakly (see+ /// `JitCode::embedded_cells`).+ fn trace_embedded_cells_of_running_jit_code(&self, visitor: &mut Visitor) {+ // NB: Frames of recursive calls run the same code, which is traced once.+ let mut traced_executables = HashSet::new();+ self.for_each_live_execution_context(|frame| {+ if frame.runs_jit_code.get()+ && let Some(head) = frame.executable.get()+ && traced_executables.insert(head.as_ptr().addr())+ {+ Executable::from_head(head).trace_embedded_cells_of_jit_code(self, visitor);+ }+ ControlFlow::Continue(())+ });+ }+/// Clears the idle count of the executables that frames still run: they are not idle, even when no frame entered/// them for many collections (as in a long loop).fn clear_idle_collection_counts_of_running_executables(&self) {@@ -1665,6 +1682,7 @@ impl Vm {return false;}executable.remove_dead_cells(sweep);+ executable.drop_jit_code_that_lost_embedded_cells(self, sweep);let idle_collection_count = &executable.head.idle_collection_count;idle_collection_count.set(idle_collection_count.get().saturating_add(1));true@@ -1674,7 +1692,7 @@ impl Vm {self.prototype_transition_cache.remove_dead_entries(sweep);self.construct_shape_cache.remove_dead_entries(sweep);self.keyed_property_store_cache.remove_dead_entries(sweep);- self.jit.dependents.remove_dead_entries(sweep);+ self.jit.dependents.remove_dead_entries(self, sweep);}/// Has the JIT code that idled long enough in this collection flushed once the collection is over.diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 82358bfdf16..a708484dee4 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -9,7 +9,7 @@use core::cell::{Cell, OnceCell, RefCell};use core::ffi::c_void;use core::ops::ControlFlow;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use ak::Zone;use libjs_jit::artifact::{Artifact, FrameView, Layout, Patch, SiteView};@@ -32,6 +32,8 @@ use crate::layout::execution_context::ExecutionContext;use crate::layout::function_object::EcmascriptFunctionObject;use crate::layout::object::Object;use crate::layout::property_lookup_cache::PropertyLookupCacheEntryType;+use crate::layout::realm::Realm;+use crate::layout::shape::Shape;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;/// The status word of what JIT code returns, `libjs_jit::code::JitStatus`.@@ -148,6 +150,11 @@ fn speculated_property_lookup_cache_index(bytecode: &[u8], pc: u32) -> Option<u3/// The most memory the array of one decoded instruction takes.const DECODED_ARRAY_LIMIT: usize = 1 << 30;+/// JIT code that was detached from its executable and waits to be dropped (see+/// `JitState::parking_for_detached_code()`).+#[allow(clippy::vec_box, reason = "the code moves over from the JIT entry table in its box")]+pub type DetachedJitCode = Vec<Box<JitCode>>;+/// The function object of an inlined executable, which its materialized frames run.#[derive(Clone, Copy, PartialEq, Eq, Hash, Trace)]pub enum InlinedFunction {@@ -183,9 +190,18 @@ pub struct JitCode {/// The tables of the code that the runtime reads once the code is installed, which have `layout`.tables: DataMemory,layout: Layout,- /// The cells the code compares against or uses. The executable the code is attached to keeps them alive, so they- /// keep their addresses for as long as the code may run.+ /// The cells the code compares against or uses, which keep their addresses for as long as the code lives. While a+ /// frame runs the code, the VM keeps them alive. Otherwise the code keeps a realm, a shape or an object alive only+ /// while that realm is otherwise alive (see `realm_of_embedded_cell()`), so that the code of one realm does not+ /// keep another realm that went away alive through the shapes of its objects. The code is dropped once one of+ /// them dies (see `Executable::drop_jit_code_that_lost_embedded_cells()`). The inlined functions of+ /// `snapshot_executables` are held the same way.embedded_cells: Vec<Gc<CellHeader>>,+ /// Cells that belong to an ECMAScript function among the embedded cells, with that function: its environments,+ /// which the code embeds too, and its shared data and executable if the code embeds them. The code keeps such a+ /// cell alive only while the function is alive, as these cells may reach the function's realm, but have no realm+ /// of their own (see `split_function_cells()`).+ function_cells: FunctionCells,snapshot_executables: Vec<SnapshotExecutable>,/// The slots of the samples the code copies closures of, whose addresses the code holds rather than those of the/// samples. A collection rewrites them where they are when a sample moves.@@ -231,9 +247,10 @@ impl JitCode {layout: Layout,embedded_cells: Vec<Gc<CellHeader>>,snapshot_executables: Vec<SnapshotExecutable>,- _defer_gc: &DeferGc<'_>,+ defer_gc: &DeferGc<'_>,) -> Self {let entry = entry_at(&memory, entry_offset);+ let (embedded_cells, function_cells) = split_function_cells(embedded_cells, defer_gc);Self {exit_count: Cell::new(0),interpreted_frames: RefCell::new(HashMap::new()),@@ -243,6 +260,7 @@ impl JitCode {tables,layout,embedded_cells,+ function_cells,snapshot_executables,sample_slots: Vec::new(),id: 0,@@ -327,6 +345,40 @@ impl JitCode {self.id}+ /// The embedded cells and the inlined functions, which the code holds only while their realms are alive (see+ /// `JitCode::embedded_cells`), without the cells of functions.+ fn cells_held_by_realm(&self) -> impl Iterator<Item = Gc<CellHeader>> {+ let functions = self+ .snapshot_executables+ .iter()+ .filter_map(|snapshot| snapshot.function)+ .map(|function| match function {+ InlinedFunction::Ecmascript(function) => function.upcast(),+ InlinedFunction::Builtin(function) => function.upcast(),+ });+ self.embedded_cells.iter().copied().chain(functions)+ }++ /// Keeps the embedded cells and the inlined functions alive, for code that a frame runs.+ fn trace_embedded_cells(&self, visitor: &mut Visitor) {+ for cell in self.cells_held_by_realm() {+ visitor.visit(cell);+ }+ for &(_, cell) in &self.function_cells {+ visitor.visit(cell);+ }+ }++ /// Whether a cell the code embeds or an inlined function died in the collection.+ fn lost_embedded_cell(&self, sweep: &Sweep<'_>) -> bool {+ self.cells_held_by_realm().any(|cell| sweep.is_dead(cell))+ || self.function_cells.iter().any(|&(_, cell)| sweep.is_dead(cell))+ || self+ .snapshot_executables+ .iter()+ .any(|snapshot| sweep.is_dead(snapshot.executable))+ }+pub fn is_invalidated(&self) -> bool {self.invalidated.get()}@@ -435,22 +487,112 @@ impl JitCode {}}+/// Cells that belong to ECMAScript functions, each with its function (see `JitCode::function_cells`).+type FunctionCells = Vec<(Gc<CellHeader>, Gc<CellHeader>)>;++/// Splits the cells that belong to an ECMAScript function among `embedded_cells` off them (see+/// `JitCode::function_cells`), returning the other embedded cells and those cells, with their functions.+fn split_function_cells(+ mut embedded_cells: Vec<Gc<CellHeader>>,+ _defer_gc: &DeferGc<'_>,+) -> (Vec<Gc<CellHeader>>, FunctionCells) {+ let embedded: HashSet<usize> = embedded_cells.iter().map(|cell| cell.as_ptr().addr()).collect();+ let mut function_cells = Vec::new();+ for function in embedded_cells+ .iter()+ .filter_map(|cell| cell.downcast::<EcmascriptFunctionObject>())+ {+ // NB: Code that embeds an ECMAScript function may also embed the words its frames start with (see+ // `FunctionFrameFields`), whose environments the code then keeps from moving like the cells it lists.+ let environments = [+ function.environment().map(Gc::upcast),+ function.private_environment().map(Gc::upcast),+ ];+ let shared_data = function.shared_data();+ let embedded_code = [+ Some(shared_data.upcast::<CellHeader>()),+ shared_data.executable().map(Gc::upcast),+ ]+ .into_iter()+ .flatten()+ .filter(|cell| embedded.contains(&cell.as_ptr().addr()));+ for cell in environments.into_iter().flatten().chain(embedded_code) {+ function_cells.push((function.upcast(), cell));+ }+ }+ let function_owned: HashSet<usize> = function_cells.iter().map(|&(_, cell)| cell.as_ptr().addr()).collect();+ embedded_cells.retain(|cell| !function_owned.contains(&cell.as_ptr().addr()));+ (embedded_cells, function_cells)+}++/// The realm of a realm, a shape or an object, which code that embeds the cell keeps alive only while the realm is+/// alive. Other cells, such as executables, strings and environments, belong to no realm, and the code keeps them+/// alive.+fn realm_of_embedded_cell(cell: Gc<CellHeader>) -> Option<Gc<Realm>> {+ if let Some(realm) = cell.downcast::<Realm>() {+ return Some(realm);+ }+ if let Some(shape) = cell.downcast::<Shape>() {+ return Some(shape.realm());+ }+ cell.downcast::<Object>().map(|object| object.shape().realm())+}++// SAFETY: Visits what the code keeps alive. The realms, shapes and objects it embeds and its inlined functions stay+// where they are, and are kept alive only while their realms are. The code is dropped before any of them that died is+// swept (see `JitCode::embedded_cells`).unsafe impl Trace for JitCode {fn trace(&self, visitor: &mut Visitor) {- for cell in &self.embedded_cells {- visitor.visit(*cell);+ for cell in self.cells_held_by_realm() {+ match realm_of_embedded_cell(cell) {+ Some(realm) => visitor.visit_ephemeron_cell(realm, cell),+ None => visitor.visit(cell),+ }+ }+ for &(function, cell) in &self.function_cells {+ visitor.visit_ephemeron_cell(function, cell);}for materialized in self.materialized_objects.borrow().iter() {visitor.visit(materialized.object);}- self.snapshot_executables.trace(visitor);+ // NB: The executables of inlined calls are held like the cells of their functions.+ for snapshot in &self.snapshot_executables {+ match snapshot.function {+ Some(InlinedFunction::Ecmascript(function)) => {+ visitor.visit_ephemeron_cell(function, snapshot.executable);+ }+ Some(InlinedFunction::Builtin(function)) => {+ visitor.visit_ephemeron_cell(function, snapshot.executable);+ }+ None => visitor.visit(snapshot.executable),+ }+ }for slot in &self.sample_slots {- // SAFETY: Nothing writes the slots, and only dropping the code, which no sweep callback does, frees them.+ // SAFETY: Nothing writes the slots, and only dropping the code frees them, which a sweep callback defers until+ // the collection is over if it moves cells (see `Executable::drop_jit_code_that_lost_embedded_cells()`).unsafe { visitor.visit_owned_values(core::slice::from_ref(&**slot)) };}}}+/// A reason to discard JIT code that says nothing about the code.+#[derive(Clone, Copy)]+enum UncountedDiscard {+ /// The executable idled (see `Executable::flush_idle_jit_code()`).+ IdleFlush,+ /// A cell the code embeds died (see `Executable::drop_jit_code_that_lost_embedded_cells()`).+ LostEmbeddedCell,+}++impl UncountedDiscard {+ fn coverage_key(self) -> &'static str {+ match self {+ Self::IdleFlush => "flush",+ Self::LostEmbeddedCell => "lost-embedded-cell",+ }+ }+}+/// The JIT state of an executable that the interpreter and JIT code do not read: they read the fields of its head.#[derive(Default)]pub struct ExecutableJitState {@@ -474,9 +616,9 @@ pub struct ExecutableJitState {/// Whether the executable is refused once its discarded code is detached, because it was refused while frames/// still ran that code (see `refuse_jit_compile_once_detached()`).refused_once_detached: Cell<bool>,- /// Whether the discarded code is discarded because the executable idled (see `flush_idle_jit_code()`), which does- /// not count as a discard.- discarded_while_idle: Cell<bool>,+ /// Why the discarded code is discarded, if for a reason that says nothing about the code, which does not count as+ /// a discard.+ uncounted_discard: Cell<Option<UncountedDiscard>>,/// The loads and stores of bindings of the environments of the executable's closure (see `jit::snapshot`). The/// bytecode never changes, so snapshots find them once.pub(crate) captured_binding_accesses: OnceCell<CapturedBindingAccesses>,@@ -595,6 +737,14 @@ impl Executable {}}+ /// Keeps the cells that the executable's attached JIT code embeds alive, for an executable that a frame runs in JIT+ /// code (see `JitCode::embedded_cells`).+ pub fn trace_embedded_cells_of_jit_code(&self, vm: &Vm, visitor: &mut Visitor) {+ if let Some(code) = self.jit_code(vm) {+ code.trace_embedded_cells(visitor);+ }+ }+pub fn jit_exit_sites(&self) -> Vec<(u32, ExitKind)> {self.jit_state().exit_sites.borrow().clone()}@@ -722,7 +872,13 @@ impl Executable {/// but without counting a discard: it says nothing about the code. The executable has to get hot again to be/// compiled again.pub fn flush_idle_jit_code(&self, vm: &Vm) {- self.jit_state().discarded_while_idle.set(true);+ self.discard_jit_code_without_counting(vm, UncountedDiscard::IdleFlush);+ }++ /// Discards the executable's JIT code like discard_jit_code(), without counting a discard. The executable has to+ /// get hot again to be compiled again.+ fn discard_jit_code_without_counting(&self, vm: &Vm, reason: UncountedDiscard) {+ self.jit_state().uncounted_discard.set(Some(reason));self.discard_jit_code(vm);if self.jit_compile_state() == CompileState::Discarding {self.head@@ -761,6 +917,31 @@ impl Executable {true}+ /// Drops the executable's JIT code if a cell it embeds died in the collection whose sweep callback calls this. No+ /// frame runs such code, as the VM keeps the embedded cells of code that frames run alive, so it is dropped before+ /// the dead cell is swept and its memory reused.+ pub fn drop_jit_code_that_lost_embedded_cells(&self, vm: &Vm, sweep: &Sweep<'_>) {+ if !self.jit_code(vm).is_some_and(|code| code.lost_embedded_cell(sweep)) {+ return;+ }+ // NB: A collection that moves cells may still rewrite the slots that the code's trace handed it (see+ // `JitCode::sample_slots`), so the code is only dropped once the collection is over.+ let _deferral = sweep+ .moves_cells()+ .then(|| vm.jit.defer_code_drops_until_collection_is_over(vm));+ match self.jit_compile_state() {+ CompileState::Installed => self.discard_jit_code_without_counting(vm, UncountedDiscard::LostEmbeddedCell),+ CompileState::Discarding => {+ self.detach_discarded_jit_code_if_unused(vm);+ }+ state => unreachable!("only installed or discarded code is attached, not in state {state:?}"),+ }+ assert!(+ self.jit_code(vm).is_none(),+ "no frame runs code that lost an embedded cell"+ );+ }+/// Makes the executable's frames run in the interpreter for good, like `tier_up::refuse_jit_compile()`, once its/// discarded code, which frames still run, is detached.pub fn refuse_jit_compile_once_detached(&self) {@@ -772,9 +953,11 @@ impl Executable {fn detach_jit_code(&self, vm: &Vm) {let state = self.jit_state();let (table, slot) = self.jit_entry_table_slot(vm).expect("the code is attached");- table.detach_code(slot);- if state.discarded_while_idle.replace(false) && !state.refused_once_detached.get() {- vm.jit.count_coverage("flush");+ table.detach_code(slot, vm.jit.parking_for_detached_code());+ if let Some(reason) = state.uncounted_discard.take()+ && !state.refused_once_detached.get()+ {+ vm.jit.count_coverage(reason.coverage_key());self.set_jit_compile_state(CompileState::None);self.head.tier_up_budgetdiff --git a/Libraries/LibJS/Rust/src/jit/dependencies.rs b/Libraries/LibJS/Rust/src/jit/dependencies.rsindex b3993db082c..587179c6054 100644--- a/Libraries/LibJS/Rust/src/jit/dependencies.rs+++ b/Libraries/LibJS/Rust/src/jit/dependencies.rs@@ -25,7 +25,7 @@ use crate::bytecode::executable::Executable;use crate::gc::sweep::Sweep;use crate::gc::weak::GcWeak;use crate::interpreter::vm::Vm;-use crate::layout::cell::Gc;+use crate::layout::cell::{CellHeader, Gc};use crate::layout::environment::DeclarativeEnvironment;use crate::layout::object::Object;use crate::layout::shape::WatchpointSet;@@ -86,11 +86,30 @@ impl Dependents {}}- /// Forgets the entries of code whose executable died, and the slots of global objects that died.- pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {- self.code.borrow_mut().retain(|_, dependents| {- dependents.retain(|dependent| dependent.executable.get().is_some());- !dependents.is_empty()+ /// Forgets the entries of code that is gone, the dependencies on cells that died, and the slots of global objects+ /// that died.+ ///+ /// NB: Code may lose a cell it depends on while its executable lives on, as it holds shapes and objects only while+ /// their realms are alive (see `JitCode::embedded_cells`). Such code is dropped earlier in this callback, so+ /// its entries go with it, before another cell can take the cell's address.+ pub fn remove_dead_entries(&self, vm: &Vm, sweep: &Sweep<'_>) {+ self.code.borrow_mut().retain(|dependency, dependents| {+ dependents.retain(|dependent| {+ dependent+ .executable+ .get()+ .and_then(|executable| executable.jit_code(vm))+ .is_some_and(|code| code.id() == dependent.id)+ });+ if dependents.is_empty() {+ return false;+ }+ !cell_of(dependency).is_some_and(|cell| {+ // SAFETY: Code that is still attached embeds the cells it depends on, which stay where they are while+ // it lives, and a dead cell is intact until the sweep that follows this callback.+ let cell = unsafe { Gc::from_non_null(NonNull::new_unchecked(cell.0 as *mut CellHeader)) };+ sweep.is_dead(cell)+ })});self.assigned_global_object_slots.borrow_mut().retain(|&object, _| {// SAFETY: The map only holds objects that were live when their entries were added, and a dead object is@@ -143,9 +162,20 @@ pub fn note_global_object_slot_assignments(vm: &Vm, object: &Object, offsets: Ra}}+/// The cell a dependency names, if it names one.+fn cell_of(dependency: &Dependency) -> Option<CellId> {+ match *dependency {+ Dependency::WatchpointSetValid(cell) | Dependency::StableShape(cell) => Some(cell),+ Dependency::GlobalDeclarations { environment, .. }+ | Dependency::GlobalBindingUnassigned { environment, .. } => Some(environment),+ Dependency::GlobalPropertyUnassigned { object, .. } => Some(object),+ Dependency::NoHtmlDdaObjects => None,+ }+}+/// The global declarative environment a dependency names.fn declarative_environment(environment: CellId) -> &'static DeclarativeEnvironment {- // SAFETY: Code that depends on the environment embeds it, which keeps it alive.+ // SAFETY: Only code that is being installed asks, and its compile job keeps the cells it depends on alive.unsafe { &*(environment.0 as *const DeclarativeEnvironment) }}@@ -153,7 +183,7 @@ fn declarative_environment(environment: CellId) -> &'static DeclarativeEnvironmepub fn holds(vm: &Vm, dependency: &Dependency) -> bool {match dependency {Dependency::WatchpointSetValid(validity) => {- // SAFETY: Code that depends on the cell embeds it, which keeps it alive.+ // SAFETY: As in declarative_environment().unsafe { &*(validity.0 as *const WatchpointSet) }.is_valid()}Dependency::GlobalDeclarations { environment, serial } => {@@ -163,7 +193,7 @@ pub fn holds(vm: &Vm, dependency: &Dependency) -> bool {!declarative_environment(*environment).binding_may_have_been_assigned(*index as usize)}Dependency::GlobalPropertyUnassigned { object, offset } => {- // SAFETY: Code that depends on the object embeds it, which keeps it alive.+ // SAFETY: As in declarative_environment().!global_object_slot_may_have_been_assigned(vm, unsafe { &*(object.0 as *const Object) }, *offset)}Dependency::NoHtmlDdaObjects => !vm.jit.htmldda_objects_exist(),@@ -173,7 +203,7 @@ pub fn holds(vm: &Vm, dependency: &Dependency) -> bool {/// The shape a dependency names.fn shape_of(shape: CellId) -> &'static Shape {- // SAFETY: Code that depends on the shape embeds it, which keeps it alive.+ // SAFETY: As in declarative_environment().unsafe { &*(shape.0 as *const Shape) }}diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rsindex 450ab47d435..f54e3002d40 100644--- a/Libraries/LibJS/Rust/src/jit/disabled.rs+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs@@ -109,6 +109,10 @@ pub mod code {pub fn trace_jit_code(&self, _visitor: &mut Visitor) {}+ pub fn trace_embedded_cells_of_jit_code(&self, _vm: &Vm, _visitor: &mut Visitor) {}++ pub fn drop_jit_code_that_lost_embedded_cells(&self, _vm: &Vm, _sweep: &Sweep<'_>) {}+pub fn jit_compile_state(&self) -> CompileState {CompileState::None}@@ -252,7 +256,7 @@ pub mod dependencies {pub struct Dependents;impl Dependents {- pub fn remove_dead_entries(&self, _: &crate::gc::sweep::Sweep<'_>) {}+ pub fn remove_dead_entries(&self, _vm: &Vm, _: &crate::gc::sweep::Sweep<'_>) {}}pub fn invalidate_dependents(_vm: &Vm, _dependency: Dependency) {}diff --git a/Libraries/LibJS/Rust/src/jit/entry_table.rs b/Libraries/LibJS/Rust/src/jit/entry_table.rsindex cc79fd80f29..c1ac273a758 100644--- a/Libraries/LibJS/Rust/src/jit/entry_table.rs+++ b/Libraries/LibJS/Rust/src/jit/entry_table.rs@@ -18,7 +18,7 @@ use core::cell::{Cell, RefCell};use core::ffi::c_void;use core::ptr::NonNull;-use super::code::JitCode;+use super::code::{DetachedJitCode, JitCode};use crate::gc::defer_gc::DeferGc;use crate::gc::sweep::Sweep;@@ -229,10 +229,13 @@ impl JitEntryTable {assert!(self.code_cell(slot).replace(Some(Box::new(code))).is_none());}- /// Drops the code attached to the slot.- pub fn detach_code(&self, slot: u32) {+ /// Drops the code attached to the slot, or moves it to `parking`, whose owner drops it later.+ pub fn detach_code(&self, slot: u32, parking: Option<&RefCell<DetachedJitCode>>) {assert_ne!(slot & JIT_ENTRY_SLOT_MASK, NO_JIT_ENTRY_SLOT);- drop(self.code_cell(slot).take());+ match parking {+ Some(parking) => parking.borrow_mut().extend(self.code_cell(slot).take()),+ None => drop(self.code_cell(slot).take()),+ }}}diff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex 31c6afbf0d8..bd46cb074f0 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -30,6 +30,7 @@ pub mod translate;pub use crate::jit_options as options;use core::cell::{Cell, OnceCell, RefCell};+use core::ffi::c_void;use core::ptr::NonNull;use std::collections::{BTreeMap, HashMap};use std::rc::Rc;@@ -43,6 +44,7 @@ use crate::interpreter::dispatch_tables::DispatchTable;use crate::interpreter::vm::Vm;use crate::layout::cell::{CellHeader, Gc};use crate::layout::execution_context::ExecutionContext;+use code::DetachedJitCode;use code::EntryTrampoline;use code::SnapshotExecutable;use compile_queue::{CompileQueue, CompileResult};@@ -166,6 +168,11 @@ pub struct JitState {/// With the "stress-install" option, the results of finished compile jobs that are not installed yet, with how/// many more tier-up checks they wait for.held_compile_results: RefCell<Vec<(u32, u64, CompileResult)>>,+ /// The code detached while drops were deferred (see `defer_code_drops_until_collection_is_over()`), which a+ /// post-GC task drops.+ codes_detached_in_collection: RefCell<DetachedJitCode>,+ /// Whether code that is detached now goes into `codes_detached_in_collection`.+ defers_code_drops: Cell<bool>,/// With the "stress-invalidate" option, how many more tier-up checks happen before the next invalidation.stress_invalidation_countdown: Cell<u32>,/// With the "coverage" option, how often each coverage key was counted.@@ -233,6 +240,8 @@ impl JitState {stress_random,stress_exit_countdown,held_compile_results: RefCell::default(),+ codes_detached_in_collection: RefCell::default(),+ defers_code_drops: Cell::new(false),stress_invalidation_countdown,coverage: RefCell::default(),warming_up_dispatch_table,@@ -328,6 +337,30 @@ impl JitState {true}+ /// Where code that is detached from its executable now goes to be dropped once the collection in progress is+ /// over, while drops are deferred. Otherwise it is dropped right away.+ pub(crate) fn parking_for_detached_code(&self) -> Option<&RefCell<DetachedJitCode>> {+ self.defers_code_drops+ .get()+ .then_some(&self.codes_detached_in_collection)+ }++ /// Has the code detached until the returned guard goes away kept until the collection in progress is over, for+ /// the sweep callback of a collection that may still rewrite slots in the code.+ pub(crate) fn defer_code_drops_until_collection_is_over<'a>(&'a self, vm: &Vm) -> CodeDropDeferral<'a> {+ assert!(!self.defers_code_drops.replace(true));+ if self.codes_detached_in_collection.borrow().is_empty() {+ // SAFETY: The VM outlives its heap, whose collections run the task.+ unsafe {+ vm.heap().enqueue_post_gc_task(+ drop_codes_detached_in_collection,+ core::ptr::from_ref(vm).cast_mut().cast(),+ );+ }+ }+ CodeDropDeferral(self)+ }+/// With the "coverage" option, counts `key`, which is only formatted then: what compiled code contained when it was/// installed (see `libjs_jit::coverage`), and what happened to it ("exit.BadShape", "discard", "osr-entry", ...).#[inline]@@ -529,3 +562,18 @@ pub fn describe_executable(executable: &Executable) -> String {}format!("{name} ({filename}:{}:{})", entry.line, entry.column)}++/// Defers drops of detached code while it lives (see `JitState::defer_code_drops_until_collection_is_over()`).+pub(crate) struct CodeDropDeferral<'a>(&'a JitState);++impl Drop for CodeDropDeferral<'_> {+ fn drop(&mut self) {+ self.0.defers_code_drops.set(false);+ }+}++unsafe extern "C" fn drop_codes_detached_in_collection(context: *mut c_void) {+ // SAFETY: The task was enqueued with the VM as its context.+ let vm = unsafe { &*context.cast::<Vm>() };+ vm.jit.codes_detached_in_collection.borrow_mut().clear();+}diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex d0cb78f9940..1047a0d798f 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -359,27 +359,13 @@ fn install(defer_gc: &DeferGc<'_>,) {let artifact = compiled.artifact();- let mut embedded_cells: Vec<Gc<CellHeader>> = artifact+ let embedded_cells: Vec<Gc<CellHeader>> = artifact.embedded_cells().map(|cell| {// SAFETY: The snapshot kept every cell it captured alive, and the code embeds only those.unsafe { Gc::from_non_null(NonNull::new(cell.0 as *mut CellHeader).expect("embedded cells are not null")) }}).collect();- // NB: Code that embeds an ECMAScript function may also embed the words its frames start with (see- // `FunctionFrameFields`), whose environments the code then keeps from moving like the cells it lists.- let frame_field_cells: Vec<Gc<CellHeader>> = embedded_cells- .iter()- .filter_map(|cell| cell.downcast::<EcmascriptFunctionObject>())- .flat_map(|function| {- [- function.environment().map(Gc::upcast),- function.private_environment().map(Gc::upcast),- ]- })- .flatten()- .collect();- embedded_cells.extend(frame_field_cells);let id = vm.jit.next_code_id();let mut code = JitCode::new(memory,