Truly independent web browser
LibWasm+LibJS+LibWeb: Stop WebAssembly code on an interrupt
Andreas Kling5723e6d14b92
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 0ebb81da45c..91449b7114b 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -8,12 +8,12 @@ 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 core::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering, fence};use std::collections::HashMap;use std::collections::HashSet;use std::collections::VecDeque;use std::rc::Rc;-use std::sync::Arc;+use std::sync::{Arc, Mutex, PoisonError};use ak::futex::WaitInterrupt;use ak::{Utf16FlyString, Utf16String};@@ -518,10 +518,13 @@ pub struct Vm {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,- /// What wakes this VM's thread from Atomics.wait() for an interrupt.+ /// What wakes this VM's thread from Atomics.wait() and memory.atomic.wait for an interrupt.wait_interrupt: Arc<WaitInterrupt>,/// The tables `VmHead::dispatch_tables` points to.pub(crate) own_dispatch_tables: VmDispatchTables,+ /// The word that stops the WebAssembly code of this VM's agent (see set_wasm_stack_limit_word()), if it has any.+ /// The lock keeps the word from going away during an interrupt.+ wasm_stack_limit_word: Mutex<*const AtomicU64>,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@@ -697,6 +700,7 @@ impl Vm {interrupt_requested: AtomicBool::new(false),wait_interrupt: Arc::new(WaitInterrupt::new()),own_dispatch_tables: VmDispatchTables::new(),+ wasm_stack_limit_word: Mutex::new(core::ptr::null()),heap: OnceCell::new(),_interpreter_stack_memory: interpreter_stack_memory,execution_context_stack_storage: RefCell::new(execution_context_stack_storage),@@ -904,6 +908,14 @@ impl Vm {self.jit_native_stack_limit.store(usize::MAX, Ordering::Relaxed);fence(Ordering::SeqCst);self.own_dispatch_tables.stop_dispatching();+ let word = self+ .wasm_stack_limit_word+ .lock()+ .unwrap_or_else(PoisonError::into_inner);+ // SAFETY: Whoever set the word clears it before it goes away, which takes the lock.+ if let Some(word) = unsafe { word.as_ref() } {+ word.store(u64::MAX, Ordering::Relaxed);+ }self.wait_interrupt.interrupt();}@@ -911,6 +923,24 @@ impl Vm {pub fn wait_interrupt(&self) -> &Arc<WaitInterrupt> {&self.wait_interrupt}++ /// Has an interrupt also store the highest address to `word` (null for none), which is how the embedder's+ /// WebAssembly store learns of it. Only the VM's thread may call this.+ ///+ /// # Safety+ ///+ /// `word` must be null, or point to a word that stays live until it is replaced or cleared by another call.+ pub unsafe fn set_wasm_stack_limit_word(&self, word: *const AtomicU64) {+ *self+ .wasm_stack_limit_word+ .lock()+ .unwrap_or_else(PoisonError::into_inner) = word;+ // SAFETY: The caller guarantees that the word is live, or null.+ if self.interrupt_requested()+ && let Some(word) = unsafe { word.as_ref() }+ {+ word.store(u64::MAX, Ordering::Relaxed);+ }}#[inline]diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rsindex 3c9138dcd45..9c4a0ce669f 100644--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs@@ -280,11 +280,14 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {}};let timeout = (timeout >= 0).then(|| std::time::Duration::from_nanos(timeout as u64));- match futex::atomic_wait(word, expected, timeout, None) {+ match futex::atomic_wait(word, expected, timeout, store.wait_interrupt.as_deref()) {AtomicWaitResult::Woken => 0,AtomicWaitResult::NotEqual => 1,AtomicWaitResult::TimedOut => 2,- AtomicWaitResult::Interrupted => unreachable!("nothing can interrupt this wait"),+ AtomicWaitResult::Interrupted => {+ store.pending_trap = Some(Trap::StackExhausted);+ crate::abi::WAIT_CANNOT_BLOCK+ }}}diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rsindex 07006a64074..b6ae1fa1b86 100644--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs@@ -277,9 +277,16 @@ pub(crate) fn enabled() -> bool {}impl Store {+ fn compile_state(&mut self) -> &mut StoreJit {+ let stack_limit = self.stack_limit_word() as u64;+ let jit = self.jit.get_or_insert_with(Default::default);+ jit.stack_limit = stack_limit;+ jit+ }+/// Keeps everything in this store interpreted, whatever `LIBWASM_JIT` says, as tests comparing the tiers want.pub fn disable_jit(&mut self) {- self.jit.get_or_insert_with(Default::default).disabled = true;+ self.compile_state().disabled = true;}}@@ -958,7 +965,7 @@ mod native {unreachable!("the function is a WebAssembly function");};let body = &module.code[(*index - module.imported_function_count) as usize];- let jit = store.jit.get_or_insert_with(Default::default);+ let jit = store.compile_state();let key = jit.key(module, *index, Some(body.code.start));assert_eq!(jit.compile(key, super::Compile::Now), super::CompileState::Compiled);unsafe { loops.get_mut() }.header.tier_up_budget = crate::abi::TIER_UP_CALL_COST;@@ -1206,6 +1213,8 @@ mod native {/// instances hold it, and code of a module only runs in frames of its functions.#[derive(Default)]pub struct StoreJit {+ /// The address of the store's stack limit, which compiled code polls.+ pub stack_limit: u64,context: CompileContext,/// What the store compiled of each module, by the module's address.modules: HashMap<usize, ModuleCode>,@@ -1277,6 +1286,7 @@ mod native {module: self.modules[&key.module].module.upgrade()?,function: key.function,runtime: stubs().runtime,+ stack_limit: self.stack_limit,options: super::options().compile_options(),osr: key.osr,})@@ -1446,7 +1456,7 @@ mod native {/// Compiles every function of an instance, on the compile threads unless in sync mode, and installs the code.pub fn compile_instance(store: &mut Store, instance: InstanceAddress) {let functions = store.instance(instance).functions.clone();- let jit = store.jit.get_or_insert_with(Default::default);+ let jit = store.compile_state();if jit.disabled {return;}@@ -1469,7 +1479,7 @@ mod native {/// Compiles a WebAssembly function, unless the store compiled its module's function already, and installs the/// code once there is some.pub fn compile_function(store: &mut Store, address: FunctionAddress, when: Compile) -> CompileState {- let jit = store.jit.get_or_insert_with(Default::default);+ let jit = store.compile_state();if jit.disabled {return CompileState::Failed;}@@ -1680,7 +1690,7 @@ mod native {return LoopEntry::Never;};let offset = (pc - module.bytes.as_ptr() as u64) as u32;- let jit = store.jit.get_or_insert_with(Default::default);+ let jit = store.compile_state();if jit.disabled {return LoopEntry::Never;}@@ -1728,6 +1738,7 @@ mod native {#[derive(Default)]pub struct StoreJit {+ pub stack_limit: u64,pub disabled: bool,}diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex ce8ca5a8544..8e21d4c9b7b 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -45,14 +45,17 @@ pub mod ranges;use crate::abi::{EntryRecord, ExecutionContext, FRAME_HEADER_SIZE, FUNCTION_KIND_HOST, FUNCTION_KIND_WASM,- FUNCTION_KIND_WASM_VECTOR, FunctionHeader, InstanceData, SPILL_AREA_SIZE, Segment, TableData,+ FUNCTION_KIND_WASM_VECTOR, FunctionHeader, InstanceData, SPILL_AREA_SIZE, STACK_LIMIT_INTERRUPTED, Segment,+ TableData,};use crate::module::{DataMode, ElementItems, ElementMode, ExternalKind, ImportDescription, Module};use crate::types::{FuncType, GlobalType, HeapType, RefType, TableType, TypeCanonicalizer, ValType};+use ak::futex::WaitInterrupt;use memory::MemoryInstance;use std::collections::HashMap;use std::rc::Rc;use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};/// A value as the runtime's API sees it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -387,6 +390,9 @@ pub struct Store {/// Whether the agent the store runs code for may block, its [[CanBlock]]: `memory.atomic.wait` traps where it/// may not. The embedder decides (a browser's window agents may not block).pub can_block: bool,+ /// What lets another thread end a `memory.atomic.wait` of this store's code. The embedder sets this, along with+ /// whatever makes it stop the store.+ pub wait_interrupt: Option<Arc<WaitInterrupt>>,/// The store's compiled code, once it has some.jit: Option<jit::StoreJit>,}@@ -422,7 +428,7 @@ impl Store {interpreter::install_fault_handler();Self {context: Box::new(ExecutionContext {- stack_limit: 0,+ stack_limit: AtomicU64::new(0),entry_fp: 0,entry_record: std::ptr::null_mut(),store: std::ptr::null_mut(),@@ -441,10 +447,17 @@ impl Store {rtt_pointers: Vec::new(),memory_grow_callback: None,can_block: true,+ wait_interrupt: None,jit: None,}}+ /// What another thread stores `STACK_LIMIT_INTERRUPTED` to, to stop the code of this store for good. It stays where+ /// it is for as long as the store lives.+ pub fn stack_limit_word(&self) -> *const AtomicU64 {+ &raw const self.context.stack_limit+ }+/// Have the heap keep the runtime types for as long as the store lives. The store must not move after this.pub fn attach_to_heap(&mut self) {let Some(heap) = self.heap.gc() else {@@ -1177,7 +1190,16 @@ impl Store {let header: *const FunctionHeader = &raw const function.header;let is_outermost = self.context.entry_record.is_null();if is_outermost {- self.context.stack_limit = interpreter::stack_limit(STACK_RESERVE);+ // NB: The limit is the one thing another thread writes, and an interrupt must stick.+ let limit = self.context.stack_limit.load(Ordering::Relaxed);+ if limit != STACK_LIMIT_INTERRUPTED {+ let _ = self.context.stack_limit.compare_exchange(+ limit,+ interpreter::stack_limit(STACK_RESERVE),+ Ordering::Relaxed,+ Ordering::Relaxed,+ );+ }}let large_images = jit::large_images_in_use();self.context.store = (self as *mut Store).cast();diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rsindex b7368de758d..d4a299c782a 100644--- a/Libraries/LibWasm/Engine/tests/execution.rs+++ b/Libraries/LibWasm/Engine/tests/execution.rs@@ -469,3 +469,98 @@ fn calls_between_the_tiers_with_many_values() {};assert_eq!(run(false), run(true));}++/// (func (export "spin") (loop (br 0)))+const LOOP_FOREVER: &[u8] = &[+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0x07,+ 0x08, 0x01, 0x04, 0x73, 0x70, 0x69, 0x6e, 0x00, 0x00, 0x0a, 0x09, 0x01, 0x07, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b,+ 0x0b,+];++/// Runs LOOP_FOREVER in `store` while another thread interrupts the store.+fn interrupt_a_loop(mut store: Store, delay: std::time::Duration) {+ let module = libwasm_engine::compile(LOOP_FOREVER).unwrap();+ let instance = store.instantiate(Arc::new(module), &[]).unwrap();+ let word = store.stack_limit_word() as usize;+ let interrupter = std::thread::spawn(move || {+ std::thread::sleep(delay);+ // SAFETY: The store outlives this thread.+ let word = unsafe { &*(word as *const std::sync::atomic::AtomicU64) };+ word.store(+ libwasm_engine::abi::STACK_LIMIT_INTERRUPTED,+ std::sync::atomic::Ordering::Relaxed,+ );+ });+ assert_eq!(call(&mut store, instance, "spin", &[]), Err(Trap::StackExhausted));+ interrupter.join().unwrap();++ // NB: It stays that way.+ assert_eq!(call(&mut store, instance, "spin", &[]), Err(Trap::StackExhausted));+}++#[test]+fn another_thread_interrupts_an_interpreted_loop() {+ let mut store = Store::new();+ store.disable_jit();+ interrupt_a_loop(store, std::time::Duration::from_millis(50));+}++#[test]+fn another_thread_interrupts_a_compiled_loop() {+ // NB: The loop tiers up on the way there, wherever the JIT runs.+ interrupt_a_loop(Store::new(), std::time::Duration::from_millis(500));+}++/// Starts a memory.atomic.wait on a thread of its own, which `interrupt` can end, and returns the address of its word.+fn start_wait(+ timeout: i64,+ interrupt: Arc<ak::futex::WaitInterrupt>,+ disable_jit: bool,+) -> (usize, std::thread::JoinHandle<Result<Vec<Value>, Trap>>) {+ let (sender, receiver) = std::sync::mpsc::channel();+ let waiter = std::thread::spawn(move || {+ let mut store = Store::new();+ if disable_jit {+ store.disable_jit();+ }+ store.wait_interrupt = Some(interrupt);+ let instance = instantiate(&mut store, "shared_memory_export.wasm");+ let Some(ExternValue::Memory(memory)) = store.instance(instance).export("memory") else {+ panic!("no memory export");+ };+ sender.send(store.memory(memory).bytes().as_ptr() as usize).unwrap();+ call(+ &mut store,+ instance,+ "wait",+ &[Value::I32(8), Value::I32(0), Value::I64(timeout)],+ )+ });+ (receiver.recv().unwrap() + 8, waiter)+}++#[test]+fn another_thread_interrupts_a_wait() {+ for disable_jit in [false, true] {+ // No timeout, and ten minutes.+ for timeout in [-1, 600_000_000_000] {+ let interrupt = Arc::new(ak::futex::WaitInterrupt::new());+ let (_, waiter) = start_wait(timeout, interrupt.clone(), disable_jit);+ std::thread::sleep(std::time::Duration::from_millis(50));+ interrupt.interrupt();+ assert_eq!(waiter.join().unwrap(), Err(Trap::StackExhausted));+ }+ }+}++/// Only a wake ends a wait: it does not look at the word again.+#[cfg(target_os = "linux")]+#[test]+fn a_change_of_the_word_does_not_end_a_wait() {+ let interrupt = Arc::new(ak::futex::WaitInterrupt::new());+ let (address, waiter) = start_wait(300_000_000, interrupt, false);+ std::thread::sleep(std::time::Duration::from_millis(100));+ // SAFETY: The word is in the memory of the store, which lives until the wait is over.+ unsafe { &*(address as *const std::sync::atomic::AtomicU32) }.store(1, std::sync::atomic::Ordering::SeqCst);+ assert_eq!(waiter.join().unwrap(), Ok(vec![Value::I32(2)]));+}diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flapindex ae8345197f3..84eb9026794 100644--- a/Libraries/LibWasm/Interpreter/interpreter.flap+++ b/Libraries/LibWasm/Interpreter/interpreter.flap@@ -902,6 +902,14 @@ handler Block() @opcode(0x02) {}handler Loop() @opcode(0x03) {+ # Another thread stops the code of a store by making its stack limit the highest address. Calls notice, but only+ # this stops a loop that does not call.+ let interrupt_context = context();+ let mut stack_limit: u64;+ load64(stack_limit, [interrupt_context, CONTEXT_STACK_LIMIT]);+ if stack_limit + 1 == 0 @cold {+ trap_with(TRAP_STACK_EXHAUSTED, interrupt_context);+ }let function = frame_word(FRAME_FUNCTION);let mut budget: u64;load32(budget, [function, FUNCTION_TIER_UP_BUDGET]);diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex 09a59d02ebd..9349a8b96f9 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -99,6 +99,7 @@ truncations, unless their flags say they cannot), and are neither removed nor mo| CheckFunction, CheckNull | The checks of `call_indirect` (null, then type identity, then the subtype check of GC types) and of references that must not be null. || Call | A call through a `FunctionHeader`, direct or not; its value is the first result. || Helper | A call of a function of the runtime, which takes its operands in the context and may return a trap code. |+| CheckInterrupt | Traps if another thread interrupted the store (section on calls, "Interrupts"). || CallResult | A further result of the call right before it. Never removed, since the results' places depend on them all. || Jump, Branch, BranchCompare, BranchFloatCompare, BrTable, Return, Trap, TailCall | Terminators. A branch goes to its first successor where its condition holds. |@@ -244,6 +245,14 @@ The prologue writes the instance to the frame and checks the new rsp against thethe store's `ExecutionContext`, which `InstanceData::context` points at, trapping with`TRAP_STACK_EXHAUSTED`. `RuntimeInfo` has the trap exit.+**Interrupts.** Another thread stops the code of a store by making that limit+`STACK_LIMIT_INTERRUPTED`, above every stack pointer. Calls then trap in their prologue at no cost,+and `CheckInterrupt`, in the header of every loop, compares the limit with rsp for code that does+not call. Each store has its own code, so x86-64 code has the limit's address as a constant: a move,+a compare and a branch to the shared trap stub, which take no allocatable register. aarch64 reaches+it through the frame's instance. The embedder turns the trap into whatever stopped the store;+nothing else can observe it.+**Calls.** Every call goes through `FunctionHeader::native_entry`. A direct call of a function ofthe same instance passes the caller's instance and memory base; any other call (imports,`call_indirect`, `call_ref`) passes the callee's, from its header (`CalleeInstance`). `call_indirect`diff --git a/Libraries/LibWasm/JIT/examples/compile_all.rs b/Libraries/LibWasm/JIT/examples/compile_all.rsindex 582524e7a4b..a2a37295ec6 100644--- a/Libraries/LibWasm/JIT/examples/compile_all.rs+++ b/Libraries/LibWasm/JIT/examples/compile_all.rs@@ -136,6 +136,7 @@ fn timed_compile(module: &Arc<libwasm_engine::Module>, functions: &[u32], threadbreak;};let request = CompileRequest {+ stack_limit: 0,osr: None,module: module.clone(),function,@@ -182,6 +183,7 @@ fn main() {options.dump_ir = !arguments.quiet;options.stats = true;let request = CompileRequest {+ stack_limit: 0,osr: arguments.osr,module: module.clone(),function,@@ -192,6 +194,7 @@ fn main() {let mut best = None::<Vec<u64>>;for _ in 1..arguments.runs {let quiet = CompileRequest {+ stack_limit: 0,osr: None,module: module.clone(),function,@@ -242,6 +245,7 @@ fn main() {let mut failures: BTreeMap<&'static str, usize> = BTreeMap::new();for index in 0..module.code.len() as u32 {let request = CompileRequest {+ stack_limit: 0,osr: None,module: module.clone(),function: first + index,@@ -269,6 +273,7 @@ fn main() {for run in 0..arguments.runs.max(1) {for (position, &function) in compiled.iter().enumerate() {let request = CompileRequest {+ stack_limit: 0,osr: None,module: module.clone(),function,diff --git a/Libraries/LibWasm/JIT/examples/osr_check.rs b/Libraries/LibWasm/JIT/examples/osr_check.rsindex 9ed745090d0..7322ab805f4 100644--- a/Libraries/LibWasm/JIT/examples/osr_check.rs+++ b/Libraries/LibWasm/JIT/examples/osr_check.rs@@ -60,6 +60,7 @@ fn main() {if let Some((function, pc)) = dump {let mut context = CompileContext::default();let request = CompileRequest {+ stack_limit: 0,module: module.clone(),function,runtime: RUNTIME,@@ -101,6 +102,7 @@ fn main() {}for pc in loops {let request = CompileRequest {+ stack_limit: 0,module: module.clone(),function: first + index,runtime: RUNTIME,diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rsindex bac54b120c1..5d75ddf30aa 100644--- a/Libraries/LibWasm/JIT/src/builder/mod.rs+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs@@ -1429,6 +1429,7 @@ impl Builder {}// Calls and global.set in the body may change globals before the header runs again.self.call_epoch += 1;+ Self::append(func, Node::new(Op::CheckInterrupt, Type::None, 0, [0, 0, 0]));}/// Begins a loop an OSR compile enters from the frame (see `Osr`): the loop the frame is at if `target`, else adiff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rsindex 5d046d271ab..537400cf97f 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/mod.rs@@ -733,6 +733,7 @@ impl<'a> CodeGenerator<'a> {| Op::TableStore| Op::CalleeInstance| Op::CheckNull+ | Op::CheckInterrupt| Op::CheckFunction| Op::Helper => self.lower_runtime(value),Op::CheckedAddress@@ -780,6 +781,7 @@ pub fn generate(func: &Func,allocation: &Allocation,runtime: &RuntimeInfo,+ _stack_limit: u64,) -> Result<Generated, crate::CompileFailure> {let _ = (NONE, Shift::Lsl);CodeGenerator::new(func, allocation, runtime).generate()diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rsindex 6c915a780e2..04860afcd91 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs@@ -118,6 +118,23 @@ impl CodeGenerator<'_> {let null = self.trap_label(u32::from(node.flags));self.asm.cbz(Width::W64, input(0), null);}+ Op::CheckInterrupt => {+ let interrupted = self.trap_label(libwasm_module::abi::TRAP_STACK_EXHAUSTED);+ self.asm+ .ldr(Width::W64, SCRATCH, MemOperand::Offset(FP, convention::FRAME_INSTANCE));+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(SCRATCH, field(offset_of!(InstanceData, context))),+ );+ self.asm.ldr(+ Width::W64,+ SCRATCH,+ MemOperand::Offset(SCRATCH, field(offset_of!(ExecutionContext, stack_limit))),+ );+ self.asm.cmp(Width::W64, FP, SCRATCH);+ self.asm.b_cond(Cond::Lo, interrupted);+ }Op::CheckFunction => {let (reference, identity) = (input(0), input(1));let null = self.trap_label(u32::from(node.flags));diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rsindex 603d1566f78..fc8dbbe6f02 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/mod.rs@@ -92,6 +92,7 @@ pub struct CodeGenerator<'a> {func: &'a Func,allocation: &'a Allocation,runtime: &'a RuntimeInfo,+ stack_limit: u64,asm: Assembler,block_labels: Vec<Label>,trap_labels: Vec<Option<Label>>,@@ -109,12 +110,13 @@ pub struct CodeGenerator<'a> {}impl<'a> CodeGenerator<'a> {- pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo) -> Self {+ pub fn new(func: &'a Func, allocation: &'a Allocation, runtime: &'a RuntimeInfo, stack_limit: u64) -> Self {let size = convention::FRAME_HEADER_SIZE as u32 + 8 * allocation.slot_count + allocation.outgoing_size;Self {func,allocation,runtime,+ stack_limit,asm: Assembler::for_host(),block_labels: Vec::new(),trap_labels: vec![None; 32],@@ -694,6 +696,7 @@ impl<'a> CodeGenerator<'a> {| Op::TableStore| Op::CalleeInstance| Op::CheckNull+ | Op::CheckInterrupt| Op::CheckFunction| Op::Helper => self.lower_runtime(value),Op::VectorLoad => self.lower_memory(value),@@ -728,7 +731,8 @@ pub fn generate(func: &Func,allocation: &Allocation,runtime: &RuntimeInfo,+ stack_limit: u64,) -> Result<Generated, crate::CompileFailure> {let _ = NONE;- CodeGenerator::new(func, allocation, runtime).generate()+ CodeGenerator::new(func, allocation, runtime, stack_limit).generate()}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rsindex 9df0e5b6e19..703fad235c0 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs@@ -8,9 +8,9 @@//! the runtime's functions.use super::gc::Operand32;-use super::{CodeGenerator, FP, SCRATCH, gpr};+use super::{CodeGenerator, FP, SCRATCH, SP, gpr};use crate::asm::x86_64::AluOp;-use crate::asm::x86_64::Cond;+use crate::asm::x86_64::{BranchGroups, Cond};use crate::asm::{Address, Gpr, Label, Scale, Width};use crate::convention;use crate::ir::{Helper, Op, Value};@@ -105,6 +105,14 @@ impl CodeGenerator<'_> {self.asm.test_rr(Width::W64, input(0), input(0));self.asm.jcc(Cond::Equal, null);}+ Op::CheckInterrupt => {+ let interrupted = self.trap_label(libwasm_module::abi::TRAP_STACK_EXHAUSTED);+ self.asm.mov_ri(SCRATCH, self.stack_limit);+ self.asm.branch_group(|asm| {+ asm.cmp_mr(Width::W64, &Address::new(SCRATCH, 0), SP);+ asm.jcc(Cond::Above, interrupted);+ });+ }Op::CheckFunction => {let (reference, identity) = (input(0), input(1));let null = self.trap_label(u32::from(node.flags));diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsindex c317657f605..3cc0e24a6d6 100644--- a/Libraries/LibWasm/JIT/src/ir/mod.rs+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -745,6 +745,10 @@ ops! {CheckFunction: Fixed(2), Write, "check_function";/// args: reference; flags: the TRAP_* code. Traps if the reference is null.CheckNull: Fixed(1), Write, "check_null";+ /// Traps if another thread interrupted the store, which raised the stack limit. In the header of every loop: a+ /// function entry checks the limit anyway, but loops may not call. It finds the limit through the frame, so that it+ /// keeps no register busy across the loop.+ CheckInterrupt: Fixed(0), Write, "check_interrupt";/// operands: callee FunctionHeader, its instance, its memory base, arguments; args[2]: the function index, or/// NONE for an indirect call. The value is the first result.Call: Variadic, Write, "call";diff --git a/Libraries/LibWasm/JIT/src/ir/verify.rs b/Libraries/LibWasm/JIT/src/ir/verify.rsindex d13ccebcc1b..3bcbbae0ae1 100644--- a/Libraries/LibWasm/JIT/src/ir/verify.rs+++ b/Libraries/LibWasm/JIT/src/ir/verify.rs@@ -274,6 +274,7 @@ fn check_types(func: &Func, value: Value, error: &mut impl FnMut(String)) {Op::TableStore => input_type(0) == Type::Pointer && input_type(2) == Type::Ref,Op::CheckFunction => input_type(0) == Type::Ref && input_type(1) == Type::I32,Op::CheckNull => input_type(0) == Type::Ref,+ Op::CheckInterrupt => true,Op::CalleeInstance => matches!(input_type(0), Type::Ref | Type::Pointer) && input_type(1) == Type::Pointer,Op::Call | Op::TailCall => {matches!(input_type(0), Type::Ref | Type::Pointer)diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsindex fddf3d80964..a4a9e2807ac 100644--- a/Libraries/LibWasm/JIT/src/lib.rs+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -99,6 +99,9 @@ pub struct CompileRequest {/// The function, counting imports.pub function: u32,pub runtime: RuntimeInfo,+ /// The address of the store's `ExecutionContext::stack_limit`, which stays the same for as long as the store lives+ /// (each store has its own code).+ pub stack_limit: u64,pub options: Options,/// For an OSR compile, the module offset of the loop that it continues an interpreter frame at, in any number of/// other loops. Its code takes the frame's fp as its only argument and returns the function's results.@@ -246,7 +249,12 @@ pub fn compile(context: &mut CompileContext, request: &CompileRequest) -> Resultregalloc::verify::dump(&context.func, &context.allocation));}- let generated = codegen::target::generate(&context.func, &context.allocation, &request.runtime)?;+ let generated = codegen::target::generate(+ &context.func,+ &context.allocation,+ &request.runtime,+ request.stack_limit,+ )?;lap(4, &mut stats);stats.nodes = context.func.nodes.len() as u32;stats.slots = context.allocation.slot_count;diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rsindex 3ab28ee0149..23782423611 100644--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs@@ -80,6 +80,9 @@ const TRAP_OFFSET: i32 = offset_of!(SessionState, trap) as i32;const CODE_SPACE_SIZE: usize = 1 << 30;+/// The stack limit that compiled code polls, which nothing interrupts here.+static NO_STACK_LIMIT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+/// Executable memory, reserved up front. Code is added in batches, which are written while their pages are not/// executable.pub struct CodeSpace {@@ -307,6 +310,7 @@ impl CompiledModule {let mut context = CompileContext::default();for (index, slot) in failures.iter_mut().enumerate().skip(first) {let request = CompileRequest {+ stack_limit: (&raw const NO_STACK_LIMIT) as u64,osr: None,module: module.clone(),function: index as u32,@@ -465,7 +469,7 @@ impl TestBinding {let mut result_slots = vec![0u64; result_count];unsafe {let context: *mut ExecutionContext = (*self.data).context;- (*context).stack_limit = lowest_stack_address() + 256 * 1024;+ (*context).stack_limit = std::sync::atomic::AtomicU64::new(lowest_stack_address() + 256 * 1024);(*context).store = (store as *mut Store).cast();}let function: extern "C" fn(u64, *const u64, *mut u64, *const InstanceData) -> u32 =diff --git a/Libraries/LibWasm/JIT/tests/osr.rs b/Libraries/LibWasm/JIT/tests/osr.rsindex d94aec4bb92..4fcd93acdf8 100644--- a/Libraries/LibWasm/JIT/tests/osr.rs+++ b/Libraries/LibWasm/JIT/tests/osr.rs@@ -22,6 +22,7 @@ fn compile_at_first_loop(bytes: &[u8]) -> Result<(), CompileFailure> {}};let request = CompileRequest {+ stack_limit: 0,module: module.clone(),function: module.imported_function_count,runtime: RuntimeInfo::default(),diff --git a/Libraries/LibWasm/Module/src/abi.rs b/Libraries/LibWasm/Module/src/abi.rsindex da378b84188..c77b85baeac 100644--- a/Libraries/LibWasm/Module/src/abi.rs+++ b/Libraries/LibWasm/Module/src/abi.rs@@ -31,6 +31,7 @@#![allow(dead_code)]use std::mem::offset_of;+use std::sync::atomic::AtomicU64;/// The frame header. All fields are 8 bytes, at `fp + FRAME_*`. Its first two words are where a native call and/// `push fp` leave the return address and the caller's fp, so that compiled frames have the same header.@@ -188,11 +189,16 @@ pub const TRAP_EXPECTED_SHARED_MEMORY: u32 = 17;/// (TRAP_RUNTIME).pub const WAIT_CANNOT_BLOCK: u64 = 3;+/// The stack limit that no frame stays above, of a store whose code has to stop for good: compiled code traps at its+/// next function entry or loop, and so does the interpreter. The trap is the one for an exhausted stack.+pub const STACK_LIMIT_INTERRUPTED: u64 = u64::MAX;+/// The state one thread executes WebAssembly with.#[repr(C)]pub struct ExecutionContext {- /// The lowest address a frame may reach.- pub stack_limit: u64,+ /// The lowest address a frame may reach. Another thread may make this `STACK_LIMIT_INTERRUPTED`, whenever it wants+ /// the code running here to stop.+ pub stack_limit: AtomicU64,/// The fp of the innermost entry into the interpreter.pub entry_fp: u64,/// The `EntryRecord` of the innermost entry into the interpreter.diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rsindex 272e6e51442..76600240629 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs@@ -222,6 +222,11 @@ impl Agent {let store = unsafe { &mut *store_cell.get() };store.attach_to_heap();+ // NB: An interrupt of the agent's VM has to stop the store's code too.+ // SAFETY: The word is in the boxed store, which does not move, and shut_down() clears it before the store goes.+ unsafe { vm.set_wasm_stack_limit_word(store.stack_limit_word()) };+ store.wait_interrupt = Some(vm.wait_interrupt().clone());+// NB: The store is the agent's, whose [[CanBlock]] decides whether memory.atomic.wait may block.store.can_block = libjs_rust::api::agent_can_suspend(vm);@@ -261,6 +266,8 @@ impl Agent {let Some(agent) = AGENT.take() else {return;};+ // SAFETY: Null is always allowed.+ unsafe { agent.vm().set_wasm_stack_limit_word(std::ptr::null()) };// SAFETY: The root belongs to the agent, which is going away, and the heap it is in is alive.unsafe { gc_root_destroy(agent._js_tag_root.as_ptr()) };// SAFETY: the() leaked this box, and AGENT held the only way to reach the agent.