Truly independent web browser
LibJS: Let another thread stop the script of a VM
Andreas Klingf6acbc4b6c77
diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex 1fcb87c09ea..2091216d24d 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -444,6 +444,16 @@ bool VM::debugging_enabled() constreturn js_debugger_is_enabled(vm_abi(*this));}+void VM::request_interrupt()+{+ js_vm_request_interrupt(vm_abi(*this));+}++bool VM::interrupt_requested() const+{+ return js_vm_interrupt_requested(vm_abi(*this));+}+Debugger* VM::debugger(){if (!debugging_enabled())diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.hindex e36a5933fc0..746c9219550 100644--- a/Libraries/LibJS/Runtime/VM.h+++ b/Libraries/LibJS/Runtime/VM.h@@ -158,6 +158,12 @@ public:[[nodiscard]] Debugger* debugger();[[nodiscard]] Debugger const* debugger() const;+ // Stops script on this VM for good: it unwinds past every handler, finally blocks included, up to the native code+ // that ran it, and nothing runs on this VM anymore. Native code sees a thrown exception, and whatever it tries to+ // run next throws one as well. Any thread may call this, as long as the VM stays alive until it returns.+ void request_interrupt();+ [[nodiscard]] bool interrupt_requested() const;+#define __JS_ENUMERATE(SymbolName, snake_name) \GC::Ref<Symbol> well_known_symbol_##snake_name() const \{ \diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rsindex cd81bf9a269..2ab593c8afb 100644--- a/Libraries/LibJS/Rust/src/embedding/vm.rs+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs@@ -232,6 +232,29 @@ pub unsafe extern "C" fn js_vm_set_source_text_syntaxes(vm: *mut JSVM, stack_fra);}+/// Stops script on the VM for good: it unwinds past every handler, and nothing runs on the VM from then on. Any thread+/// may call this.+///+/// # Safety+///+/// `vm` must stay alive until this returns.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_request_interrupt(vm: *mut JSVM) {+ // SAFETY: The caller keeps the VM alive, and the call only touches its atomics.+ unsafe { vm_from_abi(vm) }.request_interrupt();+}++/// Whether js_vm_request_interrupt() was called on the VM. Any thread may call this.+///+/// # Safety+///+/// `vm` must stay alive until this returns.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_interrupt_requested(vm: *mut JSVM) -> bool {+ // SAFETY: The caller keeps the VM alive, and the call only touches its atomics.+ unsafe { vm_from_abi(vm) }.interrupt_requested()+}+/// Makes `agent` the surrounding agent of the VM: its [[CanBlock]] says whether Atomics.wait() may block, and await in/// native code spins its event loop until the awaited promise settles. Without an agent, which a null `agent` sets,/// Atomics.wait() may block and await runs the VM's own queue of promise jobs, which is empty if an enqueue_promise_jobdiff --git a/Libraries/LibJS/Rust/src/interpreter/dispatch_tables.rs b/Libraries/LibJS/Rust/src/interpreter/dispatch_tables.rsindex c515fccaf0b..aa5d8d50d5b 100644--- a/Libraries/LibJS/Rust/src/interpreter/dispatch_tables.rs+++ b/Libraries/LibJS/Rust/src/interpreter/dispatch_tables.rs@@ -8,7 +8,9 @@//! executable's frames with.use core::ffi::c_void;+use core::sync::atomic::{AtomicPtr, Ordering, fence};+use crate::bytecode::instruction::NUM_OPCODES;use crate::interpreter::vm::Vm;/// How many entries a dispatch table has: one per possible opcode byte.@@ -43,21 +45,78 @@ pub fn debug_dispatch_table() -> *const c_void {table_address(&js_interpreter_debug_dispatch_table)}+/// The most tables a VM runs executables with: one for each interpreter tier (see `InterpreterTier`).+const MAX_TIER_COUNT: usize = 4;++/// The dispatch tables a VM's interpreter runs with. They start as copies of the tables above, which are immutable and+/// shared by all VMs, so that another thread can stop this VM's interpreter wherever it is. The table a running+/// interpreter dispatches through lives in a register, out of reach of other threads, but what that table holds is+/// not. That makes the interrupt free for the interpreter (see `Vm::request_interrupt()`): a check at every back edge+/// costs tight loops several percent.+pub struct VmDispatchTables {+ tables: Box<[[AtomicPtr<c_void>; DISPATCH_TABLE_SIZE]; MAX_TIER_COUNT]>,+}++impl VmDispatchTables {+ pub fn new() -> Self {+ Self {+ tables: Box::new(core::array::from_fn(|_| {+ core::array::from_fn(|_| AtomicPtr::new(core::ptr::null_mut()))+ })),+ }+ }++ /// Makes the table at `index` a copy of `source`, and returns it.+ fn copy(&self, index: usize, source: *const c_void) -> *const c_void {+ let table = &self.tables[index];+ // SAFETY: Dispatch tables have DISPATCH_TABLE_SIZE entries, and this only reads the immutable ones.+ let source = unsafe { &*source.cast::<DispatchTable>() };+ for (entry, handler) in table.iter().zip(source) {+ entry.store(handler.cast_mut(), Ordering::Relaxed);+ }+ table.as_ptr().cast()+ }++ /// Makes the interpreter call the fallback handler at its next dispatch in every table, which any thread may do.+ pub fn stop_dispatching(&self) {+ const { assert!((NUM_OPCODES as usize) < DISPATCH_TABLE_SIZE) };+ let fallback_handler = plain_handlers()[DISPATCH_TABLE_SIZE - 1].cast_mut();+ for entry in self.tables.iter().flatten() {+ entry.store(fallback_handler, Ordering::Relaxed);+ }+ }+}++impl Default for VmDispatchTables {+ fn default() -> Self {+ Self::new()+ }+}+impl Vm {- /// Fills in the VM's dispatch tables: the debug table at every index while the VM is debugging, and otherwise the- /// table of each interpreter tier at its index and the plain table at every other index.+ /// Fills in the VM's dispatch tables: copies of the debug table while the VM is debugging, and otherwise of the+ /// table of each interpreter tier at its index, with the plain table at every other index.pub(crate) fn update_dispatch_tables(&self) {- if self.debugging_enabled() {- for table in &self.head.dispatch_tables {- table.set(debug_dispatch_table());+ let source_of = |table| {+ if self.debugging_enabled() {+ debug_dispatch_table()+ } else {+ table}- return;- }+ };+ let plain_table = self.own_dispatch_tables.copy(0, source_of(plain_dispatch_table()));for table in &self.head.dispatch_tables {- table.set(plain_dispatch_table());+ table.set(plain_table);}for (tier, table) in self.jit.dispatch_tables() {+ let table = self.own_dispatch_tables.copy(tier as usize, source_of(table));self.head.dispatch_tables[tier as usize].set(table);}++ // NB: An interrupt that came in while this ran must not get lost.+ fence(Ordering::SeqCst);+ if self.interrupt_requested() {+ self.own_dispatch_tables.stop_dispatching();+ }}}diff --git a/Libraries/LibJS/Rust/src/interpreter/run.rs b/Libraries/LibJS/Rust/src/interpreter/run.rsindex f45bcbef50e..18f41d9c2ee 100644--- a/Libraries/LibJS/Rust/src/interpreter/run.rs+++ b/Libraries/LibJS/Rust/src/interpreter/run.rs@@ -100,7 +100,11 @@ impl Vm {this_register.set(context_ref.this_value.get());}- if self.interpreter_stack().is_exhausted() || self.did_reach_stack_space_limit() {+ if self.interrupt_requested() {+ context_ref+ .register(register::EXCEPTION)+ .set(self.interrupt_exception());+ } else if self.interpreter_stack().is_exhausted() || self.did_reach_stack_space_limit() {let Err(throw) =self.throw_completion::<()>(ErrorKind::InternalError, ErrorType::CallStackSizeExceeded, &[])else {@@ -578,7 +582,14 @@ impl Vm {/// Unwinds to the innermost handler of an exception thrown at `program_counter` in the running frame, leaving/// frames the interpreter entered without returning to the runtime.+ ///+ /// Once the VM is interrupted, whatever was thrown becomes the interrupt exception, which no handler catches, not+ /// even a finally block: it unwinds to the native caller, and no script runs on the way.pub fn handle_exception(&self, mut program_counter: u32, exception: Value) -> HandleExceptionResponse {+ if self.interrupt_requested() {+ return self.unwind_for_interrupt();+ }+// An exception that unwinds out to a native caller enters here again in the frame that called it, so remember// only where it was first thrown.if !self.is_last_throw(exception) {@@ -671,6 +682,28 @@ impl Vm {return HandleExceptionResponse::ExitFromExecutable;}}++ /// Like handle_exception() for a thrown interrupt: leaves frames the interpreter entered, up to one that a native+ /// caller waits for. A native caller that goes on to run code gets the same exception, as the VM stays interrupted.+ #[cold]+ #[inline(never)]+ fn unwind_for_interrupt(&self) -> HandleExceptionResponse {+ let exception = self.interrupt_exception();+ loop {+ let context_pointer = self+ .running_execution_context()+ .expect("an exception is thrown in a running frame");+ // SAFETY: The running context is live until it is deallocated below.+ let context = unsafe { context_pointer.as_ref() };+ let caller_frame = context.caller_frame.get();+ if context.returns_to_native_caller.get() || caller_frame.is_null() {+ context.register(register::EXCEPTION).set(exception);+ return HandleExceptionResponse::ExitFromExecutable;+ }+ self.interpreter_stack().deallocate(context_pointer.as_ptr().cast());+ self.head.running_execution_context.set(caller_frame);+ }+ }}#[derive(Clone, Copy, Debug, PartialEq, Eq)]diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rsindex b9db8b734b8..f0c46ceee85 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs@@ -127,9 +127,12 @@ pub fn debugger_check_breakpoint(vm: &Vm, pc: u32) {debugger.set_did_pause_before_current_instruction(did_pause);}-pub fn fallback_handler(_pc: u32) -> SlowPathControl {- // NB: Every bytecode opcode has a DSL handler, so this should never run.- unreachable!("every bytecode opcode has a handler")+/// Every dispatch table entry of an interrupted VM leads here, which stops the interpreter (see+/// `Vm::request_interrupt()`).+pub fn fallback_handler(vm: &Vm, pc: u32) -> SlowPathControl {+ // NB: Every bytecode opcode has a DSL handler, so nothing else gets here.+ assert!(vm.interrupt_requested(), "every bytecode opcode has a handler");+ handle_asm_exception(vm, pc, vm.interrupt_exception())}/// The array of an array literal with `elements`, where the empty value is a hole.diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rsindex 7f22f85033c..651ca2739de 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/mod.rs@@ -1296,8 +1296,8 @@ impl RuntimeFunctions for Runtime {control::debugger_check_breakpoint(vm, pc);}- fn fallback_handler(_vm: &Vm, pc: u32, _instruction: *const u8) -> SlowPathControl {- control::fallback_handler(pc)+ fn fallback_handler(vm: &Vm, pc: u32, _instruction: *const u8) -> SlowPathControl {+ control::fallback_handler(vm, pc)}fn new_array(diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 02ceaeb9acc..94cf4f075df 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -8,6 +8,7 @@ use core::cell::{Cell, OnceCell, Ref, RefCell};use core::ffi::c_void;use core::ops::ControlFlow;use core::ptr::NonNull;+use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering, fence};use std::collections::HashMap;use std::collections::HashSet;use std::collections::VecDeque;@@ -16,6 +17,7 @@ use std::rc::Rc;use ak::{Utf16FlyString, Utf16String};use libjs_runtime_macros::Trace;+use super::dispatch_tables::VmDispatchTables;use super::interpreter_stack::InterpreterStackMemory;use crate::build_configuration::VM_STACK_SPACE_LIMIT;use crate::bytecode::executable::{@@ -509,7 +511,13 @@ pub struct Vm {/// The lowest native stack address JIT code runs at, JIT_NATIVE_STACK_HEADROOM above the native stack limit./// Below it, JIT code leaves calls to the interpreter, which runs JavaScript on its own stack, so that the code/// running after a stack overflow (catch blocks and the native functions they call) does not overflow again.- pub jit_native_stack_limit: Cell<usize>,+ /// Atomic since request_interrupt() raises it past every stack pointer from any thread, which sends JIT code that+ /// is entered from then on to the interpreter without JIT code ever having to check for that.+ pub jit_native_stack_limit: AtomicUsize,+ /// Set once script on this VM has to stop for good (see request_interrupt()). Any thread may set it.+ interrupt_requested: AtomicBool,+ /// The tables `VmHead::dispatch_tables` points to.+ pub(crate) own_dispatch_tables: VmDispatchTables,heap: OnceCell<Heap>,_interpreter_stack_memory: InterpreterStackMemory,/// The storage of the execution context stack, whose length is its capacity. The head points into it and knows@@ -545,6 +553,9 @@ pub struct Vm {cached_strings: OnceCell<CachedStrings>,single_ascii_character_strings: OnceCell<[Gc<PrimitiveString>; SINGLE_ASCII_CHARACTER_STRING_COUNT]>,well_known_symbols: OnceCell<WellKnownSymbols>,+ /// What unwinds script after an interrupt (see request_interrupt()). Nothing can allocate it at that point, and+ /// script never gets to see it.+ interrupt_exception: OnceCell<Gc<Symbol>>,global_symbol_registry: OnceCell<Gc<GlobalSymbolRegistry>>,/// The executables whose inline caches the sweep callback prunes. The list is weak: the callback drops the@@ -678,7 +689,9 @@ impl Vm {keyed_property_lookup_cache_entries: Cell::new(core::ptr::null()),dispatch_tables: [const { Cell::new(core::ptr::null()) }; DISPATCH_TABLE_COUNT],},- jit_native_stack_limit: Cell::new(0),+ jit_native_stack_limit: AtomicUsize::new(0),+ interrupt_requested: AtomicBool::new(false),+ own_dispatch_tables: VmDispatchTables::new(),heap: OnceCell::new(),_interpreter_stack_memory: interpreter_stack_memory,execution_context_stack_storage: RefCell::new(execution_context_stack_storage),@@ -707,6 +720,7 @@ impl Vm {cached_strings: OnceCell::new(),single_ascii_character_strings: OnceCell::new(),well_known_symbols: OnceCell::new(),+ interrupt_exception: OnceCell::new(),global_symbol_registry: OnceCell::new(),executables: RefCell::new(Vec::new()),static_property_lookup_caches: StaticPropertyLookupCaches::new(),@@ -775,8 +789,10 @@ impl Vm {vm.head.native_stack_limit.set(heap.stack_bounds().0 + VM_STACK_SPACE_LIMIT as usize);- vm.jit_native_stack_limit- .set(vm.head.native_stack_limit.get() + JIT_NATIVE_STACK_HEADROOM);+ vm.jit_native_stack_limit.store(+ vm.head.native_stack_limit.get() + JIT_NATIVE_STACK_HEADROOM,+ Ordering::Relaxed,+ );if vm.heap.set(heap).is_err() {unreachable!("the heap is created once");}@@ -817,6 +833,11 @@ impl Vm {});let _ = self.well_known_symbols.set(WellKnownSymbols::create(self));+ let _ = self.interrupt_exception.set(Symbol::create(+ self,+ Some(Utf16String::from_utf8("interrupt")),+ symbol::Kind::Unique,+ ));let _ = self.global_symbol_registry.set(GlobalSymbolRegistry::create(self));let _ = self.job_queues.set(self.heap().allocate(|_| JobQueues {header: CellHeader::for_class(JobQueues::CLASS),@@ -858,6 +879,47 @@ impl Vm {self.head.native_stack_limit.get()}+ /// Stops script on this VM for good. This and interrupt_requested() are the only methods of a VM that any thread+ /// may call, as they stay away from everything else in it. The VM must stay alive until it returns, which an owner+ /// that joins the VM's thread before destroying the VM ensures.+ ///+ /// Script costs nothing to run for this: the interpreter stops at its next dispatch, as every dispatch table entry+ /// becomes the fallback handler, and JIT code stops at its next call or loop back edge, which compare the stack+ /// pointer with a limit anyway, so raising the limit past every stack pointer does it. Blocking native functions+ /// poll the flag.+ ///+ /// Script unwinds with interrupt_exception(), past every handler. The flag is never cleared: every later attempt to+ /// run code fails at once, which is what makes the places in native code that catch exceptions harmless. They can+ /// only ever try to run more code.+ pub fn request_interrupt(&self) {+ self.interrupt_requested.store(true, Ordering::SeqCst);+ self.jit_native_stack_limit.store(usize::MAX, Ordering::Relaxed);+ fence(Ordering::SeqCst);+ self.own_dispatch_tables.stop_dispatching();+ }+ }++ #[inline]+ pub fn interrupt_requested(&self) -> bool {+ self.interrupt_requested.load(Ordering::Relaxed)+ }++ /// What an interrupted VM throws.+ pub fn interrupt_exception(&self) -> Value {+ Value::from_symbol(+ *self+ .interrupt_exception+ .get()+ .expect("the VM allocates its interrupt exception"),+ )+ }++ /// Throws interrupt_exception() from native code that noticed the interrupt.+ #[cold]+ pub fn throw_interrupt<T>(&self) -> ThrowCompletionOr<T> {+ Err(Throw::new(self.interrupt_exception()))+ }+pub fn push_execution_context(&self, context: NonNull<ExecutionContext>) {// SAFETY: The caller passes a live context.let context_ref = unsafe { context.as_ref() };@@ -1104,6 +1166,7 @@ impl Vm {self.json_stringify_cache.trace(visitor);self.cached_strings.trace(visitor);self.well_known_symbols.trace(visitor);+ self.interrupt_exception.trace(visitor);self.global_symbol_registry.trace(visitor);self.head.type_error_realm_override.trace(visitor);self.job_queues.trace(visitor);@@ -1612,7 +1675,10 @@ impl Vm {pub fn run_queued_promise_jobs(&self) {// A reaction must finish settling its result promise before another job starts, even if its callback runs// bytecode that would otherwise trigger another checkpoint.- if self.running_promise_jobs.get() || self.job_queues().promise_jobs.borrow().is_empty() {+ if self.running_promise_jobs.get()+ || self.job_queues().promise_jobs.borrow().is_empty()+ || self.interrupt_requested()+ {return;}self.run_queued_promise_jobs_impl(|| false);@@ -1627,7 +1693,7 @@ impl Vm {fn run_queued_promise_jobs_impl(&self, should_stop: impl Fn() -> bool) {let was_running_promise_jobs = self.running_promise_jobs.replace(true);let job_queues = self.job_queues();- while !should_stop() {+ while !should_stop() && !self.interrupt_requested() {let Some(job) = job_queues.promise_jobs.borrow_mut(self).pop_front() else {break;};@@ -1648,7 +1714,8 @@ impl Vm {pub fn run_queued_finalization_registry_cleanup_jobs(&self) {let job_queues = self.job_queues();- loop {+ // NB: A cleanup that fails is queued again, and it would fail forever once interrupted.+ while !self.interrupt_requested() {let Some(finalization_registry) = job_queues.finalization_registry_cleanup_jobs.borrow_mut(self).pop()else {break;diff --git a/Libraries/LibJS/Rust/src/runtime/completion.rs b/Libraries/LibJS/Rust/src/runtime/completion.rsindex 1049d25dcc8..d392a83958f 100644--- a/Libraries/LibJS/Rust/src/runtime/completion.rs+++ b/Libraries/LibJS/Rust/src/runtime/completion.rs@@ -214,12 +214,19 @@ pub fn r#await(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {// Embedder case (i.e. LibWeb). Runs all promise jobs by performing a microtask checkpoint.// NB: The goal condition reads the outcome itself, as a copy taken before the promise settles would never// make it true.- agent.spin_event_loop_until(vm, &|| awaited_completion.success.get().is_some());+ agent.spin_event_loop_until(vm, &|| {+ awaited_completion.success.get().is_some() || vm.interrupt_requested()+ });} else {// No embedder, standalone LibJS implementationvm.run_queued_promise_jobs_for_await(|| awaited_completion.success.get().is_some());}+ // NB: The jobs that would settle the promise do not run anymore.+ if vm.interrupt_requested() {+ return vm.throw_interrupt();+ }+// 8. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.// NOTE: Since we don't push any EC, this step is not performed.