Truly independent web browser
LibWasm: Harden the runtime and the JIT
Andreas Kling5e073ba2e88a
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rsindex d14ffb316e7..8b571db5304 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/extended.rs@@ -7,7 +7,7 @@//! Encoders beyond what libjs_jit's code generation uses, for the WebAssembly JIT: scalar floating point of both//! precisions, conversions, bit counting, LSE atomics, and Advanced SIMD (NEON).-use super::{Assembler, Cond, Fpr, Gpr, Width, rd, rm, rn, sf, vd, vm, vn};+use super::{Assembler, Cond, Fpr, Gpr, SP, Width, rd, rm, rn, sf, vd, vm, vn};/// The precision of a scalar floating point instruction (its `ftype` field).#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -144,7 +144,8 @@ impl Assembler {}/// `add rd, rn, #imm`, for any 64-bit `imm`, through `scratch` where it does not fit an immediate. rd and rn- /// may be SP.+ /// may be SP. SP changes in one instruction: what lies below its final value may be live, and a signal handler+ /// may write below SP at any time.pub fn add_any(&mut self, rd_: Gpr, rn_: Gpr, imm: i64, scratch: Gpr) {let magnitude = imm.unsigned_abs();let negative = imm < 0;@@ -161,6 +162,11 @@ impl Assembler {self.add_imm(Width::W64, rd_, rn_, (magnitude >> 12) as u32, true);}} else if magnitude < (1 << 24) {+ if rd_ == SP {+ self.add_any(scratch, rn_, imm, scratch);+ self.mov_sp(SP, scratch);+ return;+ }let (high, low) = ((magnitude >> 12) as u32, (magnitude & 0xfff) as u32);if negative {self.sub_imm(Width::W64, rd_, rn_, high, true);@@ -470,12 +476,26 @@ const fn single_structure_fields(size_log2: u32, index: u32) -> u32 {#[cfg(test)]mod tests {use super::*;- use crate::asm::aarch64::{Cond, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15};+ use crate::asm::aarch64::{Cond, X1, X2, X3, X4, X5, X6, X7, X8, X9, X10, X11, X12, X13, X14, X15, X17};fn v(index: u8) -> Fpr {Fpr(index)}+ /// SP moves in one instruction even where the immediate takes two.+ #[test]+ fn moves_sp_in_one_instruction() {+ let mut asm = Assembler::new();+ asm.add_any(SP, Gpr(29), -0x12345, X17); // sub x17, x29, #0x12, lsl #12; sub x17, x17, #0x345; mov sp, x17+ asm.add_any(X1, X2, 0x12345, X17); // add x1, x2, #0x12, lsl #12; add x1, x1, #0x345+ let code = asm.finish().unwrap();+ let words: Vec<u32> = code+ .chunks(4)+ .map(|word| u32::from_le_bytes(word.try_into().unwrap()))+ .collect();+ assert_eq!(words, [0xd1404bb1, 0xd10d1631, 0x9100023f, 0x91404841, 0x910d1421]);+ }+/// The encodings llvm-mc gives these instructions (`llvm-mc -triple=aarch64 -mattr=+lse,+neon,+rdm`).#[test]fn encodes_like_llvm_mc() {diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rsindex 66cdb315497..a46dc590a94 100644--- a/Libraries/LibWasm/Engine/src/abi.rs+++ b/Libraries/LibWasm/Engine/src/abi.rs@@ -174,6 +174,10 @@ pub const TRAP_UNCAUGHT_EXCEPTION: u32 = 15;pub const TRAP_UNALIGNED_ATOMIC: u32 = 16;pub const TRAP_EXPECTED_SHARED_MEMORY: u32 = 17;+/// What `wasm_runtime_wait` returns, besides its results 0 to 2, when the agent cannot block: the store has the trap+/// (TRAP_RUNTIME).+pub const WAIT_CANNOT_BLOCK: u64 = 3;+/// The state one thread executes WebAssembly with.#[repr(C)]pub struct ExecutionContext {@@ -238,6 +242,18 @@ pub const OBJECT_DATA_OFFSET: usize = 16;pub const OBJECT_LENGTH_OFFSET: usize = 24;pub const OBJECT_INLINE_DATA_OFFSET: usize = 32;+/// The sizes of the data a GC object can keep inline, the size classes of the runtime's heap. Larger data is+/// allocated outside of the heap.+pub const OBJECT_DATA_SIZE_CLASSES: [usize; 17] = [+ 0, 16, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096,+];++/// The most data an object keeps inline.+pub const MAX_INLINE_DATA_SIZE: usize = OBJECT_DATA_SIZE_CLASSES[OBJECT_DATA_SIZE_CLASSES.len() - 1];++// NB: The bytes a field or element takes in an object's data are `StorageType::object_field_size()` (types.rs); a+// struct's fields follow each other in order from offset 0.+/// An exception is a cell with the identity of its tag, the address of its payload (its values' slots in operand/// stack order, the last value in the lowest slot), the payload's length in slots, and how the collector follows/// each slot.@@ -357,6 +373,7 @@ pub fn layout_constants() -> String {constant("STORAGE_FUNCTION_REFERENCE", STORAGE_FUNCTION_REFERENCE as usize);constant("OBJECT_DATA_OFFSET", OBJECT_DATA_OFFSET);constant("OBJECT_LENGTH_OFFSET", OBJECT_LENGTH_OFFSET);+ constant("WAIT_CANNOT_BLOCK", WAIT_CANNOT_BLOCK as usize);constant("CONTEXT_ARGUMENT_1", offset_of!(ExecutionContext, arguments) + 8);constant("CONTEXT_ARGUMENT_2", offset_of!(ExecutionContext, arguments) + 16);constant("CONTEXT_ARGUMENT_3", offset_of!(ExecutionContext, arguments) + 24);diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rsindex a553fead866..4df897ed8e9 100644--- a/Libraries/LibWasm/Engine/src/capi.rs+++ b/Libraries/LibWasm/Engine/src/capi.rs@@ -1401,6 +1401,16 @@ pub unsafe extern "C" fn wasm_store_clear_memory_grow_callback(store: *mut WasmSstore_of(store).memory_grow_callback = None;}+/// Sets whether the agent the store runs code for may block, which `memory.atomic.wait` needs.+///+/// # Safety+///+/// `store` must be a live store.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasm_store_set_can_block(store: *mut WasmStore, can_block: bool) {+ store_of(store).can_block = can_block;+}+// WASI./// The state of a WASI command, whose functions a store gets with `wasm_wasi_allocate_function()`.diff --git a/Libraries/LibWasm/Engine/src/lib.rs b/Libraries/LibWasm/Engine/src/lib.rsindex 3caee26aa60..2645e4a90bb 100644--- a/Libraries/LibWasm/Engine/src/lib.rs+++ b/Libraries/LibWasm/Engine/src/lib.rs@@ -18,6 +18,10 @@ mod rust_demangle;#[path = "../../../RustPanic.rs"]mod rust_panic;+// NB: Atomics.wait and Atomics.notify's waiting and waking, which memory.atomic.wait and memory.atomic.notify share.+#[path = "../../../LibJS/Rust/src/futex.rs"]+mod futex;+pub mod capi;pub mod runtime;pub mod wasi;diff --git a/Libraries/LibWasm/Engine/src/runtime/constant.rs b/Libraries/LibWasm/Engine/src/runtime/constant.rsindex a68220aa9aa..878e1d103bf 100644--- a/Libraries/LibWasm/Engine/src/runtime/constant.rs+++ b/Libraries/LibWasm/Engine/src/runtime/constant.rs@@ -95,7 +95,11 @@ pub fn evaluate(.map(|field| Value::default_for(field.storage.unpacked())).collect()};- stack.push(Value::Ref(store.allocate_struct(identity, &values)));+ let object = store.allocate_struct(identity, &values);+ if object == 0 {+ return Err(Trap::Host("out of memory".to_string()));+ }+ stack.push(Value::Ref(object));}opcode::gc::ARRAY_NEW | opcode::gc::ARRAY_NEW_DEFAULT | opcode::gc::ARRAY_NEW_FIXED => {let type_index = immediate()?;@@ -104,10 +108,13 @@ pub fn evaluate(return Err(malformed());};let element = element.storage.unpacked();- let values = match sub_opcode {+ // NB: The length of array.new is any u32, so its elements go into the array directly, which+ // checks its size first, rather than into a vector of that length.+ let array = match sub_opcode {opcode::gc::ARRAY_NEW_FIXED => {let count = immediate()? as usize;- stack.split_off(stack.len().checked_sub(count).ok_or_else(malformed)?)+ let values = stack.split_off(stack.len().checked_sub(count).ok_or_else(malformed)?);+ store.allocate_array(identity, &values)}_ => {let Some(Value::I32(length)) = stack.pop() else {@@ -118,10 +125,9 @@ pub fn evaluate(} else {Value::default_for(element)};- vec![value; length as u32 as usize]+ store.allocate_filled_array(identity, value, length as u32)}};- let array = store.allocate_array(identity, &values);if array == 0 {return Err(Trap::Host("out of memory".to_string()));}diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rsindex 0de36e9fd29..c25f6052ea4 100644--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs@@ -93,10 +93,6 @@ fn trace_of_storage(kind: u8) -> u8 {}}-fn storage_size(kind: u8) -> u32 {- if kind == STORAGE_V128 { 16 } else { 8 }-}-fn leak<T>(values: Vec<T>) -> *const T {Box::leak(values.into_boxed_slice()).as_ptr()}@@ -141,15 +137,16 @@ pub fn allocate_rtt(store: &Store, identity: u32) -> *const Rtt {.collect();let mut offsets = Vec::with_capacity(kinds.len());let mut offset = 0;- for &kind in &kinds {+ for field in fields {offsets.push(offset);- offset += storage_size(kind);+ offset += field.storage.object_field_size();}(RTT_KIND_STRUCT, kinds, offsets, offset)}CompositeType::Array(element) => {let kind = storage_kind(element.storage, &store.types);- (RTT_KIND_ARRAY, vec![kind], Vec::new(), storage_size(kind))+ let size = element.storage.object_field_size();+ (RTT_KIND_ARRAY, vec![kind], Vec::new(), size)}};let depth = display.len() as u32 - 1;@@ -195,7 +192,7 @@ unsafe extern "C" fn rtt_destroy(cell: *mut c_void) {}/// Allocate a zeroed object of the type `rtt` with `data_size` bytes of data and, for an array, `length` elements.-/// Returns zero if the data is too large.+/// Returns zero if the data is too large, or if there is no memory for it.pub fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {if data_size > MAX_OBJECT_DATA_SIZE {return 0;@@ -209,8 +206,13 @@ pub fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64// The data lives outside the heap, after a word that holds the number of words after it. It counts towards// the next collection before the cell is allocated, which may collect.let words = data_size.div_ceil(8) as usize;+ let mut block = Vec::new();+ if block.try_reserve_exact(words + 1).is_err() {+ return 0;+ }+ block.resize(words + 1, 0u64);heap.did_allocate_external_memory((words + 1) * 8);- let block = Box::leak(vec![0u64; words + 1].into_boxed_slice());+ let block = Box::leak(block.into_boxed_slice());block[0] = words as u64;let data = unsafe { block.as_mut_ptr().add(1) }.cast::<u8>();(heap.allocate_cell(CellType::Object(0)), data)@@ -375,11 +377,15 @@ impl Store {allocate_object(&self.heap, rtt, data_size, length)}- /// Allocate a struct of the type `identity` with the given field values.+ /// Allocate a struct of the type `identity` with the given field values, or return zero if there is no memory+ /// for it.pub fn allocate_struct(&mut self, identity: u32, fields: &[Value]) -> u64 {let rtt: *const Rtt = self.rtt(identity);let size = u64::from(unsafe { (*rtt).size });let object = self.allocate_object(rtt, size, 0);+ if object == 0 {+ return 0;+ }let data = unsafe { read::<*mut u8>(object as *const c_void, OBJECT_DATA_OFFSET) };for (index, value) in fields.iter().enumerate() {unsafe {@@ -406,6 +412,22 @@ impl Store {object}+ /// Allocate an array of the type `identity` with `length` elements of `value`, or return zero if it is too large+ /// or there is no memory for it.+ pub fn allocate_filled_array(&mut self, identity: u32, value: Value, length: u32) -> u64 {+ let rtt: *const Rtt = self.rtt(identity);+ let (element_size, kind) = unsafe { (u64::from((*rtt).size), *(*rtt).field_kinds) };+ let object = self.allocate_object(rtt, u64::from(length) * element_size, u64::from(length));+ if object == 0 {+ return 0;+ }+ let data = unsafe { read::<*mut u8>(object as *const c_void, OBJECT_DATA_OFFSET) };+ for index in 0..length as usize {+ unsafe { store_field(data.add(index * element_size as usize), kind, value) };+ }+ object+ }+/// Make an exception with `tag` and the values of `payload` (in operand stack order), and return its reference.pub fn allocate_exception(&mut self, tag: TagAddress, payload: &[u64]) -> u64 {let mut traces = Vec::with_capacity(payload.len());diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rsindex 7a89168f033..17a998c4004 100644--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs@@ -119,10 +119,7 @@ pub enum CellType {Entity(usize),}-/// The sizes of the data a GC object can keep inline. Larger data is allocated outside of the heap.-pub const OBJECT_DATA_SIZE_CLASSES: [usize; 17] = [- 0, 16, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096,-];+pub use crate::abi::OBJECT_DATA_SIZE_CLASSES;/// The size class of objects with `size` bytes of data, or None if the data does not fit inline.pub fn object_size_class(size: usize) -> Option<usize> {diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rsindex d1fd42996b4..e2816a22614 100644--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs@@ -12,6 +12,7 @@ use crate::abi::{ExecutionContext, FRAME_FUNCTION, FRAME_HEADER_SIZE, FRAME_INSTANCE, FRAME_RETURN_IP, FRAME_SAVED_FP, MemoryData,TableData,};+use crate::futex::{self, AtomicWaitResult, WaitWord};use crate::validator::{CatchKind, NO_EXCEPTION_LOCAL, NOT_DELEGATED};/// Export the runtime functions under the names the interpreter calls them by. The interpreter calls them with the@@ -287,17 +288,10 @@ pub(crate) unsafe fn unwind(}}-/// The threads waiting in `memory.atomic.wait`, with the address they wait on, oldest first.-static WAITERS: std::sync::Mutex<Vec<(u64, std::sync::Arc<Waiter>)>> = std::sync::Mutex::new(Vec::new());--struct Waiter {- woken: std::sync::Mutex<bool>,- condition: std::sync::Condvar,-}-/// Wait on the shared memory location at address `arguments[0]` while it holds `arguments[1]` (compared at/// `arguments[3]` bytes), for at most `arguments[2]` nanoseconds if that is not negative. Returns 0 when woken, 1 if-/// the location held another value, and 2 when the time ran out.+/// the location held another value, and 2 when the time ran out, or WAIT_CANNOT_BLOCK with the trap in the store if+/// the store's agent cannot block.////// # Safety///@@ -311,56 +305,28 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {(*context).arguments[3],)};- let waiter = {- let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");- // Notifies take the lock, so none can come between reading the value and waiting for it.- let current = unsafe {- if size == 4 {- u64::from((*(address as *const std::sync::atomic::AtomicU32)).load(std::sync::atomic::Ordering::SeqCst))- } else {- (*(address as *const std::sync::atomic::AtomicU64)).load(std::sync::atomic::Ordering::SeqCst)- }- };- if current != expected {- return 1;- }- let waiter = std::sync::Arc::new(Waiter {- woken: std::sync::Mutex::new(false),- condition: std::sync::Condvar::new(),- });- waiters.push((address, waiter.clone()));- waiter- };- let mut woken = waiter.woken.lock().expect("a waiter is never poisoned");- if timeout < 0 {- while !*woken {- woken = waiter.condition.wait(woken).expect("a waiter is never poisoned");- }- return 0;+ let store = unsafe { store_of(context) };+ if !store.can_block {+ store.pending_trap = Some(Trap::Host(+ "memory.atomic.wait in an agent that cannot block".to_string(),+ ));+ return crate::abi::WAIT_CANNOT_BLOCK;}- let deadline = std::time::Instant::now() + std::time::Duration::from_nanos(timeout as u64);- while !*woken {- let now = std::time::Instant::now();- if now >= deadline {- break;+ // NB: The waits and wakes are those of Atomics.wait and Atomics.notify (LibJS's futex), whose waiter lists are+ // the operating system's, per address: JavaScript and WebAssembly wake each other, as the memory model's+ // single WaiterList per location requires.+ let word = unsafe {+ if size == 4 {+ WaitWord::Word32(&*(address as *const std::sync::atomic::AtomicU32))+ } else {+ WaitWord::Word64(&*(address as *const std::sync::atomic::AtomicU64))}- woken = waiter- .condition- .wait_timeout(woken, deadline - now)- .expect("a waiter is never poisoned")- .0;- }- if *woken {- return 0;- }- drop(woken);- let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");- waiters.retain(|(_, other)| !std::sync::Arc::ptr_eq(other, &waiter));- // A notify may have come in after the time ran out but before the waiter left the list.- if *waiter.woken.lock().expect("a waiter is never poisoned") {- 0- } else {- 2+ };+ let timeout = (timeout >= 0).then(|| std::time::Duration::from_nanos(timeout as u64));+ match futex::atomic_wait(word, expected, timeout) {+ AtomicWaitResult::Woken => 0,+ AtomicWaitResult::NotEqual => 1,+ AtomicWaitResult::TimedOut => 2,}}@@ -372,16 +338,6 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {/// Only the interpreter calls this.unsafe fn notify(context: *mut ExecutionContext) -> u64 {let (address, count) = unsafe { ((*context).arguments[0], (*context).arguments[1]) };- let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");- let mut woken = 0;- waiters.retain(|(waiting_on, waiter)| {- if woken >= count || *waiting_on != address {- return true;- }- *waiter.woken.lock().expect("a waiter is never poisoned") = true;- waiter.condition.notify_one();- woken += 1;- false- });- woken+ let word = unsafe { &*(address as *const std::sync::atomic::AtomicU32) };+ futex::atomic_notify(word, usize::try_from(count).unwrap_or(usize::MAX)) as u64}diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rsindex 50d7d66f3f0..4eed4d685c4 100644--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs@@ -125,14 +125,21 @@ pub fn stack_limit(reserve: usize) -> u64 {static LOWEST: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };}let lowest = LOWEST.with(|lowest| {- if lowest.get() == 0 {- let marker = 0u8;- let current = &raw const marker as usize;- lowest.set(thread_stack_lowest_address().unwrap_or(current.saturating_sub(1024 * 1024)));+ if lowest.get() == 0+ && let Some(address) = thread_stack_lowest_address()+ {+ lowest.set(address);}lowest.get()});- (lowest + reserve) as u64+ if lowest != 0 {+ return (lowest + reserve) as u64;+ }+ // NB: Without the stack's bounds, the limit is a mebibyte below wherever this is called from, which depends on the+ // caller, so it is not cached.+ let marker = 0u8;+ let current = &raw const marker as usize;+ (current.saturating_sub(1024 * 1024) + reserve) as u64}#[cfg(target_os = "linux")]diff --git a/Libraries/LibWasm/Engine/src/runtime/jit.rs b/Libraries/LibWasm/Engine/src/runtime/jit.rsindex 9a25ff82ced..0478f969a79 100644--- a/Libraries/LibWasm/Engine/src/runtime/jit.rs+++ b/Libraries/LibWasm/Engine/src/runtime/jit.rs@@ -33,7 +33,7 @@//! default).use super::ranges::RangeSet;-use super::{FunctionAddress, FunctionInstance, InstanceAddress, Store, Trap, Value};+use super::{FunctionAddress, FunctionInstance, FunctionKind, InstanceAddress, Store, Trap, Value};use crate::abi::ExecutionContext;use crate::types::ValType;use std::sync::OnceLock;@@ -117,7 +117,11 @@ pub fn options() -> Options {}}}- options.enabled &= cfg!(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")));+ // NB: Only where compiled code can trap on memory faults (see `redirect_fault()`) and have executable memory.+ options.enabled &= cfg!(any(+ all(any(target_os = "linux", target_os = "macos"), target_arch = "x86_64"),+ all(any(target_os = "linux", target_os = "macos"), target_arch = "aarch64")+ ));options})}@@ -166,7 +170,7 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {let [header, pc, reason, frame, ..] = (*context).arguments;let address = FunctionAddress::from_ptr(header as *const FunctionInstance);let store = store_of(context);- if !options().enabled {+ if !enabled() {address.get_mut().header.tier_up_budget = u32::MAX;return 0;}@@ -180,7 +184,7 @@ unsafe fn tier_up(context: *mut ExecutionContext) -> u64 {let state = native::compile_function(store, address);address.get_mut().header.tier_up_budget = match state {// A compiled function keeps a budget, so that frames of it still running in the interpreter continue- // compiled at their next outermost loop.+ // compiled at the next loop header they reach.native::CompileState::Compiled => options().threshold.max(1) + crate::abi::TIER_UP_CALL_COST,native::CompileState::Pending => POLL_BUDGET + crate::abi::TIER_UP_CALL_COST,native::CompileState::Failed => u32::MAX,@@ -264,7 +268,7 @@ const DEFAULT_THRESHOLD: u32 = 1000;/// few billion calls and loop iterations.pub fn initial_tier_up_budget() -> u32 {let options = options();- if options.enabled && !options.eager {+ if enabled() && !options.eager {options.threshold} else {u32::MAX@@ -273,12 +277,18 @@ pub fn initial_tier_up_budget() -> u32 {/// What `native_entry` starts as in a new function's header.pub fn initial_native_entry() -> u64 {- if !options().enabled {+ if !enabled() {return 0;}native::stubs().adapter}+/// Whether the JIT runs: if `LIBWASM_JIT` wants it and the process has executable memory for its stubs, which a+/// hardened runtime without the JIT entitlement does not give it.+pub(crate) fn enabled() -> bool {+ options().enabled && native::try_stubs().is_some()+}+impl Store {/// Keeps everything in this store interpreted, whatever `LIBWASM_JIT` says, as tests comparing the tiers want.pub fn disable_jit(&mut self) {@@ -288,7 +298,10 @@ impl Store {/// Called once a module is instantiated, before its start function runs.pub fn instantiated(store: &mut Store, instance: InstanceAddress) {- if options().eager {+ if let Some(jit) = store.jit.as_mut() {+ native::forget_dead_modules(jit);+ }+ if options().eager && enabled() {native::compile_instance(store, instance);}}@@ -304,7 +317,7 @@ pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {let context = context.cast::<libc::ucontext_t>();let registers = &mut (*context).uc_mcontext.gregs;let pc = registers[libc::REG_RIP as usize] as usize;- let Some(stubs) = native::STUBS.get() else {+ let Some(stubs) = native::STUBS.get().and_then(Option::as_ref) else {return false;};if !CODE_RANGES.contains(pc) {@@ -326,7 +339,7 @@ pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {unsafe {let context = context.cast::<libc::ucontext_t>();let mcontext = &mut (*context).uc_mcontext;- let Some(stubs) = native::STUBS.get() else {+ let Some(stubs) = native::STUBS.get().and_then(Option::as_ref) else {return false;};if !CODE_RANGES.contains(mcontext.pc as usize) {@@ -348,7 +361,7 @@ pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {unsafe {let context = context.cast::<libc::ucontext_t>();let state = &mut (*(*context).uc_mcontext).__ss;- let Some(stubs) = native::STUBS.get() else {+ let Some(stubs) = native::STUBS.get().and_then(Option::as_ref) else {return false;};if !CODE_RANGES.contains(state.__pc as usize) {@@ -360,8 +373,30 @@ pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {}}+/// Redirects a memory fault in compiled code to the trap exit. `context` is the signal handler's.+///+/// # Safety+///+/// Only the fault handler calls this, with its context.+#[cfg(all(target_os = "macos", target_arch = "x86_64"))]+pub unsafe fn redirect_fault(context: *mut libc::c_void) -> bool {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ let state = &mut (*(*context).uc_mcontext).__ss;+ let Some(stubs) = native::STUBS.get().and_then(Option::as_ref) else {+ return false;+ };+ if !CODE_RANGES.contains(state.__rip as usize) {+ return false;+ }+ state.__rip = stubs.trap_exit;+ state.__rdi = u64::from(crate::abi::TRAP_MEMORY_OUT_OF_BOUNDS);+ true+ }+}+#[cfg(not(any(- all(target_os = "linux", target_arch = "x86_64"),+ all(any(target_os = "linux", target_os = "macos"), target_arch = "x86_64"),all(any(target_os = "linux", target_os = "macos"), target_arch = "aarch64"))))]pub unsafe fn redirect_fault(_context: *mut libc::c_void) -> bool {@@ -397,37 +432,116 @@ fn trap_code(trap: &Trap) -> u32 {}}-/// The value of type `ty` in `words`, as compiled code holds it: zero-extended i32 values, f32 values in the low 32-/// bits.-fn value_from_words(ty: ValType, words: &[u64]) -> Value {- match ty {- ValType::I32 => Value::I32(words[0] as u32 as i32),- ValType::I64 => Value::I64(words[0] as i64),- ValType::F32 => Value::F32(words[0] as u32),- ValType::F64 => Value::F64(words[0]),- ValType::Ref(_) => Value::Ref(words[0]),- ValType::V128 => Value::V128(u128::from(words[0]) | (u128::from(words[1]) << 64)),- }+fn ir_type(ty: ValType) -> libwasm_jit::ir::Type {+ libwasm_jit::builder::ir_type(ty).expect("the JIT has a type for every value")}-fn words_of_value(value: &Value, words: &mut [u64]) {- match *value {- Value::I32(value) => words[0] = u64::from(value as u32),- Value::I64(value) => words[0] = value as u64,- Value::F32(bits) => words[0] = u64::from(bits),- Value::F64(bits) | Value::Ref(bits) => words[0] = bits,- Value::V128(bits) => {- words[0] = bits as u64;- words[1] = (bits >> 64) as u64;+/// Where compiled code passes the parameters and results of a function, worked out once per function (in+/// `FunctionInstance::native_shapes`), so that calls between the tiers allocate nothing, and own nothing that a trap,+/// which leaves through the compiled code and skips their frames, would leak.+pub struct NativeShapes {+ /// Of calls of the function.+ pub call: CallShape,+ /// Of an OSR compile of it, which takes the fp of an interpreter frame.+ pub osr: CallShape,+}++/// Where compiled code passes values of a signature (see `libwasm_jit::convention`).+pub struct CallShape {+ params: Box<[ValueShape]>,+ results: Box<[ValueShape]>,+ /// The slots of the parameters' home area, after which the result area pointer is, and where the result area+ /// starts.+ parameter_slots: usize,+ result_area_slot: usize,+ /// The slots of the outgoing area: the home slots, and the result area pointer and the result area if there is+ /// one.+ image_slots: usize,+ has_result_area: bool,+}++/// Where compiled code passes one value: its type, its place, the slot of its home (or of its place among the+/// results), the slots it takes, and for a register, its position among the registers of its class.+#[derive(Clone, Copy)]+struct ValueShape {+ ty: libwasm_jit::ir::Type,+ place: libwasm_jit::convention::Place,+ home: usize,+ slots: usize,+ register: usize,+}++impl CallShape {+ fn new(params: &[libwasm_jit::ir::Type], results: &[libwasm_jit::ir::Type]) -> Self {+ use libwasm_jit::convention;+ let shapes = |types: &[libwasm_jit::ir::Type], places: &[convention::Place]| -> Box<[ValueShape]> {+ let (mut gprs, mut xmms) = (0, 0);+ types+ .iter()+ .zip(places)+ .enumerate()+ .map(|(index, (&ty, &place))| {+ let counter = if ty.uses_xmm() { &mut xmms } else { &mut gprs };+ let register = *counter;+ if let convention::Place::Register(_) = place {+ *counter += 1;+ }+ ValueShape {+ ty,+ place,+ home: convention::home_slot(types, index) as usize,+ slots: ty.slots() as usize,+ register,+ }+ })+ .collect()+ };+ let mut places = Vec::new();+ convention::parameter_places(params, &mut places);+ let param_shapes = shapes(params, &places);+ convention::result_places(results, &mut places);+ let result_shapes = shapes(results, &places);+ Self {+ params: param_shapes,+ results: result_shapes,+ parameter_slots: convention::slots(params) as usize,+ result_area_slot: convention::result_area_slot(params) as usize,+ image_slots: (convention::outgoing_size(params, results) / 8) as usize,+ has_result_area: convention::has_result_area(results),}}}-fn ir_types(types: &[ValType]) -> Vec<libwasm_jit::ir::Type> {- types- .iter()- .map(|ty| libwasm_jit::builder::ir_type(*ty).expect("the JIT has a type for every value"))- .collect()+/// The shapes of `function`'s calls, made the first time they are needed.+fn shapes(function: &FunctionInstance) -> &NativeShapes {+ function.native_shapes.get_or_init(|| {+ let params: Vec<_> = function.ty.params.iter().map(|ty| ir_type(*ty)).collect();+ let results: Vec<_> = function.ty.results.iter().map(|ty| ir_type(*ty)).collect();+ Box::new(NativeShapes {+ call: CallShape::new(¶ms, &results),+ osr: CallShape::new(&[libwasm_jit::ir::Type::Pointer], &results),+ })+ })+}++/// The bits of a slot of a value of type `ty` that compiled code holds in a 64-bit register: i32 and f32 values+/// zero-extended.+fn slot_bits(ty: libwasm_jit::ir::Type, word: u64) -> u64 {+ if matches!(ty, libwasm_jit::ir::Type::I32 | libwasm_jit::ir::Type::F32) {+ word & 0xffff_ffff+ } else {+ word+ }+}++/// How many of the thread's large call images are in use, which the runtime notes when it enters the interpreter and+/// restores when the entry returns, so that the images of calls a trap skipped are free again.+pub fn large_images_in_use() -> usize {+ native::large_images_in_use()+}++pub fn release_large_images(in_use: usize) {+ native::release_large_images(in_use);}/// Calls a compiled function from the interpreter: `arguments[0]` is its header and `arguments[1]` the top of the@@ -450,40 +564,76 @@ unsafe fn call_compiled(context: *mut ExecutionContext) -> u64 {/// header, `arguments[1]` the adapter's save area, and `arguments[2]` the adapter's frame, above which the home/// slots of the arguments are. Returns 0 with the results in place, or a trap code, with the trap in the store.unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {- use libwasm_jit::convention::{self, Place};+ use libwasm_jit::convention::Place;unsafe {let [header, save_area, frame, ..] = (*context).arguments;let function = &*(header as *const FunctionInstance);- let ty = function.ty.clone();+ let shape = &shapes(function).call;let save_area = save_area as *mut u64;- let params = ir_types(&ty.params);- let mut places = Vec::new();- convention::parameter_places(¶ms, &mut places);- let (mut gprs, mut xmms) = (0, 0);- let mut arguments = Vec::with_capacity(params.len());- for (index, place) in places.iter().enumerate() {- let words = match *place {- Place::Register(_) if params[index].uses_xmm() => {- xmms += 1;- ak::slice_from_raw_parts(save_area.add(convention::GPR_ARGUMENTS.len() + 2 * (xmms - 1)), 2)- }- Place::Register(_) => {- gprs += 1;- ak::slice_from_raw_parts(save_area.add(gprs - 1), 1)- }- Place::Memory(slot) => {- ak::slice_from_raw_parts((frame as *const u64).add(slot as usize), params[index].slots() as usize)- }- };- arguments.push(value_from_words(ty.params[index], words));- }+ let frame = frame as *mut u64;+ // Where a value is in the adapter's save area, or in the home slots above its frame.+ let location = |value: &ValueShape| match value.place {+ Place::Register(_) if value.ty.uses_xmm() => {+ save_area.add(libwasm_jit::convention::GPR_ARGUMENTS.len() + 2 * value.register)+ }+ Place::Register(_) => save_area.add(value.register),+ Place::Memory(slot) => frame.add(slot as usize),+ };let store = store_of(context);let address = FunctionAddress::from_ptr(function);- let results = match store.invoke(address, &arguments) {- Ok(results) => results,+ let parameter_slots = function.header.param_slots as usize;+ let result_slots = function.header.result_slots as usize;+ // NB: On the stack where they fit; this frame is never skipped, since traps come back as results here.+ const SMALL: usize = 32;+ let (mut small_arguments, mut small_results) = ([0u64; SMALL], [0u64; SMALL]);+ let (mut large_arguments, mut large_results) = (Vec::new(), Vec::new());+ let arguments: &mut [u64] = if parameter_slots <= SMALL {+ &mut small_arguments[..parameter_slots]+ } else {+ large_arguments.resize(parameter_slots, 0);+ &mut large_arguments+ };+ let results: &mut [u64] = if result_slots <= SMALL {+ &mut small_results[..result_slots]+ } else {+ large_results.resize(result_slots, 0);+ &mut large_results+ };+ // The operand stack grows down, so the first value is in the highest slots.+ for param in &shape.params {+ let source = location(param);+ let start = parameter_slots - param.home - param.slots;+ for slot in 0..param.slots {+ arguments[start + slot] = slot_bits(param.ty, *source.add(slot));+ }+ }+ let outcome = if let FunctionKind::Host(_) = function.kind {+ // NB: Host functions take and return values.+ let values: Vec<Value> = function+ .ty+ .params+ .iter()+ .zip(&shape.params)+ .map(|(&ty, param)| {+ let start = parameter_slots - param.home - param.slots;+ Value::from_slots(ty, &arguments[start..])+ })+ .collect();+ store.invoke(address, &values).map(|values| {+ let mut slots = Vec::with_capacity(result_slots);+ for value in values.iter().rev() {+ value.push_slots(&mut slots);+ }+ results.copy_from_slice(&slots);+ })+ } else {+ store.invoke_slots(address, arguments, results)+ };+ match outcome {+ Ok(()) => {}Err(Trap::UncaughtException(exception)) => {// NB: The adapter's frame is a frame of the compiled caller's callee.- native::unwind(store, exception, frame);+ native::unwind(store, exception, frame as u64);return libwasm_jit::stubs::ADAPTER_RESUME;}Err(trap) => {@@ -491,26 +641,24 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {store.pending_trap = Some(trap);return u64::from(code);}+ }+ let area = if shape.has_result_area {+ *frame.add(shape.parameter_slots) as *mut u64+ } else {+ std::ptr::null_mut()};- let result_types = ir_types(&ty.results);- convention::result_places(&result_types, &mut places);- let area = *(frame as *const u64).add(convention::result_area_pointer(¶ms) as usize) as *mut u64;- let (mut gprs, mut xmms) = (0, 0);- for (index, place) in places.iter().enumerate() {- let words = match *place {- Place::Register(_) if result_types[index].uses_xmm() => {- xmms += 1;- ak::slice_from_raw_parts_mut(save_area.add(convention::GPR_ARGUMENTS.len() + 2 * (xmms - 1)), 2)- }- Place::Register(_) => {- gprs += 1;- ak::slice_from_raw_parts_mut(save_area.add(gprs - 1), 1)- }- Place::Memory(slot) => {- ak::slice_from_raw_parts_mut(area.add(slot as usize), result_types[index].slots() as usize)+ for result in &shape.results {+ let destination = match result.place {+ Place::Register(_) if result.ty.uses_xmm() => {+ save_area.add(libwasm_jit::convention::GPR_ARGUMENTS.len() + 2 * result.register)}+ Place::Register(_) => save_area.add(result.register),+ Place::Memory(slot) => area.add(slot as usize),};- words_of_value(&results[index], words);+ let start = result_slots - result.home - result.slots;+ for slot in 0..result.slots {+ *destination.add(slot) = slot_bits(result.ty, results[start + slot]);+ }}0}@@ -518,16 +666,16 @@ unsafe fn call_from_native(context: *mut ExecutionContext) -> u64 {#[cfg(all(unix, any(target_arch = "x86_64", target_arch = "aarch64")))]mod native {- use super::{CODE_RANGES, ir_types, value_from_words, words_of_value};+ use super::{CODE_RANGES, CallShape, shapes, slot_bits};use crate::abi::{ExecutionContext, FUNCTION_KIND_COMPILED, FunctionHeader, OPCODE_TRAP_FROM_NATIVE};use crate::module::Module;use crate::runtime::{FunctionAddress, FunctionInstance, FunctionKind, InstanceAddress, Store, helpers};- use libwasm_jit::convention::{self, Place};+ use libwasm_jit::convention::Place;use libwasm_jit::stubs::NativeCall;use libwasm_jit::{CompileContext, CompileRequest, CompiledFunction, RuntimeInfo};use std::collections::{HashMap, HashSet};use std::sync::mpsc::{Receiver, Sender, channel};- use std::sync::{Arc, Mutex, OnceLock};+ use std::sync::{Arc, Mutex, OnceLock, Weak};/// The code the process's stores share.pub struct Stubs {@@ -539,46 +687,55 @@ mod native {pub runtime: RuntimeInfo,}- pub static STUBS: OnceLock<Stubs> = OnceLock::new();+ /// The stubs, or None if the process has no executable memory for them.+ pub static STUBS: OnceLock<Option<Stubs>> = OnceLock::new();+ /// The stubs, once the JIT is known to run (see `super::enabled()`).pub fn stubs() -> &'static Stubs {- STUBS.get_or_init(|| {- let handler = crate::runtime::interpreter::dispatch_table_entry(OPCODE_TRAP_FROM_NATIVE) as u64;- // NB: The trap exit goes first, so that the others can jump to it. The chunk is never freed.- let mut chunk = CodeChunk::new(64 * 1024);- let trap_exit = chunk.add(&libwasm_jit::stubs::trap_exit(handler));- let runtime = RuntimeInfo {- trap_exit,- memory_grow: helpers::wasm_runtime_memory_grow as *const () as u64,- table_grow: helpers::wasm_runtime_table_grow as *const () as u64,- call_host: helpers::wasm_runtime_call_host as *const () as u64,- allocate: helpers::wasm_runtime_allocate as *const () as u64,- wait: helpers::wasm_runtime_wait as *const () as u64,- notify: helpers::wasm_runtime_notify as *const () as u64,- allocate_exception: super::wasm_runtime_allocate_exception as *const () as u64,- throw: super::wasm_runtime_throw_from_native as *const () as u64,- };- let (trampoline, return_offset) = libwasm_jit::stubs::entry_trampoline();- let entry = chunk.add(&trampoline);- let adapter_code =- libwasm_jit::stubs::runtime_adapter(super::wasm_runtime_call_from_native as *const () as u64, &runtime);- let adapter = chunk.add(&adapter_code);- if super::options().perf_map {- super::write_perf_map_entry(entry, trampoline.len(), "wasm-entry-trampoline");- super::write_perf_map_entry(adapter, adapter_code.len(), "wasm-runtime-adapter");- }- std::mem::forget(chunk);- Stubs {- trap_exit,- entry,- entry_return: entry + return_offset as u64,- adapter,- runtime,- }+ try_stubs().expect("compiled code runs only with its stubs")+ }++ pub fn try_stubs() -> Option<&'static Stubs> {+ STUBS.get_or_init(make_stubs).as_ref()+ }++ fn make_stubs() -> Option<Stubs> {+ let handler = crate::runtime::interpreter::dispatch_table_entry(OPCODE_TRAP_FROM_NATIVE) as u64;+ // NB: The trap exit goes first, so that the others can jump to it. The chunk is never freed.+ let mut chunk = CodeChunk::new(64 * 1024)?;+ let trap_exit = chunk.add(&libwasm_jit::stubs::trap_exit(handler))?;+ let runtime = RuntimeInfo {+ trap_exit,+ memory_grow: helpers::wasm_runtime_memory_grow as *const () as u64,+ table_grow: helpers::wasm_runtime_table_grow as *const () as u64,+ call_host: helpers::wasm_runtime_call_host as *const () as u64,+ allocate: helpers::wasm_runtime_allocate as *const () as u64,+ wait: helpers::wasm_runtime_wait as *const () as u64,+ notify: helpers::wasm_runtime_notify as *const () as u64,+ allocate_exception: super::wasm_runtime_allocate_exception as *const () as u64,+ throw: super::wasm_runtime_throw_from_native as *const () as u64,+ };+ let (trampoline, return_offset) = libwasm_jit::stubs::entry_trampoline();+ let entry = chunk.add(&trampoline)?;+ let adapter_code =+ libwasm_jit::stubs::runtime_adapter(super::wasm_runtime_call_from_native as *const () as u64, &runtime);+ let adapter = chunk.add(&adapter_code)?;+ if super::options().perf_map {+ super::write_perf_map_entry(entry, trampoline.len(), "wasm-entry-trampoline");+ super::write_perf_map_entry(adapter, adapter_code.len(), "wasm-runtime-adapter");+ }+ std::mem::forget(chunk);+ Some(Stubs {+ trap_exit,+ entry,+ entry_return: entry + return_offset as u64,+ adapter,+ runtime,})}- /// Executable memory, written while it is not executable.+ /// Executable memory, written while it is not executable (on macOS, while the writing thread's view of it is not).+ /// Failing to map it, or to make it writable, fails the compile, which leaves the function interpreted.struct CodeChunk {base: *mut u8,size: usize,@@ -587,13 +744,19 @@ mod native {const CHUNK_SIZE: usize = 16 << 20;+ /// How many compiles a store installs between looking for modules that died.+ const SWEEP_INTERVAL: usize = 64;+fn page_size() -> usize {static PAGE_SIZE: OnceLock<usize> = OnceLock::new();*PAGE_SIZE.get_or_init(|| unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize)}+ /// The longest an eager instantiation waits for its compiles.+ const EAGER_WAIT: std::time::Duration = std::time::Duration::from_secs(60);+impl CodeChunk {- fn new(size: usize) -> Self {+ fn new(size: usize) -> Option<Self> {// NB: macOS on Apple silicon maps code writable and executable at once, with MAP_JIT, and switches each// thread's view of it between the two with pthread_jit_write_protect_np().#[cfg(target_os = "macos")]@@ -607,26 +770,32 @@ mod native {libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,);let base = unsafe { libc::mmap(std::ptr::null_mut(), size, protection, flags, -1, 0) };- assert_ne!(base, libc::MAP_FAILED, "no memory for compiled code");- assert!(- CODE_RANGES.add(base as usize, size),- "too much compiled code to fault in"- );- Self {+ if base == libc::MAP_FAILED {+ return None;+ }+ // NB: The fault handler has to know the code, or faults in it would crash the process.+ if !CODE_RANGES.add(base as usize, size) {+ unsafe { libc::munmap(base, size) };+ return None;+ }+ Some(Self {base: base.cast(),size,used: 0,- }+ })}fn has_room(&self, length: usize) -> bool {self.used.next_multiple_of(16) + length <= self.size}- /// Copies `code` in and returns its address.- fn add(&mut self, code: &[u8]) -> u64 {+ /// Copies `code` in and returns its address, or None if the pages could not be made writable, which leaves them+ /// as they were.+ // NB: On macOS, switching the thread's view of the code cannot fail.+ #[cfg_attr(target_os = "macos", allow(clippy::unnecessary_wraps))]+ fn add(&mut self, code: &[u8]) -> Option<u64> {let start = self.used.next_multiple_of(16);- assert!(start + code.len() <= self.size);+ debug_assert!(start + code.len() <= self.size);#[cfg(target_os = "macos")]unsafe {libc::pthread_jit_write_protect_np(0);@@ -640,19 +809,124 @@ mod native {let first_page = start / page_size * page_size;let length = (start + code.len()).next_multiple_of(page_size) - first_page;let region = self.base.add(first_page);- assert_eq!(- libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_WRITE),- 0- );+ if libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_WRITE) != 0 {+ return None;+ }std::ptr::copy_nonoverlapping(code.as_ptr(), self.base.add(start), code.len());- assert_eq!(- libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_EXEC),- 0- );+ // NB: The pages may hold code that is installed already, which must not stop being executable. The+ // change back can only fail for lack of kernel memory, when the process cannot go on anyway.+ if libc::mprotect(region.cast(), length, libc::PROT_READ | libc::PROT_EXEC) != 0 {+ eprintln!(+ "LibWasm JIT: making compiled code executable again failed: {}",+ std::io::Error::last_os_error()+ );+ std::process::abort();+ }libwasm_jit::runtime::flush_instruction_cache(self.base as usize + start, code.len());}self.used = start + code.len();- self.base as u64 + start as u64+ Some(self.base as u64 + start as u64)+ }+ }++ #[cfg(test)]+ mod tests {+ use super::{CODE_RANGES, CompileContext, StoreJit};+ use std::sync::Arc;++ #[test]+ fn a_failed_mapping_makes_no_chunk() {+ assert!(super::CodeChunk::new(1 << 60).is_none());+ }++ #[test]+ fn code_goes_away_with_its_module() {+ // (module (func))+ const MODULE: &[u8] = &[+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01,+ 0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,+ ];+ let module = Arc::new(crate::compile(MODULE).expect("the module is valid"));+ let mut jit = StoreJit::default();+ let key = jit.key(&module, 0, None);+ let request = jit.request(key).expect("the module lives");+ let code = super::compile(&mut CompileContext::default(), &request);+ drop(request);+ jit.finish(key, code);+ let entry = jit.entry(key).expect("the function compiled");+ assert!(CODE_RANGES.contains(entry as usize));+ jit.forget_dead_modules();+ assert!(jit.entry(key).is_some(), "the module still lives");+ drop(module);+ jit.forget_dead_modules();+ assert!(jit.modules.is_empty());+ assert!(!CODE_RANGES.contains(entry as usize));+ }++ #[test]+ fn traps_inside_one_entry_free_their_large_images() {+ use crate::runtime::{ExternValue, FunctionAddress, Store, Value};+ use std::cell::Cell;+ use std::rc::Rc;+ if !crate::runtime::jit::enabled() {+ return;+ }+ let bytes = include_bytes!("../../tests/fixtures/nested_traps.wasm");+ let module = Arc::new(crate::compile(bytes).expect("the module is valid"));+ let mut store = Store::new();+ let wide: Rc<Cell<Option<FunctionAddress>>> = Rc::default();+ let wide_in_host = wide.clone();+ let host = store.allocate_host_function(+ crate::types::FuncType {+ params: Vec::new(),+ results: Vec::new(),+ },+ Rc::new(move |store: &mut Store, _: &[Value]| {+ // NB: The interpreter calls the compiled function, so every call has a large image, which the trap+ // skips.+ let wide = wide_in_host.get().expect("the instance exists");+ let arguments = [Value::I64(0); 70];+ for _ in 0..1_000_000 {+ assert!(store.invoke(wide, &arguments).is_err());+ }+ Ok(Vec::new())+ }),+ );+ let instance = store+ .instantiate(module, &[ExternValue::Function(host)])+ .expect("the module instantiates");+ let export = |name| match store.instance(instance).export(name) {+ Some(ExternValue::Function(function)) => function,+ _ => panic!("no function {name}"),+ };+ let (outer, wide_function) = (export("outer"), export("wide"));+ wide.set(Some(wide_function));+ // The function whose frames the traps skip runs compiled, with a call image too large for the stack.+ while super::compile_function(&mut store, wide_function) != super::CompileState::Compiled {+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ store.invoke(outer, &[]).expect("the host function returns");+ assert!(super::large_image_buffers() <= 2);+ assert_eq!(super::large_images_in_use(), 0);+ }++ #[test]+ fn a_compile_finishing_after_its_module_died_maps_nothing() {+ // (module (func))+ const MODULE: &[u8] = &[+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x04, 0x01, 0x60, 0x00, 0x00, 0x03, 0x02, 0x01,+ 0x00, 0x0a, 0x04, 0x01, 0x02, 0x00, 0x0b,+ ];+ let module = Arc::new(crate::compile(MODULE).expect("the module is valid"));+ let mut jit = StoreJit::default();+ let key = jit.key(&module, 0, None);+ let request = jit.request(key).expect("the module lives");+ let code = super::compile(&mut CompileContext::default(), &request);+ drop(request);+ drop(module);+ jit.finish(key, code);+ assert!(jit.entry(key).is_none());+ assert!(jit.modules.values().all(|module| module.chunks.is_empty()));}}@@ -675,7 +949,16 @@ mod native {/// A compile a compile thread finished, for the store that asked for it.struct Finished {key: CompileKey,- code: Result<CompiledFunction, libwasm_jit::CompileFailure>,+ code: Option<CompiledFunction>,+ }++ /// Compiles `request`, or returns None if the compile fails.+ ///+ /// NB: A panic of the compiler is a bug, and aborts the process like any other: the crates of a process share the+ /// panic hooks and runtime of whichever copy of the standard library the dynamic linker binds first, so+ /// neither catching it nor keeping it out of the crash report can be relied on.+ fn compile(context: &mut CompileContext, request: &CompileRequest) -> Option<CompiledFunction> {+ libwasm_jit::compile(context, request).ok()}struct Job {@@ -712,7 +995,7 @@ mod native {let Ok(job) = job else {return;};- let code = libwasm_jit::compile(&mut context, &job.request);+ let code = compile(&mut context, &job.request);// NB: The store may be gone, and its results with it.let _ = job.reply.send(Finished { key: job.key, code });}@@ -748,36 +1031,64 @@ mod native {Never,}- /// A store's compiled code.+ /// A store's compiled code, kept with the module it is of, for as long as the module lives: its functions and+ /// instances hold it, and code of a module only runs in frames of its functions.#[derive(Default)]pub struct StoreJit {- chunks: Vec<CodeChunk>,context: CompileContext,- /// The code of each compile, and the compiles that failed.- code: HashMap<CompileKey, u64>,- failed: HashSet<CompileKey>,+ /// What the store compiled of each module, by the module's address.+ modules: HashMap<usize, ModuleCode>,/// The return addresses of the calls in compiled code that handle exceptions.exception_sites: HashSet<u64>,/// The compiles the compile threads have yet to finish, and where they send them.pending: HashSet<CompileKey>,finished: Option<(Sender<Finished>, Receiver<Finished>)>,- /// The modules of the keys, so that their addresses stay theirs.- modules: HashMap<usize, Arc<Module>>,+ /// How many modules gained code since the store last looked for modules that died.+ new_code: usize,pub disabled: bool,}- impl StoreJit {- fn add_code(&mut self, code: &[u8]) -> u64 {+ /// The code a store compiled of one module. The reference to the module is weak, so that the module, and then+ /// its code, goes away with its last function or instance; until the store forgets it, the address is not+ /// reused for another module.+ struct ModuleCode {+ module: Weak<Module>,+ chunks: Vec<CodeChunk>,+ /// The code of each compile (by function and OSR loop), and the compiles that failed.+ code: HashMap<(u32, Option<u32>), u64>,+ failed: HashSet<(u32, Option<u32>)>,+ /// The exception sites in the code.+ exception_sites: Vec<u64>,+ }++ /// The first chunk of a module's code; each next one is twice as large, up to `CHUNK_SIZE`.+ const FIRST_CHUNK_SIZE: usize = 64 << 10;++ impl ModuleCode {+ /// Copies `code` into executable memory and returns its address, or None if there is none to be had.+ fn add_code(&mut self, code: &[u8]) -> Option<u64> {if !self.chunks.last().is_some_and(|chunk| chunk.has_room(code.len())) {+ let size = self+ .chunks+ .last()+ .map_or(FIRST_CHUNK_SIZE, |chunk| (chunk.size * 2).min(CHUNK_SIZE));self.chunks- .push(CodeChunk::new(CHUNK_SIZE.max(code.len().next_multiple_of(page_size()))));+ .push(CodeChunk::new(size.max(code.len().next_multiple_of(page_size())))?);}self.chunks.last_mut().expect("there is a chunk").add(code)}+ }+ impl StoreJit {fn key(&mut self, module: &Arc<Module>, function: u32, osr: Option<u32>) -> CompileKey {let address = Arc::as_ptr(module) as usize;- self.modules.entry(address).or_insert_with(|| module.clone());+ self.modules.entry(address).or_insert_with(|| ModuleCode {+ module: Arc::downgrade(module),+ chunks: Vec::new(),+ code: HashMap::new(),+ failed: HashSet::new(),+ exception_sites: Vec::new(),+ });CompileKey {module: address,function,@@ -785,50 +1096,87 @@ mod native {}}- fn request(&self, key: CompileKey) -> CompileRequest {- CompileRequest {- module: self.modules[&key.module].clone(),+ fn request(&self, key: CompileKey) -> Option<CompileRequest> {+ Some(CompileRequest {+ module: self.modules[&key.module].module.upgrade()?,function: key.function,runtime: stubs().runtime,options: super::options().compile_options(),osr: key.osr,- }+ })+ }++ /// The code of a compile, if there is some.+ fn entry(&self, key: CompileKey) -> Option<u64> {+ self.modules+ .get(&key.module)?+ .code+ .get(&(key.function, key.osr))+ .copied()}/// Installs the result of a compile.- fn finish(&mut self, key: CompileKey, compiled: Result<CompiledFunction, libwasm_jit::CompileFailure>) {- let Ok(CompiledFunction {- code, exception_sites, ..- }) = compiled+ fn finish(&mut self, key: CompileKey, compiled: Option<CompiledFunction>) {+ if self.new_code >= SWEEP_INTERVAL {+ self.forget_dead_modules();+ }+ // NB: A module that died while its function compiled gets no code.+ let Some(module) = self+ .modules+ .get_mut(&key.module)+ .filter(|module| module.module.strong_count() > 0)else {- self.failed.insert(key);return;};- let entry = self.add_code(&code);- self.exception_sites- .extend(exception_sites.iter().map(|offset| entry + u64::from(*offset)));+ let entry = compiled.and_then(|compiled| Some((module.add_code(&compiled.code)?, compiled)));+ let Some((entry, compiled)) = entry else {+ module.failed.insert((key.function, key.osr));+ return;+ };+ self.new_code += 1;+ for offset in &compiled.exception_sites {+ let site = entry + u64::from(*offset);+ module.exception_sites.push(site);+ self.exception_sites.insert(site);+ }if super::options().perf_map {let name = match key.osr {None => format!("wasm-function-{}", key.function),Some(offset) => format!("wasm-function-{}-osr-{offset}", key.function),};- super::write_perf_map_entry(entry, code.len(), &name);+ super::write_perf_map_entry(entry, compiled.code.len(), &name);}- self.code.insert(key, entry);+ module.code.insert((key.function, key.osr), entry);+ }++ /// Frees the code of the modules that died, which no function or instance runs any more.+ fn forget_dead_modules(&mut self) {+ self.new_code = 0;+ let exception_sites = &mut self.exception_sites;+ self.modules.retain(|_, module| {+ if module.module.strong_count() > 0 {+ return true;+ }+ for site in &module.exception_sites {+ exception_sites.remove(site);+ }+ false+ });}/// Where the compile of `key` is, after compiling it here and now in sync mode, or else having it compiled/// in the background.fn compile(&mut self, key: CompileKey) -> CompileState {- if self.code.contains_key(&key) {+ if self.entry(key).is_some() {return CompileState::Compiled;}- if self.failed.contains(&key) {+ if self.modules[&key.module].failed.contains(&(key.function, key.osr)) {return CompileState::Failed;}if super::options().sync {- let request = self.request(key);- let code = libwasm_jit::compile(&mut self.context, &request);+ let code = self+ .request(key)+ .and_then(|request| compile(&mut self.context, &request));self.finish(key, code);return self.compile(key);}@@ -839,7 +1187,9 @@ mod native {}fn submit(&mut self, key: CompileKey) {- let request = self.request(key);+ let request = self+ .request(key)+ .expect("a function of the module asks for the compile");let (reply, _) = self.finished.get_or_insert_with(channel);let job = Job {key,@@ -861,8 +1211,15 @@ mod native {};let mut finished = Vec::new();if wait {+ // NB: Every job gets an answer, but if one never came, the store would wait forever; past the+ // deadline, what is still pending is installed later, as in the background.+ let deadline = std::time::Instant::now() + EAGER_WAIT;for _ in 0..self.pending.len() {- finished.push(receiver.recv().expect("the store holds a sender"));+ let Ok(done) = receiver.recv_timeout(deadline.saturating_duration_since(std::time::Instant::now()))+ else {+ break;+ };+ finished.push(done);}} else {finished.extend(receiver.try_iter());@@ -901,6 +1258,10 @@ mod native {}}+ pub fn forget_dead_modules(jit: &mut StoreJit) {+ jit.forget_dead_modules();+ }+pub fn install_finished(jit: &mut StoreJit) {if !jit.pending.is_empty() {jit.take_finished(false);@@ -923,7 +1284,10 @@ mod native {}jit.take_finished(true);for address in functions {- compile_function(store, address);+ if compile_function(store, address) == CompileState::Pending {+ // NB: Eager functions have no budget, so one whose compile is late asks for it like a hot one.+ unsafe { address.get_mut() }.header.tier_up_budget = super::POLL_BUDGET + crate::abi::TIER_UP_CALL_COST;+ }}}@@ -942,7 +1306,7 @@ mod native {let key = jit.key(module, *index, None);let state = jit.compile(key);if state == CompileState::Compiled {- function.header.native_entry = jit.code[&key];+ function.header.native_entry = jit.entry(key).expect("the function is compiled");function.header.kind = FUNCTION_KIND_COMPILED;}state@@ -952,40 +1316,66 @@ mod native {unsafe {let [header, top, ..] = (*context).arguments;let function = &*(header as *const FunctionInstance);- let params = ir_types(&function.ty.params);+ let shape = &shapes(function).call;let parameter_slots = function.header.param_slots as usize;// The operand stack grows down, so the first argument is in the highest slots, and the results replace// the arguments.let stack = top as *mut u64;- let arguments = |index: usize| {- let home = convention::home_slot(¶ms, index) as usize;- stack- .add(parameter_slots - home - params[index].slots() as usize)- .cast_const()- };run(function,function.header.native_entry,- ¶ms,- arguments,+ shape,+ |_, param| stack.add(parameter_slots - param.home - param.slots).cast_const(),stack.add(parameter_slots),)}}- /// Calls `entry`, compiled code of `function` that takes arguments of types `params`, the `index`th of which- /// is at `argument(index)`. Stores the function's results on an operand stack ending at `end`, and returns its- /// new top, or the exception it threw. A trap leaves through the code and does not return.+ /// The images of calls whose image does not fit on the stack, one per call in progress, and how many calls use one.+ /// A trap skips the calls between it and the innermost interpreter entry, which leaves their images counted until+ /// that entry returns and releases them (see `super::release_large_images()`).+ struct LargeImages {+ buffers: Vec<Box<[u64]>>,+ in_use: usize,+ }++ thread_local! {+ static LARGE_IMAGES: std::cell::RefCell<LargeImages> = const {+ std::cell::RefCell::new(LargeImages {+ buffers: Vec::new(),+ in_use: 0,+ })+ };+ }++ pub fn large_images_in_use() -> usize {+ LARGE_IMAGES.with(|images| images.borrow().in_use)+ }++ pub fn release_large_images(in_use: usize) {+ LARGE_IMAGES.with(|images| images.borrow_mut().in_use = in_use);+ }++ #[cfg(test)]+ pub fn large_image_buffers() -> usize {+ LARGE_IMAGES.with(|images| images.borrow().buffers.len())+ }++ /// Calls `entry`, compiled code of `function` whose values `shape` describes, with the `index`th argument at+ /// `argument(index, param)`. Stores the function's results on an operand stack ending at `end`, and returns its+ /// new top, or the exception it threw.+ ///+ /// NB: A trap leaves through the compiled code and does not return, skipping this frame and its callers' up to+ /// the interpreter, so none of them may own anything that needs dropping.unsafe fn run(function: &FunctionInstance,entry: u64,- params: &[libwasm_jit::ir::Type],- argument: impl Fn(usize) -> *const u64,+ shape: &CallShape,+ argument: impl Fn(usize, &super::ValueShape) -> *const u64,end: *mut u64,) -> Result<u64, u64> {unsafe {let header_data: &FunctionHeader = &function.header;- let results = ir_types(&function.ty.results);let result_slots = header_data.result_slots as usize;let mut call = NativeCall {entry,@@ -995,82 +1385,74 @@ mod native {result_pointer_slot: u64::MAX,..NativeCall::default()};- let parameter_slots = convention::slots(params) as usize;- let image_slots = (convention::outgoing_size(params, &results) / 8) as usize;- // NB: On the stack where it fits, since a trap leaves through compiled code and skips this frame, which- // leaks what it owns.const SMALL_IMAGE: usize = 64;let mut small_image = [0u64; SMALL_IMAGE];- let mut large_image = Vec::new();- let image = if image_slots <= SMALL_IMAGE {- small_image.as_mut_ptr()+ let large = shape.image_slots > SMALL_IMAGE;+ let image = if large {+ LARGE_IMAGES.with(|images| {+ let mut images = images.borrow_mut();+ let index = images.in_use;+ images.in_use += 1;+ if images.buffers.len() <= index {+ images.buffers.push(Box::new([]));+ }+ if images.buffers[index].len() < shape.image_slots {+ images.buffers[index] = vec![0; shape.image_slots].into_boxed_slice();+ }+ images.buffers[index].as_mut_ptr()+ })} else {- large_image.resize(image_slots, 0);- large_image.as_mut_ptr()+ small_image.as_mut_ptr()};- let mut places = Vec::new();- convention::parameter_places(params, &mut places);- let (mut gprs, mut xmms) = (0, 0);- for (index, place) in places.iter().enumerate() {- let home = convention::home_slot(params, index) as usize;- let count = params[index].slots() as usize;- let source = argument(index);- std::ptr::copy_nonoverlapping(source, image.add(home), count);- if let Place::Register(_) = place {- if params[index].uses_xmm() {- call.xmms[xmms] = [*source, if count == 2 { *source.add(1) } else { 0 }];- xmms += 1;+ for (index, param) in shape.params.iter().enumerate() {+ let source = argument(index, param);+ std::ptr::copy_nonoverlapping(source, image.add(param.home), param.slots);+ if let Place::Register(_) = param.place {+ if param.ty.uses_xmm() {+ call.xmms[param.register] = [*source, if param.slots == 2 { *source.add(1) } else { 0 }];} else {- call.gprs[gprs] = *source;- gprs += 1;+ call.gprs[param.register] = *source;}}}- if convention::has_result_area(&results) {- call.result_pointer_slot = parameter_slots as u64;+ if shape.has_result_area {+ call.result_pointer_slot = shape.parameter_slots as u64;+ call.result_area_slot = shape.result_area_slot as u64;}call.image = image as u64;- call.image_slots = image_slots as u64;+ call.image_slots = shape.image_slots as u64;let trampoline: extern "C" fn(*mut NativeCall) = std::mem::transmute(stubs().entry as usize);trampoline(&raw mut call);+ if large {+ LARGE_IMAGES.with(|images| images.borrow_mut().in_use -= 1);+ }let context = (*header_data.instance).context;if (*context).exception != 0 {return Err(std::mem::take(&mut (*context).exception));}let return_top = end.sub(result_slots);- convention::result_places(&results, &mut places);- let (mut gprs, mut xmms) = (0, 0);- for (index, place) in places.iter().enumerate() {- let home = convention::home_slot(&results, index) as usize;- let count = results[index].slots() as usize;+ for result in &shape.results {let mut words = [0u64; 2];- match *place {- Place::Register(_) if results[index].uses_xmm() => {- words = call.result_xmms[xmms];- xmms += 1;- }- Place::Register(_) => {- words[0] = call.result_gprs[gprs];- gprs += 1;- }+ match result.place {+ Place::Register(_) if result.ty.uses_xmm() => words = call.result_xmms[result.register],+ Place::Register(_) => words[0] = call.result_gprs[result.register],Place::Memory(slot) => {- let area = image.add(parameter_slots + 1 + slot as usize);- words[..count].copy_from_slice(ak::slice_from_raw_parts(area, count));+ let area = image.add(shape.result_area_slot + slot as usize);+ words[..result.slots].copy_from_slice(ak::slice_from_raw_parts(area, result.slots));}}- // NB: Through a value, so that i32 and f32 results take their slot's low half only.- let value = value_from_words(function.ty.results[index], &words);- words_of_value(&value, &mut words);// The first result is in the highest slots.- let destination = return_top.add(result_slots - home - count);- std::ptr::copy_nonoverlapping(words.as_ptr(), destination, count);+ let destination = return_top.add(result_slots - result.home - result.slots);+ for (slot, word) in words[..result.slots].iter().enumerate() {+ *destination.add(slot) = slot_bits(result.ty, *word);+ }}Ok(return_top as u64)}}/// Continues the interpreter frame at `frame`, of `address`, compiled at the loop at `pc` (OSR), once there is- /// code for that. It cannot be entered at a loop in another loop, or if the function does not compile.+ /// code for that. It cannot be entered at a loop in a legacy catch handler (see `CompileFailure::NoOsrEntry`).pub unsafe fn enter_at_loop(store: &mut Store, address: FunctionAddress, pc: u64, frame: u64) -> LoopEntry {unsafe {let function = address.get();@@ -1088,10 +1470,9 @@ mod native {CompileState::Pending => return LoopEntry::Pending,CompileState::Failed => return LoopEntry::Never,}- let entry = jit.code[&key];- let params = [libwasm_jit::ir::Type::Pointer];+ let entry = jit.entry(key).expect("the loop is compiled");let base = (frame as *mut u8).sub(crate::abi::FRAME_HEADER_SIZE).cast::<u64>();- match run(function, entry, ¶ms, |_| &raw const frame, base) {+ match run(function, entry, &shapes(function).osr, |_, _| &raw const frame, base) {Ok(top) => LoopEntry::Ran(top),Err(exception) => LoopEntry::Threw(exception),}@@ -1109,12 +1490,18 @@ mod native {pub adapter: u64,}- pub static STUBS: std::sync::OnceLock<Stubs> = std::sync::OnceLock::new();+ pub static STUBS: std::sync::OnceLock<Option<Stubs>> = std::sync::OnceLock::new();pub fn stubs() -> &'static Stubs {unreachable!("the JIT is off where it has no code generator")}+ pub fn try_stubs() -> Option<&'static Stubs> {+ None+ }++ pub fn forget_dead_modules(_jit: &mut StoreJit) {}+#[derive(Default)]pub struct StoreJit {pub disabled: bool,@@ -1156,6 +1543,12 @@ mod native {pub unsafe fn call_compiled(_context: *mut ExecutionContext) -> Result<u64, u64> {unreachable!("the JIT is off where it has no code generator")}++ pub fn large_images_in_use() -> usize {+ 0+ }++ pub fn release_large_images(_in_use: usize) {}}pub use native::StoreJit;diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex 87f56378946..f2be4ab66e9 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -205,6 +205,8 @@ pub struct FunctionInstance {/// What `header.vector_storage` points at.pub vector_storage: Box<[u32]>,pub kind: FunctionKind,+ /// Where compiled code passes its values, once a call between the tiers needed it.+ pub native_shapes: std::cell::OnceCell<Box<jit::NativeShapes>>,}/// A table. The interpreter sees its data, which is its first field and so at its handle.@@ -340,6 +342,9 @@ pub struct Store {pending_trap: Option<Trap>,/// What runs after `memory.grow` grows a memory.pub memory_grow_callback: Option<Rc<dyn Fn(MemoryAddress)>>,+ /// 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,/// The store's compiled code, once it has some.jit: Option<jit::StoreJit>,}@@ -393,6 +398,7 @@ impl Store {root: None,rtt_pointers: Vec::new(),memory_grow_callback: None,+ can_block: true,jit: None,}}@@ -565,6 +571,7 @@ impl Store {ty,vector_storage: Box::new([]),kind: FunctionKind::Host(callback),+ native_shapes: std::cell::OnceCell::new(),},);unsafe { function.get_mut() }.header.host = function.as_ptr().cast_const().cast();@@ -820,6 +827,7 @@ impl Store {index: module.imported_function_count + offset as u32,instance: instance_address,},+ native_shapes: std::cell::OnceCell::new(),},);functions.push(address);@@ -965,6 +973,8 @@ impl Store {let instance = unsafe { instance_address.get_mut() };let table_address = instance.tables[*table as usize];let values = std::mem::take(&mut instance.element_storage[index]);+ // NB: The segment no longer owns the values, so it does not point at them either.+ instance.element_segments[index].contents = std::ptr::null();let table = self.table_mut(table_address);let end = offset.checked_add(values.len() as u64);if end.is_none_or(|end| end > table.elements.len() as u64) {@@ -1075,18 +1085,42 @@ impl Store {if let FunctionKind::Host(_) = function.kind {return self.call_host(address, arguments);}- let ty = function.ty.clone();- let header: *const FunctionHeader = &raw const function.header;// The arguments are laid out as they will be on the operand stack, which grows down: the last one first.let mut argument_slots = Vec::new();for argument in arguments.iter().rev() {argument.push_slots(&mut argument_slots);}let mut result_slots = vec![0u64; function.header.result_slots as usize];+ self.invoke_slots(address, &argument_slots, &mut result_slots)?;+ // The results are laid out as the operand stack holds them, the first one in the highest slots.+ let function = self.function(address);+ let mut results = Vec::with_capacity(function.ty.results.len());+ let mut slot = result_slots.len();+ for &result in &function.ty.results {+ slot -= result.slot_count() as usize;+ results.push(Value::from_slots(result, &result_slots[slot..]));+ }+ Ok(results)+ }++ /// Calls the WebAssembly function `address` with the slots of its arguments as the operand stack holds them (the+ /// last argument in the lowest slots), and stores its results' slots the same way in `result_slots`.+ pub fn invoke_slots(+ &mut self,+ address: FunctionAddress,+ argument_slots: &[u64],+ result_slots: &mut [u64],+ ) -> Result<(), Trap> {+ let function = self.function(address);+ debug_assert!(!matches!(function.kind, FunctionKind::Host(_)));+ debug_assert_eq!(argument_slots.len(), function.header.param_slots as usize);+ debug_assert_eq!(result_slots.len(), function.header.result_slots as usize);+ 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);}+ let large_images = jit::large_images_in_use();self.context.store = (self as *mut Store).cast();let mut record = EntryRecord {function: header,@@ -1099,17 +1133,12 @@ impl Store {saved_entry_record: std::ptr::null_mut(),};unsafe { interpreter::enter(&mut record) };+ // NB: A trap may have skipped calls into compiled code that held large images.+ jit::release_large_images(large_images);if record.trap != 0 {return Err(Trap::from_code(record.trap, self.pending_trap.take()));}- // The results are laid out as the operand stack holds them, the first one in the highest slots.- let mut results = Vec::with_capacity(ty.results.len());- let mut slot = result_slots.len();- for &result in &ty.results {- slot -= result.slot_count() as usize;- results.push(Value::from_slots(result, &result_slots[slot..]));- }- Ok(results)+ Ok(())}fn call_host(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {diff --git a/Libraries/LibWasm/Engine/src/runtime/ranges.rs b/Libraries/LibWasm/Engine/src/runtime/ranges.rsindex 399034a35f4..b84afdf0727 100644--- a/Libraries/LibWasm/Engine/src/runtime/ranges.rs+++ b/Libraries/LibWasm/Engine/src/runtime/ranges.rs@@ -5,9 +5,12 @@*///! Sets of address ranges that the fault handler looks addresses up in: the reservations of memories, and later the-//! code of compiled functions. A lookup takes no lock and touches only a fixed static array, so it is async-signal-safe-//! and cannot be blocked by a thread that is adding or removing a range. Adding and removing take a lock among-//! themselves.+//! code of compiled functions. A lookup takes no lock and only reads memory that is never freed, so it is+//! async-signal-safe and cannot be blocked by a thread that is adding or removing a range. Adding and removing take a+//! lock among themselves.+//!+//! The slots are in a fixed array and, once that is full, in further segments that adding allocates and links in;+//! segments are never freed, and a lookup follows the links.//!//! Each slot is a seqlock: its writer makes the sequence odd, writes the range, and makes the sequence even again. A//! lookup that sees an odd sequence, or a sequence that changed while it read the range, skips the slot. That is safe@@ -15,19 +18,28 @@//! handler must recognize lands in a range that is changing.use std::sync::Mutex;-use std::sync::atomic::{AtomicUsize, Ordering, fence};+use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering, fence};-/// The most ranges a set holds.+/// The slots of the fixed array, and of each further segment.pub const CAPACITY: usize = 4096;+#[derive(Default)]struct Slot {sequence: AtomicUsize,start: AtomicUsize,end: AtomicUsize,}+/// Slots beyond the fixed array.+struct Segment {+ slots: Box<[Slot]>,+ next: AtomicPtr<Segment>,+}+pub struct RangeSet {slots: [Slot; CAPACITY],+ /// The first further segment, or null.+ next: AtomicPtr<Segment>,/// Serializes the writers.lock: Mutex<()>,}@@ -42,10 +54,28 @@ impl RangeSet {end: AtomicUsize::new(0),}}; CAPACITY],+ next: AtomicPtr::new(std::ptr::null_mut()),lock: Mutex::new(()),}}+ /// Calls `visit` with every slot, until it returns true. Returns whether it did.+ fn any_slot(&self, mut visit: impl FnMut(&Slot) -> bool) -> bool {+ if self.slots.iter().any(&mut visit) {+ return true;+ }+ let mut segment = self.next.load(Ordering::Acquire);+ while !segment.is_null() {+ // SAFETY: Segments are never freed once they are linked in.+ let current = unsafe { &*segment };+ if current.slots.iter().any(&mut visit) {+ return true;+ }+ segment = current.next.load(Ordering::Acquire);+ }+ false+ }+fn write(slot: &Slot, start: usize, end: usize) {let sequence = slot.sequence.load(Ordering::Relaxed);slot.sequence.store(sequence.wrapping_add(1), Ordering::Relaxed);@@ -55,32 +85,57 @@ impl RangeSet {slot.sequence.store(sequence.wrapping_add(2), Ordering::Release);}- /// Add the range [start, start + length). Returns false if the set is full.+ /// Add the range [start, start + length). Returns false if the set is full, which it never is: it grows.pub fn add(&self, start: usize, length: usize) -> bool {assert!(start != 0 && length != 0, "ranges are not empty and not at null");let _guard = self.lock.lock().expect("the range lock is never poisoned");- let Some(slot) = self.slots.iter().find(|slot| slot.end.load(Ordering::Relaxed) == 0) else {- return false;- };- Self::write(slot, start, start + length);+ let mut free = None;+ self.any_slot(|slot| {+ if slot.end.load(Ordering::Relaxed) == 0 {+ free = Some(std::ptr::from_ref(slot));+ return true;+ }+ false+ });+ if let Some(slot) = free {+ // SAFETY: Slots are never freed.+ Self::write(unsafe { &*slot }, start, start + length);+ return true;+ }+ // Every slot is taken: link in a segment whose first slot holds the range before anyone can see it.+ let segment = Box::leak(Box::new(Segment {+ slots: (0..CAPACITY).map(|_| Slot::default()).collect(),+ next: AtomicPtr::new(std::ptr::null_mut()),+ }));+ Self::write(&segment.slots[0], start, start + length);+ let mut link = &self.next;+ loop {+ let next = link.load(Ordering::Acquire);+ if next.is_null() {+ break;+ }+ // SAFETY: As in any_slot().+ link = unsafe { &(*next).next };+ }+ link.store(segment, Ordering::Release);true}/// Remove the range that starts at `start`.pub fn remove(&self, start: usize) {let _guard = self.lock.lock().expect("the range lock is never poisoned");- if let Some(slot) = self- .slots- .iter()- .find(|slot| slot.end.load(Ordering::Relaxed) != 0 && slot.start.load(Ordering::Relaxed) == start)- {- Self::write(slot, 0, 0);- }+ self.any_slot(|slot| {+ if slot.end.load(Ordering::Relaxed) != 0 && slot.start.load(Ordering::Relaxed) == start {+ Self::write(slot, 0, 0);+ return true;+ }+ false+ });}/// Whether `address` is in one of the ranges. Async-signal-safe.pub fn contains(&self, address: usize) -> bool {- self.slots.iter().any(|slot| {+ self.any_slot(|slot| {let before = slot.sequence.load(Ordering::Acquire);if before & 1 != 0 {return false;@@ -114,4 +169,18 @@ mod tests {set.remove(0x1000);assert!(!set.contains(0x1000) && set.contains(0x4000));}++ #[test]+ fn grows_past_its_fixed_slots() {+ let set = RangeSet::new();+ let count = 3 * super::CAPACITY;+ for index in 0..count {+ assert!(set.add(0x1000 * (index + 1), 0x10));+ }+ assert!(set.contains(0x1000) && set.contains(0x1000 * count + 0xf));+ set.remove(0x1000 * count);+ assert!(!set.contains(0x1000 * count));+ assert!(set.add(0x1000 * (count + 1), 0x10));+ assert!(set.contains(0x1000 * (count + 1)));+ }}diff --git a/Libraries/LibWasm/Engine/src/types.rs b/Libraries/LibWasm/Engine/src/types.rsindex 80f37861548..2d8d8df2621 100644--- a/Libraries/LibWasm/Engine/src/types.rs+++ b/Libraries/LibWasm/Engine/src/types.rs@@ -121,6 +121,12 @@ pub enum StorageType {}impl StorageType {+ /// The bytes a struct field or array element of this storage type takes in a GC object's data (see+ /// `abi::STORAGE_64`): 16 for a v128, else 8.+ pub fn object_field_size(self) -> u32 {+ if self == Self::Val(ValType::V128) { 16 } else { 8 }+ }+pub fn is_packed(self) -> bool {matches!(self, Self::I8 | Self::I16)}diff --git a/Libraries/LibWasm/Engine/src/validator.rs b/Libraries/LibWasm/Engine/src/validator.rsindex c93c04c823b..3ad7e232c95 100644--- a/Libraries/LibWasm/Engine/src/validator.rs+++ b/Libraries/LibWasm/Engine/src/validator.rs@@ -1523,7 +1523,14 @@ impl FunctionValidator<'_> {let type_index = reader.read_u32()?;let count = reader.read_u32()?;let element = self.array_type(type_index)?;- for _ in 0..count {+ // NB: Beyond the operands on the stack, an unreachable frame's stack is polymorphic and every pop+ // succeeds; those pops change nothing, so they are skipped rather than done up to 2^32 times.+ let frame = self.frames.last().expect("validation always has a frame");+ let available = self.operands.len() - frame.height;+ if count as usize > available && !frame.unreachable {+ return type_mismatch();+ }+ for _ in 0..(count as usize).min(available) {self.pop_expecting(element.storage.unpacked())?;}self.push_value(reference(false, type_index));diff --git a/Libraries/LibWasm/Engine/src/wasi.rs b/Libraries/LibWasm/Engine/src/wasi.rsindex 218c8d0462c..2c431264a89 100644--- a/Libraries/LibWasm/Engine/src/wasi.rs+++ b/Libraries/LibWasm/Engine/src/wasi.rs@@ -40,13 +40,23 @@ pub struct Wasi {environment: Vec<String>,/// The preopened directories, which are the guest's descriptors from 3 up.preopens: Vec<Preopen>,- /// The guest descriptors path_open created, and the host descriptors they are.- files: RefCell<HashMap<u32, i32>>,+ /// The guest's open descriptors besides the preopens: 0 to 2, which are the host's standard input, output and+ /// error, and those path_open created.+ files: RefCell<HashMap<u32, File>>,next_fd: Cell<u32>,memory: Cell<Option<MemoryAddress>>,exit_code: Cell<Option<i32>>,}+/// A guest descriptor's host descriptor.+#[derive(Clone, Copy)]+struct File {+ host_fd: i32,+ /// Whether the guest owns the host descriptor, which closing the guest's then closes. The host's standard+ /// streams stay open whatever the guest closes.+ owned: bool,+}+/// A WASI errno value.type Errno = u16;@@ -60,6 +70,8 @@ const ERRNO_INVAL: Errno = 28;const ERRNO_IO: Errno = 29;const ERRNO_ISDIR: Errno = 31;const ERRNO_NOSYS: Errno = 52;+#[cfg_attr(not(unix), allow(dead_code))]+const ERRNO_NOTCAPABLE: Errno = 76;/// What a guest descriptor refers to.enum Descriptor {@@ -74,7 +86,19 @@ impl Wasi {arguments,environment,preopens,- files: RefCell::new(HashMap::new()),+ files: RefCell::new(+ (0..3)+ .map(|fd| {+ (+ fd,+ File {+ host_fd: fd as i32,+ owned: false,+ },+ )+ })+ .collect(),+ ),next_fd: Cell::new(next_fd),memory: Cell::new(None),exit_code: Cell::new(None),@@ -137,14 +161,12 @@ impl Wasi {}fn descriptor(&self, fd: u32) -> Option<Descriptor> {- if fd <= 2 {- return Some(Descriptor::Host(fd as i32));+ if let Some(preopen) = fd.checked_sub(3)+ && (preopen as usize) < self.preopens.len()+ {+ return Some(Descriptor::Preopen(preopen as usize));}- let preopen = (fd - 3) as usize;- if preopen < self.preopens.len() {- return Some(Descriptor::Preopen(preopen));- }- self.files.borrow().get(&fd).map(|&host_fd| Descriptor::Host(host_fd))+ self.files.borrow().get(&fd).map(|file| Descriptor::Host(file.host_fd))}fn host_fd(&self, fd: u32) -> Result<i32, Errno> {@@ -155,14 +177,10 @@ impl Wasi {}}- /// The host descriptor to resolve paths relative to `fd` from, which is the working directory for a descriptor- /// the guest does not have.+ /// The host descriptor to resolve paths relative to `fd` from. Paths only reach what is beneath a descriptor the+ /// guest has (the capability model): the platform functions resolve them beneath it.fn directory_fd(&self, fd: u32) -> Result<i32, Errno> {- match self.descriptor(fd) {- Some(Descriptor::Host(host_fd)) => Ok(host_fd),- Some(Descriptor::Preopen(index)) => self.preopen_fd(index),- None => Ok(platform::AT_FDCWD),- }+ self.host_fd(fd)}fn preopen_fd(&self, index: usize) -> Result<i32, Errno> {@@ -185,9 +203,11 @@ impl Wasi {"clock_res_get" => memory.write_u64(a(1), platform::clock_resolution(a(0))?),"clock_time_get" => memory.write_u64(a(2), platform::clock_time(a(0))?),"fd_close" => match self.descriptor(a(0)) {- Some(Descriptor::Host(host_fd)) => {- platform::close(host_fd)?;- self.files.borrow_mut().remove(&a(0));+ Some(Descriptor::Host(_)) => {+ let file = self.files.borrow_mut().remove(&a(0)).expect("the descriptor is a file");+ if file.owned {+ platform::close(file.host_fd)?;+ }Ok(())}Some(Descriptor::Preopen(_)) => Err(ERRNO_ISDIR),@@ -280,7 +300,7 @@ impl Wasi {let host_fd = platform::open_at(directory, memory.slice(a(2), a(3))?, &options)?;let fd = self.next_fd.get();self.next_fd.set(fd + 1);- self.files.borrow_mut().insert(fd, host_fd);+ self.files.borrow_mut().insert(fd, File { host_fd, owned: true });memory.write_u32(a(8), fd)}"random_get" => platform::fill_with_random(memory.slice(a(0), a(1))?),@@ -431,12 +451,143 @@ fn write_filestat(memory: &mut Memory, address: u32, status: &FileStatus) -> Res#[cfg(unix)]mod platform {- use super::{ERRNO_INVAL, ERRNO_IO, Errno, FileStatus, OpenOptions};+ use super::{ERRNO_INVAL, ERRNO_IO, ERRNO_NOTCAPABLE, Errno, FileStatus, OpenOptions};+ use std::collections::VecDeque;use std::ffi::CString;- pub const AT_FDCWD: i32 = libc::AT_FDCWD;pub const WHENCE_CURRENT: u32 = 1;+ /// The most symbolic links one path resolution follows, as Linux's.+ const MAX_SYMLINKS: u32 = 40;++ /// A path resolved beneath a directory: the directory its last component is in, and that component, which is+ /// neither `..` nor a symbolic link that the resolution was to follow.+ struct Beneath {+ directory: i32,+ /// Whether `directory` is a descriptor of the resolution's own, which it closes.+ owned: bool,+ name: CString,+ }++ impl Drop for Beneath {+ fn drop(&mut self) {+ if self.owned {+ unsafe { libc::close(self.directory) };+ }+ }+ }++ fn components(path: &[u8]) -> impl DoubleEndedIterator<Item = &[u8]> {+ path.split(|byte| *byte == b'/')+ .filter(|component| !component.is_empty() && *component != b".")+ }++ /// The symbolic link `name` in `directory` points to, or None if it is not one.+ fn link_target(directory: i32, name: &CString) -> Result<Option<Vec<u8>>, Errno> {+ let mut status = unsafe { std::mem::zeroed::<libc::stat>() };+ if unsafe { libc::fstatat(directory, name.as_ptr(), &raw mut status, libc::AT_SYMLINK_NOFOLLOW) } != 0+ || status.st_mode & libc::S_IFMT != libc::S_IFLNK+ {+ return Ok(None);+ }+ let mut target = vec![0u8; libc::PATH_MAX as usize];+ let length = unsafe { libc::readlinkat(directory, name.as_ptr(), target.as_mut_ptr().cast(), target.len()) };+ if length < 0 {+ return Err(last_errno());+ }+ target.truncate(length as usize);+ Ok(Some(target))+ }++ /// Resolves `path` beneath the directory `base`, one component at a time, so that it never leaves it: absolute+ /// paths and symbolic links, and `..` above `base`, are not capable. Symbolic links in the middle are followed+ /// (beneath `base`), and the last one too if `follow_last`.+ fn resolve_beneath(base: i32, path: &[u8], follow_last: bool) -> Result<Beneath, Errno> {+ if path.is_empty() {+ return Err(errno_of(libc::ENOENT));+ }+ if path[0] == b'/' {+ return Err(ERRNO_NOTCAPABLE);+ }+ // The directories below `base` the resolution is in, innermost last, which it owns.+ let mut directories: Vec<i32> = Vec::new();+ let close_all = |directories: &mut Vec<i32>| {+ for fd in directories.drain(..) {+ unsafe { libc::close(fd) };+ }+ };+ let mut queue: VecDeque<Vec<u8>> = components(path).map(<[u8]>::to_vec).collect();+ let mut links = 0;+ let result = loop {+ let Some(component) = queue.pop_front() else {+ break Ok(c".".to_owned());+ };+ let current = *directories.last().unwrap_or(&base);+ if component == b".." {+ match directories.pop() {+ Some(fd) => unsafe {+ libc::close(fd);+ },+ None => break Err(ERRNO_NOTCAPABLE),+ }+ continue;+ }+ let name = match path_of(&component) {+ Ok(name) => name,+ Err(errno) => break Err(errno),+ };+ let last = queue.is_empty();+ if !last || follow_last {+ match link_target(current, &name) {+ Ok(Some(target)) => {+ links += 1;+ if links > MAX_SYMLINKS {+ break Err(errno_of(libc::ELOOP));+ }+ if target.first() == Some(&b'/') {+ break Err(ERRNO_NOTCAPABLE);+ }+ for component in components(&target).rev() {+ queue.push_front(component.to_vec());+ }+ continue;+ }+ Ok(None) => {}+ Err(errno) => break Err(errno),+ }+ }+ if last {+ break Ok(name);+ }+ let fd = unsafe {+ libc::openat(+ current,+ name.as_ptr(),+ libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_RDONLY | libc::O_CLOEXEC,+ )+ };+ if fd < 0 {+ break Err(last_errno());+ }+ directories.push(fd);+ };+ match result {+ Ok(name) => {+ let directory = directories.pop();+ close_all(&mut directories);+ Ok(Beneath {+ directory: directory.unwrap_or(base),+ owned: directory.is_some(),+ name,+ })+ }+ Err(errno) => {+ close_all(&mut directories);+ Err(errno)+ }+ }+ }+const NANOSECONDS_PER_SECOND: u64 = 1_000_000_000;fn last_errno() -> Errno {@@ -518,7 +669,7 @@ mod platform {const RIGHTS_FD_READ: u64 = 1 << 1;const RIGHTS_FD_WRITE: u64 = 1 << 6;- let path = path_of(path)?;+ let resolved = resolve_beneath(directory, path, options.follow_symlinks)?;let readable = options.rights & RIGHTS_FD_READ != 0;let writable = options.rights & RIGHTS_FD_WRITE != 0;let mut flags = match (readable, writable) {@@ -548,10 +699,10 @@ mod platform {if options.fd_flags & FDFLAGS_SYNC != 0 {flags |= libc::O_SYNC;}- if !options.follow_symlinks {- flags |= libc::O_NOFOLLOW;- }- let fd = unsafe { libc::openat(directory, path.as_ptr(), flags, 0o644 as libc::c_uint) };+ // NB: The resolution followed the symbolic links it was to follow: a link in the last place now is one that+ // appeared since, which must not be followed out.+ flags |= libc::O_NOFOLLOW;+ let fd = unsafe { libc::openat(resolved.directory, resolved.name.as_ptr(), flags, 0o644 as libc::c_uint) };if fd < 0 { Err(last_errno()) } else { Ok(fd) }}@@ -596,8 +747,8 @@ mod platform {}pub fn create_directory(directory: i32, path: &[u8]) -> Result<(), Errno> {- let path = path_of(path)?;- if unsafe { libc::mkdirat(directory, path.as_ptr(), 0o755) } != 0 {+ let resolved = resolve_beneath(directory, path, false)?;+ if unsafe { libc::mkdirat(resolved.directory, resolved.name.as_ptr(), 0o755) } != 0 {return Err(last_errno());}Ok(())@@ -644,10 +795,10 @@ mod platform {}pub fn stat_at(directory: i32, path: &[u8], follow_symlinks: bool) -> Result<FileStatus, Errno> {- let path = path_of(path)?;- let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };+ let resolved = resolve_beneath(directory, path, follow_symlinks)?;let mut status = unsafe { std::mem::zeroed::<libc::stat>() };- if unsafe { libc::fstatat(directory, path.as_ptr(), &raw mut status, flags) } != 0 {+ let (directory, name) = (resolved.directory, resolved.name.as_ptr());+ if unsafe { libc::fstatat(directory, name, &raw mut status, libc::AT_SYMLINK_NOFOLLOW) } != 0 {return Err(last_errno());}Ok(status_of(&status))@@ -728,7 +879,6 @@ mod platform {mod platform {use super::{ERRNO_NOSYS, Errno, FileStatus, OpenOptions};- pub const AT_FDCWD: i32 = -100;pub const WHENCE_CURRENT: u32 = 1;pub fn open_directory(_: &str) -> Result<i32, Errno> {diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rsindex ed42154e965..7e778ee28de 100644--- a/Libraries/LibWasm/Engine/tests/execution.rs+++ b/Libraries/LibWasm/Engine/tests/execution.rs@@ -267,6 +267,111 @@ fn waits_on_shared_memory() {);}+#[test]+fn wait_traps_in_an_agent_that_cannot_block() {+ let mut store = Store::new();+ store.can_block = false;+ let instance = instantiate(&mut store, "shared_waits.wasm");+ // Even where the value differs and nothing would block.+ for expected in [0, 1] {+ assert!(matches!(+ call(+ &mut store,+ instance,+ "wait",+ &[Value::I32(0), Value::I32(expected), Value::I64(0)]+ ),+ Err(Trap::Host(_))+ ));+ }+ assert_eq!(+ call(&mut store, instance, "notify", &[Value::I32(0)]),+ Ok(vec![Value::I32(0)])+ );+}++#[test]+fn active_element_segments_point_nowhere_after_instantiation() {+ let mut store = Store::new();+ let instance = instantiate(&mut store, "element_segments.wasm");+ // The active segment's values went into the table and the segment was dropped: nothing points at its storage.+ let segments = &store.instance(instance).element_segments;+ assert!(segments[0].contents.is_null());+ assert_eq!(segments[0].length, 0);+ assert!(!segments[1].contents.is_null());+ assert_eq!(segments[1].length, 2);+ assert_eq!(+ call(&mut store, instance, "call", &[Value::I32(1)]),+ Ok(vec![Value::I32(7)])+ );+ assert_eq!(call(&mut store, instance, "init", &[Value::I32(2)]), Ok(vec![]));+ assert_eq!(+ call(&mut store, instance, "call", &[Value::I32(3)]),+ Ok(vec![Value::I32(7)])+ );+}++#[test]+fn constant_arrays_too_large_for_memory_trap() {+ for name in ["huge_constant_arrays.wasm", "huge_constant_arrays_new.wasm"] {+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("tests/fixtures")+ .join(name);+ let module = libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap();+ let mut store = Store::new();+ // The length is 2^32 - 1: building the elements first aborted the process.+ assert!(store.instantiate(Arc::new(module), &[]).is_err(), "{name}");+ }+}++/// memory.atomic.wait waits where Atomics.wait does, on the operating system's waiter list for the address, so that+/// a wake of the address from outside WebAssembly (here a FUTEX_WAKE, as Atomics.notify does) ends it.+#[cfg(target_os = "linux")]+#[test]+fn waits_end_with_wakes_from_outside_webassembly() {+ let (sender, receiver) = std::sync::mpsc::channel();+ let waiter = std::thread::spawn(move || {+ let mut store = Store::new();+ 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();+ // Ten seconds, which only a wake cuts short.+ call(+ &mut store,+ instance,+ "wait",+ &[Value::I32(8), Value::I32(0), Value::I64(10_000_000_000)],+ )+ });+ let address = receiver.recv().unwrap() + 8;+ let start = std::time::Instant::now();+ loop {+ // Until the wait has started: a wake before it wakes nobody.+ let woken = unsafe {+ libc::syscall(+ libc::SYS_futex,+ address as *mut u32,+ libc::FUTEX_WAKE,+ 1,+ std::ptr::null::<libc::timespec>(),+ std::ptr::null::<u32>(),+ 0,+ )+ };+ if woken == 1 {+ break;+ }+ assert!(+ start.elapsed() < std::time::Duration::from_secs(5),+ "the wait never started"+ );+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ assert_eq!(waiter.join().unwrap(), Ok(vec![Value::I32(0)]));+}+#[test]fn traps_on_ranges_that_wrap_around() {let mut store = Store::new();@@ -303,3 +408,16 @@ fn traps_on_ranges_that_wrap_around() {Ok(vec![]));}++#[test]+fn calls_between_the_tiers_with_many_values() {+ let run = |interpreted: bool| {+ let mut store = Store::new();+ if interpreted {+ store.disable_jit();+ }+ let instance = instantiate(&mut store, "wide_calls.wasm");+ call(&mut store, instance, "run", &[]).unwrap()+ };+ assert_eq!(run(false), run(true));+}diff --git a/Libraries/LibWasm/Engine/tests/fixtures/element_segments.wasm b/Libraries/LibWasm/Engine/tests/fixtures/element_segments.wasmnew file mode 100644index 00000000000..350a44aff83Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/element_segments.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/element_segments.wat b/Libraries/LibWasm/Engine/tests/fixtures/element_segments.watnew file mode 100644index 00000000000..18a0fb376ad--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/element_segments.wat@@ -0,0 +1,10 @@+;; An active element segment, which instantiation copies into the table and drops, and a passive one.+(module+ (table 4 funcref)+ (func $f (result i32) (i32.const 7))+ (elem (i32.const 1) func $f)+ (elem $passive func $f $f)+ (func (export "call") (param i32) (result i32)+ (call_indirect (result i32) (local.get 0)))+ (func (export "init") (param i32)+ (table.init $passive (local.get 0) (i32.const 0) (i32.const 2))))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.wasm b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.wasmnew file mode 100644index 00000000000..a5d224f27adBinary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.wat b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.watnew file mode 100644index 00000000000..6dd58b50163--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays.wat@@ -0,0 +1,4 @@+;; Arrays of constant expressions with the largest lengths, which do not fit in memory.+(module+ (type $a (array (mut i64)))+ (global (ref $a) (array.new_default $a (i32.const -1))))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.wasm b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.wasmnew file mode 100644index 00000000000..9e09d3315cfBinary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.wat b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.watnew file mode 100644index 00000000000..6e66066420f--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/huge_constant_arrays_new.wat@@ -0,0 +1,4 @@+;; array.new in a constant expression with the largest length, which does not fit in memory.+(module+ (type $a (array (mut i64)))+ (global (ref $a) (array.new $a (i64.const 7) (i32.const -1))))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.wasm b/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.wasmnew file mode 100644index 00000000000..aa42b2faf7fBinary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.wat b/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.watnew file mode 100644index 00000000000..58cee05f98f--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/nested_traps.wat@@ -0,0 +1,6 @@+;; A host function that calls a function many times inside one call of the module, which traps in compiled code+;; whose call image is too large for the stack.+(module+ (import "env" "host" (func $host))+ (func $wide (export "wide") (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64) (unreachable))+ (func (export "outer") (call $host)))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.wasm b/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.wasmnew file mode 100644index 00000000000..b50faafeb68Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.wat b/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.watnew file mode 100644index 00000000000..d6a269aba74--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/shared_memory_export.wat@@ -0,0 +1,5 @@+;; A shared memory, exported, and waits on it.+(module+ (memory (export "memory") 1 1 shared)+ (func (export "wait") (param i32 i32 i64) (result i32)+ (memory.atomic.wait32 (local.get 0) (local.get 1) (local.get 2))))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.wasm b/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.wasmnew file mode 100644index 00000000000..fea18c92c62Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.wat b/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.watnew file mode 100644index 00000000000..c7c99970c0e--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/wasi_calls.wat@@ -0,0 +1,15 @@+;; WASI functions, exported as they are, for tests to call with arguments of their choice.+(module+ (import "wasi_snapshot_preview1" "fd_close" (func $fd_close (param i32) (result i32)))+ (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))+ (import "wasi_snapshot_preview1" "path_open"+ (func $path_open (param i32 i32 i32 i32 i32 i64 i64 i32 i32) (result i32)))+ (import "wasi_snapshot_preview1" "path_create_directory" (func $path_create_directory (param i32 i32 i32) (result i32)))+ (import "wasi_snapshot_preview1" "path_filestat_get"+ (func $path_filestat_get (param i32 i32 i32 i32 i32) (result i32)))+ (memory (export "memory") 1)+ (export "fd_close" (func $fd_close))+ (export "fd_write" (func $fd_write))+ (export "path_open" (func $path_open))+ (export "path_create_directory" (func $path_create_directory))+ (export "path_filestat_get" (func $path_filestat_get)))diff --git a/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.wasm b/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.wasmnew file mode 100644index 00000000000..0b700c19342Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.wat b/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.watnew file mode 100644index 00000000000..341f78ddb7f--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/wide_calls.wat@@ -0,0 +1,18 @@+;; Calls between the tiers with more values than fit in registers or in the runtime's stack buffers: compiled code+;; calls $f through the runtime adapter while $f is interpreted, and the interpreter calls it once it is compiled.+(module+ (func $f (param i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64 v128) (result i64 v128 i64 i64 i64 i64 i64 i64 i64 i64 i64)+ (local.get 0) (local.get 1) (local.get 2) (local.get 3) (local.get 4) (local.get 5) (local.get 6) (local.get 7) (local.get 8) (local.get 9) (local.get 10) (local.get 11) (local.get 12) (local.get 13) (local.get 14) (local.get 15) (local.get 16) (local.get 17) (local.get 18) (local.get 19) (local.get 20) (local.get 21) (local.get 22) (local.get 23) (local.get 24) (local.get 25) (local.get 26) (local.get 27) (local.get 28) (local.get 29) (local.get 30) (local.get 31) (local.get 32) (local.get 33) (local.get 34) (local.get 35) (local.get 36) (local.get 37) (local.get 38) (local.get 39) (local.get 40) (local.get 41) (local.get 42) (local.get 43) (local.get 44) (local.get 45) (local.get 46) (local.get 47) (local.get 48) (local.get 49) (local.get 50) (local.get 51) (local.get 52) (local.get 53) (local.get 54) (local.get 55) (local.get 56) (local.get 57) (local.get 58) (local.get 59) (local.get 60) (local.get 61) (local.get 62) (local.get 63) (local.get 64) (local.get 65) (local.get 66) (local.get 67) (local.get 68) (local.get 69) (i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)(i64.add)+ (local.get 70)+ (i64.const 1) (i64.const 2) (i64.const 3) (i64.const 4) (i64.const 5) (i64.const 6) (i64.const 7) (i64.const 8) (i64.const 9))+ (func (export "run") (result i64 v128) (local $i i64) (local $sum i64) (local $v v128)+ (loop $l+ (i64.add (local.get $i) (i64.const 0)) (i64.add (local.get $i) (i64.const 1)) (i64.add (local.get $i) (i64.const 2)) (i64.add (local.get $i) (i64.const 3)) (i64.add (local.get $i) (i64.const 4)) (i64.add (local.get $i) (i64.const 5)) (i64.add (local.get $i) (i64.const 6)) (i64.add (local.get $i) (i64.const 7)) (i64.add (local.get $i) (i64.const 8)) (i64.add (local.get $i) (i64.const 9)) (i64.add (local.get $i) (i64.const 10)) (i64.add (local.get $i) (i64.const 11)) (i64.add (local.get $i) (i64.const 12)) (i64.add (local.get $i) (i64.const 13)) (i64.add (local.get $i) (i64.const 14)) (i64.add (local.get $i) (i64.const 15)) (i64.add (local.get $i) (i64.const 16)) (i64.add (local.get $i) (i64.const 17)) (i64.add (local.get $i) (i64.const 18)) (i64.add (local.get $i) (i64.const 19)) (i64.add (local.get $i) (i64.const 20)) (i64.add (local.get $i) (i64.const 21)) (i64.add (local.get $i) (i64.const 22)) (i64.add (local.get $i) (i64.const 23)) (i64.add (local.get $i) (i64.const 24)) (i64.add (local.get $i) (i64.const 25)) (i64.add (local.get $i) (i64.const 26)) (i64.add (local.get $i) (i64.const 27)) (i64.add (local.get $i) (i64.const 28)) (i64.add (local.get $i) (i64.const 29)) (i64.add (local.get $i) (i64.const 30)) (i64.add (local.get $i) (i64.const 31)) (i64.add (local.get $i) (i64.const 32)) (i64.add (local.get $i) (i64.const 33)) (i64.add (local.get $i) (i64.const 34)) (i64.add (local.get $i) (i64.const 35)) (i64.add (local.get $i) (i64.const 36)) (i64.add (local.get $i) (i64.const 37)) (i64.add (local.get $i) (i64.const 38)) (i64.add (local.get $i) (i64.const 39)) (i64.add (local.get $i) (i64.const 40)) (i64.add (local.get $i) (i64.const 41)) (i64.add (local.get $i) (i64.const 42)) (i64.add (local.get $i) (i64.const 43)) (i64.add (local.get $i) (i64.const 44)) (i64.add (local.get $i) (i64.const 45)) (i64.add (local.get $i) (i64.const 46)) (i64.add (local.get $i) (i64.const 47)) (i64.add (local.get $i) (i64.const 48)) (i64.add (local.get $i) (i64.const 49)) (i64.add (local.get $i) (i64.const 50)) (i64.add (local.get $i) (i64.const 51)) (i64.add (local.get $i) (i64.const 52)) (i64.add (local.get $i) (i64.const 53)) (i64.add (local.get $i) (i64.const 54)) (i64.add (local.get $i) (i64.const 55)) (i64.add (local.get $i) (i64.const 56)) (i64.add (local.get $i) (i64.const 57)) (i64.add (local.get $i) (i64.const 58)) (i64.add (local.get $i) (i64.const 59)) (i64.add (local.get $i) (i64.const 60)) (i64.add (local.get $i) (i64.const 61)) (i64.add (local.get $i) (i64.const 62)) (i64.add (local.get $i) (i64.const 63)) (i64.add (local.get $i) (i64.const 64)) (i64.add (local.get $i) (i64.const 65)) (i64.add (local.get $i) (i64.const 66)) (i64.add (local.get $i) (i64.const 67)) (i64.add (local.get $i) (i64.const 68)) (i64.add (local.get $i) (i64.const 69)) (local.get $v)+ (call $f)+ (drop) (drop) (drop) (drop) (drop) (drop) (drop) (drop) (drop)+ (local.set $v)+ (local.set $sum (i64.add (local.get $sum)))+ (local.set $v (i64x2.add (local.get $v) (i64x2.splat (local.get $i))))+ (local.set $i (i64.add (local.get $i) (i64.const 1)))+ (br_if $l (i64.lt_u (local.get $i) (i64.const 20000))))+ (local.get $sum) (local.get $v)))diff --git a/Libraries/LibWasm/Engine/tests/validation.rs b/Libraries/LibWasm/Engine/tests/validation.rsnew file mode 100644index 00000000000..f29936f1801--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/validation.rs@@ -0,0 +1,76 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use libwasm_engine::compile;++fn leb(mut value: u32, out: &mut Vec<u8>) {+ loop {+ let byte = (value & 0x7f) as u8;+ value >>= 7;+ if value == 0 {+ out.push(byte);+ return;+ }+ out.push(byte | 0x80);+ }+}++fn section(id: u8, contents: &[u8], out: &mut Vec<u8>) {+ out.push(id);+ leb(contents.len() as u32, out);+ out.extend_from_slice(contents);+}++/// A module with type 0 `(array (mut i32))` and one function of type `[] -> [(ref 0)]` with the given code, which+/// must end with the function's `end`.+fn array_module(code: &[u8]) -> Vec<u8> {+ let mut bytes = b"\0asm\x01\0\0\0".to_vec();+ section(1, &[2, 0x5e, 0x7f, 0x01, 0x60, 0, 1, 0x64, 0], &mut bytes);+ section(3, &[1, 1], &mut bytes);+ let mut body = vec![0];+ body.extend_from_slice(code);+ let mut contents = vec![1];+ leb(body.len() as u32, &mut contents);+ contents.extend_from_slice(&body);+ section(10, &contents, &mut bytes);+ bytes+}++fn array_new_fixed(count: u32) -> Vec<u8> {+ let mut code = vec![0xfb, 0x08, 0];+ leb(count, &mut code);+ code+}++#[test]+fn array_new_fixed_in_unreachable_code_takes_any_count_at_once() {+ // Each of the 2^32 - 1 operands would be a pop of the polymorphic stack, which took seconds.+ let mut code = vec![0x00];+ code.extend(array_new_fixed(u32::MAX));+ code.push(0x0b);+ let start = std::time::Instant::now();+ assert!(compile(&array_module(&code)).is_ok());+ assert!(start.elapsed() < std::time::Duration::from_secs(1));++ // The operands that are on the stack are still checked.+ let mut code = vec![0x00, 0x42, 0x00];+ code.extend(array_new_fixed(u32::MAX));+ code.push(0x0b);+ assert!(compile(&array_module(&code)).is_err());+}++#[test]+fn array_new_fixed_needs_its_operands_in_reachable_code() {+ let mut code = vec![0x41, 0x01, 0x41, 0x02];+ code.extend(array_new_fixed(2));+ code.push(0x0b);+ assert!(compile(&array_module(&code)).is_ok());++ let mut code = vec![0x41, 0x01];+ code.extend(array_new_fixed(2));+ code.push(0x0b);+ assert!(compile(&array_module(&code)).is_err());+}diff --git a/Libraries/LibWasm/Engine/tests/wasi.rs b/Libraries/LibWasm/Engine/tests/wasi.rsnew file mode 100644index 00000000000..2f6669fb408--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/wasi.rs@@ -0,0 +1,233 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! WASI's descriptors and its capability model, through the functions a guest imports.++#![cfg(unix)]++use libwasm_engine::runtime::{ExternValue, InstanceAddress, Store, Value};+use libwasm_engine::wasi::{MODULE_NAME, Preopen, Wasi};+use std::rc::Rc;+use std::sync::Arc;++const ERRNO_SUCCESS: i32 = 0;+const ERRNO_BADF: i32 = 8;++struct Guest {+ store: Store,+ instance: InstanceAddress,+}++impl Guest {+ fn new(preopens: Vec<Preopen>) -> Self {+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/wasi_calls.wasm");+ let module = Arc::new(libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap());+ let mut store = Store::new();+ let wasi = Rc::new(Wasi::new(Vec::new(), Vec::new(), preopens));+ let mut imports = Vec::new();+ for import in &module.imports {+ assert_eq!(import.module, MODULE_NAME);+ let function = wasi.allocate_function(&mut store, &import.name).unwrap();+ imports.push(ExternValue::Function(function));+ }+ let instance = store.instantiate(module, &imports).unwrap();+ let Some(ExternValue::Memory(memory)) = store.instance(instance).export("memory") else {+ panic!("no memory export");+ };+ wasi.set_memory(memory);+ Self { store, instance }+ }++ fn call(&mut self, name: &str, arguments: &[Value]) -> i32 {+ let Some(ExternValue::Function(function)) = self.store.instance(self.instance).export(name) else {+ panic!("no function export {name}");+ };+ match self.store.invoke(function, arguments).unwrap()[..] {+ [Value::I32(errno)] => errno,+ ref other => panic!("{name} returned {other:?}"),+ }+ }+}++#[test]+fn closing_standard_streams_keeps_the_hosts_open() {+ let mut guest = Guest::new(Vec::new());+ assert_eq!(guest.call("fd_close", &[Value::I32(1)]), ERRNO_SUCCESS);+ // The guest's descriptor is gone, the host's standard output is not.+ assert_eq!(guest.call("fd_close", &[Value::I32(1)]), ERRNO_BADF);+ assert_eq!(+ guest.call(+ "fd_write",+ &[Value::I32(1), Value::I32(0), Value::I32(0), Value::I32(64)]+ ),+ ERRNO_BADF+ );+ assert!(unsafe { libc::fcntl(1, libc::F_GETFD) } >= 0);+}++const ERRNO_LOOP: i32 = 32;+const ERRNO_NOTCAPABLE: i32 = 76;+const LOOKUP_SYMLINK_FOLLOW: i32 = 1;+const OFLAGS_CREAT: i32 = 1;+const RIGHTS_FD_READ: i64 = 1 << 1;++/// A directory tree for sandbox tests, removed afterwards:+/// root/secret.txt+/// root/sandbox/inside.txt, sub/, link_in -> inside.txt, link_out -> ../secret.txt, link_absolute -> <secret.txt>,+/// sub/link_up -> ../inside.txt, sub/link_out -> ../../secret.txt+struct Tree(std::path::PathBuf);++impl Tree {+ fn new(name: &str) -> Self {+ let root = std::env::temp_dir().join(format!("libwasm-wasi-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let sandbox = root.join("sandbox");+ std::fs::create_dir_all(sandbox.join("sub")).unwrap();+ std::fs::write(root.join("secret.txt"), "secret").unwrap();+ std::fs::write(sandbox.join("inside.txt"), "inside").unwrap();+ std::os::unix::fs::symlink("inside.txt", sandbox.join("link_in")).unwrap();+ std::os::unix::fs::symlink("../secret.txt", sandbox.join("link_out")).unwrap();+ std::os::unix::fs::symlink(root.join("secret.txt"), sandbox.join("link_absolute")).unwrap();+ std::os::unix::fs::symlink("../inside.txt", sandbox.join("sub/link_up")).unwrap();+ std::os::unix::fs::symlink("../../secret.txt", sandbox.join("sub/link_out")).unwrap();+ Self(root)+ }++ fn guest(&self) -> Guest {+ let sandbox = self.0.join("sandbox").to_str().unwrap().to_string();+ Guest::new(vec![Preopen::new(sandbox, "/sandbox".to_string())])+ }+}++impl Drop for Tree {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++impl Guest {+ /// Writes `path` at address 16, and returns its length.+ fn path(&mut self, path: &str) -> i32 {+ let Some(ExternValue::Memory(memory)) = self.store.instance(self.instance).export("memory") else {+ panic!("no memory export");+ };+ self.store.memory_mut(memory).bytes_mut()[16..16 + path.len()].copy_from_slice(path.as_bytes());+ path.len() as i32+ }++ fn open(&mut self, fd: i32, path: &str, follow: bool, oflags: i32) -> i32 {+ let length = self.path(path);+ let lookup = if follow { LOOKUP_SYMLINK_FOLLOW } else { 0 };+ self.call(+ "path_open",+ &[+ Value::I32(fd),+ Value::I32(lookup),+ Value::I32(16),+ Value::I32(length),+ Value::I32(oflags),+ Value::I64(RIGHTS_FD_READ),+ Value::I64(0),+ Value::I32(0),+ Value::I32(0),+ ],+ )+ }+}++#[test]+fn paths_stay_beneath_their_preopen() {+ let tree = Tree::new("open");+ let mut guest = tree.guest();+ for path in [+ "inside.txt",+ "./inside.txt",+ "sub/../inside.txt",+ "sub/",+ "sub/link_up",+ "link_in",+ ] {+ assert_eq!(guest.open(3, path, true, 0), ERRNO_SUCCESS, "{path}");+ }+ for path in [+ "../secret.txt",+ "sub/../../secret.txt",+ "..",+ "/etc/passwd",+ &tree.0.join("secret.txt").to_string_lossy(),+ "link_out",+ "link_absolute",+ "sub/link_out",+ "link_out/../sandbox/inside.txt",+ ] {+ assert_eq!(guest.open(3, path, true, 0), ERRNO_NOTCAPABLE, "{path}");+ }+ // Without following, a symbolic link in the last place is not opened.+ assert_eq!(guest.open(3, "link_out", false, 0), ERRNO_LOOP);+ // A link in the middle is followed, but not out.+ assert_eq!(guest.open(3, "link_out/x", false, 0), ERRNO_NOTCAPABLE);+ // Nothing is created outside either.+ assert_eq!(guest.open(3, "../created.txt", false, OFLAGS_CREAT), ERRNO_NOTCAPABLE);+ assert!(!tree.0.join("created.txt").exists());+}++#[test]+fn descriptors_the_guest_does_not_have_resolve_nothing() {+ let tree = Tree::new("badf");+ let mut guest = tree.guest();+ // These resolved against the host's working directory before.+ assert_eq!(guest.open(99, "inside.txt", true, 0), ERRNO_BADF);+ let length = guest.path("created");+ assert_eq!(+ guest.call(+ "path_create_directory",+ &[Value::I32(99), Value::I32(16), Value::I32(length)]+ ),+ ERRNO_BADF+ );+}++#[test]+fn directories_and_status_stay_beneath_their_preopen() {+ let tree = Tree::new("other");+ let mut guest = tree.guest();+ let length = guest.path("../escaped");+ assert_eq!(+ guest.call(+ "path_create_directory",+ &[Value::I32(3), Value::I32(16), Value::I32(length)]+ ),+ ERRNO_NOTCAPABLE+ );+ assert!(!tree.0.join("escaped").exists());+ let length = guest.path("sub/made");+ assert_eq!(+ guest.call(+ "path_create_directory",+ &[Value::I32(3), Value::I32(16), Value::I32(length)]+ ),+ ERRNO_SUCCESS+ );+ assert!(tree.0.join("sandbox/sub/made").is_dir());+ for (path, follow, errno) in [+ ("inside.txt", true, ERRNO_SUCCESS),+ ("link_in", true, ERRNO_SUCCESS),+ ("link_out", false, ERRNO_SUCCESS),+ ("link_out", true, ERRNO_NOTCAPABLE),+ ("../secret.txt", false, ERRNO_NOTCAPABLE),+ ] {+ let length = guest.path(path);+ let lookup = if follow { LOOKUP_SYMLINK_FOLLOW } else { 0 };+ let arguments = [+ Value::I32(3),+ Value::I32(lookup),+ Value::I32(16),+ Value::I32(length),+ Value::I32(1024),+ ];+ assert_eq!(guest.call("path_filestat_get", &arguments), errno, "{path}");+ }+}diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flapindex 11df05f8814..ee044b362ef 100644--- a/Libraries/LibWasm/Interpreter/interpreter.flap+++ b/Libraries/LibWasm/Interpreter/interpreter.flap@@ -7956,6 +7956,9 @@ inline fn atomic_wait(size: u64) {store64([context_pointer, CONTEXT_ARGUMENT_2], timeout);store64([context_pointer, CONTEXT_ARGUMENT_3], size);let result: u64 = call_helper(wasm_runtime_wait, context_pointer);+ guard result != WAIT_CANNOT_BLOCK else @cold {+ trap(TRAP_RUNTIME);+ };set_top(result);advance(length);}diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex 67592a4939a..13d7eb27959 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -29,11 +29,10 @@ reused from one compile to the next:`Options::verify_ir` checks the IR after building and after cleanup (`ir/verify.rs`), and theregister allocation (`regalloc/verify.rs`).-The JIT is meant to compile every function that validates, of any size: a hot function that does-not compile would run interpreted forever. Until the JIT gets there, functions that use something it-does not compile yet fail with `CompileFailure::Unsupported` and stay interpreted: exceptions. Nothing-fails for its size, depth, number of locals or-register pressure.+The JIT compiles every function that validates, of any size: a hot function that did not compile+would run interpreted forever. Nothing fails for its size, depth, number of locals or register+pressure. The only compile that can fail is an OSR compile at a loop in a legacy catch handler+(`CompileFailure::NoOsrEntry`), whose frame then stays interpreted.## 2. Decoding@@ -336,8 +335,17 @@ there; a phi in a register with a slot is stored where its block starts.## 10. The runtimeThe engine's `runtime/jit.rs` decides what is compiled, installs it, and connects compiled code with-the interpreter and the host. `LIBWASM_JIT` configures it: `eager` compiles every function when its-module is instantiated, `perf-map` writes `/tmp/perf-PID.map`. It is off otherwise for now.+the interpreter and the host. The JIT is on by default; `LIBWASM_JIT` configures it (`off`, `forced`,+`eager`, `threshold=N`, `perf-map`, the stress modes; see the module's documentation).++- **Tier-up.** The interpreter charges each function's `tier_up_budget` for calls and loop+ iterations and asks the runtime once it runs out. The runtime sends the compile to the process's+ compile threads and lets the interpreter go on, asking again after a small budget; it installs the+ code once it is done. At a loop, it continues the frame compiled (OSR): an OSR compile enters the+ outermost loop around the frame's position and branches down to the loop the frame is at.+- **Exceptions.** Compiled code handles its own handlers in IR. An exception that leaves compiled+ code is unwound over the compiled frames to the first call that checks for exceptions or to the+ entry trampoline, and from there goes on in the interpreter frame that called it.- **Installing** a function's code stores it in its header: `native_entry`, and the kind`FUNCTION_KIND_COMPILED`. Code is per module function, so each store compiles a module's functiondiff --git a/Libraries/LibWasm/JIT/examples/osr_check.rs b/Libraries/LibWasm/JIT/examples/osr_check.rsnew file mode 100644index 00000000000..9ed745090d0--- /dev/null+++ b/Libraries/LibWasm/JIT/examples/osr_check.rs@@ -0,0 +1,143 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Compiles every function of modules as an OSR continuation at each of its loops, with the IR and register+//! allocation verified, and reports what fails. Loops that cannot be OSR entries (see `CompileFailure::NoOsrEntry`) are+//! skipped.+//!+//! ```text+//! osr_check [--threads N] [--stress-registers] [--dump FUNCTION:PC] MODULE...+//! ```++use libwasm_jit::decode::{Decoder, Instruction};+use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, RuntimeInfo};+use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};++const RUNTIME: RuntimeInfo = RuntimeInfo {+ trap_exit: 0x7fff_0000_1000,+ memory_grow: 0x7fff_0000_2000,+ table_grow: 0x7fff_0000_3000,+ call_host: 0x7fff_0000_4000,+ allocate: 0x7fff_0000_5000,+ wait: 0x7fff_0000_6000,+ notify: 0x7fff_0000_7000,+ allocate_exception: 0x7fff_0000_8000,+ throw: 0x7fff_0000_9000,+};++fn main() {+ let mut threads = 1;+ let mut options = Options {+ verify_ir: true,+ ..Options::default()+ };+ let mut dump = None;+ let mut paths = Vec::new();+ let mut arguments = std::env::args().skip(1);+ while let Some(argument) = arguments.next() {+ match argument.as_str() {+ "--threads" => threads = arguments.next().and_then(|n| n.parse().ok()).expect("--threads N"),+ "--stress-registers" => options.stress_registers = true,+ "--dump" => {+ let value = arguments.next().expect("--dump FUNCTION:PC");+ let (function, pc) = value.split_once(':').expect("--dump FUNCTION:PC");+ dump = Some((+ function.parse::<u32>().expect("a function index"),+ pc.parse::<u32>().expect("a module offset"),+ ));+ }+ _ => paths.push(argument),+ }+ }+ let mut failures = 0;+ for path in &paths {+ let bytes = std::fs::read(path).expect("a readable module");+ let module = Arc::new(libwasm_engine::compile(&bytes).expect("a valid module"));+ if let Some((function, pc)) = dump {+ let mut context = CompileContext::default();+ let request = CompileRequest {+ module: module.clone(),+ function,+ runtime: RUNTIME,+ options: Options {+ dump_ir: true,+ dump_asm: true,+ ..options+ },+ osr: Some(pc),+ };+ match libwasm_jit::compile(&mut context, &request) {+ Ok(compiled) => println!("{}", compiled.dump.unwrap_or_default()),+ Err(failure) => println!("{failure:?}"),+ }+ continue;+ }+ let first = module.imported_function_count;+ let count = module.code.len() as u32;+ let next = AtomicUsize::new(0);+ let compiled = AtomicUsize::new(0);+ let failed = AtomicUsize::new(0);+ std::thread::scope(|scope| {+ for _ in 0..threads {+ scope.spawn(|| {+ let mut context = CompileContext::default();+ loop {+ let index = next.fetch_add(1, Ordering::Relaxed) as u32;+ if index >= count {+ break;+ }+ let body = &module.code[index as usize];+ let mut decoder = Decoder::new(&module.bytes, body.code.start as usize, body.code.end as usize);+ let mut loops = Vec::new();+ while !decoder.is_at_end() {+ let pc = decoder.position() as u32;+ if let Instruction::Loop(_) = decoder.decode() {+ loops.push(pc);+ }+ }+ for pc in loops {+ let request = CompileRequest {+ module: module.clone(),+ function: first + index,+ runtime: RUNTIME,+ options,+ osr: Some(pc),+ };+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ libwasm_jit::compile(&mut context, &request)+ }));+ match result {+ Ok(Ok(_)) => {+ compiled.fetch_add(1, Ordering::Relaxed);+ }+ Ok(Err(CompileFailure::NoOsrEntry { .. })) => {}+ Ok(Err(failure)) => {+ failed.fetch_add(1, Ordering::Relaxed);+ println!("FAIL {path} function {}:{pc}: {failure:?}", first + index);+ }+ Err(_) => {+ failed.fetch_add(1, Ordering::Relaxed);+ println!("FAIL {path} function {}:{pc}: panicked", first + index);+ context = CompileContext::default();+ }+ }+ }+ }+ });+ }+ });+ let failed = failed.load(Ordering::Relaxed);+ failures += failed;+ println!(+ "{path}: {} OSR compiles, {failed} failures",+ compiled.load(Ordering::Relaxed)+ );+ }+ if failures > 0 {+ std::process::exit(1);+ }+}diff --git a/Libraries/LibWasm/JIT/src/builder/exceptions.rs b/Libraries/LibWasm/JIT/src/builder/exceptions.rsindex 0f0e8310bb0..a74164ac515 100644--- a/Libraries/LibWasm/JIT/src/builder/exceptions.rs+++ b/Libraries/LibWasm/JIT/src/builder/exceptions.rs@@ -77,11 +77,15 @@ impl Builder {/// A legacy `try` whose body starts at module offset `body`.pub(super) fn begin_try(&mut self, module: &Module, params: (u32, u32), results: (u32, u32), body: usize) {let info = &module.function_infos[self.defined as usize];- let region = info- .try_regions- .iter()- .find(|region| region.start as usize == body)- .expect("validation made a region of every try");+ // NB: The regions are in the order their instructions appear, and the builder meets them in that order (but+ // for those in unreachable code, which it skips), so the region is at or after the cursor.+ let regions = &info.try_regions;+ while (regions[self.try_region_cursor].start as usize) < body {+ self.try_region_cursor += 1;+ }+ let region = ®ions[self.try_region_cursor];+ assert_eq!(region.start as usize, body, "validation made a region of every try");+ self.try_region_cursor += 1;let start = self.clauses.len();let clauses =&info.catch_clauses[region.first_clause as usize..(region.first_clause + region.clause_count) as usize];diff --git a/Libraries/LibWasm/JIT/src/builder/gc.rs b/Libraries/LibWasm/JIT/src/builder/gc.rsindex d0c02b41d5e..dcdcd292e4d 100644--- a/Libraries/LibWasm/JIT/src/builder/gc.rs+++ b/Libraries/LibWasm/JIT/src/builder/gc.rs@@ -9,7 +9,8 @@//! Objects are cells of the runtime's heap (see `abi::Rtt`): the Rtt first, the data's address at OBJECT_DATA_OFFSET//! and an array's length at OBJECT_LENGTH_OFFSET. Data of up to `MAX_INLINE_DATA_SIZE` bytes is inline at//! OBJECT_INLINE_DATA_OFFSET, so a struct's fields are at constant offsets from the object where the struct is small-//! enough. Fields take 8 bytes (16 for v128), with packed and 32-bit values zero-extended in them.+//! enough. Fields take `StorageType::object_field_size()` bytes, with packed and 32-bit values zero-extended in them:+//! the runtime's layout, which `abi` and `types` define for both.//!//! GC references in compiled frames need nothing special: the collector scans the stack conservatively and recognizes//! pointers into cells, and every allocation is a call of the runtime, around which values live in stack slots or in@@ -21,26 +22,14 @@ use super::Builder;use crate::ir::{Func, HeapTest, Helper, LoadKind, Node, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Type, Value};use libwasm_module::Module;use libwasm_module::abi::{- InstanceData, OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET, TRAP_MEMORY_OUT_OF_BOUNDS,- TRAP_NULL_REFERENCE, TRAP_TABLE_OUT_OF_BOUNDS,+ InstanceData, MAX_INLINE_DATA_SIZE, OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET,+ TRAP_MEMORY_OUT_OF_BOUNDS, TRAP_NULL_REFERENCE, TRAP_TABLE_OUT_OF_BOUNDS,};use libwasm_module::opcode::gc::*;use libwasm_module::opcode::simd::I64X2_EXTRACT_LANE;use libwasm_module::types::{CompositeType, HeapType, StorageType, ValType};use std::mem::offset_of;-/// The most data an object has inline, which is the largest size class of the runtime's heap (heap.rs).-pub const MAX_INLINE_DATA_SIZE: u32 = 4096;--/// The bytes a field or element of `storage` takes in an object.-fn storage_bytes(storage: StorageType) -> u32 {- if storage == StorageType::Val(ValType::V128) {- 16- } else {- 8- }-}-/// The bytes an element of `storage` takes in a data segment.fn data_bytes(storage: StorageType) -> u64 {match storage {@@ -99,7 +88,7 @@ impl Builder {for (index, field_type) in struct_fields(module, type_index).iter().enumerate() {self.field_offsets.insert((u64::from(type_index) << 32) | index as u64, offset);- offset += storage_bytes(field_type.storage);+ offset += field_type.storage.object_field_size();}let count = struct_fields(module, type_index).len() as u64;self.field_offsets.insert((u64::from(type_index) << 32) | count, offset);@@ -117,7 +106,7 @@ impl Builder {/// Where the data of an object with `size` bytes of it is: the object and the offset of its inline data, or the/// address of data outside the heap.fn object_data(func: &mut Func, object: Value, size: u32) -> (Value, u32) {- if size <= MAX_INLINE_DATA_SIZE {+ if size as usize <= MAX_INLINE_DATA_SIZE {return (object, OBJECT_INLINE_DATA_OFFSET as u32);}let data = Self::append(@@ -309,7 +298,7 @@ impl Builder {let count = self.pop();let storage = array_storage(module, first);let length = self.unary(func, Op::ExtendI32U, Type::I64, count);- let element_size = self.constant(func, Type::I64, u64::from(storage_bytes(storage)));+ let element_size = self.constant(func, Type::I64, u64::from(storage.object_field_size()));let size = self.binary(func, Op::Mul, Type::I64, length, element_size);let array = if sub_opcode == ARRAY_NEW {let value = self.pop();@@ -328,7 +317,7 @@ impl Builder {ARRAY_NEW_FIXED => {let storage = array_storage(module, first);let values = self.stack.split_off(self.stack.len() - second as usize);- let element_size = storage_bytes(storage);+ let element_size = storage.object_field_size();let data_size = second * element_size;let size = self.constant(func, Type::I64, u64::from(data_size));let length = self.constant(func, Type::I64, u64::from(second));@@ -373,7 +362,7 @@ impl Builder {Type::None,);let length = self.unary(func, Op::ExtendI32U, Type::I64, count);- let element_size = self.constant(func, Type::I64, u64::from(storage_bytes(storage)));+ let element_size = self.constant(func, Type::I64, u64::from(storage.object_field_size()));let size = self.binary(func, Op::Mul, Type::I64, length, element_size);let array = self.allocate(func, first, size, length);let zero = self.constant(func, Type::I64, 0);@@ -384,7 +373,7 @@ impl Builder {let index = Self::resolve(func, self.pop());let array = Self::resolve(func, self.pop());let storage = array_storage(module, first);- let size_log2 = storage_bytes(storage).trailing_zeros() as u8;+ let size_log2 = storage.object_field_size().trailing_zeros() as u8;let address = Self::append(func,Node::new(Op::ElementAddress, Type::Pointer, size_log2, [array, index, 0]),@@ -397,7 +386,7 @@ impl Builder {let index = Self::resolve(func, self.pop());let array = Self::resolve(func, self.pop());let storage = array_storage(module, first);- let size_log2 = storage_bytes(storage).trailing_zeros() as u8;+ let size_log2 = storage.object_field_size().trailing_zeros() as u8;let address = Self::append(func,Node::new(Op::ElementAddress, Type::Pointer, size_log2, [array, index, 0]),diff --git a/Libraries/LibWasm/JIT/src/builder/mod.rs b/Libraries/LibWasm/JIT/src/builder/mod.rsindex 60d25ccd4a4..ae21f8b220a 100644--- a/Libraries/LibWasm/JIT/src/builder/mod.rs+++ b/Libraries/LibWasm/JIT/src/builder/mod.rs@@ -188,6 +188,8 @@ pub struct Builder {memory_base: Value,/// The zero vector, which every v128 local starts as, once made.vector_zero: Value,+ /// The next of the function's `try_regions` a legacy `try` may be (see `begin_try`).+ try_region_cursor: usize,/// The byte offsets of struct fields, by (type index, field index); the field count gives the size.field_offsets: Table<u64>,/// What an OSR compile needs (see `build_osr`), or what probing for one found.@@ -283,6 +285,7 @@ impl Builder {self.read_values.clear();self.params.clear();self.vector_zero = NONE;+ self.try_region_cursor = 0;self.field_offsets.clear();self.handler = NONE;self.clauses.clear();@@ -1034,10 +1037,17 @@ impl Builder {if self.osr.as_ref().is_some_and(|osr| osr.probing) {// NB: A legacy handler's exception is no value the frame has, so loops in handlers do not OSR.let in_handler = self.controls.iter().any(|control| control.kind == ControlKind::Catch);+ // NB: A value below the operand stack of an enclosing construct that is no loop flows to the+ // construct's end around the loops too, where it would need a phi of the value the frame has+ // and the one the function's start made, which the merge does not make for values below its+ // height. Such loops do not OSR.+ let below_construct = self.controls.iter().any(|control| {+ !matches!(control.kind, ControlKind::Function | ControlKind::Loop) && control.height != 0+ });let stack_types = self.stack.iter().map(|value| func.node(*value).ty).collect();let osr = self.osr.as_mut().expect("probing");if at_osr_loop {- osr.found = !in_handler;+ osr.found = !in_handler && !below_construct;osr.stack_types = stack_types;osr.around = osr.open_loops.clone();}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rsindex 0ede764e51c..dd26ddbdc86 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/calls.rs@@ -9,8 +9,8 @@//! frame wants it, which also undoes whatever a callee's tail calls did to it.use super::{ADDRESS, CodeGenerator, FP, LR, SCRATCH, SP, fpr, fpr_access, gpr, gpr_access};-use crate::asm::Width;use crate::asm::aarch64::{MemOperand, PairOperand};+use crate::asm::{Gpr, Width};use crate::convention::{self, Place};use crate::ir::{FLAG_CHECKS_EXCEPTION, Func, Op, Type, Value};use crate::regalloc::call_result_types;@@ -35,7 +35,8 @@ impl CodeGenerator<'_> {let results = call_result_types(func, value);if convention::has_result_area(&results) {let pointer = 8 * i64::from(argument_slots);- self.asm.add_any(SCRATCH, SP, pointer + 8, ADDRESS);+ let area = 8 * i64::from((argument_slots + 1).next_multiple_of(2));+ self.asm.add_any(SCRATCH, SP, area, ADDRESS);let operand = self.operand(SP, pointer, 3);self.asm.str(Width::W64, SCRATCH, operand);}@@ -59,7 +60,7 @@ impl CodeGenerator<'_> {convention::result_places(&results, &mut places);if let Place::Memory(slot) = places[index] {let output = self.allocation.node(value).output;- let area = 8 * (i64::from(argument_slots(func, call)) + 1);+ let area = 8 * i64::from((argument_slots(func, call) + 1).next_multiple_of(2));let size_log2 = if node.ty == Type::V128 { 4 } else { 3 };let operand = self.operand(SP, area + 8 * i64::from(slot), size_log2);if node.ty.uses_xmm() {@@ -74,8 +75,8 @@ impl CodeGenerator<'_> {}/// A tail call: the allocator put the arguments where a call passes them, which this copies the stack arguments- /// from into the incoming area (see `convention`). The return address stays in the link register, so where the- /// stack arguments need more room than the function was called with, only sp moves down.+ /// from into the incoming area (see `convention`). The return address stays in the link register, so only sp+ /// moves where the callee's incoming area differs from the function's.pub(super) fn lower_tail_call(&mut self, value: Value) {let func = self.func;let parameters = func.inputs(value)[3..]@@ -84,14 +85,17 @@ impl CodeGenerator<'_> {.collect::<Vec<_>>();let has_result_area = convention::has_result_area(&func.results);let callee_slots = convention::slots(¶meters);- let own_slots = convention::slots(&func.params);- let needed = callee_slots + u32::from(has_result_area);- let available = own_slots + u32::from(has_result_area);- let slide = if needed > available {- i64::from((8 * (needed - available)).next_multiple_of(16))- } else {- 0- };+ // NB: The callee returns the function's results, so both have a result area or neither has. Moving sp by the+ // difference of their incoming areas, down or up, keeps the area's top in place.+ let needed = convention::incoming_area_slots(¶meters, &func.results);+ let available = convention::incoming_area_slots(&func.params, &func.results);+ let slide = 8 * (i64::from(needed) - i64::from(available));+ // SECURITY: The frame record at fp - 16 is in the incoming area once it grows, so the saved fp and the return+ // address come out before the arguments go in. The callee's operands are in their registers, which+ // leaves x9 free.+ let saved_fp = Gpr(9);+ self.asm+ .ldp(saved_fp, LR, PairOperand::Offset(FP, convention::FRAME_SAVED_FP));let mut copied = Vec::new();let mut places = Vec::new();convention::parameter_places(¶meters, &mut places);@@ -116,12 +120,9 @@ impl CodeGenerator<'_> {let operand = self.operand(FP, 8 * i64::from(slot) - slide, 3);self.asm.str(Width::W64, SCRATCH, operand);}- // The link register and fp come back from the frame, and sp goes where the function's caller had it, less- // the slide.- self.asm- .ldp(ADDRESS, LR, PairOperand::Offset(FP, convention::FRAME_SAVED_FP));+ // sp goes where the function's caller had it, less the slide, and fp back to the caller's.self.asm.add_any(SP, FP, -slide, SCRATCH);- self.asm.mov(Width::W64, FP, ADDRESS);+ self.asm.mov(Width::W64, FP, saved_fp);let callee = gpr(convention::CALLEE_REGISTER);self.asm.ldr(Width::W64,diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rsindex a2e2ca256d6..acbd406537f 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/gc.rs@@ -9,7 +9,7 @@use super::{ADDRESS, CodeGenerator, FP, SCRATCH, gpr};use crate::asm::aarch64::{AtomicRmw, AtomicSize, Cond, Extend, MemOperand, Shift};-use crate::asm::{Gpr, Width};+use crate::asm::{Gpr, Label, Width};use crate::convention::{self, Register};use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, HeapTest, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Value};use crate::regalloc::{CONSTANT_INPUT, NO_REGISTER};@@ -20,6 +20,13 @@ use libwasm_module::abi::{};use std::mem::offset_of;+/// An operand of a 32-bit comparison: a register, or an immediate.+#[derive(Clone, Copy)]+pub(super) enum Operand32 {+ Register(Gpr),+ Immediate(u32),+}+fn field(offset: usize) -> i32 {offset as i32}@@ -204,6 +211,44 @@ impl CodeGenerator<'_> {self.asm.sub_imm(Width::W64, output, output, size as u32, false);}+ /// Compares the u32 in `register` with `operand`.+ fn compare32(&mut self, register: Gpr, operand: Operand32) {+ match operand {+ Operand32::Register(other) => self.asm.cmp(Width::W32, register, other),+ Operand32::Immediate(immediate) => self.compare_immediate(Width::W32, register, u64::from(immediate)),+ }+ }++ /// Branches to `failed` unless the type whose Rtt is in `rtt` is the expected type, of `identity` at `depth`, or+ /// a subtype of it: a type's display lists the identities of its supertypes by depth, and its own last. Clobbers+ /// `rtt` and ADDRESS.+ pub(super) fn check_subtype(&mut self, rtt: Gpr, depth: Operand32, identity: Operand32, failed: Label) {+ self.asm.ldr(+ Width::W32,+ ADDRESS,+ MemOperand::Offset(rtt, field(offset_of!(Rtt, depth))),+ );+ self.compare32(ADDRESS, depth);+ self.asm.b_cond(Cond::Lo, failed);+ self.asm.ldr(+ Width::W64,+ rtt,+ MemOperand::Offset(rtt, field(offset_of!(Rtt, display))),+ );+ let entry = match depth {+ Operand32::Register(depth) => MemOperand::Register {+ base: rtt,+ index: depth,+ extend: Extend::Uxtx,+ shifted: true,+ },+ Operand32::Immediate(depth) => self.operand(rtt, 4 * i64::from(depth), 2),+ };+ self.asm.ldr(Width::W32, ADDRESS, entry);+ self.compare32(ADDRESS, identity);+ self.asm.b_cond(Cond::Ne, failed);+ }+/// `RefTest`: whether a reference matches a heap type, as 0 or 1, or for a cast a trap where it does not.fn ref_test(&mut self, value: Value) {let func = self.func;@@ -211,7 +256,7 @@ impl CodeGenerator<'_> {let record = *self.allocation.node(value);let reference = gpr(record.inputs[0]);let identity: Register = record.inputs[1];- let depth = node.args[2] as i32;+ let depth = node.args[2];let cast = node.flags & REF_TEST_CAST != 0;let matched = self.asm.new_label();let failed = if cast {@@ -222,34 +267,13 @@ impl CodeGenerator<'_> {let null_matches = node.flags & REF_TEST_NULLABLE != 0;self.asm.cbz(Width::W64, reference, if null_matches { matched } else { failed });- // Compares the u32 at `operand` with the expected type identity.- let compare_identity = |generator: &mut Self, operand: MemOperand| {- generator.asm.ldr(Width::W32, ADDRESS, operand);- if identity == CONSTANT_INPUT {- let bits = generator.immediate(value, 1);- generator.compare_immediate(Width::W32, ADDRESS, bits);- } else {- generator.asm.cmp(Width::W32, ADDRESS, gpr(identity));- }+ let identity = if identity == CONSTANT_INPUT {+ Operand32::Immediate(self.immediate(value, 1) as u32)+ } else {+ Operand32::Register(gpr(identity))};- // Whether the Rtt in `rtt` is the expected type or a subtype of it: the expected type is in its display at- // the expected type's depth.let subtype_check = |generator: &mut Self, rtt: Gpr| {- generator.asm.ldr(- Width::W32,- ADDRESS,- MemOperand::Offset(rtt, field(offset_of!(Rtt, depth))),- );- generator.compare_immediate(Width::W32, ADDRESS, depth as u64);- generator.asm.b_cond(Cond::Lo, failed);- generator.asm.ldr(- Width::W64,- rtt,- MemOperand::Offset(rtt, field(offset_of!(Rtt, display))),- );- let operand = generator.operand(rtt, 4 * i64::from(depth), 2);- compare_identity(generator, operand);- generator.asm.b_cond(Cond::Ne, failed);+ generator.check_subtype(rtt, Operand32::Immediate(depth), identity, failed);};match HeapTest::from_flags(node.flags) {HeapTest::NonNull => {}@@ -290,7 +314,8 @@ impl CodeGenerator<'_> {HeapTest::ConcreteFunction => {let [rtt, rtts] = [gpr(record.temps[0]), gpr(record.temps[1])];let type_identity = MemOperand::Offset(reference, field(offset_of!(FunctionHeader, type_identity)));- compare_identity(self, type_identity);+ self.asm.ldr(Width::W32, ADDRESS, type_identity);+ self.compare32(ADDRESS, identity);self.asm.b_cond(Cond::Eq, matched);self.asm.ldr(Width::W32, rtt, type_identity);self.asmdiff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rsindex aba9b8d0d58..f6a98257ac1 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/memory.rs@@ -164,7 +164,10 @@ impl CodeGenerator<'_> {} else {2};- let mut operand = self.operand(gpr(a), i64::from(node.args[1] as i32), 3);+ // NB: The slot of a v128 local holds the address of its storage, 8 bytes; other slots the value, whose+ // size decides which offsets the load takes.+ let slot_size_log2 = if node.flags == 1 { 3 } else { size_log2 };+ let mut operand = self.operand(gpr(a), i64::from(node.args[1] as i32), slot_size_log2);if node.flags == 1 {self.asm.ldr(Width::W64, ADDRESS, operand);operand = MemOperand::Offset(ADDRESS, 0);diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rsindex 78ff2e40eb2..6c915a780e2 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/tables.rs@@ -7,6 +7,7 @@//! Runtime data: fields of memories, tables and segments, table elements, the checks of indirect calls, and calls of//! the runtime's functions.+use super::gc::Operand32;use super::{ADDRESS, CodeGenerator, FP, SCRATCH, gpr};use crate::asm::aarch64::{Cond, Extend, MemOperand, XZR};use crate::asm::{Gpr, Label, Width};@@ -168,6 +169,10 @@ impl CodeGenerator<'_> {} else if helper.traps_on_zero() {let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);self.asm.cbz(Width::W64, result, trap);+ } else if let Some(value) = helper.trap_value() {+ let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);+ self.asm.cmp_imm(Width::W64, result, value as u32, false);+ self.asm.b_cond(crate::asm::aarch64::Cond::Eq, trap);}}_ => unreachable!("{} is no runtime operation", node.op.name()),@@ -215,31 +220,12 @@ impl CodeGenerator<'_> {SCRATCH,MemOperand::Offset(target, field(offset_of!(Rtt, depth))),);- // The expected type is a supertype if it is at its depth in the actual type's display.- self.asm.ldr(- Width::W32,- ADDRESS,- MemOperand::Offset(actual, field(offset_of!(Rtt, depth))),- );- self.asm.cmp(Width::W32, ADDRESS, SCRATCH);- self.asm.b_cond(Cond::Lo, mismatch);- self.asm.ldr(- Width::W64,- actual,- MemOperand::Offset(actual, field(offset_of!(Rtt, display))),- );- self.asm.ldr(- Width::W32,+ self.check_subtype(actual,- MemOperand::Register {- base: actual,- index: SCRATCH,- extend: Extend::Uxtx,- shifted: true,- },+ Operand32::Register(SCRATCH),+ Operand32::Register(check.identity),+ mismatch,);- self.asm.cmp(Width::W32, actual, check.identity);- self.asm.b_cond(Cond::Ne, mismatch);self.asm.b(check.back);}}diff --git a/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rsindex a180991d167..c7f4163eae3 100644--- a/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rs+++ b/Libraries/LibWasm/JIT/src/codegen/aarch64/vector.rs@@ -316,7 +316,9 @@ impl CodeGenerator<'_> {let lanes = func.constants[node.args[2] as usize];let dst = fpr(output);if node.args[0] == node.args[1] {- self.vector_constant(dst, lanes);+ // NB: The builder makes the lanes of a shuffle of one vector 0 to 15, but its operands may have+ // become the same value since. A table of one register gives zero for lanes of 16 and up.+ self.vector_constant(dst, lanes & u128::from_le_bytes([15; 16]));self.asm.vector_table(dst, fpr(a), 1, dst);} else {// The table of two registers has to be in consecutive ones.diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rsindex 683f87f5418..ea7949383fd 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/calls.rs@@ -34,7 +34,8 @@ impl CodeGenerator<'_> {let results = call_result_types(func, value);if convention::has_result_area(&results) {let pointer = 8 * argument_slots as i32;- self.asm.lea(Width::W64, SCRATCH, &Address::new(SP, pointer + 8));+ let area = 8 * (argument_slots + 1).next_multiple_of(2) as i32;+ self.asm.lea(Width::W64, SCRATCH, &Address::new(SP, area));self.asm.mov_mr(Width::W64, &Address::new(SP, pointer), SCRATCH);}let callee = gpr(convention::CALLEE_REGISTER);@@ -54,7 +55,7 @@ impl CodeGenerator<'_> {convention::result_places(&results, &mut places);if let Place::Memory(slot) = places[index] {let output = self.allocation.node(value).output;- let area = 8 * (argument_slots(func, call) as i32 + 1);+ let area = 8 * (argument_slots(func, call) + 1).next_multiple_of(2) as i32;let address = Address::new(SP, area + 8 * slot as i32);if node.ty == Type::V128 {self.load_vector(fpr(output).0, &address);@@ -79,14 +80,11 @@ impl CodeGenerator<'_> {.collect::<Vec<_>>();let has_result_area = convention::has_result_area(&func.results);let callee_slots = convention::slots(¶meters);- let own_slots = convention::slots(&func.params);- let needed = callee_slots + u32::from(has_result_area);- let available = own_slots + u32::from(has_result_area);- let slide = if needed > available {- (8 * (needed - available)).next_multiple_of(16) as i32- } else {- 0- };+ // NB: The callee returns the function's results, so both have a result area or neither has. Moving the bottom+ // of the frame by the difference of their incoming areas, down or up, keeps the area's top in place.+ let needed = convention::incoming_area_slots(¶meters, &func.results);+ let available = convention::incoming_area_slots(&func.params, &func.results);+ let slide = 8 * (needed as i32 - available as i32);// NB: The callee's operands are in their registers, which leaves rax and rbx free.let (return_address, saved_fp) = (Gpr(convention::RAX), Gpr(convention::RBX));if slide != 0 {diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rsindex abd1e6a6438..f150ba1a839 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/gc.rs@@ -9,7 +9,7 @@use super::{CodeGenerator, FP, SCRATCH, gpr};use crate::asm::x86_64::{AluOp, Cond};-use crate::asm::{Address, Gpr, Scale, Width};+use crate::asm::{Address, Gpr, Label, Scale, Width};use crate::convention::{self, Register};use crate::ir::{AtomicOp, CHECKED_ATOMIC, CHECKED_MEMORY64, HeapTest, Op, REF_TEST_CAST, REF_TEST_NULLABLE, Value};use crate::regalloc::CONSTANT_INPUT;@@ -20,6 +20,13 @@ use libwasm_module::abi::{};use std::mem::offset_of;+/// An operand of a 32-bit comparison: a register, or an immediate.+#[derive(Clone, Copy)]+pub(super) enum Operand32 {+ Register(Gpr),+ Immediate(i32),+}+fn field(offset: usize) -> i32 {offset as i32}@@ -223,6 +230,30 @@ impl CodeGenerator<'_> {);}+ /// `cmp dword [address], operand`.+ fn compare32(&mut self, address: &Address, operand: Operand32) {+ match operand {+ Operand32::Register(register) => self.asm.cmp_mr(Width::W32, address, register),+ Operand32::Immediate(immediate) => self.asm.cmp_mi(Width::W32, address, immediate),+ }+ }++ /// Jumps to `failed` unless the type whose Rtt is in `rtt` is the expected type, of `identity` at `depth`, or a+ /// subtype of it: a type's display lists the identities of its supertypes by depth, and its own last. Clobbers+ /// `rtt`.+ pub(super) fn check_subtype(&mut self, rtt: Gpr, depth: Operand32, identity: Operand32, failed: Label) {+ self.compare32(&Address::new(rtt, field(offset_of!(Rtt, depth))), depth);+ self.asm.jcc(Cond::Below, failed);+ self.asm+ .mov_rm(Width::W64, rtt, &Address::new(rtt, field(offset_of!(Rtt, display))));+ let entry = match depth {+ Operand32::Register(depth) => Address::indexed(rtt, depth, Scale::Four, 0),+ Operand32::Immediate(depth) => Address::new(rtt, 4 * depth),+ };+ self.compare32(&entry, identity);+ self.asm.jcc(Cond::NotEqual, failed);+ }+/// `RefTest`: whether a reference matches a heap type, as 0 or 1, or for a cast a trap where it does not.fn ref_test(&mut self, value: Value) {let func = self.func;@@ -241,26 +272,13 @@ impl CodeGenerator<'_> {self.asm.test_rr(Width::W64, reference, reference);let null_matches = node.flags & REF_TEST_NULLABLE != 0;self.asm.jcc(Cond::Equal, if null_matches { matched } else { failed });- let compare_identity = |generator: &mut Self, address: &Address| {- if identity == CONSTANT_INPUT {- let bits = generator.immediate(value, 1);- generator.asm.cmp_mi(Width::W32, address, bits as i32);- } else {- generator.asm.cmp_mr(Width::W32, address, gpr(identity));- }+ let identity = if identity == CONSTANT_INPUT {+ Operand32::Immediate(self.immediate(value, 1) as i32)+ } else {+ Operand32::Register(gpr(identity))};- // Whether the Rtt in `rtt` is the expected type or a subtype of it: the expected type is in its display at- // the expected type's depth.let subtype_check = |generator: &mut Self, rtt: Gpr| {- generator- .asm- .cmp_mi(Width::W32, &Address::new(rtt, field(offset_of!(Rtt, depth))), depth);- generator.asm.jcc(Cond::Below, failed);- generator- .asm- .mov_rm(Width::W64, rtt, &Address::new(rtt, field(offset_of!(Rtt, display))));- compare_identity(generator, &Address::new(rtt, 4 * depth));- generator.asm.jcc(Cond::NotEqual, failed);+ generator.check_subtype(rtt, Operand32::Immediate(depth), identity, failed);};match HeapTest::from_flags(node.flags) {HeapTest::NonNull => {}@@ -303,7 +321,7 @@ impl CodeGenerator<'_> {HeapTest::ConcreteFunction => {let [rtt, rtts] = [gpr(record.temps[0]), gpr(record.temps[1])];let type_identity = Address::new(reference, field(offset_of!(FunctionHeader, type_identity)));- compare_identity(self, &type_identity);+ self.compare32(&type_identity, identity);self.asm.jcc(Cond::Equal, matched);self.asm.mov_rm(Width::W32, rtt, &type_identity);self.asmdiff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rsindex 8eea3005d76..9df0e5b6e19 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/tables.rs@@ -7,6 +7,7 @@//! Runtime data: fields of memories, tables and segments, table elements, the checks of indirect calls, and calls of//! the runtime's functions.+use super::gc::Operand32;use super::{CodeGenerator, FP, SCRATCH, gpr};use crate::asm::x86_64::AluOp;use crate::asm::x86_64::Cond;@@ -154,6 +155,10 @@ impl CodeGenerator<'_> {let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);self.asm.test_rr(Width::W64, target, target);self.asm.jcc(Cond::Equal, trap);+ } else if let Some(value) = helper.trap_value() {+ let trap = self.trap_label(libwasm_module::abi::TRAP_RUNTIME);+ self.asm.cmp_ri(Width::W64, target, value as i32);+ self.asm.jcc(Cond::Equal, trap);}}_ => unreachable!("{} is no runtime operation", node.op.name()),@@ -197,22 +202,12 @@ impl CodeGenerator<'_> {SCRATCH,&Address::new(target, offset_of!(Rtt, depth) as i32),);- // The expected type is a supertype if it is at its depth in the actual type's display.- self.asm.cmp_mr(- Width::W32,- &Address::new(actual, offset_of!(Rtt, depth) as i32),- SCRATCH,- );- self.asm.jcc(Cond::Below, mismatch);- self.asm.mov_rm(- Width::W64,+ self.check_subtype(actual,- &Address::new(actual, offset_of!(Rtt, display) as i32),+ Operand32::Register(SCRATCH),+ Operand32::Register(check.identity),+ mismatch,);- self.asm- .mov_rm(Width::W32, actual, &Address::indexed(actual, SCRATCH, Scale::Four, 0));- self.asm.cmp_rr(Width::W32, actual, check.identity);- self.asm.jcc(Cond::NotEqual, mismatch);self.asm.jmp(check.back);}}diff --git a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rsindex 9c03d14be09..3bd8a085272 100644--- a/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs+++ b/Libraries/LibWasm/JIT/src/codegen/x86_64/vector.rs@@ -579,8 +579,13 @@ impl CodeGenerator<'_> {}}Op::Shuffle => {- let lanes = func.constants[node.args[2] as usize].to_le_bytes();let single = node.args[0] == node.args[1];+ let mut lanes = func.constants[node.args[2] as usize].to_le_bytes();+ if single {+ // NB: The builder makes the lanes of a shuffle of one vector 0 to 15, but its operands may have+ // become the same value since; the patterns below take lanes of one vector.+ lanes = lanes.map(|lane| lane & 15);+ }let temp = if temp == crate::regalloc::NO_REGISTER {0} else {diff --git a/Libraries/LibWasm/JIT/src/convention.rs b/Libraries/LibWasm/JIT/src/convention.rsindex e57a3dfdc2d..5b90f040763 100644--- a/Libraries/LibWasm/JIT/src/convention.rs+++ b/Libraries/LibWasm/JIT/src/convention.rs@@ -14,13 +14,15 @@//! - Results of integer types come back in the first two integer result registers, and those of float and vector//! types in the first two vector ones. The results that do not fit go to a result area the caller provides, at 8 *//! the slots of the results before them; the caller passes its address in the slot after the parameters' home-//! slots.+//! slots. The area itself starts at the next even slot (`result_area_slot()`).//! - `INSTANCE_REGISTER` holds the callee's instance and `MEMORY_BASE_REGISTER` the base of its memory 0 at the call,//! and `CALLEE_REGISTER` its `FunctionHeader`.//! - Every register but the stack pointer and fp is caller-saved. The stack pointer is 16-byte aligned at the call.-//! - A tail call writes its stack arguments into the incoming area and jumps to the callee. If they do not fit, it-//! moves the frame's bottom down first (on x86-64 with the return address and saved fp); callers set the stack-//! pointer from fp after every call, which undoes it.+//! - A tail call writes its stack arguments into the incoming area and jumps to the callee. Every caller provides an+//! incoming area of `incoming_area_slots()`, an even number of slots, so a tail call moves the frame's bottom (on+//! x86-64 with the return address and saved fp) down or up by whole 16 bytes to make the area exactly the callee's,+//! with its top where it was: mutual tail calls run in constant space. Callers set the stack pointer from fp after+//! every call, which undoes the moves.//! - i32 values are zero-extended to 64 bits in registers and slots; f32 values use the low 32 bits.//!//! A compiled frame:@@ -136,12 +138,23 @@ pub fn result_area_pointer(params: &[Type]) -> u32 {slots(params)}-/// The bytes of outgoing area a call with these parameter and result types needs: the home slots, and if the-/// results need a result area, its pointer and the area.+/// Where the result area of a call with these parameters starts, in slots from the callee's fp: the first even slot+/// after the result area pointer, so that the incoming area below it is a whole number of 16 bytes.+pub fn result_area_slot(params: &[Type]) -> u32 {+ (slots(params) + 1).next_multiple_of(2)+}++/// The slots of the incoming area a function with these parameter and result types may use, and that a tail call+/// to it needs: the home slots and the result area pointer if any, rounded up to an even number.+pub fn incoming_area_slots(params: &[Type], results: &[Type]) -> u32 {+ (slots(params) + u32::from(has_result_area(results))).next_multiple_of(2)+}++/// The bytes of outgoing area a call with these parameter and result types needs: the incoming area, then the result+/// area if the results need one.pub fn outgoing_size(params: &[Type], results: &[Type]) -> u32 {- let mut total = slots(params);if has_result_area(results) {- total += 1 + slots(results);+ return 8 * (result_area_slot(params) + slots(results));}- 8 * total+ 8 * incoming_area_slots(params, results)}diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsindex a0a6093b5f5..4c77a15d53e 100644--- a/Libraries/LibWasm/JIT/src/ir/mod.rs+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -341,7 +341,8 @@ pub enum Helper {TableCopy,/// table data, segment, destination, source, count.TableInit,- /// address, expected value, timeout in nanoseconds, size: 0 when woken, 1 if the value differed, 2 on timeout.+ /// address, expected value, timeout in nanoseconds, size: 0 when woken, 1 if the value differed, 2 on timeout,+ /// or WAIT_CANNOT_BLOCK when the runtime has the trap.AtomicWait,/// address, count: how many waiters it woke.AtomicNotify,@@ -404,6 +405,11 @@ impl Helper {self == Helper::Allocate}+ /// The value, besides zero for `traps_on_zero()`, that means the runtime trapped, with TRAP_RUNTIME.+ pub fn trap_value(self) -> Option<u64> {+ (self == Helper::AtomicWait).then_some(libwasm_module::abi::WAIT_CANNOT_BLOCK)+ }+pub fn name(self) -> &'static str {match self {Helper::MemoryGrow => "memory_grow",diff --git a/Libraries/LibWasm/JIT/src/lib.rs b/Libraries/LibWasm/JIT/src/lib.rsindex e864d80af3c..80659faf0ab 100644--- a/Libraries/LibWasm/JIT/src/lib.rs+++ b/Libraries/LibWasm/JIT/src/lib.rs@@ -103,8 +103,8 @@ pub struct CompileRequest {pub function: u32,pub runtime: RuntimeInfo,pub options: Options,- /// For an OSR compile, the module offset of the outermost loop that it continues an interpreter frame at. Its- /// code takes the frame's fp as its only argument and returns the function's results.+ /// 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.pub osr: Option<u32>,}diff --git a/Libraries/LibWasm/JIT/src/regalloc/mod.rs b/Libraries/LibWasm/JIT/src/regalloc/mod.rsindex ad32733b658..d9da5c51c68 100644--- a/Libraries/LibWasm/JIT/src/regalloc/mod.rs+++ b/Libraries/LibWasm/JIT/src/regalloc/mod.rs@@ -78,6 +78,19 @@ pub struct Move {pub vector: bool,}+/// The storage of `resolve_many()`: the pending readers of each location, the pending move that writes each+/// location, the locations read as a v128, the locations whose value went to the cycle slot, which pending moves are+/// placed, and the moves ready to be placed.+#[derive(Default)]+struct MoveScratch {+ readers: crate::table::Table<u64>,+ writers: crate::table::Table<u64>,+ vector_reads: crate::table::Table<u64>,+ saved: crate::table::Table<u64>,+ done: Vec<bool>,+ ready: Vec<u32>,+}+/// How the allocator placed one node.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct NodeAllocation {@@ -364,8 +377,7 @@ pub struct Allocator {current_block: BlockId,pending: Vec<Move>,resolved: Vec<Move>,- /// How many pending moves read each location, in `resolve_many()`.- readers: crate::table::Table<u64>,+ move_scratch: MoveScratch,places: Vec<Place>,types: Vec<Type>,/// The inputs of the node being allocated, whose registers only it may take.@@ -856,8 +868,9 @@ impl Allocator {allocation.moves.extend_from_slice(&self.resolved);}- /// `resolve()` for many moves, like the edges into a merge with many phis: it counts the readers of each- /// location, so that finding the moves whose destination nobody reads any more takes one pass, not one per move.+ /// `resolve()` for many moves, like the edges into a merge with many phis, in linear time: it counts the pending+ /// readers of each location, and places a move once nothing reads its destination any more, which may make the+ /// move into its source ready in turn.fn resolve_many(&mut self, allocation: &mut Allocation) {fn key(location: Location) -> u64 {match location {@@ -868,53 +881,84 @@ impl Allocator {Location::Constant(value) => (5 << 40) | u64::from(value),}}- let readers = &mut self.readers;- readers.clear();- let add = |readers: &mut crate::table::Table<u64>, location: Location, delta: i64| {- let count = i64::from(readers.get(key(location)).unwrap_or(0)) + delta;- readers.insert(key(location), count as u32);- };- for pending in &self.pending {- add(readers, pending.from, 1);- }- while !self.pending.is_empty() {- let mut progress = false;- let mut index = 0;- while index < self.pending.len() {- if readers.get(key(self.pending[index].to)).unwrap_or(0) == 0 {- let ready = self.pending.swap_remove(index);- add(readers, ready.from, -1);- self.resolved.push(ready);- progress = true;- } else {- index += 1;- }+ let scratch = &mut self.move_scratch;+ scratch.readers.clear();+ scratch.writers.clear();+ scratch.vector_reads.clear();+ scratch.saved.clear();+ scratch.done.clear();+ scratch.done.resize(self.pending.len(), false);+ scratch.ready.clear();+ for (index, pending) in self.pending.iter().enumerate() {+ let source = key(pending.from);+ let count = scratch.readers.get(source).unwrap_or(0);+ scratch.readers.insert(source, count + 1);+ if pending.vector {+ scratch.vector_reads.insert(source, 1);}- if progress || self.pending.is_empty() {- continue;+ let previous = scratch.writers.insert(key(pending.to), index as u32);+ debug_assert!(previous.is_none(), "parallel moves write each location once");+ }+ for (index, pending) in self.pending.iter().enumerate() {+ if scratch.readers.get(key(pending.to)).unwrap_or(0) == 0 {+ scratch.ready.push(index as u32);}- // Every destination is still a source: the moves form cycles. Save one destination in the cycle slot.+ }+ let temp = |allocation: &mut Allocation| {if allocation.cycle_slot == NO_SLOT {// NB: Two slots, in case the value is a v128.allocation.slot_count += 2;allocation.cycle_slot = convention::spill_slot_offset(allocation.slot_count - 1);}- let saved = self.pending[0].to;- let temp = Location::Slot(allocation.cycle_slot);- let vector = self.pending[0].vector;+ Location::Slot(allocation.cycle_slot)+ };+ let mut unfinished = 0;+ loop {+ while let Some(index) = scratch.ready.pop() {+ let index = index as usize;+ if scratch.done[index] {+ continue;+ }+ scratch.done[index] = true;+ let mut ready = self.pending[index];+ let source = key(ready.from);+ if scratch.saved.get(source).is_some() {+ // The source was overwritten after its value went to the cycle slot.+ ready.from = temp(allocation);+ self.resolved.push(ready);+ continue;+ }+ self.resolved.push(ready);+ let count = scratch.readers.get(source).unwrap_or(0) - 1;+ scratch.readers.insert(source, count);+ if count == 0+ && let Some(writer) = scratch.writers.get(source)+ {+ scratch.ready.push(writer);+ }+ }+ while unfinished < self.pending.len() && scratch.done[unfinished] {+ unfinished += 1;+ }+ if unfinished == self.pending.len() {+ break;+ }+ // Every destination left is still a source: the moves form cycles. Save one destination in the cycle+ // slot, after which its readers read it there and its move is ready. The cycle runs to its end before+ // the slot is needed again.+ let saved = self.pending[unfinished].to;+ let saved_key = key(saved);+ let to = temp(allocation);self.resolved.push(Move {from: saved,- to: temp,- vector,+ to,+ vector: scratch.vector_reads.get(saved_key).is_some(),});- for pending in &mut self.pending {- if pending.from == saved {- pending.from = temp;- add(readers, saved, -1);- add(readers, temp, 1);- }- }+ scratch.saved.insert(saved_key, 1);+ scratch.readers.insert(saved_key, 0);+ scratch.ready.push(unfinished as u32);}+ self.pending.clear();}// Nodes.@@ -1302,3 +1346,48 @@ pub fn edge_slot(func: &Func, from: BlockId, to: BlockId) -> u32 {.expect("predecessors list their successors");data.successors_start + index as u32}++#[cfg(test)]+mod tests {+ use super::{Allocation, Allocator, Location, Move, NO_SLOT};+ use crate::ir::Func;+ use std::collections::HashMap;++ /// Runs `moves` as `resolve()` orders them, and checks that every destination gets what its source had before.+ fn check(moves: &[(u8, u8)]) {+ let mut allocator = Allocator::default();+ let mut allocation = Allocation {+ cycle_slot: NO_SLOT,+ ..Allocation::default()+ };+ allocator.pending.extend(moves.iter().map(|&(from, to)| Move {+ from: Location::Register(from),+ to: Location::Register(to),+ vector: false,+ }));+ allocator.resolve(&Func::default(), &mut allocation);+ let mut state: HashMap<Location, u64> = (0..64)+ .map(|register| (Location::Register(register), u64::from(register)))+ .collect();+ for placed in &allocation.moves {+ let value = state[&placed.from];+ state.insert(placed.to, value);+ }+ for &(from, to) in moves {+ assert_eq!(state[&Location::Register(to)], u64::from(from), "{moves:?}");+ }+ }++ #[test]+ fn parallel_moves_keep_their_sources() {+ // A long chain, one cycle through everything, two cycles, and fan-out from cycle members.+ check(&(0..40).map(|index| (index + 1, index)).collect::<Vec<_>>());+ check(&(0..40).map(|index| ((index + 1) % 40, index)).collect::<Vec<_>>());+ let mut two: Vec<(u8, u8)> = (0..10).map(|index| ((index + 1) % 10, index)).collect();+ two.extend((10..20).map(|index| (10 + (index + 1) % 10, index)));+ check(&two);+ let mut fan: Vec<(u8, u8)> = (0..12).map(|index| ((index + 1) % 12, index)).collect();+ fan.extend((20..30).map(|index| (index % 12, index)));+ check(&fan);+ }+}diff --git a/Libraries/LibWasm/JIT/src/stubs.rs b/Libraries/LibWasm/JIT/src/stubs.rsindex 97637823276..1df5e737255 100644--- a/Libraries/LibWasm/JIT/src/stubs.rs+++ b/Libraries/LibWasm/JIT/src/stubs.rs@@ -202,8 +202,10 @@ pub struct NativeCall {/// call, and back after it.pub image: u64,pub image_slots: u64,- /// The slot of the result area pointer in the image, or u64::MAX.+ /// The slot of the result area pointer in the image, or u64::MAX, and the slot the result area starts at+ /// (`convention::result_area_slot()`); the image lays them out as the outgoing area does.pub result_pointer_slot: u64,+ pub result_area_slot: u64,/// rax and rdx after the call.pub result_gprs: [u64; 2],/// xmm0 and xmm1 after the call.@@ -309,16 +311,18 @@ pub fn entry_trampoline() -> (Vec<u8>, usize) {asm.mov_rm(Width::W64, rsi, &call_field(offset_of!(NativeCall, image)));asm.mov_rr(Width::W64, rdi, SP);copy_words(&mut asm, rsi, rdi, rcx, rdx);+ // The result area pointer points at the result area on the stack.let no_area = asm.new_label();asm.mov_rm(Width::W64,rax,- &Address::new(record, field(offset_of!(NativeCall, result_pointer_slot))),+ &call_field(offset_of!(NativeCall, result_pointer_slot)),);asm.cmp_ri(Width::W64, rax, -1);asm.jcc(Cond::Equal, no_area);- asm.lea(Width::W64, rdx, &Address::indexed(SP, rax, crate::asm::Scale::Eight, 8));- asm.mov_mr(Width::W64, &Address::indexed(SP, rax, crate::asm::Scale::Eight, 0), rdx);+ asm.mov_rm(Width::W64, rcx, &call_field(offset_of!(NativeCall, result_area_slot)));+ asm.lea(Width::W64, rsi, &Address::indexed(SP, rcx, crate::asm::Scale::Eight, 0));+ asm.mov_mr(Width::W64, &Address::indexed(SP, rax, crate::asm::Scale::Eight, 0), rsi);asm.bind(no_area);for index in 0..8u8 {let address = Address::new(record, field(offset_of!(NativeCall, xmms) + 16 * index as usize));diff --git a/Libraries/LibWasm/JIT/src/stubs_aarch64.rs b/Libraries/LibWasm/JIT/src/stubs_aarch64.rsindex 46ad19e1270..f6bfc49f4d7 100644--- a/Libraries/LibWasm/JIT/src/stubs_aarch64.rs+++ b/Libraries/LibWasm/JIT/src/stubs_aarch64.rs@@ -218,8 +218,10 @@ pub struct NativeCall {/// call, and back after it.pub image: u64,pub image_slots: u64,- /// The slot of the result area pointer in the image, or u64::MAX.+ /// The slot of the result area pointer in the image, or u64::MAX, and the slot the result area starts at+ /// (`convention::result_area_slot()`); the image lays them out as the outgoing area does.pub result_pointer_slot: u64,+ pub result_area_slot: u64,/// x0 and x1 after the call.pub result_gprs: [u64; 2],/// v0 and v1 after the call.@@ -315,18 +317,25 @@ pub fn entry_trampoline() -> (Vec<u8>, usize) {MemOperand::Offset(record, call_field(offset_of!(NativeCall, image))),);copy_words(&mut asm, x(12), x(11), count, x(13));+ // The result area pointer points at the result area on the stack.let no_area = asm.new_label();+ let (pointer, area) = (x(10), x(15));asm.ldr(Width::W64,- x(10),+ pointer,MemOperand::Offset(record, call_field(offset_of!(NativeCall, result_pointer_slot))),);- asm.cmn_imm(Width::W64, x(10), 1, false);+ asm.cmn_imm(Width::W64, pointer, 1, false);asm.b_cond(Cond::Eq, no_area);+ asm.ldr(+ Width::W64,+ area,+ MemOperand::Offset(record, call_field(offset_of!(NativeCall, result_area_slot))),+ );asm.mov_sp(x(11), SP);- asm.add(Width::W64, x(11), x(11), x(10), Shift::Lsl, 3);- asm.add_imm(Width::W64, x(12), x(11), 8, false);- asm.str(Width::W64, x(12), MemOperand::Offset(x(11), 0));+ asm.add(Width::W64, x(12), x(11), area, Shift::Lsl, 3);+ asm.add(Width::W64, x(13), x(11), pointer, Shift::Lsl, 3);+ asm.str(Width::W64, x(12), MemOperand::Offset(x(13), 0));asm.bind(no_area);for index in 0..8u8 {let offset = call_field(offset_of!(NativeCall, xmms) + 16 * index as usize);diff --git a/Libraries/LibWasm/JIT/tests/cannot_block.rs b/Libraries/LibWasm/JIT/tests/cannot_block.rsnew file mode 100644index 00000000000..9af1aefe0eb--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/cannot_block.rs@@ -0,0 +1,36 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! `memory.atomic.wait` in compiled code traps in an agent that cannot block. A process of its own, since the JIT's+//! options are the process's.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++use libwasm_engine::runtime::{ExternValue, Store, Trap, Value};+use std::sync::Arc;++#[test]+fn wait_traps_compiled_in_an_agent_that_cannot_block() {+ // SAFETY: Nothing else runs yet.+ unsafe { std::env::set_var("LIBWASM_JIT", "forced") };+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../Engine/tests/fixtures/shared_waits.wasm");+ let module = Arc::new(libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap());+ for can_block in [true, false] {+ let mut store = Store::new();+ store.can_block = can_block;+ let instance = store.instantiate(module.clone(), &[]).unwrap();+ let Some(ExternValue::Function(wait)) = store.instance(instance).export("wait") else {+ panic!("no wait export");+ };+ // The location holds 0, so a wait for 1 returns at once where the agent can block.+ let result = store.invoke(wait, &[Value::I32(0), Value::I32(1), Value::I64(0)]);+ if can_block {+ assert_eq!(result, Ok(vec![Value::I32(1)]));+ } else {+ assert!(matches!(result, Err(Trap::Host(_))), "{result:?}");+ }+ }+}diff --git a/Libraries/LibWasm/JIT/tests/frame_loads.rs b/Libraries/LibWasm/JIT/tests/frame_loads.rsnew file mode 100644index 00000000000..50d31f1479e--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/frame_loads.rs@@ -0,0 +1,79 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Functions continued compiled at a loop of an interpreter frame (OSR) read their locals and operand stack from the+//! frame: locals of every type far from fp, where the offsets of loads of 4 and 16 bytes reach less far than those+//! of 8 bytes, and v128 values on the operand stack. A process of its own, since the JIT's options are the process's.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use std::fmt::Write as _;++/// Locals before the ones the loop reads, so that their offsets from fp are large: 8 bytes each.+const PADDING_LOCALS: usize = 3000;++fn script() -> String {+ let mut text = String::from("(module\n");+ // The loop reads an i32, an f32, an i64, an f64 and a v128 local beyond the padding, and keeps v128 values on+ // the operand stack across it.+ writeln!(+ text,+ " (func (export \"far_locals\") (param i32) (result i32)\n (local{})\n (local $i i32) (local $f \+ f32) (local $l i64) (local $d f64) (local $v v128)",+ " i32".repeat(PADDING_LOCALS)+ )+ .unwrap();+ text.push_str(+ " (local.set $i (local.get 0)) (local.set $f (f32.const 1.5)) (local.set $l (i64.const 7))+ (local.set $d (f64.const 2.25)) (local.set $v (v128.const i32x4 1 2 3 4))+ (local.set 2999 (i32.const 11))+ (v128.const i32x4 10 20 30 40) (v128.const i32x4 5 6 7 8)+ (loop $again (param v128 v128) (result v128 v128)+ (local.set $v (i32x4.add (local.get $v) (v128.const i32x4 1 1 1 1)))+ (local.set $f (f32.add (local.get $f) (f32.const 1)))+ (local.set $l (i64.add (local.get $l) (i64.const 3)))+ (local.set $d (f64.mul (local.get $d) (f64.const 2)))+ (local.set $i (i32.sub (local.get $i) (i32.const 1)))+ (br_if $again (local.get $i)))+ (i32x4.add) (i32x4.add (local.get $v)) (i32x4.extract_lane 3)+ (i32.add (i32.trunc_f32_s (local.get $f)))+ (i32.add (i32.wrap_i64 (local.get $l)))+ (i32.add (i32.trunc_f64_s (local.get $d)))+ (i32.add (local.get 2999)))\n",+ );+ text.push_str(")\n");+ for count in [1, 2, 5] {+ writeln!(text, "(invoke \"far_locals\" (i32.const {count}))").unwrap();+ }+ text+}++#[test]+fn osr_reads_far_locals_and_vectors_of_the_frame() {+ let panics = harness::panics();+ // SAFETY: Nothing else runs yet.+ unsafe { std::env::set_var("LIBWASM_JIT", "stress-osr,verify-ir") };+ let directory = std::env::temp_dir().join(format!("libwasm-frame-loads-{}", std::process::id()));+ let Some(json) = harness::script::write_wast(&directory, "frame_loads", &script()) else {+ eprintln!("no wasm-tools; skipped");+ return;+ };+ let options = libwasm_jit::Options {+ verify_ir: true,+ ..Default::default()+ };+ let totals = harness::script::run(&[json.to_string_lossy().into_owned()], false, options, true);+ assert_eq!(totals.cases, 3);+ assert_eq!(totals.failures, 0);+ let _ = std::fs::remove_dir_all(&directory);+ assert_eq!(+ panics.load(std::sync::atomic::Ordering::Relaxed),+ 0,+ "a compile panicked"+ );+}diff --git a/Libraries/LibWasm/JIT/tests/harness/aarch64.rs b/Libraries/LibWasm/JIT/tests/harness/aarch64.rsindex 130815fb1ea..b0e7463f163 100644--- a/Libraries/LibWasm/JIT/tests/harness/aarch64.rs+++ b/Libraries/LibWasm/JIT/tests/harness/aarch64.rs@@ -157,7 +157,8 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Seslet parameter_slots = convention::slots(params) as i32;if convention::has_result_area(results) {let pointer = 8 * parameter_slots;- asm.add_any(Gpr(9), SP, i64::from(pointer + 8), X17);+ let area = 8 * convention::result_area_slot(params) as i32;+ asm.add_any(Gpr(9), SP, i64::from(area), X17);let operand = operand(&mut asm, SP, pointer, 3);asm.str(Width::W64, Gpr(9), operand);}@@ -177,7 +178,7 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Sestransfer(&mut asm, results[index], *register, results_pointer, 8 * slot, false);}Place::Memory(area_slot) => {- let area = 8 * (parameter_slots + 1) + 8 * *area_slot as i32;+ let area = 8 * convention::result_area_slot(params) as i32 + 8 * *area_slot as i32;copy(&mut asm, results[index], (SP, area), (results_pointer, 8 * slot));}}diff --git a/Libraries/LibWasm/JIT/tests/harness/mod.rs b/Libraries/LibWasm/JIT/tests/harness/mod.rsindex 8ff9bda170d..5009ad97dc9 100644--- a/Libraries/LibWasm/JIT/tests/harness/mod.rs+++ b/Libraries/LibWasm/JIT/tests/harness/mod.rs@@ -50,6 +50,21 @@ pub fn run_main<T: Send + 'static>(main: impl FnOnce() -> T + Send + 'static) ->main()}+/// Counts the panics of every thread from the first call on, so that a test sees those of the runtime's compile+/// threads, which would otherwise only leave the functions they compile interpreted.+pub fn panics() -> &'static std::sync::atomic::AtomicUsize {+ static PANICS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+ static INSTALL: std::sync::Once = std::sync::Once::new();+ INSTALL.call_once(|| {+ let previous = std::panic::take_hook();+ std::panic::set_hook(Box::new(move |info| {+ PANICS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ previous(info);+ }));+ });+ &PANICS+}+/// The trap code of a call that reached a function the JIT did not compile.pub const TRAP_NOT_COMPILED: u32 = 100;diff --git a/Libraries/LibWasm/JIT/tests/harness/script.rs b/Libraries/LibWasm/JIT/tests/harness/script.rsindex 178071fea1c..ad46318539e 100644--- a/Libraries/LibWasm/JIT/tests/harness/script.rs+++ b/Libraries/LibWasm/JIT/tests/harness/script.rs@@ -559,3 +559,27 @@ pub fn run_with_dump(}totals}++/// Writes `text`, a script in the spec testsuite's text format, to `directory` as `NAME.json` and the binary modules+/// next to it, and returns the JSON file's path, or None where there is no wasm-tools to convert it.+pub fn write_wast(directory: &Path, name: &str, text: &str) -> Option<PathBuf> {+ std::fs::create_dir_all(directory).unwrap();+ let wast = directory.join(format!("{name}.wast"));+ std::fs::write(&wast, text).unwrap();+ let json = directory.join(format!("{name}.json"));+ let status = std::process::Command::new(std::env::var("WASM_TOOLS").unwrap_or_else(|_| "wasm-tools".into()))+ .arg("json-from-wast")+ .arg(&wast)+ .arg("-o")+ .arg(&json)+ .arg("--wasm-dir")+ .arg(directory)+ .status()+ .ok()?;+ assert!(+ status.success(),+ "wasm-tools json-from-wast failed on {}",+ wast.display()+ );+ Some(json)+}diff --git a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs b/Libraries/LibWasm/JIT/tests/harness/x86_64.rsindex a9da2b5bda4..1478d13d640 100644--- a/Libraries/LibWasm/JIT/tests/harness/x86_64.rs+++ b/Libraries/LibWasm/JIT/tests/harness/x86_64.rs@@ -158,7 +158,8 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Seslet parameter_slots = convention::slots(params) as i32;if convention::has_result_area(results) {let pointer = 8 * parameter_slots;- asm.lea(Width::W64, g(convention::RAX), &Address::new(sp, pointer + 8));+ let area = 8 * convention::result_area_slot(params) as i32;+ asm.lea(Width::W64, g(convention::RAX), &Address::new(sp, area));asm.mov_mr(Width::W64, &Address::new(sp, pointer), g(convention::RAX));}asm.call_r(entry);@@ -176,7 +177,7 @@ pub(super) fn trampoline_code(params: &[Type], results: &[Type], state: *mut Sesmatch place {Place::Register(register) => transfer(&mut asm, results[index], *register, address, false),Place::Memory(slot) => {- let area = 8 * (parameter_slots + 1) + 8 * *slot as i32;+ let area = 8 * convention::result_area_slot(params) as i32 + 8 * *slot as i32;copy(&mut asm, results[index], Address::new(sp, area), address);}}diff --git a/Libraries/LibWasm/JIT/tests/osr.rs b/Libraries/LibWasm/JIT/tests/osr.rsnew file mode 100644index 00000000000..d94aec4bb92--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/osr.rs@@ -0,0 +1,104 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! OSR compiles of particular shapes of code, with the IR and register allocation verified.++use libwasm_jit::decode::{Decoder, Instruction};+use libwasm_jit::{CompileContext, CompileFailure, CompileRequest, Options, RuntimeInfo};+use std::sync::Arc;++/// The OSR compile of the first defined function of `bytes` at its first loop.+fn compile_at_first_loop(bytes: &[u8]) -> Result<(), CompileFailure> {+ let module = Arc::new(libwasm_engine::compile(bytes).expect("a valid module"));+ let body = &module.code[0];+ let mut decoder = Decoder::new(&module.bytes, body.code.start as usize, body.code.end as usize);+ let pc = loop {+ let pc = decoder.position() as u32;+ if let Instruction::Loop(_) = decoder.decode() {+ break pc;+ }+ };+ let request = CompileRequest {+ module: module.clone(),+ function: module.imported_function_count,+ runtime: RuntimeInfo::default(),+ options: Options {+ verify_ir: true,+ ..Options::default()+ },+ osr: Some(pc),+ };+ libwasm_jit::compile(&mut CompileContext::default(), &request).map(|_| ())+}++#[test]+fn loop_in_a_block_with_a_value_below_it() {+ // (func (param i32) (result i32)+ // i32.const 7+ // block+ // local.get 0+ // br_if 0 ;; past the loop, with the 7 below the block+ // loop+ // local.get 0 i32.const 1 i32.sub local.tee 0+ // br_if 0+ // end+ // end+ // local.get 0+ // i32.add)+ //+ // The 7 reaches the block's end both from the function's start and from the loop, which an OSR compile enters+ // with the frame's value of it. The merge has no phi for values below the block's operand stack, so the loop must+ // not be an OSR entry, or the IR must merge the two values: it used to build IR where a use was not dominated by+ // its definition, which crashed transformersjs in the browser.+ #[rustfmt::skip]+ let bytes = [+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,+ 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,+ 0x03, 0x02, 0x01, 0x00,+ 0x0a, 0x1c, 0x01, 0x1a, 0x00,+ 0x41, 0x07,+ 0x02, 0x40,+ 0x20, 0x00, 0x0d, 0x00,+ 0x03, 0x40,+ 0x20, 0x00, 0x41, 0x01, 0x6b, 0x22, 0x00, 0x0d, 0x00,+ 0x0b,+ 0x0b,+ 0x20, 0x00, 0x6a,+ 0x0b,+ ];+ assert!(matches!(+ compile_at_first_loop(&bytes),+ Ok(()) | Err(CompileFailure::NoOsrEntry { .. })+ ));+}++#[test]+fn loop_with_a_value_below_it_at_the_function_level() {+ // (func (param i32) (result i32)+ // i32.const 7+ // loop+ // local.get 0 i32.const 1 i32.sub local.tee 0+ // br_if 0+ // end+ // local.get 0+ // i32.add)+ //+ // The 7 is below no construct but the function, so the loop can be an OSR entry.+ #[rustfmt::skip]+ let bytes = [+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,+ 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,+ 0x03, 0x02, 0x01, 0x00,+ 0x0a, 0x15, 0x01, 0x13, 0x00,+ 0x41, 0x07,+ 0x03, 0x40,+ 0x20, 0x00, 0x41, 0x01, 0x6b, 0x22, 0x00, 0x0d, 0x00,+ 0x0b,+ 0x20, 0x00, 0x6a,+ 0x0b,+ ];+ assert_eq!(compile_at_first_loop(&bytes), Ok(()));+}diff --git a/Libraries/LibWasm/JIT/tests/shuffles.rs b/Libraries/LibWasm/JIT/tests/shuffles.rsnew file mode 100644index 00000000000..20575c46f5f--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/shuffles.rs@@ -0,0 +1,125 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! `i8x16.shuffle` of one vector and of two, with lanes of either operand, in every pattern code generation picks+//! instructions for: compiled code against the interpreter, directly (with global value numbering too, which may+//! make both operands one value after building) and through the runtime in forced mode. A process of its own, since+//! the JIT's options are the process's.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use std::fmt::Write as _;++/// Lane patterns: whole 32-bit lanes, rotations, interleavings, and byte permutations without structure.+fn patterns() -> Vec<[u8; 16]> {+ let mut patterns = Vec::new();+ let dwords = |d: [u8; 4]| {+ let mut lanes = [0u8; 16];+ for (index, lane) in lanes.iter_mut().enumerate() {+ *lane = 4 * d[index / 4] + (index % 4) as u8;+ }+ lanes+ };+ for d in [+ [0, 1, 2, 3],+ [1, 0, 3, 2],+ [3, 2, 1, 0],+ [0, 4, 1, 5],+ [2, 6, 3, 7],+ [4, 0, 5, 1],+ [6, 2, 7, 3],+ [0, 1, 6, 7],+ [4, 5, 2, 3],+ [0, 5, 2, 7],+ [7, 6, 5, 4],+ ] {+ patterns.push(dwords(d));+ }+ for n in [1u8, 3, 8, 15, 17, 24, 31] {+ patterns.push(std::array::from_fn(|index| (index as u8 + n) & 31));+ }+ let mut state = 0x2545_f491u32;+ for _ in 0..8 {+ patterns.push(std::array::from_fn(|_| {+ state ^= state << 13;+ state ^= state >> 17;+ state ^= state << 5;+ (state % 32) as u8+ }));+ }+ patterns+}++fn script() -> String {+ let mut text = String::from("(module\n");+ let patterns = patterns();+ for (index, lanes) in patterns.iter().enumerate() {+ let lanes: String = lanes.iter().map(|lane| format!(" {lane}")).collect();+ for (name, operands) in [+ ("both", "(local.get 0) (local.get 1)"),+ ("first", "(local.get 0) (local.get 0)"),+ ("second", "(local.get 1) (local.get 1)"),+ // The same value twice, after a merge that the builder sees through only once it is done.+ (+ "merged",+ "(local.get 0) (if (result v128) (local.get 2) (then (local.get 0)) (else (local.get 0)))",+ ),+ ] {+ writeln!(+ text,+ " (func (export \"{name}_{index}\") (param v128 v128 i32) (result v128) (i8x16.shuffle{lanes} {operands}))"+ )+ .unwrap();+ }+ }+ text.push_str(")\n");+ for index in 0..patterns.len() {+ for name in ["both", "first", "second", "merged"] {+ writeln!(+ text,+ "(invoke \"{name}_{index}\" (v128.const i8x16 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) \+ (v128.const i8x16 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115) (i32.const 1))"+ )+ .unwrap();+ }+ }+ text+}++#[test]+fn shuffles_run_the_same_compiled() {+ let panics = harness::panics();+ // SAFETY: Nothing else runs yet.+ unsafe { std::env::set_var("LIBWASM_JIT", "forced,verify-ir") };+ let directory = std::env::temp_dir().join(format!("libwasm-shuffles-{}", std::process::id()));+ let Some(json) = harness::script::write_wast(&directory, "shuffles", &script()) else {+ eprintln!("no wasm-tools; skipped");+ return;+ };+ let paths = [json.to_string_lossy().into_owned()];+ let expected_cases = 4 * patterns().len();+ for (gvn, runtime) in [(false, false), (true, false), (false, true)] {+ let options = libwasm_jit::Options {+ verify_ir: true,+ gvn,+ ..Default::default()+ };+ let totals = harness::script::run(&paths, false, options, runtime);+ assert_eq!(+ totals.cases, expected_cases,+ "not every call ran compiled (runtime: {runtime})"+ );+ assert_eq!(totals.failures, 0, "gvn: {gvn}, runtime: {runtime}");+ }+ let _ = std::fs::remove_dir_all(&directory);+ assert_eq!(+ panics.load(std::sync::atomic::Ordering::Relaxed),+ 0,+ "a compile panicked"+ );+}diff --git a/Libraries/LibWasm/JIT/tests/tail_calls.rs b/Libraries/LibWasm/JIT/tests/tail_calls.rsnew file mode 100644index 00000000000..b0c598f8e11--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/tail_calls.rs@@ -0,0 +1,133 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Tail calls between functions of every pair of parameter counts from 0 to 12, so that the callee's stack arguments+//! take less, as much and more room than the caller's incoming area, with and without a result area and with v128+//! arguments: compiled code against the interpreter, compiled directly and through the runtime in forced mode. A+//! process of its own, since the JIT's options are the process's.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use std::fmt::Write as _;++const MAXIMUM_PARAMETERS: usize = 12;++fn parameters(count: usize, ty: &str) -> String {+ (0..count).map(|_| format!(" {ty}")).collect()+}++/// Callees that combine every argument, so that a misplaced one changes the result, and callers of every arity that+/// tail call each of them.+fn script() -> String {+ let mut text = String::from("(module\n");+ for count in 0..=MAXIMUM_PARAMETERS {+ let mut body = format!("(i64.const {count})");+ for index in 0..count {+ body = format!(+ "(i64.add {body} (i64.mul (local.get {index}) (i64.const {})))",+ index + 3+ );+ }+ writeln!(+ text,+ " (func $callee_{count} (param{}) (result i64) {body})",+ parameters(count, "i64")+ )+ .unwrap();+ // More results than result registers: a result area, whose pointer the tail call passes on.+ writeln!(+ text,+ " (func $area_{count} (param{}) (result i64 i64 i64) {body} (i64.const 7) (i64.const 8))",+ parameters(count, "i64")+ )+ .unwrap();+ // A v128 argument first, which takes two slots.+ writeln!(+ text,+ " (func $vector_{count} (param v128{}) (result i64) (i64.add (i64x2.extract_lane 1 (local.get 0)) \+ (call $callee_{count}{})))",+ parameters(count, "i64"),+ (1..=count)+ .map(|index| format!(" (local.get {index})"))+ .collect::<String>()+ )+ .unwrap();+ }+ for caller in 0..=MAXIMUM_PARAMETERS {+ for callee in 0..=MAXIMUM_PARAMETERS {+ let arguments: String = (0..callee)+ .map(|index| format!(" (i64.const {})", 1000 * (index as i64 + 1) + caller as i64))+ .collect();+ writeln!(+ text,+ " (func (export \"plain_{caller}_{callee}\") (param{}) (result i64) (return_call $callee_{callee}{arguments}))",+ parameters(caller, "i64")+ )+ .unwrap();+ writeln!(+ text,+ " (func (export \"area_{caller}_{callee}\") (param{}) (result i64 i64 i64) (return_call $area_{callee}{arguments}))",+ parameters(caller, "i64")+ )+ .unwrap();+ writeln!(+ text,+ " (func (export \"vector_{caller}_{callee}\") (param{}) (result i64) (return_call $vector_{callee} \+ (v128.const i64x2 5 {caller}){arguments}))",+ parameters(caller, "i64")+ )+ .unwrap();+ }+ }+ text.push_str(")\n");+ for caller in 0..=MAXIMUM_PARAMETERS {+ let arguments: String = (0..caller).map(|index| format!(" (i64.const {})", index + 1)).collect();+ for callee in 0..=MAXIMUM_PARAMETERS {+ for kind in ["plain", "area", "vector"] {+ writeln!(text, "(invoke \"{kind}_{caller}_{callee}\"{arguments})").unwrap();+ }+ }+ }+ text+}++#[test]+fn tail_calls_of_every_arity_run_the_same_compiled() {+ let panics = harness::panics();+ // SAFETY: Nothing else runs yet.+ unsafe { std::env::set_var("LIBWASM_JIT", "forced,verify-ir") };+ let directory = std::env::temp_dir().join(format!("libwasm-tail-calls-{}", std::process::id()));+ let Some(json) = harness::script::write_wast(&directory, "tail_calls", &script()) else {+ eprintln!("no wasm-tools; skipped");+ return;+ };+ let paths = [json.to_string_lossy().into_owned()];+ let expected_cases = 3 * (MAXIMUM_PARAMETERS + 1) * (MAXIMUM_PARAMETERS + 1);+ for (stress_registers, runtime) in [(false, false), (true, false), (false, true)] {+ let options = libwasm_jit::Options {+ verify_ir: true,+ stress_registers,+ ..Default::default()+ };+ let totals = harness::script::run(&paths, false, options, runtime);+ assert_eq!(+ totals.cases, expected_cases,+ "not every call ran compiled (runtime: {runtime})"+ );+ assert_eq!(+ totals.failures, 0,+ "stress registers: {stress_registers}, runtime: {runtime}"+ );+ }+ let _ = std::fs::remove_dir_all(&directory);+ assert_eq!(+ panics.load(std::sync::atomic::Ordering::Relaxed),+ 0,+ "a compile panicked"+ );+}diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cppindex 075de7b02bb..bdb6bf7f48c 100644--- a/Libraries/LibWasm/Runtime.cpp+++ b/Libraries/LibWasm/Runtime.cpp@@ -425,6 +425,11 @@ void Store::set_memory_grow_callback(Function<void(Entity)> callback)this);}+void Store::set_can_block(bool can_block)+{+ FFI::wasm_store_set_can_block(m_store, can_block);+}+u64 Store::table_size(Entity table){return FFI::wasm_store_table_size(m_store, to_ffi(table));diff --git a/Libraries/LibWasm/Runtime.h b/Libraries/LibWasm/Runtime.hindex bdf70c3bc80..946ffae6ef7 100644--- a/Libraries/LibWasm/Runtime.h+++ b/Libraries/LibWasm/Runtime.h@@ -284,6 +284,8 @@ public:GC::PrimitiveStorageHandle memory_primitive_storage_handle(Entity memory);// Runs after each memory.grow instruction that grows a memory, but not after grow_memory().void set_memory_grow_callback(Function<void(Entity memory)>);+ // Whether the agent the store runs code for may block ([[CanBlock]]); memory.atomic.wait traps where it may not.+ void set_can_block(bool);u64 table_size(Entity table);ValueType table_element_type(Entity table);diff --git a/Libraries/LibWasm/Tests/Executor/test-tail-call-mutual-arities.js b/Libraries/LibWasm/Tests/Executor/test-tail-call-mutual-arities.jsnew file mode 100644index 00000000000..f045d45d367--- /dev/null+++ b/Libraries/LibWasm/Tests/Executor/test-tail-call-mutual-arities.js@@ -0,0 +1,18 @@+// Mutual tail calls between functions with different numbers of stack arguments run in constant stack space: a+// million of them would exhaust the stack otherwise.+test("mutual tail calls of different arities do not grow the stack", () => {+ const bin = readBinaryWasmFile("Fixtures/Modules/tail-call-mutual-arities.wasm");+ const module = parseWebAssemblyModule(bin);++ const few = module.getExport("few");+ expect(module.invoke(few, 5)).toBe(0);+ expect(module.invoke(few, 1000000)).toBe(0);+});++test("mutual tail calls with a result area do not grow the stack", () => {+ const bin = readBinaryWasmFile("Fixtures/Modules/tail-call-mutual-arities.wasm");+ const module = parseWebAssemblyModule(bin);++ const fewResults = module.getExport("few_results");+ expect(module.invoke(fewResults, 1000000)).toEqual([1, 2, 3]);+});diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.wasmnew file mode 100644index 00000000000..209e23a3ac1Binary files /dev/null and b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.wasm differdiff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.watnew file mode 100644index 00000000000..5b60271d72a--- /dev/null+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-mutual-arities.wat@@ -0,0 +1,26 @@+(module+ ;; Mutual tail calls between functions whose stack arguments differ in number, which must run in constant stack+ ;; space: $few takes no stack arguments, $many takes several (more than the six integer argument registers).+ (func $few (export "few") (param $n i32) (result i32)+ (if (result i32) (i32.eqz (local.get $n))+ (then (i32.const 0))+ (else (return_call $many (i32.sub (local.get $n) (i32.const 1))+ (i32.const 1) (i32.const 2) (i32.const 3) (i32.const 4) (i32.const 5) (i32.const 6) (i32.const 7)+ (i32.const 8) (i32.const 9)))))+ (func $many (param $n i32) (param i32 i32 i32 i32 i32 i32 i32 i32 i32) (result i32)+ (return_call $odd (local.get $n) (local.get 1) (local.get 2)))+ ;; An odd number of stack slots in between, for the alignment of the frame.+ (func $odd (param $n i32) (param i32 i32) (result i32)+ (return_call $seven (local.get $n) (i32.const 1) (i32.const 2) (i32.const 3) (i32.const 4) (i32.const 5)+ (i32.const 6) (i32.const 7)))+ (func $seven (param $n i32) (param i32 i32 i32 i32 i32 i32 i32) (result i32)+ (return_call $few (local.get $n)))+ ;; The same with a result area: more results than result registers.+ (func $few_results (export "few_results") (param $n i32) (result i32 i32 i32)+ (if (result i32 i32 i32) (i32.eqz (local.get $n))+ (then (i32.const 1) (i32.const 2) (i32.const 3))+ (else (return_call $many_results (i32.sub (local.get $n) (i32.const 1))+ (i32.const 1) (i32.const 2) (i32.const 3) (i32.const 4) (i32.const 5) (i32.const 6) (i32.const 7)+ (i32.const 8)))))+ (func $many_results (param $n i32) (param i32 i32 i32 i32 i32 i32 i32 i32) (result i32 i32 i32)+ (return_call $few_results (local.get $n))))diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cppindex 314f60e9851..a150e1b26f0 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp@@ -12,9 +12,11 @@#include <AK/StringBuilder.h>#include <AK/Utf16String.h>#include <LibCrypto/BigInt/SignedBigInteger.h>+#include <LibGC/ConservativeVector.h>#include <LibGC/DeferGC.h>#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Agent.h>#include <LibJS/Runtime/Array.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/BigInt.h>@@ -126,6 +128,9 @@ WebAssemblyCache& WebAssemblyCache::the()WebAssemblyCache::WebAssemblyCache(GC::Heap& heap): m_store(make<Wasm::Runtime::Store>(heap)){+ // NB: The store is the agent's, whose [[CanBlock]] decides whether memory.atomic.wait may block.+ m_store->set_can_block(JS::agent_can_suspend(JS::VM::the()));+Array<WasmValueType, 1> js_tag_parameters { WasmValueType::reference(HeapKind::Extern) };m_js_tag = m_store->allocate_tag(js_tag_parameters);m_js_tag_root = GC::Root<GC::ForeignCell> { m_js_tag };@@ -568,7 +573,9 @@ JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasmreturn vm.throw_completion<JS::TypeError>("ImportObject must be provided when module has imports"_utf16);// 2. Let imports be « ».- Vector<Wasm::Runtime::Extern> imports;+ // NB: The host functions and globals made for the imports are referenced from here only until the instance+ // holds them, and the steps below run user code (getters, valueOf) that may collect garbage.+ GC::ConservativeVector<Wasm::Runtime::Extern> imports;imports.ensure_capacity(import_count);size_t imported_function_count = 0;diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cppindex eaf7a186449..864a0caf295 100644--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp@@ -4,6 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/+#include <LibGC/ConservativeVector.h>#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/ModuleEnvironment.h>@@ -250,7 +251,9 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModuauto& store = Detail::WebAssemblyCache::the().store();// 4. Let imports be « ».- Vector<Wasm::Runtime::Extern> imports;+ // NB: The host functions and globals made for the imports are referenced from here only until the instance+ // holds them, and converting values runs user code (valueOf) that may collect garbage.+ GC::ConservativeVector<Wasm::Runtime::Extern> imports;size_t imported_function_count = 0;// 5. For each (importedModuleName, name, importtype) in module_imports(module),diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-atomic-wait-in-window.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-atomic-wait-in-window.txtnew file mode 100644index 00000000000..a8cc4acda37--- /dev/null+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-atomic-wait-in-window.txt@@ -0,0 +1,2 @@+wait for 0: RuntimeError+wait for 1: RuntimeErrordiff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate-gc-during-imports.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate-gc-during-imports.txtnew file mode 100644index 00000000000..abf11b626b4--- /dev/null+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-instantiate-gc-during-imports.txt@@ -0,0 +1 @@+callF: 1, g: 42, callH: 2diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-atomic-wait-in-window.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-atomic-wait-in-window.htmlnew file mode 100644index 00000000000..f75d91814b7--- /dev/null+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-atomic-wait-in-window.html@@ -0,0 +1,26 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // (module+ // (memory 1 1 shared)+ // (func (export "wait") (param i32) (result i32)+ // (memory.atomic.wait32 (i32.const 0) (local.get 0) (i64.const 0))))+ const bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,+ 0x03, 0x02, 0x01, 0x00, 0x05, 0x04, 0x01, 0x03, 0x01, 0x01, 0x07, 0x08, 0x01, 0x04, 0x77, 0x61,+ 0x69, 0x74, 0x00, 0x00, 0x0a, 0x0e, 0x01, 0x0c, 0x00, 0x41, 0x00, 0x20, 0x00, 0x42, 0x00, 0xfe,+ 0x01, 0x02, 0x00, 0x0b,+ ]);++ test(() => {+ // A window's agent cannot block, so memory.atomic.wait traps, whether or not the value matches.+ const exports = new WebAssembly.Instance(new WebAssembly.Module(bytes)).exports;+ for (const expected of [0, 1]) {+ try {+ println(`wait for ${expected}: ${exports.wait(expected)}`);+ } catch (exception) {+ println(`wait for ${expected}: ${exception.constructor.name}`);+ }+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate-gc-during-imports.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate-gc-during-imports.htmlnew file mode 100644index 00000000000..0cdd09129d3--- /dev/null+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-instantiate-gc-during-imports.html@@ -0,0 +1,42 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // (module+ // (import "m" "f" (func $f (result i32)))+ // (import "m" "g" (global $g i32))+ // (import "m" "h" (func $h (result i32)))+ // (func (export "callF") (result i32) (call $f))+ // (func (export "callH") (result i32) (call $h))+ // (func (export "g") (result i32) (global.get $g)))+ const bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f, 0x02,+ 0x14, 0x03, 0x01, 0x6d, 0x01, 0x66, 0x00, 0x00, 0x01, 0x6d, 0x01, 0x67, 0x03, 0x7f, 0x00, 0x01,+ 0x6d, 0x01, 0x68, 0x00, 0x00, 0x03, 0x04, 0x03, 0x00, 0x00, 0x00, 0x07, 0x15, 0x03, 0x05, 0x63,+ 0x61, 0x6c, 0x6c, 0x46, 0x00, 0x02, 0x05, 0x63, 0x61, 0x6c, 0x6c, 0x48, 0x00, 0x03, 0x01, 0x67,+ 0x00, 0x04, 0x0a, 0x10, 0x03, 0x04, 0x00, 0x10, 0x00, 0x0b, 0x04, 0x00, 0x10, 0x01, 0x0b, 0x04,+ 0x00, 0x23, 0x00, 0x0b,+ ]);++ test(() => {+ // The host function and the global made for the first two imports must survive a collection that user code+ // runs while the later imports are read.+ const module = new WebAssembly.Module(bytes);+ const imports = {+ m: {+ f: () => 1,+ g: 42,+ get h() {+ internals.gc();+ // Reuses the memory of anything the collection freed.+ const garbage = [];+ for (let i = 0; i < 10000; ++i)+ garbage.push(new WebAssembly.Global({ value: "i32" }, i));+ internals.gc();+ return () => 2;+ },+ },+ };+ const exports = new WebAssembly.Instance(module, imports).exports;+ println(`callF: ${exports.callF()}, g: ${exports.g()}, callH: ${exports.callH()}`);+ });+</script>diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cppindex b494fddba44..73fa43ba4bb 100644--- a/Utilities/wasm.cpp+++ b/Utilities/wasm.cpp@@ -10,6 +10,7 @@#include <AK/Hex.h>#include <AK/JsonArray.h>#include <AK/JsonObject.h>+#include <AK/LexicalPath.h>#include <AK/ScopeGuard.h>#include <AK/UFixedBigInt.h>#include <AK/Utf16String.h>@@ -276,7 +277,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)bool wasi = false;ByteString exported_function_to_execute;Vector<ParsedValue> values_to_push;- Vector<ByteString> modules_to_link_in;+ // The modules to link in, and the module name importers know each by.+ Vector<ImportName> modules_to_link_in;Vector<StringView> args_if_wasi;Vector<StringView> wasi_preopened_mappings;HashMap<ImportName, Wasm::Runtime::Extern> js_exports;@@ -522,14 +524,18 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)});parser.add_option(Core::ArgsParser::Option {.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,- .help_string = "Extra modules to link with, use to resolve imports",+ .help_string = "Extra modules to link with, whose exports resolve imports of the module name (default: the file's name without its extension)",.long_name = "link",.short_name = 'l',- .value_name = "file",+ .value_name = "[name=]file",.accept_value = [&](StringView text) {if (text.is_empty())return false;- modules_to_link_in.append(text);+ if (auto separator = text.find('='); separator.has_value()) {+ modules_to_link_in.append({ text.substring_view(0, *separator), text.substring_view(*separator + 1) });+ return true;+ }+ modules_to_link_in.append({ LexicalPath::title(text), text });return true;},});@@ -592,14 +598,15 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)wasi_implementation = make<Wasm::Runtime::Wasi>(wasi_arguments, ReadonlySpan<ByteString> {}, preopens);}- // Each linked module's exports resolve the imports of the ones after it, and of the main module, by name.- HashMap<ByteString, Wasm::Runtime::Extern> linked_exports;+ // Each linked module's exports resolve the imports of the ones after it, and of the main module, of its module name+ // and the export's name and kind.+ HashMap<ImportName, Wasm::Runtime::Extern> linked_exports;auto resolve_imports = [&](Wasm::Runtime::Module const& module_to_link) -> Optional<Vector<Wasm::Runtime::Extern>> {Vector<Wasm::Runtime::Extern> imports;bool missing = false;for (size_t index = 0; index < module_to_link.import_count(); ++index) {auto import = module_to_link.import(index);- if (auto value = linked_exports.get(import.name); value.has_value()) {+ if (auto value = linked_exports.get({ import.module, import.name }); value.has_value() && value->kind == import.type.kind) {imports.append(*value);continue;}@@ -671,7 +678,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)return keep(instance.value());};- for (auto& name : modules_to_link_in) {+ for (auto& [module_name, name] : modules_to_link_in) {auto linked_module = timed(timings.parse, [&] { return compile(name); });if (!linked_module) {warnln("Failed to compile linked module '{}'", name);@@ -681,7 +688,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)if (!instance.has_value())return 1;for (auto& entry : store.instance_exports(*instance))- linked_exports.set(entry.name, entry.value);+ linked_exports.set({ module_name, entry.name }, entry.value);}auto instance = instantiate(*module, filename);