Truly independent web browser
LibWasm+LibWeb: Port the interpreter, and finish GC and exceptions
Andreas Kling2b2cac6af44f
diff --git a/Libraries/LibWasm/Engine/build.rs b/Libraries/LibWasm/Engine/build.rsindex 4f2a4bf8f25..38074a6ca43 100644--- a/Libraries/LibWasm/Engine/build.rs+++ b/Libraries/LibWasm/Engine/build.rs@@ -42,6 +42,7 @@ fn main() {.expect("generate the C ABI header");bindings.write_to_file(output_directory.join("RustFFI.h"));+ println!("cargo:rerun-if-env-changed=MACOSX_DEPLOYMENT_TARGET");let architecture = env::var("CARGO_CFG_TARGET_ARCH").expect("CARGO_CFG_TARGET_ARCH");let os = env::var("CARGO_CFG_TARGET_OS").expect("CARGO_CFG_TARGET_OS");let object_format = match os.as_str() {@@ -49,10 +50,12 @@ fn main() {"windows" => flapc::ObjectFormat::Coff,_ => flapc::ObjectFormat::Elf,};- // FIXME: Port the interpreter's entry and exit to AArch64 and the Windows x64 calling convention.- if architecture != "x86_64" || object_format == flapc::ObjectFormat::Coff {- return;- }+ let architecture = match architecture.as_str() {+ "x86_64" => flapc::Architecture::X86_64,+ // FIXME: Port the interpreter's entry and exit to the Windows AArch64 calling convention.+ "aarch64" if object_format != flapc::ObjectFormat::Coff => flapc::Architecture::Aarch64,+ _ => return,+ };println!("cargo:rustc-cfg=wasm_interpreter");let layout = abi::layout_constants();@@ -63,7 +66,7 @@ fn main() {let source_name = interpreter_source.display().to_string();let compiler = flapc::Compiler::new(flapc::CompileOptions {target: flapc::Target {- architecture: flapc::Architecture::X86_64,+ architecture,object_format,},has_jscvt: false,@@ -88,7 +91,45 @@ fn main() {let mut build = cc::Build::new();build.file(&assembly_path);- build.flag_if_supported("-malign-branch-boundary=32");- build.flag_if_supported("-malign-branch=fused,jcc");+ if os == "macos"+ && let Some(deployment_target) = rust_macos_deployment_target()+ {+ build.flag(format!("-mmacosx-version-min={deployment_target}"));+ }+ if env::var("CARGO_CFG_TARGET_ENV").is_ok_and(|environment| environment == "msvc") {+ // flapc writes GNU assembly, which MSVC's cl.exe cannot assemble. Ladybird builds for Windows with clang-cl.+ if !build+ .try_get_compiler()+ .is_ok_and(|compiler| compiler.is_like_clang_cl())+ {+ build.compiler("clang-cl");+ }+ // Given -Fo, clang-cl writes the preprocessed assembly to the working directory, which cargo makes the source+ // directory of the crate.+ env::set_current_dir(&output_directory)+ .unwrap_or_else(|error| panic!("enter {}: {error}", output_directory.display()));+ }+ if architecture == flapc::Architecture::X86_64 {+ build.flag_if_supported("-malign-branch-boundary=32");+ build.flag_if_supported("-malign-branch=fused,jcc");+ }build.compile("libwasm_interpreter");}++/// The minimum macOS version rustc builds the crate's own code for, which the assembled interpreter has to match.+fn rust_macos_deployment_target() -> Option<String> {+ if let Ok(target) = env::var("MACOSX_DEPLOYMENT_TARGET") {+ return Some(target);+ }+ let rustc = env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());+ let target = env::var("TARGET").ok()?;+ let output = std::process::Command::new(rustc)+ .args(["--print", "deployment-target", "--target", &target])+ .output()+ .ok()?;+ String::from_utf8(output.stdout)+ .ok()?+ .trim()+ .strip_prefix("MACOSX_DEPLOYMENT_TARGET=")+ .map(str::to_string)+}diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rsindex 687581dc986..a553fead866 100644--- a/Libraries/LibWasm/Engine/src/capi.rs+++ b/Libraries/LibWasm/Engine/src/capi.rs@@ -1218,6 +1218,56 @@ pub unsafe extern "C" fn wasm_store_allocate_tag(.cast()}+/// `ty` with its concrete heap type, which `module` defines, replaced by the type's store-wide identity. The types the+/// store reports for functions, tables, globals, and tags have identities in place of type indices too.+///+/// # Safety+///+/// `store` must be a live store and `module` a live module.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasm_store_canonical_value_type(+ store: *mut WasmStore,+ module: *const WasmModule,+ ty: WasmValueType,+) -> WasmValueType {+ if ty.kind != WasmValueKind::Reference || ty.heap != WasmHeapKind::Concrete {+ return ty;+ }+ let identities = store_of(store).module_type_identities(module_of(module));+ WasmValueType {+ type_index: identities[ty.type_index as usize],+ ..ty+ }+}++/// Whether a non-null reference matches the reference type `ty`, whose concrete heap type is an identity. A+/// reference of the any hierarchy must be in its internal form: an i31 reference, a GC object, or a host reference.+///+/// # Safety+///+/// `store` must be a live store, and `reference` a live reference of the hierarchy of `ty`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasm_store_reference_matches(+ store: *mut WasmStore,+ reference: u64,+ ty: WasmValueType,+) -> bool {+ let ValType::Ref(reference_type) = ty.to_value_type() else {+ return false;+ };+ store_of(store).reference_matches(reference, reference_type.heap)+}++/// Whether the type `identity` is a function type, as opposed to a struct or array type.+///+/// # Safety+///+/// `store` must be a live store with a type `identity`.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn wasm_store_is_function_type(store: *mut WasmStore, identity: u32) -> bool {+ store_of(store).is_function_type(identity)+}+/// The number of values an exception with the tag carries.////// # Safetydiff --git a/Libraries/LibWasm/Engine/src/opcode.rs b/Libraries/LibWasm/Engine/src/opcode.rsindex 015e79a909d..8090a87199f 100644--- a/Libraries/LibWasm/Engine/src/opcode.rs+++ b/Libraries/LibWasm/Engine/src/opcode.rs@@ -20,7 +20,10 @@ pub const BLOCK: u8 = 0x02;pub const LOOP: u8 = 0x03;pub const IF: u8 = 0x04;pub const ELSE: u8 = 0x05;+pub const TRY: u8 = 0x06;+pub const CATCH: u8 = 0x07;pub const THROW: u8 = 0x08;+pub const RETHROW: u8 = 0x09;pub const THROW_REF: u8 = 0x0a;pub const END: u8 = 0x0b;pub const BR: u8 = 0x0c;@@ -33,6 +36,8 @@ pub const RETURN_CALL: u8 = 0x12;pub const RETURN_CALL_INDIRECT: u8 = 0x13;pub const CALL_REF: u8 = 0x14;pub const RETURN_CALL_REF: u8 = 0x15;+pub const DELEGATE: u8 = 0x18;+pub const CATCH_ALL: u8 = 0x19;pub const DROP: u8 = 0x1a;pub const SELECT: u8 = 0x1b;pub const SELECT_TYPED: u8 = 0x1c;diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rsindex 1ac257842c6..8b807053536 100644--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs@@ -12,7 +12,43 @@ use crate::abi::{ExecutionContext, FRAME_FUNCTION, FRAME_HEADER_SIZE, FRAME_INSTANCE, FRAME_RETURN_IP, FRAME_SAVED_FP, MemoryData,TableData,};-use crate::validator::CatchKind;+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+/// System V calling convention on every x86-64 target, Windows included.+macro_rules! export_to_interpreter {+ ($($symbol:ident => $function:ident),* $(,)?) => {+ $(+ /// # Safety+ ///+ /// Only the interpreter calls this, with the context of the store it runs in.+ #[cfg(all(target_arch = "x86_64", windows))]+ #[unsafe(no_mangle)]+ pub unsafe extern "sysv64" fn $symbol(context: *mut ExecutionContext) -> u64 {+ unsafe { $function(context) }+ }++ /// # Safety+ ///+ /// Only the interpreter calls this, with the context of the store it runs in.+ #[cfg(not(all(target_arch = "x86_64", windows)))]+ #[unsafe(no_mangle)]+ pub unsafe extern "C" fn $symbol(context: *mut ExecutionContext) -> u64 {+ unsafe { $function(context) }+ }+ )*+ };+}++export_to_interpreter! {+ wasm_runtime_memory_grow => memory_grow,+ wasm_runtime_table_grow => table_grow,+ wasm_runtime_call_host => call_host,+ wasm_runtime_allocate => allocate,+ wasm_runtime_throw => throw,+ wasm_runtime_wait => wait,+ wasm_runtime_notify => notify,+}unsafe fn store_of(context: *mut ExecutionContext) -> &'static mut Store {unsafe { &mut *(*context).store.cast::<Store>() }@@ -24,8 +60,7 @@ unsafe fn store_of(context: *mut ExecutionContext) -> &'static mut Store {/// # Safety////// Only the interpreter calls this, with the context of the store it runs in.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_memory_grow(context: *mut ExecutionContext) -> u64 {+unsafe fn memory_grow(context: *mut ExecutionContext) -> u64 {unsafe {let data = (*context).arguments[0] as *const MemoryData;let delta = (*context).arguments[1];@@ -48,8 +83,7 @@ pub unsafe extern "C" fn wasm_runtime_memory_grow(context: *mut ExecutionContext/// # Safety////// Only the interpreter calls this, with the context of the store it runs in.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_table_grow(context: *mut ExecutionContext) -> u64 {+unsafe fn table_grow(context: *mut ExecutionContext) -> u64 {unsafe {let data = (*context).arguments[0] as *const TableData;let delta = (*context).arguments[1];@@ -71,8 +105,7 @@ pub unsafe extern "C" fn wasm_runtime_table_grow(context: *mut ExecutionContext)/// # Safety////// Only the interpreter calls this, with the context of the store it runs in.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_call_host(context: *mut ExecutionContext) -> u64 {+unsafe fn call_host(context: *mut ExecutionContext) -> u64 {unsafe {let function = &*((*context).arguments[0] as *const FunctionInstance);let top = (*context).arguments[1] as *mut u64;@@ -125,8 +158,7 @@ pub unsafe extern "C" fn wasm_runtime_call_host(context: *mut ExecutionContext)/// # Safety////// Only the interpreter calls this, with the context of the store it runs in.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_allocate(context: *mut ExecutionContext) -> u64 {+unsafe fn allocate(context: *mut ExecutionContext) -> u64 {unsafe {let store = store_of(context);let rtt = (*context).arguments[0] as *const crate::abi::Rtt;@@ -149,8 +181,7 @@ pub unsafe extern "C" fn wasm_runtime_allocate(context: *mut ExecutionContext) -/// # Safety////// Only the interpreter calls this, with the context of the store it runs in.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_throw(context: *mut ExecutionContext) -> u64 {+unsafe fn throw(context: *mut ExecutionContext) -> u64 {unsafe {let store = store_of(context);let pc = (*context).arguments[2];@@ -191,9 +222,15 @@ unsafe fn unwind(context: *mut ExecutionContext, store: &Store, exception: u64,{let info = &module.function_infos[(*index - module.imported_function_count) as usize];let offset = pc.wrapping_sub(module.bytes.as_ptr() as u64);- // Regions are in instruction order, inner ones after the regions they are in.+ // Regions are in instruction order, inner ones after the regions they are in. A legacy `delegate` leaves+ // out the regions that start after its bound.+ let mut bound = u32::MAX;for region in info.try_regions.iter().rev() {- if offset < u64::from(region.start) || offset >= u64::from(region.end) {+ if offset < u64::from(region.start) || offset >= u64::from(region.end) || region.start > bound {+ continue;+ }+ if region.delegate_bound != NOT_DELEGATED {+ bound = region.delegate_bound;continue;}let clauses = &info.catch_clauses@@ -218,6 +255,9 @@ unsafe fn unwind(context: *mut ExecutionContext, store: &Store, exception: u64,let top = empty_stack - (u64::from(clause.height) + pushed) * 8;let mut slot = top as *mut u64;unsafe {+ if clause.exception_local != NO_EXCEPTION_LOCAL {+ *((frame + u64::from(clause.exception_local) * 8) as *mut u64) = exception;+ }if pushes_reference {*slot = exception;slot = slot.add(1);@@ -256,8 +296,7 @@ struct Waiter {/// # Safety////// Only the interpreter calls this, with an address it checked.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_wait(context: *mut ExecutionContext) -> u64 {+unsafe fn wait(context: *mut ExecutionContext) -> u64 {let (address, expected, timeout, size) = unsafe {((*context).arguments[0],@@ -325,8 +364,7 @@ pub unsafe extern "C" fn wasm_runtime_wait(context: *mut ExecutionContext) -> u6/// # Safety////// Only the interpreter calls this.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn wasm_runtime_notify(context: *mut ExecutionContext) -> u64 {+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;diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rsindex 842c63040a6..4b9ae5393cf 100644--- a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs@@ -16,9 +16,19 @@ static ENTRY_CODE: [u8; 3] = [0xf0, 0xf3, 0xf1];#[cfg(wasm_interpreter)]const MEMORY_FAULT_OPCODE: usize = 0xf2;-#[cfg(wasm_interpreter)]+// The interpreter uses the System V calling convention on every x86-64 target, Windows included.+#[cfg(all(wasm_interpreter, not(all(target_arch = "x86_64", windows))))]unsafe extern "C" {fn wasm_interpreter(ip: *const u8, argument: u64);+}++#[cfg(all(wasm_interpreter, target_arch = "x86_64", windows))]+unsafe extern "sysv64" {+ fn wasm_interpreter(ip: *const u8, argument: u64);+}++#[cfg(wasm_interpreter)]+unsafe extern "C" {static wasm_interpreter_end: u8;static wasm_interpreter_dispatch_table: [usize; 256];}@@ -133,7 +143,18 @@ fn thread_stack_lowest_address() -> Option<usize> {}}-#[cfg(not(any(target_os = "linux", target_os = "macos")))]+#[cfg(windows)]+#[allow(clippy::unnecessary_wraps)] // The other platforms' versions can fail.+fn thread_stack_lowest_address() -> Option<usize> {+ unsafe extern "system" {+ fn GetCurrentThreadStackLimits(low: *mut usize, high: *mut usize);+ }+ let (mut low, mut high) = (0, 0);+ unsafe { GetCurrentThreadStackLimits(&raw mut low, &raw mut high) };+ Some(low)+}++#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]fn thread_stack_lowest_address() -> Option<usize> {None}@@ -148,7 +169,7 @@ mod fault {static mut PREVIOUS_SIGSEGV: libc::sigaction = unsafe { std::mem::zeroed() };static mut PREVIOUS_SIGBUS: libc::sigaction = unsafe { std::mem::zeroed() };- #[cfg(target_os = "linux")]+ #[cfg(all(target_os = "linux", target_arch = "x86_64"))]unsafe fn instruction_pointer(context: *mut libc::c_void) -> *mut usize {unsafe {let context = context.cast::<libc::ucontext_t>();@@ -156,7 +177,15 @@ mod fault {}}- #[cfg(target_os = "macos")]+ #[cfg(all(target_os = "linux", target_arch = "aarch64"))]+ unsafe fn instruction_pointer(context: *mut libc::c_void) -> *mut usize {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ (&raw mut (*context).uc_mcontext.pc).cast()+ }+ }++ #[cfg(all(target_os = "macos", target_arch = "x86_64"))]unsafe fn instruction_pointer(context: *mut libc::c_void) -> *mut usize {unsafe {let context = context.cast::<libc::ucontext_t>();@@ -164,6 +193,14 @@ mod fault {}}+ #[cfg(all(target_os = "macos", target_arch = "aarch64"))]+ unsafe fn instruction_pointer(context: *mut libc::c_void) -> *mut usize {+ unsafe {+ let context = context.cast::<libc::ucontext_t>();+ (&raw mut (*(*context).uc_mcontext).__ss.__pc).cast()+ }+ }+unsafe fn forward(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {unsafe {let previous = if signal == libc::SIGSEGV {@@ -216,7 +253,72 @@ mod fault {}}+/// Windows reports faults to vectored exception handlers before it looks for handlers in the faulting thread's frames.+#[cfg(all(wasm_interpreter, windows))]+mod fault {+ use super::{interpreter_code_range, memory_fault_handler};+ use crate::runtime::memory::is_in_any_reservation;+ use std::ffi::c_void;+ use std::sync::Once;++ const EXCEPTION_ACCESS_VIOLATION: u32 = 0xc000_0005;+ const EXCEPTION_CONTINUE_EXECUTION: i32 = -1;+ const EXCEPTION_CONTINUE_SEARCH: i32 = 0;+ /// Where Rip is in the x86-64 CONTEXT structure.+ const CONTEXT_RIP_OFFSET: usize = 0xf8;++ #[repr(C)]+ struct ExceptionRecord {+ code: u32,+ flags: u32,+ record: *mut ExceptionRecord,+ address: *mut c_void,+ parameter_count: u32,+ /// For access violations, whether the access was a write, and the address it accessed.+ information: [usize; 15],+ }++ #[repr(C)]+ struct ExceptionPointers {+ record: *mut ExceptionRecord,+ context: *mut u8,+ }++ unsafe extern "system" {+ fn AddVectoredExceptionHandler(+ first: u32,+ handler: unsafe extern "system" fn(*mut ExceptionPointers) -> i32,+ ) -> *mut c_void;+ }++ static INSTALL: Once = Once::new();++ unsafe extern "system" fn handle_exception(pointers: *mut ExceptionPointers) -> i32 {+ unsafe {+ let record = &*(*pointers).record;+ if record.code != EXCEPTION_ACCESS_VIOLATION || record.parameter_count < 2 {+ return EXCEPTION_CONTINUE_SEARCH;+ }+ let pc = (*pointers).context.add(CONTEXT_RIP_OFFSET).cast::<usize>();+ let (start, end) = interpreter_code_range();+ if (start..end).contains(&*pc) && is_in_any_reservation(record.information[1]) {+ // The handlers keep their frame in the pinned registers, so the trap handler can find the+ // execution context of the access from the frame pointer.+ *pc = memory_fault_handler();+ return EXCEPTION_CONTINUE_EXECUTION;+ }+ EXCEPTION_CONTINUE_SEARCH+ }+ }++ pub fn install() {+ INSTALL.call_once(|| unsafe {+ AddVectoredExceptionHandler(1, handle_exception);+ });+ }+}+pub fn install_fault_handler() {- #[cfg(all(wasm_interpreter, unix))]+ #[cfg(wasm_interpreter)]fault::install();}diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex 0d4e112e780..573cca797c4 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -21,7 +21,7 @@ use crate::abi::{FUNCTION_KIND_WASM_VECTOR, FunctionHeader, InstanceData, MemoryData, SPILL_AREA_SIZE, Segment, TableData,};use crate::module::{DataMode, ElementItems, ElementMode, ExternalKind, ImportDescription, Module};-use crate::types::{FuncType, GlobalType, HeapType, TableType, TypeCanonicalizer, ValType};+use crate::types::{FuncType, GlobalType, HeapType, RefType, TableType, TypeCanonicalizer, ValType};use memory::MemoryInstance;use std::collections::HashMap;use std::rc::Rc;@@ -442,9 +442,10 @@ impl Store {supertypes: Vec::new(),composite: crate::types::CompositeType::Func(ty.clone()),};+ // The type refers to other types by their identities, and to none in its group.let identities = self.canonicalizer- .canonicalize_group(std::slice::from_ref(&sub_type), 0, |_| 0);+ .canonicalize_group(std::slice::from_ref(&sub_type), u32::MAX, |identity| identity);self.register_types(&[sub_type], &identities);identities[0]}@@ -471,6 +472,60 @@ impl Store {self.context.rtts = self.rtt_pointers.as_ptr();}+ /// Give the types of `module` store-wide identities, and return the identity of each.+ pub fn module_type_identities(&mut self, module: &Module) -> Vec<u32> {+ let mut type_identities: Vec<u32> = Vec::with_capacity(module.types.len());+ for group in &module.recursion_groups {+ let types = &module.types[group.start as usize..(group.start + group.count) as usize];+ let identities = self+ .canonicalizer+ .canonicalize_group(types, group.start, |index| type_identities[index as usize]);+ let map = |index: u32| {+ if index >= group.start {+ identities[(index - group.start) as usize]+ } else {+ type_identities[index as usize]+ }+ };+ let store_types: Vec<_> = types.iter().map(|ty| ty.map_type_indices(&map)).collect();+ self.register_types(&store_types, &identities);+ type_identities.extend(identities);+ }+ type_identities+ }++ /// Whether a non-null reference matches `heap`, whose concrete types are identities. References of the any+ /// hierarchy must be in their internal form: i31 references, GC objects, or host references.+ pub fn reference_matches(&self, reference: u64, heap: HeapType) -> bool {+ let tag = reference & 3;+ let object_rtt = || unsafe { &**(reference as *const *const crate::abi::Rtt) };+ let is_subtype = |actual: &crate::abi::Rtt, identity: u32| {+ let target = self.rtt(identity);+ actual.depth >= target.depth && unsafe { *actual.display.add(target.depth as usize) } == identity+ };+ match heap {+ HeapType::Any | HeapType::Extern | HeapType::Func | HeapType::Exn => true,+ HeapType::Eq => reference & 1 != 0 || tag == 0,+ HeapType::I31 => reference & 1 != 0,+ HeapType::Struct => tag == 0 && object_rtt().kind == crate::abi::RTT_KIND_STRUCT,+ HeapType::Array => tag == 0 && object_rtt().kind == crate::abi::RTT_KIND_ARRAY,+ HeapType::Concrete(identity) => {+ if self.rtt(identity).kind == crate::abi::RTT_KIND_FUNCTION {+ let function = unsafe { &*(reference as *const FunctionHeader) };+ is_subtype(self.rtt(function.type_identity), identity)+ } else {+ tag == 0 && is_subtype(object_rtt(), identity)+ }+ }+ HeapType::None | HeapType::NoFunc | HeapType::NoExtern | HeapType::NoExn | HeapType::Bottom => false,+ }+ }++ /// Whether the type `identity` is a function type, as opposed to a struct or array type.+ pub fn is_function_type(&self, identity: u32) -> bool {+ self.rtt(identity).kind == crate::abi::RTT_KIND_FUNCTION+ }+/// The types of the store, where concrete heap types are identities.fn type_context(&self) -> crate::validator::TypeContext<'_> {crate::validator::TypeContext {@@ -560,28 +615,15 @@ impl Store {return link_error("wrong number of imports");}- // Give the module's types store-wide identities.- let mut type_identities: Vec<u32> = Vec::with_capacity(module.types.len());- for group in &module.recursion_groups {- let types = &module.types[group.start as usize..(group.start + group.count) as usize];- let identities = self- .canonicalizer- .canonicalize_group(types, group.start, |index| type_identities[index as usize]);- let map = |index: u32| {- if index >= group.start {- identities[(index - group.start) as usize]- } else {- type_identities[index as usize]- }- };- let store_types: Vec<_> = types.iter().map(|ty| ty.map_type_indices(&map)).collect();- self.register_types(&store_types, &identities);- type_identities.extend(identities);- }+ let type_identities = self.module_type_identities(&module);// Types of the store have identities where the module's types have indices.let module_identities = type_identities.clone();let canonical = |value: ValType| value.map_type_indices(&|index| module_identities[index as usize]);+ let canonical_function_type = |ty: &FuncType| FuncType {+ params: ty.params.iter().map(|¶m| canonical(param)).collect(),+ results: ty.results.iter().map(|&result| canonical(result)).collect(),+ };let mut functions = Vec::new();let mut tables = Vec::new();let mut memories = Vec::new();@@ -692,19 +734,29 @@ impl Store {for (offset, &type_index) in module.functions.iter().enumerate() {let info = &module.function_infos[offset];let body = &module.code[offset];- let ty = module.types[type_index as usize]- .as_func()- .expect("validation checks function types")- .clone();+ let ty = canonical_function_type(+ module.types[type_index as usize]+ .as_func()+ .expect("validation checks function types"),+ );let local_count = info.local_count;// Each local has an 8-byte slot. A v128 local's slot holds the address of its 16-byte storage, which// follows the slots, 16-byte aligned like fp.let scalar_size = (local_count * 8).next_multiple_of(16);- let local_types = ty.params.iter().copied().chain(- body.locals- .iter()- .flat_map(|&(count, local)| std::iter::repeat_n(local, count as usize)),- );+ // The locals of legacy exception handlers hold exception references.+ let local_types = ty+ .params+ .iter()+ .copied()+ .chain(+ body.locals+ .iter()+ .flat_map(|&(count, local)| std::iter::repeat_n(local, count as usize)),+ )+ .chain(std::iter::repeat_n(+ ValType::Ref(RefType::EXNREF),+ info.exception_local_count as usize,+ ));let mut vector_storage = Vec::new();let mut locals_size = scalar_size;for local in local_types {@@ -820,10 +872,11 @@ impl Store {}instance.tables = tables;for tag in &module.tags {- let ty = module.types[tag.type_index as usize]- .as_func()- .expect("validation checks tag types")- .clone();+ let ty = canonical_function_type(+ module.types[tag.type_index as usize]+ .as_func()+ .expect("validation checks tag types"),+ );let type_identity = instance.type_identities[tag.type_index as usize];tags.push(self.allocate_tag_with_identity(ty, type_identity));}diff --git a/Libraries/LibWasm/Engine/src/validator.rs b/Libraries/LibWasm/Engine/src/validator.rsindex 80366dd4f9d..c93c04c823b 100644--- a/Libraries/LibWasm/Engine/src/validator.rs+++ b/Libraries/LibWasm/Engine/src/validator.rs@@ -20,6 +20,9 @@//! - `br_table` owns one entry per label, the default last.//! - `if` owns one entry, for jumping to its `else` arm, or past its `end` if it has none.//! - `else` owns one entry, for jumping past the `end` of the `if` when its first arm completes.+//! - The legacy `catch` and `catch_all` own one entry each, for jumping past the `end` of their `try` when the body or+//! handler before them completes, as `else` does.+//! - The legacy `rethrow` owns one entry, whose `keep` is the index of the local that holds the exception to rethrow.//!//! An entry holds the distance from the branching instruction to its target, the distance from the entry itself to//! the entry the target continues with, and how to reshape the operand stack: keep the `keep` slots at its top and@@ -28,6 +31,15 @@//! final `end`, which returns.//!//! Exceptions are not linear, so `try_table` handlers live in a separate table of the regions they protect.+//!+//! # Legacy exception handling+//!+//! The body of a legacy `try` is a region whose clauses are its `catch` and `catch_all` handlers, in order. A handler+//! starts after its instruction, with the operand stack at the height of the `try`, and the runtime also stores the+//! exception it caught in a local of its own past the function's declared ones, for `rethrow`. A handler nested in+//! the handlers of `n` other tries gets the `n`th such local. The body of a `try` that ends with `delegate` is a region+//! without clauses that names where the search for a handler goes on: only regions that start at or before its+//! `delegate_bound`, which leaves out those inside the block the `delegate` names.use crate::error::{Error, Result};use crate::instruction_tables::{AtomicKind, SimdKind, atomic_kind, simd_kind};@@ -64,7 +76,7 @@ pub enum CatchKind {CatchAllRef,}-/// One catch clause of a `try_table`: which exceptions it catches and where the handler continues.+/// One catch clause of a `try_table` or a legacy `try`: which exceptions it catches and where the handler continues.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct CatchClause {pub kind: CatchKind,@@ -76,17 +88,27 @@ pub struct CatchClause {pub target_stp: u32,/// The height of the operand stack, in slots, below the values the handler pushes.pub height: u32,+ /// The local a legacy handler keeps the exception in, for `rethrow`, or NO_EXCEPTION_LOCAL.+ pub exception_local: u32,}-/// The instructions of one `try_table`, by module offset, and the range of its clauses in the catch table.+pub const NO_EXCEPTION_LOCAL: u32 = u32::MAX;++/// The instructions of one `try_table` or legacy `try` body, by module offset, and the range of its clauses in the+/// catch table.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct TryRegion {pub start: u32,pub end: u32,pub first_clause: u32,pub clause_count: u32,+ /// For the body of a legacy `try` that ends with `delegate`, the latest start of the regions the search for a+ /// handler goes on with, or NOT_DELEGATED.+ pub delegate_bound: u32,}+pub const NOT_DELEGATED: u32 = u32::MAX;+/// What validation learned about a defined function that running it needs.#[derive(Debug, Clone, Default)]pub struct FunctionInfo {@@ -94,8 +116,11 @@ pub struct FunctionInfo {/// `try_table` regions in the order their instructions appear, so that inner regions come after outer ones.pub try_regions: Box<[TryRegion]>,pub catch_clauses: Box<[CatchClause]>,- /// The number of locals, parameters included. Their types are in the function's body.+ /// The number of locals, parameters and the locals of legacy handlers included. The types of the others are in+ /// the function's body.pub local_count: u32,+ /// The number of locals legacy handlers keep their exceptions in, which come after the declared ones.+ pub exception_local_count: u32,/// The most slots the operand stack ever holds.pub max_stack_slots: u32,}@@ -251,6 +276,12 @@ enum FrameKind {If,Else,TryTable,+ /// The body of a legacy `try`.+ Try,+ /// A legacy `catch` handler.+ Catch,+ /// A legacy `catch_all` handler.+ CatchAll,Function,}@@ -278,6 +309,12 @@ struct Frame {if_entry: Option<(usize, u32)>,/// The index of the `try_table` region this frame protects.try_region: Option<usize>,+ /// The index of the region of a legacy `try`'s body, for the try and its handlers.+ legacy_region: Option<usize>,+ /// The clauses of a legacy `try`'s handlers so far, which go into the catch table together at its `end`.+ legacy_clauses: Vec<CatchClause>,+ /// The local in which a legacy handler keeps its exception.+ exception_local: Option<u32>,}impl Frame {@@ -304,6 +341,7 @@ struct FunctionValidator<'a> {side_table: Vec<SideTableEntry>,try_regions: Vec<TryRegion>,catch_clauses: Vec<CatchClause>,+ exception_local_count: u32,results: Vec<ValType>,/// Where the instruction being validated starts.instruction_start: u32,@@ -408,6 +446,9 @@ impl FunctionValidator<'_> {fixups: Vec::new(),if_entry: None,try_region: None,+ legacy_region: None,+ legacy_clauses: Vec::new(),+ exception_local: None,});self.push_values(¶ms);}@@ -806,6 +847,14 @@ impl FunctionValidator<'_> {if let Some(region) = frame.try_region {self.try_regions[region].end = pc;}+ if let Some(region) = frame.legacy_region {+ if frame.kind == FrameKind::Try {+ self.try_regions[region].end = pc;+ }+ self.try_regions[region].first_clause = self.catch_clauses.len() as u32;+ self.try_regions[region].clause_count = frame.legacy_clauses.len() as u32;+ self.catch_clauses.extend(frame.legacy_clauses);+ }self.resolve_fixups(&frame.fixups, target_pc);if frame.kind != FrameKind::Function {self.push_values(&frame.results);@@ -917,6 +966,106 @@ impl FunctionValidator<'_> {self.pop_expecting(ValType::Ref(RefType::EXNREF))?;self.set_unreachable();}+ opcode::TRY => {+ let (params, results) = self.read_block_type(reader)?;+ self.pop_values(¶ms)?;+ let region = self.try_regions.len();+ self.try_regions.push(TryRegion {+ start: reader.position() as u32,+ end: 0,+ first_clause: 0,+ clause_count: 0,+ delegate_bound: NOT_DELEGATED,+ });+ self.push_frame(FrameKind::Try, params, results, pc);+ self.frames.last_mut().expect("the frame was just pushed").legacy_region = Some(region);+ }+ opcode::CATCH | opcode::CATCH_ALL => {+ match self.frames.last().map(|frame| frame.kind) {+ Some(FrameKind::Try | FrameKind::Catch) => {}+ Some(FrameKind::CatchAll) => return invalid("catch after catch_all"),+ _ => return invalid("catch without try"),+ }+ let (kind, tag, pushed) = if opcode == opcode::CATCH {+ let tag = reader.read_u32()?;+ (CatchKind::Catch, tag, self.tag_params(tag)?)+ } else {+ (CatchKind::CatchAll, 0, Vec::new())+ };+ let frame = self.pop_frame()?;+ let region = frame.legacy_region.expect("a legacy try frame has a region");+ if frame.kind == FrameKind::Try {+ self.try_regions[region].end = pc;+ }+ // The body or the handler before this one jumps past the `end`.+ let entry = self.side_table.len();+ self.side_table.push(SideTableEntry {+ keep: slots_of(&frame.results),+ ..SideTableEntry::default()+ });+ let mut fixups = frame.fixups;+ fixups.push(Fixup::Entry { entry, branch_pc: pc });+ let nesting = self+ .frames+ .iter()+ .filter(|frame| matches!(frame.kind, FrameKind::Catch | FrameKind::CatchAll))+ .count() as u32;+ self.exception_local_count = self.exception_local_count.max(nesting + 1);+ let exception_local = self.locals.len() as u32 + nesting;+ let mut clauses = frame.legacy_clauses;+ clauses.push(CatchClause {+ kind,+ tag,+ target_pc: reader.position() as u32,+ target_stp: self.side_table.len() as u32,+ height: frame.slot_height,+ exception_local,+ });+ let handler_kind = if opcode == opcode::CATCH {+ FrameKind::Catch+ } else {+ FrameKind::CatchAll+ };+ self.push_frame(handler_kind, pushed, frame.results, frame.start_pc);+ let handler = self.frames.last_mut().expect("the frame was just pushed");+ handler.fixups = fixups;+ handler.legacy_region = Some(region);+ handler.legacy_clauses = clauses;+ handler.exception_local = Some(exception_local);+ }+ opcode::DELEGATE => {+ if self.frames.last().is_none_or(|frame| frame.kind != FrameKind::Try) {+ return invalid("delegate without try");+ }+ let depth = reader.read_u32()?;+ let frame = self.pop_frame()?;+ let target = self.label(depth)?;+ // Regions inside the block the label names start after its body does.+ let bound = match target.kind {+ FrameKind::Try => {+ self.try_regions[target.legacy_region.expect("a legacy try frame has a region")].start+ }+ FrameKind::Function => 0,+ _ => target.start_pc,+ };+ let region = frame.legacy_region.expect("a legacy try frame has a region");+ self.try_regions[region].end = pc;+ self.try_regions[region].delegate_bound = bound;+ self.try_regions[region].first_clause = self.catch_clauses.len() as u32;+ self.resolve_fixups(&frame.fixups, reader.position() as u32);+ self.push_values(&frame.results);+ }+ opcode::RETHROW => {+ let depth = reader.read_u32()?;+ let Some(local) = self.label(depth)?.exception_local else {+ return invalid("invalid rethrow label");+ };+ self.side_table.push(SideTableEntry {+ keep: local,+ ..SideTableEntry::default()+ });+ self.set_unreachable();+ }opcode::TRY_TABLE => {let (params, results) = self.read_block_type(reader)?;let count = reader.read_vector_length()?;@@ -961,6 +1110,7 @@ impl FunctionValidator<'_> {target_pc: 0,target_stp: 0,height: frame.slot_height,+ exception_local: NO_EXCEPTION_LOCAL,};if frame.kind == FrameKind::Loop {clause.target_pc = frame.start_pc;@@ -976,6 +1126,7 @@ impl FunctionValidator<'_> {end: 0,first_clause: first_clause as u32,clause_count: count,+ delegate_bound: NOT_DELEGATED,});self.push_frame(FrameKind::TryTable, params, results, pc);self.frames.last_mut().expect("the frame was just pushed").try_region = Some(region);@@ -2244,6 +2395,7 @@ pub fn validate(module: &mut Module) -> Result<()> {side_table: Vec::new(),try_regions: Vec::new(),catch_clauses: Vec::new(),+ exception_local_count: 0,results: function.results.clone(),instruction_start: body.code.start,rewrites: Vec::new(),@@ -2262,7 +2414,8 @@ pub fn validate(module: &mut Module) -> Result<()> {side_table: validator.side_table.into_boxed_slice(),try_regions: validator.try_regions.into_boxed_slice(),catch_clauses: validator.catch_clauses.into_boxed_slice(),- local_count: validator.locals.len() as u32,+ local_count: validator.locals.len() as u32 + validator.exception_local_count,+ exception_local_count: validator.exception_local_count,max_stack_slots: validator.max_slot_height,});}diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rsindex 94e9caa15a5..ed42154e965 100644--- a/Libraries/LibWasm/Engine/tests/execution.rs+++ b/Libraries/LibWasm/Engine/tests/execution.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-#![cfg(all(target_arch = "x86_64", not(windows)))]+#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]use libwasm_engine::runtime::{ExternValue, InstanceAddress, Store, Trap, Value};use std::sync::Arc;@@ -76,6 +76,26 @@ fn runs_control_flow_locals_calls_and_memory() {);}+#[test]+fn recurses_with_frames_larger_than_a_page() {+ let mut store = Store::new();+ let instance = instantiate(&mut store, "big_frames.wasm");+ // Each frame reaches more than a page below the previous one, which Windows only commits if the interpreter probes+ // the pages in between.+ assert_eq!(+ call(&mut store, instance, "deep", &[Value::I32(100)]),+ Ok(vec![Value::I32(101)])+ );+ assert_eq!(+ call(&mut store, instance, "deep", &[Value::I32(1_000_000)]),+ Err(Trap::StackExhausted)+ );+ assert_eq!(+ call(&mut store, instance, "deep", &[Value::I32(10)]),+ Ok(vec![Value::I32(11)])+ );+}+#[test]fn traps() {let mut store = Store::new();diff --git a/Libraries/LibWasm/Engine/tests/fault_stress.rs b/Libraries/LibWasm/Engine/tests/fault_stress.rsindex 41a7002faa1..6f2c5551c12 100644--- a/Libraries/LibWasm/Engine/tests/fault_stress.rs+++ b/Libraries/LibWasm/Engine/tests/fault_stress.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-#![cfg(all(target_arch = "x86_64", not(windows)))]+#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]//! Out-of-bounds accesses trap while another thread reserves, grows, and releases memories, which changes the set of//! reservations the fault handler looks addresses up in.diff --git a/Libraries/LibWasm/Engine/tests/fixtures/big_frames.wasm b/Libraries/LibWasm/Engine/tests/fixtures/big_frames.wasmnew file mode 100644index 00000000000..6808713d005Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/big_frames.wasm differdiff --git a/Libraries/LibWasm/Engine/tests/fixtures/big_frames.wat b/Libraries/LibWasm/Engine/tests/fixtures/big_frames.watnew file mode 100644index 00000000000..935a8c2bd66--- /dev/null+++ b/Libraries/LibWasm/Engine/tests/fixtures/big_frames.wat@@ -0,0 +1,9 @@+;; A function whose frame is larger than a page, with 640 i64 locals, so that each call reaches into pages below+;; the stack pointer's without touching the ones in between.+(module+ (func $deep (export "deep") (param $depth i32) (result i32)+ (local 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 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 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 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 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 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 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 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 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 i64 i64 i64 i64 i64 i64 i64 i64 i64 i64)+ (local.set 640 (i64.const 1))+ (if (result i32) (i32.eqz (local.get $depth))+ (then (i32.wrap_i64 (local.get 640)))+ (else (i32.add (call $deep (i32.sub (local.get $depth) (i32.const 1))) (i32.const 1))))))diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flapindex f1c058b5e45..4d673e2ecca 100644--- a/Libraries/LibWasm/Interpreter/interpreter.flap+++ b/Libraries/LibWasm/Interpreter/interpreter.flap@@ -267,6 +267,24 @@ inline fn align_down_16(address: u64) -> u64 {shifted << 4}+# Touch the stack from `current` down to `bottom`, below which a new frame is about to end, if the frame reaches into a+# page below that of `current`. Windows commits a thread's stack as code touches the guard page below its committed+# part, and code that skips past the guard page faults. Every page down to that of the stack pointer is committed, so+# probing the pages in between from the top down keeps that so; a frame within the stack pointer's page needs none.+# An atomic load is never removed, so it serves as the probe.+inline fn probe_stack(current: u64, bottom: u64) {+ let current_page = current >> 12;+ let bottom_page = bottom >> 12;+ if bottom_page != current_page @cold {+ let mut address = current;+ while address > bottom {+ let _ = atomic_load8([address, 0]);+ address = address - 4096;+ }+ let _ = atomic_load8([bottom, 0]);+ }+}+# Call a host function through the runtime, with its arguments on top of the operand stack.inline fn call_host_function(function: u64, return_ip: u64, context_pointer: u64) {store64([context_pointer, CONTEXT_ARGUMENTS], function);@@ -391,6 +409,7 @@ inline fn call_vector_function(function: u64, return_ip: u64, context_pointer: uguard bottom >= limit else @cold {trap_with(TRAP_STACK_EXHAUSTED, context_pointer);};+ probe_stack(current_sp, bottom);sp = bottom;store64([new_fp, FRAME_SAVED_FP], fp);store64([new_fp, FRAME_RETURN_IP], return_ip);@@ -494,6 +513,7 @@ inline fn call_function(function: u64, return_ip: u64, context_pointer: u64) {guard bottom >= limit else @cold {trap_with(TRAP_STACK_EXHAUSTED, context_pointer);};+ probe_stack(current_sp, bottom);sp = bottom;store64([new_fp, FRAME_SAVED_FP], fp);store64([new_fp, FRAME_RETURN_IP], return_ip);@@ -679,6 +699,10 @@ handler Enter() @opcode(0xf0) {let runtime_fp = align_down_16(entry_sp - FRAME_HEADER_SIZE - SPILL_AREA_SIZE);let arguments_top = runtime_fp - FRAME_HEADER_SIZE - (param_slots << 3);let new_sp = align_down_16(arguments_top - SPILL_AREA_SIZE);+ # The native code that entered the interpreter touched the stack above its frame, but maybe not the page of the+ # entry frame's stack pointer.+ let _ = atomic_load8([entry_sp, 0]);+ probe_stack(entry_sp, new_sp);sp = new_sp;fp = runtime_fp;store64([runtime_fp, FRAME_INSTANCE], 0);@@ -771,6 +795,39 @@ handler Else() @opcode(0x05) {branch();}+# Legacy exception handling. A try runs like a block, and the runtime finds its catch handlers when something throws+# inside it. Its handlers start after their catch or catch_all instruction, which runs only when the try's body or the+# handler before it completes, and skips the remaining handlers like else skips an if's second arm.+handler Try() @opcode(0x06) {+ let length = block_type_length(immediates());+ advance(length + 1);+}++handler Catch() @opcode(0x07) {+ branch();+}++handler CatchAll() @opcode(0x19) {+ branch();+}++# Reached at the end of a try's body, which delegate ends like end does.+handler Delegate() @opcode(0x18) {+ let [_, length] = read_leb(immediates());+ advance(length + 1);+}++# Rethrow the exception a catch or catch_all handler caught. The runtime kept it in a local of the frame for the+# handler, which the side-table entry of the rethrow names as its `keep` count.+handler Rethrow() @opcode(0x09) {+ let entry: u64 = stp;+ let mut local_index: u64;+ load32(local_index, [entry, 8]);+ let locals: Sequence<u64> = alias(fp);+ let exception = locals[local_index];+ throw_exception(0, exception);+}+handler End() @opcode(0x0b) {let frame: u64 = fp;let mut function: u64;@@ -7828,14 +7885,14 @@ handler AtomicWait64() @opcode(0xfe, 0x2) {# Locked instructions order everything around them, so a fence needs nothing more.handler AtomicFence() @opcode(0xfe, 0x3) {let [_, offset] = prefixed_immediates();+ atomic_fence();advance(offset + 1);}handler I32AtomicLoad() @opcode(0xfe, 0x10) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 4);- let mut value: u64;- load32(value, [address, 0]);+ let value = atomic_load32([address, 0]);set_top(value);advance(length);}@@ -7843,8 +7900,7 @@ handler I32AtomicLoad() @opcode(0xfe, 0x10) {handler I64AtomicLoad() @opcode(0xfe, 0x11) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 8);- let mut value: u64;- load64(value, [address, 0]);+ let value = atomic_load64([address, 0]);set_top(value);advance(length);}@@ -7852,8 +7908,7 @@ handler I64AtomicLoad() @opcode(0xfe, 0x11) {handler I32AtomicLoad8U() @opcode(0xfe, 0x12) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 1);- let mut value: u64;- load8(value, [address, 0]);+ let value = atomic_load8([address, 0]);set_top(value);advance(length);}@@ -7861,8 +7916,7 @@ handler I32AtomicLoad8U() @opcode(0xfe, 0x12) {handler I32AtomicLoad16U() @opcode(0xfe, 0x13) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 2);- let mut value: u64;- load16(value, [address, 0]);+ let value = atomic_load16([address, 0]);set_top(value);advance(length);}@@ -7870,8 +7924,7 @@ handler I32AtomicLoad16U() @opcode(0xfe, 0x13) {handler I64AtomicLoad8U() @opcode(0xfe, 0x14) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 1);- let mut value: u64;- load8(value, [address, 0]);+ let value = atomic_load8([address, 0]);set_top(value);advance(length);}@@ -7879,8 +7932,7 @@ handler I64AtomicLoad8U() @opcode(0xfe, 0x14) {handler I64AtomicLoad16U() @opcode(0xfe, 0x15) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 2);- let mut value: u64;- load16(value, [address, 0]);+ let value = atomic_load16([address, 0]);set_top(value);advance(length);}@@ -7888,8 +7940,7 @@ handler I64AtomicLoad16U() @opcode(0xfe, 0x15) {handler I64AtomicLoad32U() @opcode(0xfe, 0x16) {let address_operand = unary_operand();let [_, address, length] = atomic_access(address_operand, 4);- let mut value: u64;- load32(value, [address, 0]);+ let value = atomic_load32([address, 0]);set_top(value);advance(length);}diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cppindex 8728010793a..075de7b02bb 100644--- a/Libraries/LibWasm/Runtime.cpp+++ b/Libraries/LibWasm/Runtime.cpp@@ -335,6 +335,21 @@ Optional<u32> Store::function_index(Entity function)return index;}+ValueType Store::canonical_value_type(Module const& module, ValueType type)+{+ return from_ffi(FFI::wasm_store_canonical_value_type(m_store, module.handle(), to_ffi(type)));+}++bool Store::reference_matches(u64 reference, ValueType type)+{+ return FFI::wasm_store_reference_matches(m_store, reference, to_ffi(type));+}++bool Store::is_function_type(u32 identity)+{+ return FFI::wasm_store_is_function_type(m_store, identity);+}+Entity Store::allocate_tag(ReadonlySpan<ValueType> parameters){Vector<FFI::WasmValueType> types;diff --git a/Libraries/LibWasm/Runtime.h b/Libraries/LibWasm/Runtime.hindex e9cb6df5f3d..bdf70c3bc80 100644--- a/Libraries/LibWasm/Runtime.h+++ b/Libraries/LibWasm/Runtime.h@@ -259,6 +259,16 @@ public:// a host function.Optional<u32> function_index(Entity function);+ // The types of functions, tables, globals, and tags of the store name concrete heap types by store-wide+ // identities, where the types of a module name them by their indices in the module. This is a type of `module`+ // in the store's terms.+ ValueType canonical_value_type(Module const&, ValueType);+ // Whether a non-null reference matches a reference type of the store. A reference of the any hierarchy must be in+ // its internal form: an i31 reference, a GC object, or a host reference.+ bool reference_matches(u64 reference, ValueType);+ // Whether the concrete heap type `identity` is a function type, as opposed to a struct or array type.+ bool is_function_type(u32 identity);+Entity allocate_tag(ReadonlySpan<ValueType> parameters);Vector<ValueType> tag_parameters(Entity tag);// An exception is a cell of the heap, which keeps it while something refers to it.diff --git a/Libraries/LibWasm/Tests/reencode.py b/Libraries/LibWasm/Tests/reencode.pyindex f9ab0b5136a..6f509590863 100644--- a/Libraries/LibWasm/Tests/reencode.py+++ b/Libraries/LibWasm/Tests/reencode.py@@ -196,7 +196,10 @@ PLAIN = {0x03: "b",0x04: "b",0x05: "",+ 0x06: "b",+ 0x07: "u",0x08: "u",+ 0x09: "u",0x0A: "",0x0B: "",0x0C: "u",@@ -208,6 +211,8 @@ PLAIN = {0x13: "uu",0x14: "u",0x15: "u",+ 0x18: "u",+ 0x19: "",0x1A: "",0x1B: "",0x20: "u",diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 8a34d878912..68024958b8d 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -988,11 +988,13 @@ set(SOURCESWebLocks/LockManager.cppWebLocks/LockRequest.cppWebLocks/NavigatorLocks.cpp+ WebAssembly/Exception.cppWebAssembly/Global.cppWebAssembly/Instance.cppWebAssembly/Memory.cppWebAssembly/Module.cppWebAssembly/Table.cpp+ WebAssembly/Tag.cppWebAssembly/WebAssembly.cppWebAssembly/WebAssemblyModule.cppWebAudio/AnalyserNode.cppdiff --git a/Libraries/LibWeb/WebAssembly/BindingsGlue.h b/Libraries/LibWeb/WebAssembly/BindingsGlue.hindex 93bc7130730..10d238b7dd4 100644--- a/Libraries/LibWeb/WebAssembly/BindingsGlue.h+++ b/Libraries/LibWeb/WebAssembly/BindingsGlue.h@@ -23,11 +23,13 @@namespace Web::WebAssembly {+class Exception;class Global;class Instance;class Memory;class Module;class Table;+class Tag;}@@ -38,6 +40,11 @@ WEB_API WebIDL::ExceptionOr<JS::Value> value(JS::Realm&, WebAssembly::Global&);WEB_API WebIDL::ExceptionOr<void> set_value(JS::Realm&, WebAssembly::Global&, JS::Value);WEB_API WebIDL::ExceptionOr<JS::Value> value_of(JS::Realm&, WebAssembly::Global&);+WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Tag>> construct_tag(JS::Realm&, TagType const&);++WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Exception>> construct_exception(JS::Realm&, WebAssembly::Tag&, GC::RootVector<JS::Value> const& payload, ExceptionOptions const&);+WEB_API WebIDL::ExceptionOr<JS::Value> get_arg(WebAssembly::Exception&, WebAssembly::Tag&, u32 index);+WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Instance>> construct_instance(JS::Realm&, WebAssembly::Module&, GC::Ptr<JS::Object> import_object);WEB_API GC::Ref<JS::Object const> exports(JS::Realm&, GC::Ref<WebAssembly::Instance>);WEB_API JS::ThrowCompletionOr<void> initialize_webassembly_export_binding(JS::Realm&, JS::Environment&, Utf16FlyString const& name, GC::Ref<WebAssembly::Instance>);@@ -54,11 +61,13 @@ WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile_streaming(JS::RealWEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, WebIDL::BufferSource bytes, GC::Ptr<JS::Object> import_object);WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, GC::Ref<WebAssembly::Module>, GC::Ptr<JS::Object> import_object);WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::Realm&, GC::Ref<WebIDL::Promise> source, GC::Ptr<JS::Object> import_object);+WEB_API WebAssembly::Exception* exception_from_value(JS::Value);WEB_API WebAssembly::Global* global_from_value(JS::Value);WEB_API WebAssembly::Instance* instance_from_value(JS::Value);WEB_API WebAssembly::Memory* memory_from_value(JS::Value);WEB_API WebAssembly::Module* module_from_value(JS::Value);WEB_API WebAssembly::Table* table_from_value(JS::Value);+WEB_API WebAssembly::Tag* tag_from_value(JS::Value);WEB_API void resolve_webassembly_module_promise(JS::Realm&, WebIDL::Promise&, GC::Ref<WebAssembly::Module>);WEB_API void resolve_webassembly_instance_promise(JS::Realm&, WebIDL::Promise&, GC::Ref<WebAssembly::Instance>);WEB_API GC::Ref<JS::Object> create_webassembly_instantiated_source(JS::Realm&, GC::Ref<WebAssembly::Module>, GC::Ref<WebAssembly::Instance>);diff --git a/Libraries/LibWeb/WebAssembly/Exception.cpp b/Libraries/LibWeb/WebAssembly/Exception.cppnew file mode 100644index 00000000000..35e82f2b109--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Exception.cpp@@ -0,0 +1,178 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibGC/Heap.h>+#include <LibJS/Runtime/Error.h>+#include <LibJS/Runtime/VM.h>+#include <LibWeb/Bindings/Exception.h>+#include <LibWeb/WebAssembly/BindingsGlue.h>+#include <LibWeb/WebAssembly/Exception.h>+#include <LibWeb/WebAssembly/Tag.h>++namespace Web::WebAssembly {++GC_DEFINE_ALLOCATOR(Exception);++GC::Ref<Exception> Exception::create(u64 exception, Optional<Utf16String> stack)+{+ // https://webassembly.github.io/spec/js-api/#initialize-an-exception-object+ // 1. Let map be the surrounding agent's associated exception object cache.+ // 2. Assert: map[exnAddr] doesn't exist.+ auto& cache = Detail::WebAssemblyCache::the();+ VERIFY(!cache.exception_object(exception));++ // 3. Set exn.[[Address]] to exnAddr.+ // 4. Set map[exnAddr] to exn.+ // 5. Let store be the surrounding agent's associated store.+ // 6. Let tagaddr be exn_tag(store, exnAddr).+ // 7. Let payload be exn_read(store, exnAddr).+ // 8. Set exn.[[Type]] to tagaddr.+ // 9. Set exn.[[Payload]] to payload.+ // NB: The payload of an exception never changes, so getArg() reads it from the store.+ auto tag = cache.store().exception_tag(exception);+ auto object = GC::Heap::the().allocate<Exception>(exception, tag, move(stack));+ cache.set_exception_object(exception, object);+ return object;+}++// https://webassembly.github.io/spec/js-api/#create-an-exception-object+GC::Ref<Exception> Exception::from_address(u64 exception)+{+ // 1. Let map be the surrounding agent's associated exception object cache.+ // 2. If map[exnAddr] exists,+ // 1. Return map[exnAddr].+ if (auto object = Detail::WebAssemblyCache::the().exception_object(exception))+ return *object;++ // 3. Let exn be a new Exception.+ // 4. Initialize exn from exnAddr.+ // 5. Set exn.[[Stack]] to undefined.+ // 6. Return exn.+ return create(exception, {});+}++Exception::Exception(u64 exception, Wasm::Runtime::Entity tag, Optional<Utf16String> stack)+ : m_exception(exception)+ , m_tag(tag)+ , m_stack(move(stack))+{+}++void Exception::visit_edges(Visitor& visitor)+{+ Base::visit_edges(visitor);+ // NB: An exception reference is the address of the exception's cell.+ visitor.visit(reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(m_exception)));+ visitor.visit(m_tag);+}++// https://webassembly.github.io/spec/js-api/#dom-exception-is+bool Exception::is(Tag const& tag) const+{+ // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]], return false.+ // 2. Return true.+ return m_tag == tag.address();+}++// https://webassembly.github.io/spec/js-api/#dom-exception-stack+Variant<Utf16String, Empty> Exception::stack() const+{+ // 1. Return this.[[Stack]].+ if (m_stack.has_value())+ return *m_stack;+ return Empty {};+}++}++namespace Web::Bindings {++// https://webassembly.github.io/spec/js-api/#dom-exception-exception+WebIDL::ExceptionOr<GC::Ref<WebAssembly::Exception>> construct_exception(JS::Realm& realm, WebAssembly::Tag& exception_tag, GC::RootVector<JS::Value> const& payload, ExceptionOptions const& options)+{+ auto& vm = realm.vm();+ auto& cache = WebAssembly::Detail::WebAssemblyCache::the();+ auto& store = cache.store();++ // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.+ // 2. If exceptionTag.[[Address]] is equal to JSTagAddr,+ // 1. Throw a TypeError.+ if (exception_tag.address() == cache.js_tag())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot construct an exception with the JavaScript tag"_utf16 };++ // 3. Let store be the surrounding agent's associated store.+ // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).+ auto types = store.tag_parameters(exception_tag.address());++ // 5. If types's size is not payload's size,+ // 1. Throw a TypeError.+ if (types.size() != payload.size())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("The tag takes {} values, not {}", types.size(), payload.size()) };++ // 6. Let wasmPayload be « ».+ // NB: The converted values may refer to new cells, which this vector keeps alive until they are in the exception.+ Wasm::Runtime::Values wasm_payload;++ // 7. For each value and resultType of payload and types, paired linearly,+ for (size_t index = 0; index < payload.size(); ++index) {+ // 1. If resultType is v128 or exnref,+ // 1. Throw a TypeError.+ // 2. Append ? ToWebAssemblyValue(value, resultType) to wasmPayload.+ // NB: ToWebAssemblyValue throws the TypeError for v128 and exnref.+ wasm_payload.append(TRY(WebAssembly::Detail::to_webassembly_value(vm, payload[index], types[index])));+ }++ // 8. Let (store, exceptionAddr) be exn_alloc(store, exceptionTag.[[Address]], wasmPayload).+ // 9. Set the surrounding agent's associated store to store.+ auto exception = store.allocate_exception(exception_tag.address(), wasm_payload);++ // 10. Initialize this from exceptionAddr.+ // 11. If options["traceStack"] is true,+ // 1. Set this.[[Stack]] to either a DOMString representation of the current call stack or undefined.+ // 12. Otherwise,+ // 1. Set this.[[Stack]] to undefined.+ Optional<Utf16String> stack;+ if (options.trace_stack) {+ auto error = JS::Error::create(realm);+ stack = error->stack_string();+ }+ return WebAssembly::Exception::create(exception, move(stack));+}++// https://webassembly.github.io/spec/js-api/#dom-exception-getarg+WebIDL::ExceptionOr<JS::Value> get_arg(WebAssembly::Exception& exception, WebAssembly::Tag& exception_tag, u32 index)+{+ auto& store = WebAssembly::Detail::WebAssemblyCache::the().store();++ // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]],+ // 1. Throw a TypeError.+ if (exception.tag_address() != exception_tag.address())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The exception does not have this tag"_utf16 };++ // 2. Let payload be this.[[Payload]].+ auto payload = store.exception_values(exception.address());++ // 3. If index ≥ payload's size,+ // 1. Throw a RangeError.+ if (index >= payload.size())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, Utf16String::formatted("The exception has {} values", payload.size()) };++ // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).+ auto types = store.tag_parameters(exception_tag.address());++ // 5. If types[index] matches v128 or exnref,+ // 1. Throw a TypeError.+ // 6. Return ToJSValue(payload[index]).+ // NB: ToJSValue throws the TypeError for v128 and exnref.+ return TRY(WebAssembly::Detail::to_js_value(JS::VM::the(), payload[index], types[index]));+}++WebAssembly::Exception* exception_from_value(JS::Value value)+{+ return value.is_object() ? Bindings::impl_from<WebAssembly::Exception>(&value.as_object()) : nullptr;+}++}diff --git a/Libraries/LibWeb/WebAssembly/Exception.h b/Libraries/LibWeb/WebAssembly/Exception.hnew file mode 100644index 00000000000..14199ed3880--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Exception.h@@ -0,0 +1,45 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Optional.h>+#include <AK/Utf16String.h>+#include <AK/Variant.h>+#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/WebAssembly/WebAssembly.h>++namespace Web::WebAssembly {++class Tag;++// https://webassembly.github.io/spec/js-api/#exceptions+class Exception : public Bindings::GCAllocatedWrappable {+ WEB_WRAPPABLE(Exception, Bindings::GCAllocatedWrappable);+ GC_DECLARE_ALLOCATOR(Exception);++public:+ static GC::Ref<Exception> create(u64 exception, Optional<Utf16String> stack);+ // The Exception object of an exception, which is the same object for as long as it lives.+ static GC::Ref<Exception> from_address(u64 exception);++ u64 address() const { return m_exception; }+ Wasm::Runtime::Entity tag_address() const { return m_tag; }++ bool is(Tag const&) const;+ Variant<Utf16String, Empty> stack() const;++private:+ Exception(u64 exception, Wasm::Runtime::Entity tag, Optional<Utf16String> stack);++ virtual void visit_edges(Visitor&) override;++ u64 m_exception { 0 };+ Wasm::Runtime::Entity m_tag { nullptr };+ Optional<Utf16String> m_stack;+};++}diff --git a/Libraries/LibWeb/WebAssembly/Exception.idl b/Libraries/LibWeb/WebAssembly/Exception.idlnew file mode 100644index 00000000000..7a8aefb9d42--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Exception.idl@@ -0,0 +1,13 @@+// https://webassembly.github.io/spec/js-api/#dictdef-exceptionoptions+dictionary ExceptionOptions {+ boolean traceStack = false;+};++// https://webassembly.github.io/spec/js-api/#exception+[LegacyNamespace=WebAssembly, Exposed=*]+interface Exception {+ [ImplementedInBindings] constructor(Tag exceptionTag, sequence<any> payload, optional ExceptionOptions options = {});+ [ImplementedInBindings] any getArg(Tag exceptionTag, [EnforceRange] unsigned long index);+ boolean is(Tag exceptionTag);+ readonly attribute (DOMString or undefined) stack;+};diff --git a/Libraries/LibWeb/WebAssembly/Global.cpp b/Libraries/LibWeb/WebAssembly/Global.cppindex cab55c4963b..452ee30bf68 100644--- a/Libraries/LibWeb/WebAssembly/Global.cpp+++ b/Libraries/LibWeb/WebAssembly/Global.cpp@@ -108,7 +108,7 @@ WebIDL::ExceptionOr<void> Global::set_value(Wasm::Runtime::Value value)namespace Web::Bindings {// https://webassembly.github.io/spec/js-api/#tovaluetype-static Wasm::Runtime::ValueType to_value_type(ValueType type)+Wasm::Runtime::ValueType to_value_type(ValueType type){using Wasm::Runtime::HeapKind;using Wasm::Runtime::ValueKind;diff --git a/Libraries/LibWeb/WebAssembly/Global.h b/Libraries/LibWeb/WebAssembly/Global.hindex de30771cf5c..823fe3efe97 100644--- a/Libraries/LibWeb/WebAssembly/Global.h+++ b/Libraries/LibWeb/WebAssembly/Global.h@@ -11,6 +11,15 @@#include <LibWeb/WebAssembly/WebAssembly.h>#include <LibWeb/WebIDL/ExceptionOr.h>+namespace Web::Bindings {++enum class ValueType : u8;++// https://webassembly.github.io/spec/js-api/#tovaluetype+Wasm::Runtime::ValueType to_value_type(ValueType);++}+namespace Web::WebAssembly {struct GlobalDescriptor {diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cppindex 0f38d7277b7..daf7becc3e9 100644--- a/Libraries/LibWeb/WebAssembly/Instance.cpp+++ b/Libraries/LibWeb/WebAssembly/Instance.cpp@@ -23,6 +23,7 @@#include <LibWeb/WebAssembly/Memory.h>#include <LibWeb/WebAssembly/Module.h>#include <LibWeb/WebAssembly/Table.h>+#include <LibWeb/WebAssembly/Tag.h>#include <LibWeb/WebAssembly/WebAssembly.h>namespace Web::WebAssembly {@@ -140,7 +141,7 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::exports->define_direct_property(name, table(realm, instance.table_instance(address)), JS::default_attributes);break;case Wasm::Runtime::ExternKind::Tag:- dbgln("Not yet implemented: tags");+ exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, WebAssembly::Tag::from_address(address)), JS::default_attributes);break;}}diff --git a/Libraries/LibWeb/WebAssembly/Tag.cpp b/Libraries/LibWeb/WebAssembly/Tag.cppnew file mode 100644index 00000000000..b7484ab2079--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Tag.cpp@@ -0,0 +1,89 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibGC/Heap.h>+#include <LibWeb/Bindings/Tag.h>+#include <LibWeb/WebAssembly/BindingsGlue.h>+#include <LibWeb/WebAssembly/Global.h>+#include <LibWeb/WebAssembly/Tag.h>++namespace Web::WebAssembly {++GC_DEFINE_ALLOCATOR(Tag);++// https://webassembly.github.io/spec/js-api/#dom-tag-tag+GC::Ref<Tag> Tag::create(ReadonlySpan<Wasm::Runtime::ValueType> parameters)+{+ // 4. Let store be the surrounding agent's associated store.+ // 5. Let (store, tagAddress) be tag_alloc(store, « wasmParameters » → « »).+ // 6. Set the surrounding agent's associated store to store.+ auto tag = Detail::WebAssemblyCache::the().store().allocate_tag(parameters);++ // 7. Initialize this from tagAddress.+ return from_address(tag);+}++// https://webassembly.github.io/spec/js-api/#create-a-tag-object+GC::Ref<Tag> Tag::from_address(Wasm::Runtime::Entity tag)+{+ // 1. Let map be the surrounding agent's associated tag object cache.+ // 2. If map[tagAddress] exists,+ // 1. Return map[tagAddress].+ auto& cache = Detail::WebAssemblyCache::the();+ if (auto object = cache.tag_object(tag))+ return *object;++ // 3. Let tag be a new Tag.+ // 4. Initialize tag from tagAddress.+ // https://webassembly.github.io/spec/js-api/#initialize-a-tag-object+ // 3. Set tag.[[Address]] to tagAddress.+ auto object = GC::Heap::the().allocate<Tag>(tag);++ // 4. Set map[tagAddress] to tag.+ cache.set_tag_object(tag, object);++ // 5. Return tag.+ return object;+}++Tag::Tag(Wasm::Runtime::Entity tag)+ : m_tag(tag)+{+}++void Tag::visit_edges(Visitor& visitor)+{+ Base::visit_edges(visitor);+ visitor.visit(m_tag);+}++}++namespace Web::Bindings {++// https://webassembly.github.io/spec/js-api/#dom-tag-tag+WebIDL::ExceptionOr<GC::Ref<WebAssembly::Tag>> construct_tag(JS::Realm&, TagType const& type)+{+ // 1. Let parameters be type["parameters"].+ // 2. Let wasmParameters be «».+ Vector<Wasm::Runtime::ValueType> parameters;+ parameters.ensure_capacity(type.parameters.size());++ // 3. For each type of parameters,+ for (auto parameter : type.parameters) {+ // 1. Append ToValueType(type) to wasmParameters.+ parameters.unchecked_append(to_value_type(parameter));+ }++ return WebAssembly::Tag::create(parameters);+}++WebAssembly::Tag* tag_from_value(JS::Value value)+{+ return value.is_object() ? Bindings::impl_from<WebAssembly::Tag>(&value.as_object()) : nullptr;+}++}diff --git a/Libraries/LibWeb/WebAssembly/Tag.h b/Libraries/LibWeb/WebAssembly/Tag.hnew file mode 100644index 00000000000..c54acbdb242--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Tag.h@@ -0,0 +1,34 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/WebAssembly/WebAssembly.h>++namespace Web::WebAssembly {++// https://webassembly.github.io/spec/js-api/#tag+class Tag : public Bindings::GCAllocatedWrappable {+ WEB_WRAPPABLE(Tag, Bindings::GCAllocatedWrappable);+ GC_DECLARE_ALLOCATOR(Tag);++public:+ static GC::Ref<Tag> create(ReadonlySpan<Wasm::Runtime::ValueType> parameters);+ // The Tag object of a tag, which is the same object for as long as it lives.+ static GC::Ref<Tag> from_address(Wasm::Runtime::Entity tag);++ Wasm::Runtime::Entity address() const { return m_tag; }++private:+ explicit Tag(Wasm::Runtime::Entity tag);++ virtual void visit_edges(Visitor&) override;++ Wasm::Runtime::Entity m_tag { nullptr };+};++}diff --git a/Libraries/LibWeb/WebAssembly/Tag.idl b/Libraries/LibWeb/WebAssembly/Tag.idlnew file mode 100644index 00000000000..a052a1f7733--- /dev/null+++ b/Libraries/LibWeb/WebAssembly/Tag.idl@@ -0,0 +1,10 @@+// https://webassembly.github.io/spec/js-api/#dictdef-tagtype+dictionary TagType {+ required sequence<ValueType> parameters;+};++// https://webassembly.github.io/spec/js-api/#tag+[LegacyNamespace=WebAssembly, Exposed=*]+interface Tag {+ [ImplementedInBindings] constructor(TagType type);+};diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cppindex 3ff6aa5f555..c9e4301eba1 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp@@ -39,11 +39,13 @@#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/WebAssembly/BindingsGlue.h>+#include <LibWeb/WebAssembly/Exception.h>#include <LibWeb/WebAssembly/Global.h>#include <LibWeb/WebAssembly/Instance.h>#include <LibWeb/WebAssembly/Memory.h>#include <LibWeb/WebAssembly/Module.h>#include <LibWeb/WebAssembly/Table.h>+#include <LibWeb/WebAssembly/Tag.h>#include <LibWeb/WebAssembly/WebAssembly.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/Buffers.h>@@ -64,28 +66,28 @@ using WasmValueType = Wasm::Runtime::ValueType;using Wasm::Runtime::HeapKind;using Wasm::Runtime::ValueKind;-template<typename T>-GC::Ptr<T> WebAssemblyCache::ObjectCache<T>::get(Entity entity) const+template<typename T, typename Key>+GC::Ptr<T> WebAssemblyCache::ObjectCache<T, Key>::get(Key key) const{- auto entry = m_objects.get(entity);+ auto entry = m_objects.get(key);if (!entry.has_value())return nullptr;return entry->ptr();}-template<typename T>-void WebAssemblyCache::ObjectCache<T>::set(Entity entity, T& object)+template<typename T, typename Key>+void WebAssemblyCache::ObjectCache<T, Key>::set(Key key, T& object){// NB: Stale entries go once there are as many of them as live ones.if (m_objects.size() >= 2 * m_live_after_pruning + 16) {m_objects.remove_all_matching([](auto&, auto& weak) { return !weak; });m_live_after_pruning = m_objects.size();}- m_objects.set(entity, object);+ m_objects.set(key, object);}-template<typename T>-void WebAssemblyCache::ObjectCache<T>::for_each(Function<void(T&)> const& callback) const+template<typename T, typename Key>+void WebAssemblyCache::ObjectCache<T, Key>::for_each(Function<void(T&)> const& callback) const{for (auto& entry : m_objects) {if (entry.value)@@ -102,6 +104,12 @@ void WebAssemblyCache::set_memory_object(Entity memory, Memory& object) { m_memoGC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return m_table_objects.get(table); }void WebAssemblyCache::set_table_object(Entity table, Table& object) { m_table_objects.set(table, object); }void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const { m_memory_objects.for_each(callback); }+GC::Ptr<Tag> WebAssemblyCache::tag_object(Entity tag) const { return m_tag_objects.get(tag); }+void WebAssemblyCache::set_tag_object(Entity tag, Tag& object) { m_tag_objects.set(tag, object); }+GC::Ptr<Exception> WebAssemblyCache::exception_object(u64 exception) const { return m_exception_objects.get(exception); }+void WebAssemblyCache::set_exception_object(u64 exception, Exception& object) { m_exception_objects.set(exception, object); }+GC::Ptr<JS::Object> WebAssemblyCache::gc_object(u64 object) const { return m_gc_objects.get(object); }+void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object) { m_gc_objects.set(object, gc_object); }WebAssemblyCache::~WebAssemblyCache() = default;@@ -133,7 +141,7 @@ WebAssemblyCache::WebAssemblyCache(GC::Heap& heap)}// https://webassembly.github.io/spec/js-api/#error-objects-void initialize(JS::Object& self, JS::Realm&)+void initialize(JS::Object& self, JS::Realm& realm){// 1. Let namespaceObject be the namespace object.auto& namespace_object = self;@@ -149,6 +157,18 @@ void initialize(JS::Object& self, JS::Realm&)});WASM_ENUMERATE_NATIVE_ERRORS#undef __WASM_ENUMERATE++ // https://webassembly.github.io/spec/js-api/#dom-webassembly-jstag+ // NB: A regular attribute of a namespace is an accessor property of the namespace object.+ Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> js_tag_getter = [](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {+ // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.+ // 2. Let JSTagObject be the result of creating a Tag object from JSTagAddr.+ // 3. Return JSTagObject.+ auto& current_realm = *vm.current_realm();+ auto tag = Tag::from_address(Detail::WebAssemblyCache::the().js_tag());+ return Bindings::wrap(Bindings::host_defined_wrapper_world(current_realm), current_realm, tag);+ };+ namespace_object.define_native_accessor(realm, "JSTag"_utf16_fly_string, move(js_tag_getter), Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);}// https://webassembly.github.io/spec/js-api/#dom-webassembly-validate@@ -326,6 +346,110 @@ static i32 value_of_i31_reference(u64 reference)return static_cast<i32>(static_cast<u32>(reference)) >> 1;}+// https://webassembly.github.io/spec/js-api/#exported-gc-object+// An Exported GC Object stands for a struct or an array, whose reference is the address of its cell. The object keeps+// that cell as its host data, and has no properties, no prototype, and no way to get either.+struct ExportedGCObjectTraits {+ static JS::ThrowCompletionOr<JS::Object*> get_prototype_of(JS::HostObject const&)+ {+ // 1. Return null.+ return nullptr;+ }++ static JS::ThrowCompletionOr<bool> set_prototype_of(JS::HostObject const& object, JS::Object*)+ {+ // 1. Throw a TypeError.+ return object.vm().throw_completion<JS::TypeError>("Cannot set the prototype of a WebAssembly GC object"_utf16);+ }++ static JS::ThrowCompletionOr<bool> is_extensible(JS::HostObject const&)+ {+ // 1. Return false.+ return false;+ }++ static JS::ThrowCompletionOr<bool> prevent_extensions(JS::HostObject const& object)+ {+ // 1. Throw a TypeError.+ return object.vm().throw_completion<JS::TypeError>("Cannot prevent extensions of a WebAssembly GC object"_utf16);+ }++ static JS::ThrowCompletionOr<Optional<JS::PropertyDescriptor>> get_own_property(JS::HostObject const&, JS::PropertyKey const&)+ {+ // 1. Return undefined.+ return Optional<JS::PropertyDescriptor> {};+ }++ static JS::ThrowCompletionOr<bool> define_own_property(JS::HostObject const& object, JS::PropertyKey const&, JS::PropertyDescriptor&, Optional<JS::PropertyDescriptor>*)+ {+ // 1. Throw a TypeError.+ return object.vm().throw_completion<JS::TypeError>("Cannot define properties of a WebAssembly GC object"_utf16);+ }++ static JS::ThrowCompletionOr<bool> has_property(JS::HostObject const&, JS::PropertyKey const&)+ {+ // 1. Return false.+ return false;+ }++ static JS::ThrowCompletionOr<JS::Value> get(JS::HostObject const&, JS::PropertyKey const&, JS::Value, JS::CacheableGetPropertyMetadata*, JS::Object::PropertyLookupPhase)+ {+ // 1. Return undefined.+ return JS::js_undefined();+ }++ static JS::ThrowCompletionOr<bool> set(JS::HostObject const& object, JS::PropertyKey const&, JS::Value, JS::Value, JS::CacheableSetPropertyMetadata*, JS::Object::PropertyLookupPhase)+ {+ // 1. Throw a TypeError.+ return object.vm().throw_completion<JS::TypeError>("Cannot set properties of a WebAssembly GC object"_utf16);+ }++ static JS::ThrowCompletionOr<bool> delete_property(JS::HostObject const& object, JS::PropertyKey const&)+ {+ // 1. Throw a TypeError.+ return object.vm().throw_completion<JS::TypeError>("Cannot delete properties of a WebAssembly GC object"_utf16);+ }++ static JS::ThrowCompletionOr<GC::RootVector<JS::Value>> own_property_keys(JS::HostObject const&)+ {+ // 1. Let keys be a new empty list.+ // 2. Return keys.+ return GC::RootVector<JS::Value> {};+ }+};++static constexpr JSHostObjectHooks exported_gc_object_hooks = JS::make_host_object_hooks<ExportedGCObjectTraits>();+static constexpr JSHostClass exported_gc_object_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "WebAssemblyGCObject"sv, nullptr, &exported_gc_object_hooks, nullptr, JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE);++// https://webassembly.github.io/spec/js-api/#create-a-new-exported-gc-object+static GC::Ref<JS::Object> create_exported_gc_object(JS::VM& vm, u64 reference)+{+ // 1. Assert: objectaddr is a struct or array address.+ // 2. Let map be the current agent's associated exported GC object cache.+ // 3. If map[objectaddr] exists, return map[objectaddr].+ auto& cache = WebAssemblyCache::the();+ if (auto object = cache.gc_object(reference))+ return *object;++ // 4. Let object be a new Exported GC Object, with [[ObjectAddress]] set to objectaddr and [[ObjectKind]] set to+ // objectKind.+ auto* cell = reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(reference));+ auto object = JS::HostObject::create(*vm.current_realm(), exported_gc_object_host_class, nullptr, {}, cell);++ // 5. Set map[objectaddr] to object.+ cache.set_gc_object(reference, object);++ // 6. Return object.+ return object;+}++Optional<u64> exported_gc_object_address(JS::Object const& object)+{+ if (!JS::is_host_instance_of(object, exported_gc_object_host_class))+ return {};+ return static_cast<u64>(reinterpret_cast<FlatPtr>(JS::host_data_of(object).ptr()));+}+// https://webassembly.github.io/spec/js-api/#run-a-host-functionstatic JS::ThrowCompletionOr<void> run_a_host_function(JS::VM& vm, JS::FunctionObject& function, Wasm::Runtime::FunctionType const& type, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results){@@ -399,10 +523,20 @@ Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& functif (!result.is_error())return {};- // https://webassembly.github.io/spec/js-api/#run-a-host-function- // If the steps threw an exception v, throw a WebAssembly exception with the JavaScript tag and payload v, which- // WebAssembly code can catch, and which is v again once it leaves WebAssembly.+ // https://webassembly.github.io/spec/js-api/#create-a-host-function+ // If the steps threw an exception v,auto value = result.error_value();++ // 1. If v implements Exception, let address be v.[[Address]].+ if (auto* exception = Bindings::exception_from_value(value))+ return Wasm::Runtime::HostError::exception(exception->address());++ // 2. Otherwise,+ // 1. Let type be the JavaScript exception tag.+ // 2. Let payload be ! ToWebAssemblyValue(v, externref).+ // 3. Let (store, address) be exn_alloc(store, type, « payload »).+ // 3. Throw a WebAssembly exception with address, which WebAssembly code can catch, and which is v again once it+ // leaves WebAssembly.Array<WasmValue, 1> payload { WasmValue::from_reference(value.is_null() ? 0 : host_reference_of(vm, value)) };return Wasm::Runtime::HostError::exception(store.allocate_exception(WebAssemblyCache::the().js_tag(), payload));});@@ -411,6 +545,18 @@ Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& functreturn address;}+Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const& module, u32 type_index)+{+ auto& store = WebAssemblyCache::the().store();+ auto type = module.function_type(type_index);+ VERIFY(type.has_value());+ for (auto& parameter : type->parameters)+ parameter = store.canonical_value_type(module, parameter);+ for (auto& result : type->results)+ result = store.canonical_value_type(module, result);+ return type.release_value();+}+JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm::Runtime::Module const& module, GC::Ptr<JS::Object> import_object){auto& store = WebAssemblyCache::the().store();@@ -460,9 +606,7 @@ JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasmelse {// 3.4.3.1. Create a host function from v and functype, and let funcaddr be the result.// 3.4.3.2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.- auto function_type = module.function_type(import.type.type_index);- VERIFY(function_type.has_value());- address = create_host_function(vm, function, function_type.release_value(), imported_function_count);+ address = create_host_function(vm, function, function_type_in_store(module, import.type.type_index), imported_function_count);}// 3.4.4. Let externfunc be the external value func funcaddr.@@ -473,7 +617,7 @@ JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm}// 3.5. If externtype is of the form global mut valtype,case Wasm::Runtime::ExternKind::Global: {- auto value_type = import.type.value_type;+ auto value_type = store.canonical_value_type(module, import.type.value_type);Wasm::Runtime::Entity address = nullptr;// 3.5.1. If v is a Number or v is a BigInt,if (import_.is_number() || import_.is_bigint()) {@@ -540,9 +684,20 @@ JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasmimports.unchecked_append({ Wasm::Runtime::ExternKind::Table, table->address() });break;}- // FIXME: 3.8. If externtype is of the form tag attribute functype, which needs WebAssembly.Tag.- case Wasm::Runtime::ExternKind::Tag:- return vm.throw_completion<LinkError>("Tag imports are not supported"sv);+ // 3.8. If externtype is of the form tag attribute functype,+ case Wasm::Runtime::ExternKind::Tag: {+ // 3.8.1. Assert: attribute is exception.+ // 3.8.2. If v does not implement Tag, throw a LinkError exception.+ auto* tag = Bindings::tag_from_value(import_);+ if (!tag)+ return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Tag for a tag import"sv);++ // 3.8.3. Let tagaddr be v.[[Address]].+ // 3.8.4. Let externtag be the external value tag tagaddr.+ // 3.8.5. Append externtag to imports.+ imports.unchecked_append({ Wasm::Runtime::ExternKind::Tag, tag->address() });+ break;+ }}}@@ -838,10 +993,33 @@ GC::Ref<JS::NativeFunction> create_native_function(JS::Realm& realm, Wasm::Runtireturn object;}+// The internal form of a JavaScript value as a reference of the any hierarchy: an i31 reference for a Number in its+// range, the struct or array of an Exported GC Object, and otherwise a host reference.+static u64 internalized_reference_of(JS::VM& vm, JS::Value value)+{+ if (auto reference = i31_reference_of(value); reference.has_value())+ return *reference;+ if (value.is_object()) {+ if (auto address = exported_gc_object_address(value.as_object()); address.has_value())+ return *address;+ }+ return host_reference_of(vm, value);+}++// Whether a reference type is of the func hierarchy, whose references are functions.+static bool is_function_reference_type(WasmValueType type)+{+ if (type.heap == HeapKind::Concrete)+ return WebAssemblyCache::the().store().is_function_type(type.type_index);+ return type.heap == HeapKind::Function || type.heap == HeapKind::NoFunction;+}+// https://webassembly.github.io/spec/js-api/#towebassemblyvaluestatic JS::ThrowCompletionOr<u64> to_webassembly_reference(JS::VM& vm, JS::Value value, WasmValueType type){+ auto& store = WebAssemblyCache::the().store();+ // If v is null: if the type is nullable, return ref.null of its heap type, and otherwise throw a TypeError.if (value.is_null()) {if (!type.nullable)return vm.throw_completion<JS::TypeError>("Cannot convert null to a non-nullable reference"_utf16);@@ -849,26 +1027,6 @@ static JS::ThrowCompletionOr<u64> to_webassembly_reference(JS::VM& vm, JS::Value}switch (type.heap) {- case HeapKind::Function: {- if (value.is_function()) {- if (auto address = exported_function_address(value.as_function()); address.has_value())- return WebAssemblyCache::the().store().function_reference(*address);- }- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Exported function");- }- case HeapKind::Extern:- return host_reference_of(vm, value);- case HeapKind::Any:- // FIXME: Unwrap WebAssembly GC objects once they can reach JavaScript.- if (auto reference = i31_reference_of(value); reference.has_value())- return *reference;- // NB: Converting an externref to anyref keeps its bits.- return host_reference_of(vm, value);- case HeapKind::Eq:- case HeapKind::I31:- if (auto reference = i31_reference_of(value); reference.has_value())- return *reference;- return vm.throw_completion<JS::TypeError>("Cannot convert the value to an i31 reference"_utf16);case HeapKind::Exception:case HeapKind::NoException:return vm.throw_completion<JS::TypeError>("Cannot convert a JavaScript value to an exception reference"_utf16);@@ -876,14 +1034,30 @@ static JS::ThrowCompletionOr<u64> to_webassembly_reference(JS::VM& vm, JS::Valuecase HeapKind::NoExtern:case HeapKind::None:return vm.throw_completion<JS::TypeError>("Only null converts to a bottom reference type"_utf16);- case HeapKind::Struct:- case HeapKind::Array:- case HeapKind::Concrete:- // FIXME: Implement the conversions for the wasm-gc reference hierarchy- // (https://webassembly.github.io/spec/js-api/#towebassemblyvalue).- return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);+ case HeapKind::Extern:+ // NB: An externref keeps the bits of the anyref it externalizes.+ return internalized_reference_of(vm, value);+ default:+ break;}- VERIFY_NOT_REACHED();++ // If the type is of the func hierarchy, only an Exported Function of a matching type converts, to its function.+ if (is_function_reference_type(type)) {+ if (value.is_function()) {+ if (auto address = exported_function_address(value.as_function()); address.has_value()) {+ auto reference = store.function_reference(*address);+ if (store.reference_matches(reference, type))+ return reference;+ }+ }+ return vm.throw_completion<JS::TypeError>("Cannot convert the value to a function reference of this type"_utf16);+ }++ // Otherwise the type is of the any hierarchy: the internal form of v converts if it matches the type.+ auto reference = internalized_reference_of(vm, value);+ if (!store.reference_matches(reference, type))+ return vm.throw_completion<JS::TypeError>("Cannot convert the value to a reference of this type"_utf16);+ return reference;}// https://webassembly.github.io/spec/js-api/#towebassemblyvalue@@ -943,24 +1117,27 @@ JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM& vm, WasmValue wasm_value, Wreturn vm.throw_completion<JS::TypeError>("Cannot convert an exception reference to a javascript value"_utf16);auto reference = wasm_value.reference_bits();++ // 1. If w is of the form ref.null t, return null.if (reference == 0)return JS::js_null();- if (type.heap == HeapKind::Function)+ // 2. If w is of the form ref.func funcaddr, return the result of creating a new Exported Function from funcaddr.+ if (is_function_reference_type(type))return create_native_function(*vm.current_realm(), WebAssemblyCache::the().store().function_from_reference(reference));- if (type.heap == HeapKind::Concrete) {- // FIXME: Convert references of concrete types, which needs the module the type belongs to.- return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);- }+ // 3. If w is of the form ref.i31 u31, return 𝔽(signed_31(u31)).if (reference & I31_REFERENCE_BIT)return JS::Value(value_of_i31_reference(reference));++ // 4. If w is of the form ref.host hostaddr, return the result of retrieving a host value from hostaddr.+ // NB: An externref of a host value keeps the bits of the host reference.if ((reference & REFERENCE_TAG_MASK) == HOST_REFERENCE_TAG)return value_of_host_reference(reference);- // FIXME: Implement the conversions for the wasm-gc reference hierarchy- // (https://webassembly.github.io/spec/js-api/#tojsvalue).- return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);+ // 5. If w is of the form ref.struct structaddr or ref.array arrayaddr, return the result of creating a new Exported+ // GC Object from it.+ return create_exported_gc_object(vm, reference);}// https://webassembly.github.io/spec/js-api/#error-objects@@ -982,8 +1159,10 @@ JS::Completion completion_of_failure(JS::VM& vm, Wasm::Runtime::Failure const& fauto payload = store.exception_values(failure.exception);return JS::throw_completion(MUST(to_js_value(vm, payload.first(), WasmValueType::reference(HeapKind::Extern))));}- // FIXME: Throw a WebAssembly.Exception once it exists.- return vm.throw_completion<RuntimeError>(Utf16String::formatted("Wasm execution trapped (WIP): {}", failure.message));+ // Otherwise, throw the Exception object of the exception.+ auto& realm = *vm.current_realm();+ auto exception = Exception::from_address(failure.exception);+ return JS::throw_completion(Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, exception));}case Wasm::Runtime::FailureKind::Trap:// FIXME: Use the convoluted mapping of errors defined in the spec.diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.hindex f61d7ae936d..0d6f3e9eb87 100644--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h@@ -28,6 +28,9 @@namespace Web::WebAssembly {+class Exception;+class Tag;+WEB_API void initialize(JS::Object&, JS::Realm&);WEB_API bool validate(JS::Realm&, WebIDL::BufferSource bytes);@@ -49,7 +52,8 @@ struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule>NonnullRefPtr<Wasm::Runtime::Module> module;};-// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, and Table object caches.+// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, Table, Tag, Exception, and+// Exported GC Object caches.// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. The// caches only map entities to their objects for as long as both live.class WebAssemblyCache {@@ -76,6 +80,13 @@ public:void set_memory_object(Entity memory, WebAssembly::Memory&);GC::Ptr<WebAssembly::Table> table_object(Entity table) const;void set_table_object(Entity table, WebAssembly::Table&);+ GC::Ptr<WebAssembly::Tag> tag_object(Entity tag) const;+ void set_tag_object(Entity tag, WebAssembly::Tag&);+ // Exceptions and GC objects are references, which are the addresses of their cells.+ GC::Ptr<WebAssembly::Exception> exception_object(u64 exception) const;+ void set_exception_object(u64 exception, WebAssembly::Exception&);+ GC::Ptr<JS::Object> gc_object(u64 object) const;+ void set_gc_object(u64 object, JS::Object&);void for_each_memory_object(Function<void(WebAssembly::Memory&)> const&) const;// The index of a host function: how many functions were imported before it.@@ -86,16 +97,17 @@ private:explicit WebAssemblyCache(GC::Heap&);~WebAssemblyCache();- // Objects by entity. An entry whose object is gone is stale: its entity may be gone too, and its address reused.- template<typename T>+ // Objects by entity, or by reference for exceptions and GC objects. An entry whose object is gone is stale: its+ // entity may be gone too, and its address reused.+ template<typename T, typename Key = Entity>class ObjectCache {public:- GC::Ptr<T> get(Entity) const;- void set(Entity, T&);+ GC::Ptr<T> get(Key) const;+ void set(Key, T&);void for_each(Function<void(T&)> const&) const;private:- HashMap<Entity, GC::Weak<T>> m_objects;+ HashMap<Key, GC::Weak<T>> m_objects;size_t m_live_after_pruning { 0 };};@@ -106,6 +118,9 @@ private:ObjectCache<WebAssembly::Global> m_global_objects;ObjectCache<WebAssembly::Memory> m_memory_objects;ObjectCache<WebAssembly::Table> m_table_objects;+ ObjectCache<WebAssembly::Tag> m_tag_objects;+ ObjectCache<WebAssembly::Exception, u64> m_exception_objects;+ ObjectCache<JS::Object, u64> m_gc_objects;// NB: An entry outlives its function, but every host function sets its own, so a live one's entry is right.HashMap<Entity, size_t> m_host_function_indices;};@@ -116,6 +131,11 @@ GC::Ref<JS::HostFunction> create_exported_function(JS::Realm&, Utf16FlyString na// The value of the function's [[FunctionAddress]] internal slot, if it has one and is therefore an Exported Function.Optional<Wasm::Runtime::Entity> exported_function_address(JS::FunctionObject const&);+// The value of the object's [[ObjectAddress]] internal slot, if it has one and is therefore an Exported GC Object.+Optional<u64> exported_gc_object_address(JS::Object const&);++// The function type at `type_index` of a module, in the store's terms (see Store::canonical_value_type()).+Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const&, u32 type_index);JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM&, Wasm::Runtime::Module const&, GC::Ptr<JS::Object> import_object);JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_core_module(JS::VM&, Wasm::Runtime::Module const&, ReadonlySpan<Wasm::Runtime::Extern> imports);Wasm::Runtime::Entity create_host_function(JS::VM&, JS::FunctionObject& function, Wasm::Runtime::FunctionType type, size_t function_index);diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cppindex ce372ad0189..eaf7a186449 100644--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp@@ -15,6 +15,7 @@#include <LibWeb/WebAssembly/Memory.h>#include <LibWeb/WebAssembly/Module.h>#include <LibWeb/WebAssembly/Table.h>+#include <LibWeb/WebAssembly/Tag.h>#include <LibWeb/WebAssembly/WebAssembly.h>#include <LibWeb/WebAssembly/WebAssemblyModule.h>@@ -331,9 +332,7 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModuelse {// 1. Create a host function from v and functype, and let funcaddr be the result.// 2. Let index be the number of external functions in imports, defining the index of the host function funcaddr.- auto functype = module.function_type(entry.type.type_index);- VERIFY(functype.has_value());- funcaddr = Detail::create_host_function(vm, function, functype.release_value(), imported_function_count);+ funcaddr = Detail::create_host_function(vm, function, Detail::function_type_in_store(module, entry.type.type_index), imported_function_count);}// 4. Let externfunc be the external value func funcaddr.@@ -344,7 +343,7 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu// 4. If importtype is of the form global mut valtype,case Wasm::Runtime::ExternKind::Global: {- auto valtype = entry.type.value_type;+ auto valtype = store.canonical_value_type(module, entry.type.value_type);auto is_mutable = entry.type.is_mutable;// 1. Let store be the surrounding agent’s associated store.@@ -429,9 +428,20 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModubreak;}- // FIXME: Import tags once WebAssembly.Tag exists.- case Wasm::Runtime::ExternKind::Tag:- return vm.throw_completion<LinkError>("Tag imports are not supported"sv);+ // 7. If importtype is of the form tag attribute functype,+ case Wasm::Runtime::ExternKind::Tag: {+ // 1. Assert: attribute is exception.+ // 2. If v does not implement Tag, throw a LinkError exception.+ auto* tag = Bindings::tag_from_value(v);+ if (!tag)+ return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Tag for a tag import"sv);++ // 3. Let tagaddr be v.[[Address]].+ // 4. Let externtag be the external value tag tagaddr.+ // 5. Append externtag to imports.+ imports.append({ Wasm::Runtime::ExternKind::Tag, tag->address() });+ break;+ }}}diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmakeindex b58ee528b68..bfe5c9e7867 100644--- a/Libraries/LibWeb/idl_files.cmake+++ b/Libraries/LibWeb/idl_files.cmake@@ -591,11 +591,13 @@ libweb_js_bindings(ViewTransition/ViewTransition)libweb_js_bindings(WebLocks/Lock)libweb_js_bindings(WebLocks/LockManager)libweb_js_bindings(WebLocks/NavigatorLocks)+libweb_js_bindings(WebAssembly/Exception)libweb_js_bindings(WebAssembly/Global)libweb_js_bindings(WebAssembly/Instance)libweb_js_bindings(WebAssembly/Memory)libweb_js_bindings(WebAssembly/Module)libweb_js_bindings(WebAssembly/Table)+libweb_js_bindings(WebAssembly/Tag)libweb_js_bindings(WebAssembly/WebAssembly)libweb_js_bindings(WebAudio/AnalyserNode)libweb_js_bindings(WebAudio/AudioParamMap)diff --git a/Meta/CMake/wasm_spec_tests.cmake b/Meta/CMake/wasm_spec_tests.cmakeindex 7b688c9c157..6e9099f92dc 100644--- a/Meta/CMake/wasm_spec_tests.cmake+++ b/Meta/CMake/wasm_spec_tests.cmake@@ -26,8 +26,14 @@ if(INCLUDE_WASM_SPEC_TESTS)extract_path("${CMAKE_CURRENT_BINARY_DIR}" "${WASM_SPEC_TEST_GZ_PATH}" "testsuite-${WASM_SPEC_TEST_COMMIT}/*.wast" "${WASM_SPEC_TEST_PATH}")file(MAKE_DIRECTORY ${WASM_SPEC_TEST_PATH})file(GLOB WASM_TESTS "${CMAKE_CURRENT_BINARY_DIR}/testsuite-${WASM_SPEC_TEST_COMMIT}/*.wast")- foreach(PATH ${WASM_TESTS})+ # The tests of the legacy exception handling instructions are in a directory of their own, and share names with+ # the current ones.+ file(GLOB WASM_LEGACY_TESTS "${CMAKE_CURRENT_BINARY_DIR}/testsuite-${WASM_SPEC_TEST_COMMIT}/legacy/*.wast")+ foreach(PATH ${WASM_TESTS} ${WASM_LEGACY_TESTS})get_filename_component(NAME ${PATH} NAME_WLE)+ if (PATH IN_LIST WASM_LEGACY_TESTS)+ set(NAME "legacy_${NAME}")+ endif()message(STATUS "Generating test cases for WebAssembly test ${NAME}...")execute_process(COMMAND env SKIP_PRETTIER=${SKIP_PRETTIER} bash ${LADYBIRD_SOURCE_DIR}/Meta/Generators/generate_libwasm_spec_test.sh "${PATH}" "${CMAKE_CURRENT_BINARY_DIR}/Tests/Spec" "${NAME}" "${WASM_SPEC_TEST_PATH}")diff --git a/Meta/Generators/generate_libwasm_spec_test.py b/Meta/Generators/generate_libwasm_spec_test.pyindex 660ee811a78..6529db5f933 100644--- a/Meta/Generators/generate_libwasm_spec_test.py+++ b/Meta/Generators/generate_libwasm_spec_test.py@@ -296,19 +296,171 @@ def escape(s: str) -> str:return s.replace('"', '\\"')+# The legacy exception handling tests write `try` in a folded form, (try bt (do ...) (catch x ...) (delegate l)), that+# wasm-tools does not parse. It does parse the flat form, try bt ... catch x ... end, which is what these turn it into.+# The folded `try`s of the tests are all instructions of their own, never operands, where the flat form is allowed.+# Every token keeps its line, so that the tests keep the line numbers they are named by.+@dataclass+class WastToken:+ text: str+ line: int+++@dataclass+class WastList:+ items: list+ open_line: int+ close_line: int+++def tokenize_wast(text: str) -> list[WastToken]:+ tokens = []+ position = 0+ line = 1+ while position < len(text):+ character = text[position]+ if character == "\n":+ line += 1+ position += 1+ elif character.isspace():+ position += 1+ elif text.startswith(";;", position):+ end = text.find("\n", position)+ position = len(text) if end == -1 else end+ elif text.startswith("(;", position):+ depth = 0+ while position < len(text):+ if text.startswith("(;", position):+ depth += 1+ position += 2+ elif text.startswith(";)", position):+ depth -= 1+ position += 2+ if depth == 0:+ break+ else:+ line += text[position] == "\n"+ position += 1+ elif character in "()":+ tokens.append(WastToken(character, line))+ position += 1+ elif character == '"':+ end = position + 1+ while text[end] != '"':+ end += 2 if text[end] == "\\" else 1+ tokens.append(WastToken(text[position : end + 1], line))+ line += text.count("\n", position, end + 1)+ position = end + 1+ else:+ end = position+ while end < len(text) and not text[end].isspace() and text[end] not in '()";':+ end += 1+ tokens.append(WastToken(text[position:end], line))+ position = end+ return tokens+++def parse_wast_tokens(tokens: list[WastToken], position: int = 0) -> tuple[list, int]:+ items: list = []+ while position < len(tokens):+ token = tokens[position]+ if token.text == "(":+ child, position = parse_wast_tokens(tokens, position + 1)+ close_line = tokens[position - 1].line if position - 1 < len(tokens) else token.line+ items.append(WastList(child, token.line, close_line))+ elif token.text == ")":+ return items, position + 1+ else:+ items.append(token)+ position += 1+ return items, position+++def head_of(item) -> Optional[str]:+ if isinstance(item, WastList) and item.items and isinstance(item.items[0], WastToken):+ return item.items[0].text+ return None+++def is_folded_try(item) -> bool:+ return head_of(item) == "try" and any(head_of(child) == "do" for child in item.items)+++def unfold_legacy_try(items: list) -> list:+ unfolded: list = []+ for item in items:+ if isinstance(item, WastToken):+ unfolded.append(item)+ continue+ if not is_folded_try(item):+ unfolded.append(WastList(unfold_legacy_try(item.items), item.open_line, item.close_line))+ continue+ ends_with_delegate = False+ for child in item.items:+ head = head_of(child)+ if head not in ("do", "catch", "catch_all", "delegate"):+ unfolded.extend(unfold_legacy_try([child]))+ elif head == "do":+ unfolded.extend(unfold_legacy_try(child.items[1:]))+ elif head == "catch":+ unfolded.extend(child.items[:2])+ unfolded.extend(unfold_legacy_try(child.items[2:]))+ elif head == "catch_all":+ unfolded.append(child.items[0])+ unfolded.extend(unfold_legacy_try(child.items[1:]))+ else:+ unfolded.extend(child.items)+ ends_with_delegate = True+ if not ends_with_delegate:+ unfolded.append(WastToken("end", item.close_line))+ return unfolded+++def serialize_wast(items: list) -> str:+ output: list[str] = []+ line = 1++ def emit(text: str, at_line: int):+ nonlocal line+ if at_line > line:+ output.append("\n" * (at_line - line))+ line = at_line+ output.append(text + " ")++ def walk(items: list):+ for item in items:+ if isinstance(item, WastToken):+ emit(item.text, item.line)+ else:+ emit("(", item.open_line)+ walk(item.items)+ emit(")", item.close_line)++ walk(items)+ return "".join(output)++def make_description(input_path: Path, name: str, out_path: Path) -> WastDescription:out_json_path = out_path / f"{name}.json"+ text = input_path.read_text()+ unfolded_path = None+ if "(do" in text:+ items, _ = parse_wast_tokens(tokenize_wast(text))+ unfolded_path = out_path / f"{name}.wast"+ unfolded_path.write_text(serialize_wast(unfold_legacy_try(items)))result = subprocess.run(["wasm-tools","json-from-wast",- input_path,+ unfolded_path or input_path,"-o",out_json_path,"--wasm-dir",str(out_path),],)+ if unfolded_path:+ unfolded_path.unlink()result.check_returncode()with open(out_json_path, "r") as f:description = json.load(f)diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 1a5a17942a3..9a079811747 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -75,8 +75,8 @@ ALLOWED_REALM_MENTIONS = {),"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),"WebAssembly": (- 12,- 83,+ 14,+ 85,"WebAssembly constructors/exports instantiate JS objects/functions in spec-selected realms",),"WebAudio": (diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txtnew file mode 100644index 00000000000..c7195369247--- /dev/null+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-JSTag.txt@@ -0,0 +1,4 @@+accessor: function, setter: undefined, enumerable: true, configurable: true+a Tag: true, the same object: true+constructing an Exception with it: TypeError+WebAssembly catches JavaScript exceptions by it: truediff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-tags-exceptions-and-gc-objects.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-tags-exceptions-and-gc-objects.txtnew file mode 100644index 00000000000..0fef5e3491a--- /dev/null+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-tags-exceptions-and-gc-objects.txt@@ -0,0 +1,10 @@+exported tags are Tags: true, imported tag is the same object: true+thrown by WebAssembly: true, is own: true, is imported: false+arguments: 1, 2, stack: undefined+an Exception thrown through WebAssembly is itself: true+caught by its tag in WebAssembly: 5+a JavaScript exception thrown through WebAssembly is itself: true+not caught by the imported tag: true+traceStack gives a stack: string+struct: 7, same object again: true, prototype: null+anyref of numbers and strings: 42, 2147483648, textdiff --git a/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt b/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txtindex 5ee62b563fc..987fe8116d2 100644--- a/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt+++ b/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt@@ -375,6 +375,14 @@ RuntimeError configurable: trueRuntimeError enumerable: falseRuntimeError value before: function RuntimeError() { [native code] }RuntimeError value after: replaced+JSTag writable: undefined+JSTag configurable: true+JSTag enumerable: true+Exception writable: true+Exception configurable: true+Exception enumerable: false+Exception value before: function Exception() { [native code] }+Exception value after: replacedGlobal writable: trueGlobal configurable: trueGlobal enumerable: false@@ -400,3 +408,8 @@ Table configurable: trueTable enumerable: falseTable value before: function Table() { [native code] }Table value after: replaced+Tag writable: true+Tag configurable: true+Tag enumerable: false+Tag value before: function Tag() { [native code] }+Tag value after: replaceddiff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/basic.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/basic.tentative.any.txtnew file mode 100644index 00000000000..89bbf97e542--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/basic.tentative.any.txt@@ -0,0 +1,10 @@+Harness status: OK++Found 5 tests++5 Pass+Pass Wasm function throws argument+Pass Wasm function throws null+Pass Wasm function throws integer+Pass Imported JS function throws+Pass Imported JS function throws, Wasm catches and rethrows\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/constructor.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/constructor.tentative.any.txtnew file mode 100644index 00000000000..01a138813f6--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/constructor.tentative.any.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 6 tests++6 Pass+Pass name+Pass length+Pass No arguments+Pass Calling+Pass Invalid descriptor argument+Pass Invalid exception argument\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/getArg.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/getArg.tentative.any.txtnew file mode 100644index 00000000000..9e4d80fc5a7--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/getArg.tentative.any.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 5 tests++4 Pass+1 Fail+Pass Missing arguments+Pass Invalid exception argument+Pass Index out of bounds+Fail Getting out-of-range argument+Pass getArg\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/identity.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/identity.tentative.any.txtnew file mode 100644index 00000000000..8c370104656--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/identity.tentative.any.txt@@ -0,0 +1,6 @@+Harness status: OK++Found 1 tests++1 Pass+Pass Identity check\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/is.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/is.tentative.any.txtnew file mode 100644index 00000000000..90a5f3d176e--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/is.tentative.any.txt@@ -0,0 +1,8 @@+Harness status: OK++Found 3 tests++3 Pass+Pass Missing arguments+Pass Invalid exception argument+Pass is\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/toString.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/toString.tentative.any.txtnew file mode 100644index 00000000000..e1c2e4ced0b--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/exception/toString.tentative.any.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass Object.prototype.toString on an Exception+Pass @@toStringTag exists on the prototype with the appropriate descriptor\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/casts.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/casts.tentative.any.txtnew file mode 100644index 00000000000..e69b10e55cd--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/casts.tentative.any.txt@@ -0,0 +1,16 @@+Harness status: OK++Found 11 tests++11 Pass+Pass anyref casts+Pass eqref casts+Pass structref casts+Pass arrayref casts+Pass i31ref casts+Pass funcref casts+Pass externref casts+Pass null casts+Pass concrete struct casts+Pass concrete array casts+Pass concrete func casts\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.txtnew file mode 100644index 00000000000..c711765aa4c--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.txt@@ -0,0 +1,24 @@+Harness status: OK++Found 19 tests++19 Pass+Pass property access+Pass property assignment (strict mode)+Pass property assignment (non-strict mode)+Pass ownPropertyNames+Pass defineProperty+Pass delete (strict mode)+Pass delete (non-strict mode)+Pass getPrototypeOf+Pass setPrototypeOf+Pass isExtensible+Pass preventExtensions+Pass sealing+Pass typeof+Pass toString+Pass valueOf+Pass GC objects as map keys+Pass GC objects as set element+Pass GC objects as weak map keys+Pass GC objects as weak set element\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/i31.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/i31.tentative.any.txtnew file mode 100644index 00000000000..329296ccf00--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/gc/i31.tentative.any.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 6 tests++6 Pass+Pass i31ref conversion to Number+Pass Number conversion to i31ref+Pass Check i31ref argument type+Pass Numbers in i31 range are i31ref, not hostref+Pass i31ref global+Pass i31ref table\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/constructor.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/constructor.tentative.any.txtnew file mode 100644index 00000000000..a10ad6be59c--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/constructor.tentative.any.txt@@ -0,0 +1,11 @@+Harness status: OK++Found 6 tests++6 Pass+Pass name+Pass length+Pass No arguments+Pass Calling+Pass Invalid descriptor argument+Pass Invalid type parameter\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/toString.tentative.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/toString.tentative.any.txtnew file mode 100644index 00000000000..3820e4bd7b9--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/tag/toString.tentative.any.txt@@ -0,0 +1,7 @@+Harness status: OK++Found 2 tests++2 Pass+Pass Object.prototype.toString on a Tag+Pass @@toStringTag exists on the prototype with the appropriate descriptor\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.htmlnew file mode 100644index 00000000000..106b7ecbe64--- /dev/null+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-JSTag.html@@ -0,0 +1,39 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // (module+ // (import "m" "js" (tag $js (param externref)))+ // (import "m" "throws" (func $throws))+ // (func (export "catchJS") (result externref)+ // (block $handler (result externref)+ // (try_table (catch $js $handler) (call $throws))+ // (ref.null extern))))+ const bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x03, 0x60, 0x01, 0x6f, 0x00, 0x60,+ 0x00, 0x00, 0x60, 0x00, 0x01, 0x6f, 0x02, 0x14, 0x02, 0x01, 0x6d, 0x02, 0x6a, 0x73, 0x04, 0x00,+ 0x00, 0x01, 0x6d, 0x06, 0x74, 0x68, 0x72, 0x6f, 0x77, 0x73, 0x00, 0x01, 0x03, 0x02, 0x01, 0x02,+ 0x07, 0x0b, 0x01, 0x07, 0x63, 0x61, 0x74, 0x63, 0x68, 0x4a, 0x53, 0x00, 0x01, 0x0a, 0x12, 0x01,+ 0x10, 0x00, 0x02, 0x6f, 0x1f, 0x40, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0b, 0xd0, 0x6f, 0x0b,+ 0x0b, 0x00, 0x25, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x01, 0x09, 0x01, 0x00, 0x06, 0x74, 0x68, 0x72,+ 0x6f, 0x77, 0x73, 0x03, 0x0c, 0x01, 0x01, 0x01, 0x00, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65,+ 0x72, 0x0b, 0x05, 0x01, 0x00, 0x02, 0x6a, 0x73,+ ]);++ test(() => {+ const descriptor = Object.getOwnPropertyDescriptor(WebAssembly, "JSTag");+ println(`accessor: ${typeof descriptor.get}, setter: ${descriptor.set}, enumerable: ${descriptor.enumerable}, configurable: ${descriptor.configurable}`);+ println(`a Tag: ${WebAssembly.JSTag instanceof WebAssembly.Tag}, the same object: ${WebAssembly.JSTag === WebAssembly.JSTag}`);++ try {+ new WebAssembly.Exception(WebAssembly.JSTag, ["value"]);+ } catch (exception) {+ println(`constructing an Exception with it: ${exception.constructor.name}`);+ }++ const thrown = { message: "thrown by JavaScript" };+ const exports = new WebAssembly.Instance(new WebAssembly.Module(bytes), {+ m: { js: WebAssembly.JSTag, throws: () => { throw thrown; } },+ }).exports;+ println(`WebAssembly catches JavaScript exceptions by it: ${exports.catchJS() === thrown}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-tags-exceptions-and-gc-objects.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-tags-exceptions-and-gc-objects.htmlnew file mode 100644index 00000000000..cdddad1d0cc--- /dev/null+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-tags-exceptions-and-gc-objects.html@@ -0,0 +1,80 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ // (module+ // (type $point (struct (field i32)))+ // (import "m" "tag" (tag $imported (param i32)))+ // (import "m" "throws" (func $throws))+ // (tag $own (export "own") (param i32 i64))+ // (export "imported" (tag $imported))+ // (func (export "throwOwn") (param i32 i64) (throw $own (local.get 0) (local.get 1)))+ // (func (export "callThrows") (call $throws))+ // (func (export "catchImported") (result i32)+ // (block $handler (result i32)+ // (try_table (catch $imported $handler) (call $throws))+ // (i32.const -1)))+ // (func (export "makePoint") (param i32) (result (ref $point)) (struct.new $point (local.get 0)))+ // (func (export "pointX") (param (ref $point)) (result i32) (struct.get $point 0 (local.get 0)))+ // (func (export "identity") (param anyref) (result anyref) (local.get 0)))+ const bytes = new Uint8Array([+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x26, 0x08, 0x5f, 0x01, 0x7f, 0x00, 0x60,+ 0x01, 0x7f, 0x00, 0x60, 0x00, 0x00, 0x60, 0x02, 0x7f, 0x7e, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x60,+ 0x01, 0x7f, 0x01, 0x64, 0x00, 0x60, 0x01, 0x64, 0x00, 0x01, 0x7f, 0x60, 0x01, 0x6e, 0x01, 0x6e,+ 0x02, 0x15, 0x02, 0x01, 0x6d, 0x03, 0x74, 0x61, 0x67, 0x04, 0x00, 0x01, 0x01, 0x6d, 0x06, 0x74,+ 0x68, 0x72, 0x6f, 0x77, 0x73, 0x00, 0x02, 0x03, 0x07, 0x06, 0x03, 0x02, 0x04, 0x05, 0x06, 0x07,+ 0x0d, 0x03, 0x01, 0x00, 0x03, 0x07, 0x5a, 0x08, 0x03, 0x6f, 0x77, 0x6e, 0x04, 0x01, 0x08, 0x69,+ 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x04, 0x00, 0x08, 0x74, 0x68, 0x72, 0x6f, 0x77, 0x4f,+ 0x77, 0x6e, 0x00, 0x01, 0x0a, 0x63, 0x61, 0x6c, 0x6c, 0x54, 0x68, 0x72, 0x6f, 0x77, 0x73, 0x00,+ 0x02, 0x0d, 0x63, 0x61, 0x74, 0x63, 0x68, 0x49, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x00,+ 0x03, 0x09, 0x6d, 0x61, 0x6b, 0x65, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x00, 0x04, 0x06, 0x70, 0x6f,+ 0x69, 0x6e, 0x74, 0x58, 0x00, 0x05, 0x08, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x00,+ 0x06, 0x0a, 0x36, 0x06, 0x08, 0x00, 0x20, 0x00, 0x20, 0x01, 0x08, 0x01, 0x0b, 0x04, 0x00, 0x10,+ 0x00, 0x0b, 0x10, 0x00, 0x02, 0x7f, 0x1f, 0x40, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0b, 0x41,+ 0x7f, 0x0b, 0x0b, 0x07, 0x00, 0x20, 0x00, 0xfb, 0x00, 0x00, 0x0b, 0x08, 0x00, 0x20, 0x00, 0xfb,+ 0x02, 0x00, 0x00, 0x0b, 0x04, 0x00, 0x20, 0x00, 0x0b, 0x00, 0x3a, 0x04, 0x6e, 0x61, 0x6d, 0x65,+ 0x01, 0x09, 0x01, 0x00, 0x06, 0x74, 0x68, 0x72, 0x6f, 0x77, 0x73, 0x03, 0x0c, 0x01, 0x03, 0x01,+ 0x00, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x04, 0x08, 0x01, 0x00, 0x05, 0x70, 0x6f,+ 0x69, 0x6e, 0x74, 0x0b, 0x10, 0x02, 0x00, 0x08, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64,+ 0x01, 0x03, 0x6f, 0x77, 0x6e,+ ]);++ test(() => {+ const tag = new WebAssembly.Tag({ parameters: ["i32"] });+ let thrown = null;+ const exports = new WebAssembly.Instance(new WebAssembly.Module(bytes), {+ m: { tag, throws: () => { throw thrown; } },+ }).exports;++ println(`exported tags are Tags: ${exports.own instanceof WebAssembly.Tag}, imported tag is the same object: ${exports.imported === tag}`);++ try {+ exports.throwOwn(1, 2n);+ } catch (exception) {+ println(`thrown by WebAssembly: ${exception instanceof WebAssembly.Exception}, is own: ${exception.is(exports.own)}, is imported: ${exception.is(tag)}`);+ println(`arguments: ${exception.getArg(exports.own, 0)}, ${exception.getArg(exports.own, 1)}, stack: ${exception.stack}`);+ }++ thrown = new WebAssembly.Exception(tag, [5]);+ try {+ exports.callThrows();+ } catch (exception) {+ println(`an Exception thrown through WebAssembly is itself: ${exception === thrown}`);+ }+ println(`caught by its tag in WebAssembly: ${exports.catchImported()}`);++ thrown = new Error("from JavaScript");+ try {+ exports.callThrows();+ } catch (exception) {+ println(`a JavaScript exception thrown through WebAssembly is itself: ${exception === thrown}`);+ }+ println(`not caught by the imported tag: ${(() => { try { exports.catchImported(); } catch (exception) { return exception === thrown; } })()}`);++ const traced = new WebAssembly.Exception(tag, [1], { traceStack: true });+ println(`traceStack gives a stack: ${typeof traced.stack}`);++ const point = exports.makePoint(7);+ println(`struct: ${exports.pointX(point)}, same object again: ${exports.identity(point) === point}, prototype: ${Object.getPrototypeOf(point)}`);+ println(`anyref of numbers and strings: ${exports.identity(42)}, ${exports.identity(2 ** 31)}, ${exports.identity("text")}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.htmlnew file mode 100644index 00000000000..236fda0fc68--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/wasm-module-builder.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/exception/basic.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.jsnew file mode 100644index 00000000000..8a8f7d0735c--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/basic.tentative.any.js@@ -0,0 +1,125 @@+// META: global=window,worker,jsshell+// META: script=/wasm/jsapi/wasm-module-builder.js++function assert_throws_wasm(fn, message) {+ try {+ fn();+ assert_unreached(`expected to throw with ${message}`);+ } catch (e) {+ assert_true(e instanceof WebAssembly.Exception, `Error should be a WebAssembly.Exception with ${message}`);+ // According to the spec discussion, the current `WebAssembly.Exception` does not have `[[ErrorData]]` semantically.+ // - https://github.com/WebAssembly/spec/issues/1914+ // - https://webassembly.github.io/spec/js-api/#exceptions+ // - https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-properties-of-error-instances+ assert_false(Error.isError(e), `Error.isError(WebAssembly.Exception) should be false due to lacking [[ErrorData]]`);+ }+}++promise_test(async () => {+ const kSig_v_r = makeSig([kWasmExternRef], []);+ const builder = new WasmModuleBuilder();+ const tagIndex = builder.addTag(kSig_v_r);+ builder.addFunction("throw_param", kSig_v_r)+ .addBody([+ kExprLocalGet, 0,+ kExprThrow, tagIndex,+ ])+ .exportFunc();+ const buffer = builder.toBuffer();+ const {instance} = await WebAssembly.instantiate(buffer, {});+ const values = [+ undefined,+ null,+ true,+ false,+ "test",+ Symbol(),+ 0,+ 1,+ 4.2,+ NaN,+ Infinity,+ {},+ () => {},+ ];+ for (const v of values) {+ assert_throws_wasm(() => instance.exports.throw_param(v), String(v));+ }+}, "Wasm function throws argument");++promise_test(async () => {+ const builder = new WasmModuleBuilder();+ const tagIndex = builder.addTag(kSig_v_a);+ builder.addFunction("throw_null", kSig_v_v)+ .addBody([+ kExprRefNull, kAnyFuncCode,+ kExprThrow, tagIndex,+ ])+ .exportFunc();+ const buffer = builder.toBuffer();+ const {instance} = await WebAssembly.instantiate(buffer, {});+ assert_throws_wasm(() => instance.exports.throw_null());+}, "Wasm function throws null");++promise_test(async () => {+ const builder = new WasmModuleBuilder();+ const tagIndex = builder.addTag(kSig_v_i);+ builder.addFunction("throw_int", kSig_v_v)+ .addBody([+ ...wasmI32Const(7),+ kExprThrow, tagIndex,+ ])+ .exportFunc();+ const buffer = builder.toBuffer();+ const {instance} = await WebAssembly.instantiate(buffer, {});+ assert_throws_wasm(() => instance.exports.throw_int());+}, "Wasm function throws integer");++promise_test(async () => {+ const builder = new WasmModuleBuilder();+ const fnIndex = builder.addImport("module", "fn", kSig_v_v);+ const tagIndex= builder.addTag(kSig_v_r);+ builder.addFunction("catch_exception", kSig_r_v)+ .addBody([+ kExprTry, kWasmStmt,+ kExprCallFunction, fnIndex,+ kExprCatch, tagIndex,+ kExprReturn,+ kExprEnd,+ kExprRefNull, kExternRefCode,+ ])+ .exportFunc();++ const buffer = builder.toBuffer();++ const error = new Error();+ const fn = () => { throw error };+ const {instance} = await WebAssembly.instantiate(buffer, {+ module: { fn }+ });+ assert_throws_exactly(error, () => instance.exports.catch_exception());+}, "Imported JS function throws");++promise_test(async () => {+ const builder = new WasmModuleBuilder();+ const fnIndex = builder.addImport("module", "fn", kSig_v_v);+ builder.addFunction("catch_and_rethrow", kSig_r_v)+ .addBody([+ kExprTry, kWasmStmt,+ kExprCallFunction, fnIndex,+ kExprCatchAll,+ kExprRethrow, 0x00,+ kExprEnd,+ kExprRefNull, kExternRefCode,+ ])+ .exportFunc();++ const buffer = builder.toBuffer();++ const error = new Error();+ const fn = () => { throw error };+ const {instance} = await WebAssembly.instantiate(buffer, {+ module: { fn }+ });+ assert_throws_exactly(error, () => instance.exports.catch_and_rethrow());+}, "Imported JS function throws, Wasm catches and rethrows");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.htmlnew file mode 100644index 00000000000..22f78bc81e2--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/assertions.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/exception/constructor.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.jsnew file mode 100644index 00000000000..17057a22873--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/constructor.tentative.any.js@@ -0,0 +1,62 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/assertions.js++test(() => {+ assert_function_name(+ WebAssembly.Exception,+ "Exception",+ "WebAssembly.Exception"+ );+}, "name");++test(() => {+ assert_function_length(WebAssembly.Exception, 2, "WebAssembly.Exception");+}, "length");++test(() => {+ assert_throws_js(TypeError, () => new WebAssembly.Exception());+}, "No arguments");++test(() => {+ const tag = new WebAssembly.Tag({ parameters: [] });+ assert_throws_js(TypeError, () => WebAssembly.Exception(tag));+}, "Calling");++test(() => {+ const invalidArguments = [+ undefined,+ null,+ false,+ true,+ "",+ "test",+ Symbol(),+ 1,+ NaN,+ {},+ ];+ for (const invalidArgument of invalidArguments) {+ assert_throws_js(+ TypeError,+ () => new WebAssembly.Exception(invalidArgument),+ `new Exception(${format_value(invalidArgument)})`+ );+ }+}, "Invalid descriptor argument");++test(() => {+ const typesAndArgs = [+ ["i32", 123n],+ ["i32", Symbol()],+ ["f32", 123n],+ ["f64", 123n],+ ["i64", undefined],+ ];+ for (const typeAndArg of typesAndArgs) {+ const tag = new WebAssembly.Tag({ parameters: [typeAndArg[0]] });+ assert_throws_js(+ TypeError,+ () => new WebAssembly.Exception(tag, typeAndArg[1])+ );+ }+}, "Invalid exception argument");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.htmlnew file mode 100644index 00000000000..5e6e17dfb53--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/memory/assertions.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/exception/getArg.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.jsnew file mode 100644index 00000000000..f0a568a857f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/getArg.tentative.any.js@@ -0,0 +1,54 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/memory/assertions.js++test(() => {+ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ assert_throws_js(TypeError, () => exn.getArg());+ assert_throws_js(TypeError, () => exn.getArg(tag));+}, "Missing arguments");++test(() => {+ const invalidValues = [undefined, null, true, "", Symbol(), 1, {}];+ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ for (argument of invalidValues) {+ assert_throws_js(TypeError, () => exn.getArg(argument, 0));+ }+}, "Invalid exception argument");++test(() => {+ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ assert_throws_js(RangeError, () => exn.getArg(tag, 1));+}, "Index out of bounds");++test(() => {+ const outOfRangeValues = [+ undefined,+ NaN,+ Infinity,+ -Infinity,+ -1,+ 0x100000000,+ 0x1000000000,+ "0x100000000",+ {+ valueOf() {+ return 0x100000000;+ },+ },+ ];++ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ for (const value of outOfRangeValues) {+ assert_throws_js(RangeError, () => exn.getArg(tag, value));+ }+}, "Getting out-of-range argument");++test(() => {+ const tag = new WebAssembly.Tag({ parameters: ["i32"] });+ const exn = new WebAssembly.Exception(tag, [42]);+ assert_equals(exn.getArg(tag, 0), 42);+}, "getArg");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.htmlnew file mode 100644index 00000000000..dc02b36d3b1--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.html@@ -0,0 +1,16 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/assertions.js"></script>+<script src="../../../wasm/jsapi/wasm-module-builder.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/exception/identity.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.jsnew file mode 100644index 00000000000..65787c107e3--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/identity.tentative.any.js@@ -0,0 +1,61 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/assertions.js+// META: script=/wasm/jsapi/wasm-module-builder.js++test(() => {+ const tag = new WebAssembly.Tag({ parameters: ["i32"] });+ const exn = new WebAssembly.Exception(tag, [42]);+ const exn_same_payload = new WebAssembly.Exception(tag, [42]);+ const exn_diff_payload = new WebAssembly.Exception(tag, [53]);++ const builder = new WasmModuleBuilder();+ const jsfuncIndex = builder.addImport("module", "jsfunc", kSig_v_v);+ const tagIndex = builder.addImportedTag("module", "tag", kSig_v_i);+ const imports = {+ module: {+ jsfunc: function() { throw exn; },+ tag: tag+ }+ };++ builder+ .addFunction("catch_rethrow", kSig_v_v)+ .addBody([+ kExprTry, kWasmStmt,+ kExprCallFunction, jsfuncIndex,+ kExprCatch, tagIndex,+ kExprDrop,+ kExprRethrow, 0x00,+ kExprEnd+ ])+ .exportFunc();++ builder+ .addFunction("catch_all_rethrow", kSig_v_v)+ .addBody([+ kExprTry, kWasmStmt,+ kExprCallFunction, jsfuncIndex,+ kExprCatchAll,+ kExprRethrow, 0x00,+ kExprEnd+ ])+ .exportFunc();++ const buffer = builder.toBuffer();+ WebAssembly.instantiate(buffer, imports).then(result => {+ try {+ result.instance.exports.catch_rethrow();+ } catch (e) {+ assert_equals(e, exn);+ assert_not_equals(e, exn_same_payload);+ assert_not_equals(e, exn_diff_payload);+ }+ try {+ result.instance.exports.catch_all_rethrow();+ } catch (e) {+ assert_equals(e, exn);+ assert_not_equals(e, exn_same_payload);+ assert_not_equals(e, exn_diff_payload);+ }+ });+}, "Identity check");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.htmlnew file mode 100644index 00000000000..36ac73ea766--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/memory/assertions.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/exception/is.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.jsnew file mode 100644index 00000000000..e28a88a3c5f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/is.tentative.any.js@@ -0,0 +1,25 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/memory/assertions.js++test(() => {+ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ assert_throws_js(TypeError, () => exn.is());+}, "Missing arguments");++test(() => {+ const invalidValues = [undefined, null, true, "", Symbol(), 1, {}];+ const tag = new WebAssembly.Tag({ parameters: [] });+ const exn = new WebAssembly.Exception(tag, []);+ for (argument of invalidValues) {+ assert_throws_js(TypeError, () => exn.is(argument));+ }+}, "Invalid exception argument");++test(() => {+ const tag1 = new WebAssembly.Tag({ parameters: ["i32"] });+ const tag2 = new WebAssembly.Tag({ parameters: ["i32"] });+ const exn = new WebAssembly.Exception(tag1, [42]);+ assert_true(exn.is(tag1));+ assert_false(exn.is(tag2));+}, "is");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.htmlnew file mode 100644index 00000000000..4a8829fd594--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>++<div id=log></div>+<script src="../../../wasm/jsapi/exception/toString.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.jsnew file mode 100644index 00000000000..00e801a6fc1--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/exception/toString.tentative.any.js@@ -0,0 +1,21 @@+// META: global=window,dedicatedworker,jsshell++test(() => {+ const argument = { parameters: [] };+ const tag = new WebAssembly.Tag(argument);+ const exn = new WebAssembly.Exception(tag, []);+ assert_class_string(exn, "WebAssembly.Exception");+}, "Object.prototype.toString on an Exception");++test(() => {+ assert_own_property(WebAssembly.Exception.prototype, Symbol.toStringTag);++ const propDesc = Object.getOwnPropertyDescriptor(+ WebAssembly.Exception.prototype,+ Symbol.toStringTag+ );+ assert_equals(propDesc.value, "WebAssembly.Exception", "value");+ assert_equals(propDesc.configurable, true, "configurable");+ assert_equals(propDesc.enumerable, false, "enumerable");+ assert_equals(propDesc.writable, false, "writable");+}, "@@toStringTag exists on the prototype with the appropriate descriptor");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.htmlnew file mode 100644index 00000000000..36b72ba857f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/wasm-module-builder.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/gc/casts.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.jsnew file mode 100644index 00000000000..cce06224fd4--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/casts.tentative.any.js@@ -0,0 +1,332 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/wasm-module-builder.js++let exports = {};+setup(() => {+ const builder = new WasmModuleBuilder();+ const structIndex = builder.addStruct([makeField(kWasmI32, true)]);+ const arrayIndex = builder.addArray(kWasmI32, true);+ const structIndex2 = builder.addStruct([makeField(kWasmF32, true)]);+ const arrayIndex2 = builder.addArray(kWasmF32, true);+ const funcIndex = builder.addType({ params: [], results: [] });+ const funcIndex2 = builder.addType({ params: [], results: [kWasmI32] });++ const argFunctions = [+ { name: "any", code: kWasmAnyRef },+ { name: "eq", code: kWasmEqRef },+ { name: "struct", code: kWasmStructRef },+ { name: "array", code: kWasmArrayRef },+ { name: "i31", code: kWasmI31Ref },+ { name: "func", code: kWasmFuncRef },+ { name: "extern", code: kWasmExternRef },+ { name: "none", code: kWasmNullRef },+ { name: "nofunc", code: kWasmNullFuncRef },+ { name: "noextern", code: kWasmNullExternRef },+ { name: "concreteStruct", code: structIndex },+ { name: "concreteArray", code: arrayIndex },+ { name: "concreteFunc", code: funcIndex },+ ];++ for (const desc of argFunctions) {+ builder+ .addFunction(desc.name + "Arg", makeSig_v_x(wasmRefType(desc.code)))+ .addBody([])+ .exportFunc();++ builder+ .addFunction(desc.name + "NullableArg", makeSig_v_x(wasmRefNullType(desc.code)))+ .addBody([])+ .exportFunc();+ }++ builder+ .addFunction("makeStruct", makeSig_r_v(wasmRefType(structIndex)))+ .addBody([...wasmI32Const(42),+ ...GCInstr(kExprStructNew), structIndex])+ .exportFunc();++ builder+ .addFunction("makeArray", makeSig_r_v(wasmRefType(arrayIndex)))+ .addBody([...wasmI32Const(5), ...wasmI32Const(42),+ ...GCInstr(kExprArrayNew), arrayIndex])+ .exportFunc();++ builder+ .addFunction("makeStruct2", makeSig_r_v(wasmRefType(structIndex2)))+ .addBody([...wasmF32Const(42),+ ...GCInstr(kExprStructNew), structIndex2])+ .exportFunc();++ builder+ .addFunction("makeArray2", makeSig_r_v(wasmRefType(arrayIndex2)))+ .addBody([...wasmF32Const(42), ...wasmI32Const(5),+ ...GCInstr(kExprArrayNew), arrayIndex2])+ .exportFunc();++ builder+ .addFunction("testFunc", funcIndex)+ .addBody([])+ .exportFunc();++ builder+ .addFunction("testFunc2", funcIndex2)+ .addBody([...wasmI32Const(42)])+ .exportFunc();++ const buffer = builder.toBuffer();+ const module = new WebAssembly.Module(buffer);+ const instance = new WebAssembly.Instance(module, {});+ exports = instance.exports;+});++test(() => {+ exports.anyArg(exports.makeStruct());+ exports.anyArg(exports.makeArray());+ exports.anyArg(42);+ exports.anyArg(42n);+ exports.anyArg("foo");+ exports.anyArg({});+ exports.anyArg(() => {});+ exports.anyArg(exports.testFunc);+ assert_throws_js(TypeError, () => exports.anyArg(null));++ exports.anyNullableArg(null);+ exports.anyNullableArg(exports.makeStruct());+ exports.anyNullableArg(exports.makeArray());+ exports.anyNullableArg(42);+ exports.anyNullableArg(42n);+ exports.anyNullableArg("foo");+ exports.anyNullableArg({});+ exports.anyNullableArg(() => {});+ exports.anyNullableArg(exports.testFunc);+}, "anyref casts");++test(() => {+ exports.eqArg(exports.makeStruct());+ exports.eqArg(exports.makeArray());+ exports.eqArg(42);+ assert_throws_js(TypeError, () => exports.eqArg(42n));+ assert_throws_js(TypeError, () => exports.eqArg("foo"));+ assert_throws_js(TypeError, () => exports.eqArg({}));+ assert_throws_js(TypeError, () => exports.eqArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.eqArg(() => {}));+ assert_throws_js(TypeError, () => exports.eqArg(null));++ exports.eqNullableArg(null);+ exports.eqNullableArg(exports.makeStruct());+ exports.eqNullableArg(exports.makeArray());+ exports.eqNullableArg(42);+ assert_throws_js(TypeError, () => exports.eqNullableArg(42n));+ assert_throws_js(TypeError, () => exports.eqNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.eqNullableArg({}));+ assert_throws_js(TypeError, () => exports.eqNullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.eqNullableArg(() => {}));+}, "eqref casts");++test(() => {+ exports.structArg(exports.makeStruct());+ assert_throws_js(TypeError, () => exports.structArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.structArg(42));+ assert_throws_js(TypeError, () => exports.structArg(42n));+ assert_throws_js(TypeError, () => exports.structArg("foo"));+ assert_throws_js(TypeError, () => exports.structArg({}));+ assert_throws_js(TypeError, () => exports.structArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.structArg(() => {}));+ assert_throws_js(TypeError, () => exports.structArg(null));++ exports.structNullableArg(null);+ exports.structNullableArg(exports.makeStruct());+ assert_throws_js(TypeError, () => exports.structNullableArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.structNullableArg(42));+ assert_throws_js(TypeError, () => exports.structNullableArg(42n));+ assert_throws_js(TypeError, () => exports.structNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.structNullableArg({}));+ assert_throws_js(TypeError, () => exports.structNullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.structNullableArg(() => {}));+}, "structref casts");++test(() => {+ exports.arrayArg(exports.makeArray());+ assert_throws_js(TypeError, () => exports.arrayArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.arrayArg(42));+ assert_throws_js(TypeError, () => exports.arrayArg(42n));+ assert_throws_js(TypeError, () => exports.arrayArg("foo"));+ assert_throws_js(TypeError, () => exports.arrayArg({}));+ assert_throws_js(TypeError, () => exports.arrayArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.arrayArg(() => {}));+ assert_throws_js(TypeError, () => exports.arrayArg(null));++ exports.arrayNullableArg(null);+ exports.arrayNullableArg(exports.makeArray());+ assert_throws_js(TypeError, () => exports.arrayNullableArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.arrayNullableArg(42));+ assert_throws_js(TypeError, () => exports.arrayNullableArg(42n));+ assert_throws_js(TypeError, () => exports.arrayNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.arrayNullableArg({}));+ assert_throws_js(TypeError, () => exports.arrayNullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.arrayNullableArg(() => {}));+}, "arrayref casts");++test(() => {+ exports.i31Arg(42);+ assert_throws_js(TypeError, () => exports.i31Arg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.i31Arg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.i31Arg(42n));+ assert_throws_js(TypeError, () => exports.i31Arg("foo"));+ assert_throws_js(TypeError, () => exports.i31Arg({}));+ assert_throws_js(TypeError, () => exports.i31Arg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.i31Arg(() => {}));+ assert_throws_js(TypeError, () => exports.i31Arg(null));++ exports.i31NullableArg(null);+ exports.i31NullableArg(42);+ assert_throws_js(TypeError, () => exports.i31NullableArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.i31NullableArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.i31NullableArg(42n));+ assert_throws_js(TypeError, () => exports.i31NullableArg("foo"));+ assert_throws_js(TypeError, () => exports.i31NullableArg({}));+ assert_throws_js(TypeError, () => exports.i31NullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.i31NullableArg(() => {}));+}, "i31ref casts");++test(() => {+ exports.funcArg(exports.testFunc);+ assert_throws_js(TypeError, () => exports.funcArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.funcArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.funcArg(42));+ assert_throws_js(TypeError, () => exports.funcArg(42n));+ assert_throws_js(TypeError, () => exports.funcArg("foo"));+ assert_throws_js(TypeError, () => exports.funcArg({}));+ assert_throws_js(TypeError, () => exports.funcArg(() => {}));+ assert_throws_js(TypeError, () => exports.funcArg(null));++ exports.funcNullableArg(null);+ exports.funcNullableArg(exports.testFunc);+ assert_throws_js(TypeError, () => exports.funcNullableArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.funcNullableArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.funcNullableArg(42));+ assert_throws_js(TypeError, () => exports.funcNullableArg(42n));+ assert_throws_js(TypeError, () => exports.funcNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.funcNullableArg({}));+ assert_throws_js(TypeError, () => exports.funcNullableArg(() => {}));+}, "funcref casts");++test(() => {+ exports.externArg(exports.makeArray());+ exports.externArg(exports.makeStruct());+ exports.externArg(42);+ exports.externArg(42n);+ exports.externArg("foo");+ exports.externArg({});+ exports.externArg(exports.testFunc);+ exports.externArg(() => {});+ assert_throws_js(TypeError, () => exports.externArg(null));++ exports.externNullableArg(null);+ exports.externNullableArg(exports.makeArray());+ exports.externNullableArg(exports.makeStruct());+ exports.externNullableArg(42);+ exports.externNullableArg(42n);+ exports.externNullableArg("foo");+ exports.externNullableArg({});+ exports.externNullableArg(exports.testFunc);+ exports.externNullableArg(() => {});+}, "externref casts");++test(() => {+ for (const nullfunc of [exports.noneArg, exports.nofuncArg, exports.noexternArg]) {+ assert_throws_js(TypeError, () => nullfunc(exports.makeStruct()));+ assert_throws_js(TypeError, () => nullfunc(exports.makeArray()));+ assert_throws_js(TypeError, () => nullfunc(42));+ assert_throws_js(TypeError, () => nullfunc(42n));+ assert_throws_js(TypeError, () => nullfunc("foo"));+ assert_throws_js(TypeError, () => nullfunc({}));+ assert_throws_js(TypeError, () => nullfunc(exports.testFunc));+ assert_throws_js(TypeError, () => nullfunc(() => {}));+ assert_throws_js(TypeError, () => nullfunc(null));+ }++ for (const nullfunc of [exports.noneNullableArg, exports.nofuncNullableArg, exports.noexternNullableArg]) {+ nullfunc(null);+ assert_throws_js(TypeError, () => nullfunc(exports.makeStruct()));+ assert_throws_js(TypeError, () => nullfunc(exports.makeArray()));+ assert_throws_js(TypeError, () => nullfunc(42));+ assert_throws_js(TypeError, () => nullfunc(42n));+ assert_throws_js(TypeError, () => nullfunc("foo"));+ assert_throws_js(TypeError, () => nullfunc({}));+ assert_throws_js(TypeError, () => nullfunc(exports.testFunc));+ assert_throws_js(TypeError, () => nullfunc(() => {}));+ }+}, "null casts");++test(() => {+ exports.concreteStructArg(exports.makeStruct());+ assert_throws_js(TypeError, () => exports.concreteStructArg(exports.makeStruct2()));+ assert_throws_js(TypeError, () => exports.concreteStructArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.concreteStructArg(42));+ assert_throws_js(TypeError, () => exports.concreteStructArg(42n));+ assert_throws_js(TypeError, () => exports.concreteStructArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteStructArg({}));+ assert_throws_js(TypeError, () => exports.concreteStructArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.concreteStructArg(() => {}));+ assert_throws_js(TypeError, () => exports.concreteStructArg(null));++ exports.concreteStructNullableArg(null);+ exports.concreteStructNullableArg(exports.makeStruct());+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(exports.makeStruct2()));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(42));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(42n));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg({}));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.concreteStructNullableArg(() => {}));+}, "concrete struct casts");++test(() => {+ exports.concreteArrayArg(exports.makeArray());+ assert_throws_js(TypeError, () => exports.concreteArrayArg(exports.makeArray2()));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(42));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(42n));+ assert_throws_js(TypeError, () => exports.concreteArrayArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteArrayArg({}));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(() => {}));+ assert_throws_js(TypeError, () => exports.concreteArrayArg(null));++ exports.concreteArrayNullableArg(null);+ exports.concreteArrayNullableArg(exports.makeArray());+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(exports.makeArray2()));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(42));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(42n));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg({}));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(exports.testFunc));+ assert_throws_js(TypeError, () => exports.concreteArrayNullableArg(() => {}));+}, "concrete array casts");++test(() => {+ exports.concreteFuncArg(exports.testFunc);+ assert_throws_js(TypeError, () => exports.concreteFuncArg(exports.testFunc2));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(42));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(42n));+ assert_throws_js(TypeError, () => exports.concreteFuncArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteFuncArg({}));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(() => {}));+ assert_throws_js(TypeError, () => exports.concreteFuncArg(null));++ exports.concreteFuncNullableArg(null);+ exports.concreteFuncNullableArg(exports.testFunc);+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(exports.testFunc2));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(exports.makeArray()));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(exports.makeStruct()));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(42));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(42n));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg("foo"));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg({}));+ assert_throws_js(TypeError, () => exports.concreteFuncNullableArg(() => {}));+}, "concrete func casts");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.htmlnew file mode 100644index 00000000000..cbdad2ef269--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/wasm-module-builder.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/gc/exported-object.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.jsnew file mode 100644index 00000000000..b572f140067--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/exported-object.tentative.any.js@@ -0,0 +1,190 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/wasm-module-builder.js++let functions = {};+setup(() => {+ const builder = new WasmModuleBuilder();++ const structIndex = builder.addStruct([makeField(kWasmI32, true)]);+ const arrayIndex = builder.addArray(kWasmI32, true);+ const structRef = wasmRefType(structIndex);+ const arrayRef = wasmRefType(arrayIndex);++ builder+ .addFunction("makeStruct", makeSig_r_v(structRef))+ .addBody([...wasmI32Const(42),+ ...GCInstr(kExprStructNew), structIndex])+ .exportFunc();++ builder+ .addFunction("makeArray", makeSig_r_v(arrayRef))+ .addBody([...wasmI32Const(5), ...wasmI32Const(42),+ ...GCInstr(kExprArrayNew), arrayIndex])+ .exportFunc();++ const buffer = builder.toBuffer();+ const module = new WebAssembly.Module(buffer);+ const instance = new WebAssembly.Instance(module, {});+ functions = instance.exports;+});++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_equals(struct.foo, undefined);+ assert_equals(struct[0], undefined);+ assert_equals(array.foo, undefined);+ assert_equals(array[0], undefined);+}, "property access");++test(() => {+ "use strict";+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => { struct.foo = 5; });+ assert_throws_js(TypeError, () => { array.foo = 5; });+ assert_throws_js(TypeError, () => { struct[0] = 5; });+ assert_throws_js(TypeError, () => { array[0] = 5; });+}, "property assignment (strict mode)");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => { struct.foo = 5; });+ assert_throws_js(TypeError, () => { array.foo = 5; });+ assert_throws_js(TypeError, () => { struct[0] = 5; });+ assert_throws_js(TypeError, () => { array[0] = 5; });+}, "property assignment (non-strict mode)");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_equals(Object.getOwnPropertyNames(struct).length, 0);+ assert_equals(Object.getOwnPropertyNames(array).length, 0);+}, "ownPropertyNames");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => Object.defineProperty(struct, "foo", { value: 1 }));+ assert_throws_js(TypeError, () => Object.defineProperty(array, "foo", { value: 1 }));+}, "defineProperty");++test(() => {+ "use strict";+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => delete struct.foo);+ assert_throws_js(TypeError, () => delete struct[0]);+ assert_throws_js(TypeError, () => delete array.foo);+ assert_throws_js(TypeError, () => delete array[0]);+}, "delete (strict mode)");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => delete struct.foo);+ assert_throws_js(TypeError, () => delete struct[0]);+ assert_throws_js(TypeError, () => delete array.foo);+ assert_throws_js(TypeError, () => delete array[0]);+}, "delete (non-strict mode)");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_equals(Object.getPrototypeOf(struct), null);+ assert_equals(Object.getPrototypeOf(array), null);+}, "getPrototypeOf");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => Object.setPrototypeOf(struct, {}));+ assert_throws_js(TypeError, () => Object.setPrototypeOf(array, {}));+}, "setPrototypeOf");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_false(Object.isExtensible(struct));+ assert_false(Object.isExtensible(array));+}, "isExtensible");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => Object.preventExtensions(struct));+ assert_throws_js(TypeError, () => Object.preventExtensions(array));+}, "preventExtensions");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => Object.seal(struct));+ assert_throws_js(TypeError, () => Object.seal(array));+}, "sealing");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_equals(typeof struct, "object");+ assert_equals(typeof array, "object");+}, "typeof");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => struct.toString());+ assert_equals(Object.prototype.toString.call(struct), "[object Object]");+ assert_throws_js(TypeError, () => array.toString());+ assert_equals(Object.prototype.toString.call(array), "[object Object]");+}, "toString");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ assert_throws_js(TypeError, () => struct.valueOf());+ assert_equals(Object.prototype.valueOf.call(struct), struct);+ assert_throws_js(TypeError, () => array.valueOf());+ assert_equals(Object.prototype.valueOf.call(array), array);+}, "valueOf");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ const map = new Map();+ map.set(struct, "struct");+ map.set(array, "array");+ assert_equals(map.get(struct), "struct");+ assert_equals(map.get(array), "array");+}, "GC objects as map keys");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ const set = new Set();+ set.add(struct);+ set.add(array);+ assert_true(set.has(struct));+ assert_true(set.has(array));+}, "GC objects as set element");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ const map = new WeakMap();+ map.set(struct, "struct");+ map.set(array, "array");+ assert_equals(map.get(struct), "struct");+ assert_equals(map.get(array), "array");+}, "GC objects as weak map keys");++test(() => {+ const struct = functions.makeStruct();+ const array = functions.makeArray();+ const set = new WeakSet();+ set.add(struct);+ set.add(array);+ assert_true(set.has(struct));+ assert_true(set.has(array));+}, "GC objects as weak set element");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.htmlnew file mode 100644index 00000000000..a7d8c36a192--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/wasm-module-builder.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/gc/i31.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.jsnew file mode 100644index 00000000000..17fd82440cc--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/gc/i31.tentative.any.js@@ -0,0 +1,98 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/wasm-module-builder.js++let exports = {};+setup(() => {+ const builder = new WasmModuleBuilder();+ const i31Ref = wasmRefType(kWasmI31Ref);+ const i31NullableRef = wasmRefNullType(kWasmI31Ref);+ const anyRef = wasmRefType(kWasmAnyRef);++ builder+ .addFunction("makeI31", makeSig_r_x(i31Ref, kWasmI32))+ .addBody([kExprLocalGet, 0,+ ...GCInstr(kExprI31New)])+ .exportFunc();++ builder+ .addFunction("castI31", makeSig_r_x(kWasmI32, anyRef))+ .addBody([kExprLocalGet, 0,+ ...GCInstr(kExprRefCast), kI31RefCode,+ ...GCInstr(kExprI31GetU)])+ .exportFunc();++ builder+ .addFunction("getI31", makeSig_r_x(kWasmI32, i31Ref))+ .addBody([kExprLocalGet, 0,+ ...GCInstr(kExprI31GetS)])+ .exportFunc();++ builder+ .addFunction("argI31", makeSig_v_x(i31NullableRef))+ .addBody([])+ .exportFunc();++ builder+ .addGlobal(i31NullableRef, true, [...wasmI32Const(0), ...GCInstr(kExprI31New)])+ builder+ .addExportOfKind("i31Global", kExternalGlobal, 0);++ builder+ .addTable(i31NullableRef, 10)+ builder+ .addExportOfKind("i31Table", kExternalTable, 0);++ const buffer = builder.toBuffer();+ const module = new WebAssembly.Module(buffer);+ const instance = new WebAssembly.Instance(module, {});+ exports = instance.exports;+});++test(() => {+ assert_equals(exports.makeI31(42), 42);+ assert_equals(exports.makeI31(2 ** 30 - 1), 2 ** 30 - 1);+ assert_equals(exports.makeI31(2 ** 30), -(2 ** 30));+ assert_equals(exports.makeI31(-(2 ** 30)), -(2 ** 30));+ assert_equals(exports.makeI31(2 ** 31 - 1), -1);+ assert_equals(exports.makeI31(2 ** 31), 0);+}, "i31ref conversion to Number");++test(() => {+ assert_equals(exports.getI31(exports.makeI31(42)), 42);+ assert_equals(exports.getI31(42), 42);+ assert_equals(exports.getI31(2.0 ** 30 - 1), 2 ** 30 - 1);+ assert_equals(exports.getI31(-(2 ** 30)), -(2 ** 30));+}, "Number conversion to i31ref");++test(() => {+ exports.argI31(null);+ assert_throws_js(TypeError, () => exports.argI31(2 ** 30));+ assert_throws_js(TypeError, () => exports.argI31(-(2 ** 30) - 1));+ assert_throws_js(TypeError, () => exports.argI31(2n));+ assert_throws_js(TypeError, () => exports.argI31(() => 3));+ assert_throws_js(TypeError, () => exports.argI31(exports.getI31));+}, "Check i31ref argument type");++test(() => {+ assert_equals(exports.castI31(42), 42);+ assert_equals(exports.castI31(2 ** 30 - 1), 2 ** 30 - 1);+ assert_throws_js(WebAssembly.RuntimeError, () => { exports.castI31(2 ** 30); });+ assert_throws_js(WebAssembly.RuntimeError, () => { exports.castI31(-(2 ** 30) - 1); });+ assert_throws_js(WebAssembly.RuntimeError, () => { exports.castI31(2 ** 32); });+}, "Numbers in i31 range are i31ref, not hostref");++test(() => {+ assert_equals(exports.i31Global.value, 0);+ exports.i31Global.value = 42;+ assert_throws_js(TypeError, () => exports.i31Global.value = 2 ** 30);+ assert_throws_js(TypeError, () => exports.i31Global.value = -(2 ** 30) - 1);+ assert_equals(exports.i31Global.value, 42);+}, "i31ref global");++test(() => {+ assert_equals(exports.i31Table.get(0), null);+ exports.i31Table.set(0, 42);+ assert_throws_js(TypeError, () => exports.i31Table.set(0, 2 ** 30));+ assert_throws_js(TypeError, () => exports.i31Table.set(0, -(2 ** 30) - 1));+ assert_equals(exports.i31Table.get(0), 42);+}, "i31ref table");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.htmlnew file mode 100644index 00000000000..84af4c25a52--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../../wasm/jsapi/assertions.js"></script>+<div id=log></div>+<script src="../../../wasm/jsapi/tag/constructor.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.jsnew file mode 100644index 00000000000..de63e7bf46d--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/constructor.tentative.any.js@@ -0,0 +1,49 @@+// META: global=window,dedicatedworker,jsshell+// META: script=/wasm/jsapi/assertions.js++test(() => {+ assert_function_name(WebAssembly.Tag, "Tag", "WebAssembly.Tag");+}, "name");++test(() => {+ assert_function_length(WebAssembly.Tag, 1, "WebAssembly.Tag");+}, "length");++test(() => {+ assert_throws_js(TypeError, () => new WebAssembly.Tag());+}, "No arguments");++test(() => {+ const argument = { parameters: [] };+ assert_throws_js(TypeError, () => WebAssembly.Tag(argument));+}, "Calling");++test(() => {+ const invalidArguments = [+ undefined,+ null,+ false,+ true,+ "",+ "test",+ Symbol(),+ 1,+ NaN,+ {},+ ];+ for (const invalidArgument of invalidArguments) {+ assert_throws_js(+ TypeError,+ () => new WebAssembly.Tag(invalidArgument),+ `new Tag(${format_value(invalidArgument)})`+ );+ }+}, "Invalid descriptor argument");++test(() => {+ const invalidTypes = ["i16", "i128", "f16", "f128", "u32", "u64", "i32\0"];+ for (const value of invalidTypes) {+ const argument = { parameters: [value] };+ assert_throws_js(TypeError, () => new WebAssembly.Tag(argument));+ }+}, "Invalid type parameter");diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.html b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.htmlnew file mode 100644index 00000000000..fa20e4eb233--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.html@@ -0,0 +1,15 @@+<!doctype html>+<meta charset=utf-8>++<script>+self.GLOBAL = {+ isWindow: function() { return true; },+ isWorker: function() { return false; },+ isShadowRealm: function() { return false; },+};+</script>+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>++<div id=log></div>+<script src="../../../wasm/jsapi/tag/toString.tentative.any.js"></script>diff --git a/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.js b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.jsnew file mode 100644index 00000000000..ad9a4ba152f--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/wasm/jsapi/tag/toString.tentative.any.js@@ -0,0 +1,20 @@+// META: global=window,dedicatedworker,jsshell++test(() => {+ const argument = { parameters: [] };+ const tag = new WebAssembly.Tag(argument);+ assert_class_string(tag, "WebAssembly.Tag");+}, "Object.prototype.toString on a Tag");++test(() => {+ assert_own_property(WebAssembly.Tag.prototype, Symbol.toStringTag);++ const propDesc = Object.getOwnPropertyDescriptor(+ WebAssembly.Tag.prototype,+ Symbol.toStringTag+ );+ assert_equals(propDesc.value, "WebAssembly.Tag", "value");+ assert_equals(propDesc.configurable, true, "configurable");+ assert_equals(propDesc.enumerable, false, "enumerable");+ assert_equals(propDesc.writable, false, "writable");+}, "@@toStringTag exists on the prototype with the appropriate descriptor");