Skip to content

Truly independent web browser

LibWasm: Add a Rust WebAssembly engine with a Flap interpreter

Andreas Kling264b9bd484d7
diff --git a/Cargo.lock b/Cargo.lock
index a810de08cd4..49f72d807f2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1021,6 +1021,19 @@ dependencies = [
"target-lexicon",
]
+[[package]]
+name = "libwasm_engine"
+version = "0.1.0"
+dependencies = [
+ "ak",
+ "cbindgen",
+ "cc",
+ "flapc",
+ "ladybird_allocator",
+ "libc",
+ "rustc-demangle",
+]
+
[[package]]
name = "libweb_bindings_rust"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 87a020aca0b..e7685307569 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -14,6 +14,7 @@ members = [
"Libraries/LibTextCodec/Rust",
"Libraries/LibUnicode/Rust",
"Libraries/LibURL/Rust",
+ "Libraries/LibWasm/Engine",
"Libraries/LibWasm/Rust",
"Libraries/LibWeb/Bindings/Rust",
"Libraries/LibWeb/ContentBlocker/Rust",
diff --git a/Libraries/LibWasm/CMakeLists.txt b/Libraries/LibWasm/CMakeLists.txt
index 68e2e6e8d26..20891c703cb 100644
--- a/Libraries/LibWasm/CMakeLists.txt
+++ b/Libraries/LibWasm/CMakeLists.txt
@@ -67,4 +67,6 @@ if (ENABLE_CRANELIFT_JIT)
)
endif()
+add_subdirectory(Runtime)
+
include(wasm_spec_tests)
diff --git a/Libraries/LibWasm/Engine/Cargo.toml b/Libraries/LibWasm/Engine/Cargo.toml
new file mode 100644
index 00000000000..b1a22d8ad1f
--- /dev/null
+++ b/Libraries/LibWasm/Engine/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "libwasm_engine"
+version = "0.1.0"
+edition = "2024"
+
+[lib]
+crate-type = ["staticlib", "rlib"]
+
+# After changing dependencies, regenerate the Flatpak sources:
+# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[dependencies]
+ak = { path = "../../../AK/Rust" }
+ladybird_allocator = { path = "../../RustAllocator", optional = true }
+libc = "0.2"
+rustc-demangle = "0.1"
+
+[features]
+default = []
+allocator = ["dep:ladybird_allocator"]
+
+[build-dependencies]
+cbindgen = "0.29"
+cc = "1"
+flapc = { path = "../../LibJS/Flap" }
+
+[lints]
+workspace = true
diff --git a/Libraries/LibWasm/Engine/build.rs b/Libraries/LibWasm/Engine/build.rs
new file mode 100644
index 00000000000..08756165d03
--- /dev/null
+++ b/Libraries/LibWasm/Engine/build.rs
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Compiles the interpreter, Libraries/LibWasm/Interpreter/interpreter.flap, against the layout constants of
+//! src/abi.rs, and assembles it into the crate. Also generates the C++ header of the C ABI in src/capi.rs.
+
+use std::env;
+use std::fs;
+use std::path::PathBuf;
+
+#[path = "src/abi.rs"]
+mod abi;
+
+fn write_if_changed(path: &PathBuf, contents: &str) {
+ if fs::read_to_string(path).is_ok_and(|existing| existing == contents) {
+ return;
+ }
+ fs::write(path, contents).unwrap_or_else(|error| panic!("write {}: {error}", path.display()));
+}
+
+fn main() {
+ let manifest_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
+ let output_directory = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR"));
+ let interpreter_source = manifest_directory.join("../Interpreter/interpreter.flap");
+ println!("cargo:rerun-if-changed=build.rs");
+ println!("cargo:rerun-if-changed=src/abi.rs");
+ println!("cargo:rerun-if-changed={}", interpreter_source.display());
+ println!("cargo::rustc-check-cfg=cfg(wasm_interpreter)");
+ println!("cargo:rerun-if-changed=cbindgen.toml");
+ println!("cargo:rerun-if-changed=src/capi.rs");
+
+ // The bindings only cover the C ABI, so they are generated from that file alone.
+ let bindings = cbindgen::Builder::new()
+ .with_config(cbindgen::Config::from_file(manifest_directory.join("cbindgen.toml")).expect("read cbindgen.toml"))
+ .with_src(manifest_directory.join("src/capi.rs"))
+ .generate()
+ .expect("generate the C ABI header");
+ bindings.write_to_file(output_directory.join("RustFFI.h"));
+
+ 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() {
+ "macos" | "ios" => flapc::ObjectFormat::MachO,
+ "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;
+ }
+ println!("cargo:rustc-cfg=wasm_interpreter");
+
+ let layout = abi::layout_constants();
+ let layout_path = output_directory.join("layout.conf");
+ write_if_changed(&layout_path, &layout);
+
+ let source = fs::read_to_string(&interpreter_source).expect("read interpreter.flap");
+ let source_name = interpreter_source.display().to_string();
+ let compiler = flapc::Compiler::new(flapc::CompileOptions {
+ target: flapc::Target {
+ architecture: flapc::Architecture::X86_64,
+ object_format,
+ },
+ has_jscvt: false,
+ enable_assertions: true,
+ profiling: false,
+ profile: flapc::Profile::WebAssembly,
+ });
+ let assembly = compiler
+ .compile(flapc::CompilationUnit {
+ source: flapc::SourceInput {
+ name: &source_name,
+ contents: &source,
+ },
+ constants: Some(flapc::SourceInput {
+ name: "layout.conf",
+ contents: &layout,
+ }),
+ })
+ .unwrap_or_else(|error| panic!("flapc failed to compile the interpreter:\n{error}"));
+ let assembly_path = output_directory.join("interpreter.S");
+ write_if_changed(&assembly_path, assembly.as_str());
+
+ 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");
+ build.compile("libwasm_interpreter");
+}
diff --git a/Libraries/LibWasm/Engine/cbindgen.toml b/Libraries/LibWasm/Engine/cbindgen.toml
new file mode 100644
index 00000000000..e64cda1573f
--- /dev/null
+++ b/Libraries/LibWasm/Engine/cbindgen.toml
@@ -0,0 +1,20 @@
+language = "C++"
+header = """/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */"""
+pragma_once = true
+include_version = true
+namespaces = ["Wasm", "FFI"]
+line_length = 120
+tab_width = 4
+no_includes = true
+sys_includes = ["stdint.h", "stddef.h"]
+usize_is_size_t = true
+
+[export]
+include = ["WasmStatus"]
+
+[enum]
+prefix_with_name = false
diff --git a/Libraries/LibWasm/Engine/examples/validate.rs b/Libraries/LibWasm/Engine/examples/validate.rs
new file mode 100644
index 00000000000..774c48edddd
--- /dev/null
+++ b/Libraries/LibWasm/Engine/examples/validate.rs
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Print whether each module named on stdin decodes and validates, one `path<TAB>verdict` line per module, for
+//! comparing verdicts with other implementations. With `--stats`, valid modules also report the size of their code
+//! and of what validation keeps for running it.
+
+use std::io::BufRead;
+
+fn main() {
+ let stats = std::env::args().any(|argument| argument == "--stats");
+ for line in std::io::stdin().lock().lines() {
+ let path = line.expect("read a path");
+ let verdict = match std::fs::read(&path) {
+ Err(error) => format!("unreadable: {error}"),
+ Ok(bytes) => match libwasm_engine::compile(&bytes) {
+ Ok(module) if stats => {
+ let code: u32 = module.code.iter().map(|body| body.code.end - body.code.start).sum();
+ let entries: usize = module.function_infos.iter().map(|info| info.side_table.len()).sum();
+ let metadata: usize = module.function_infos.iter().map(|info| info.metadata_size()).sum();
+ format!(
+ "valid functions={} code_bytes={code} side_table_entries={entries} metadata_bytes={metadata}",
+ module.code.len()
+ )
+ }
+ Ok(_) => "valid".to_string(),
+ Err(error) => format!("error:{error}"),
+ },
+ };
+ println!("{path}\t{verdict}");
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rs
new file mode 100644
index 00000000000..0d8b3fcf819
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/abi.rs
@@ -0,0 +1,350 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The data structures the interpreter reads and writes, and the layout of its frames. The build script includes this
+//! file to write the layout constants `interpreter.flap` is compiled against, so the two always agree.
+//!
+//! # Frames
+//!
+//! Every function runs in a frame on the machine stack, which grows down. Locals sit above the frame pointer and the
+//! frame header below it, with the operand stack below the header, growing down in 8-byte slots:
+//!
+//! ```text
+//! caller's operand stack ... the arguments (copied into the callee's locals, then dropped)
+//! ───────────────────────────────────────── <- the caller's operand stack without the arguments ("return vsp")
+//! v128 locals, 16 bytes each from fp + FunctionHeader::v128_locals_offset (16-byte aligned), if there are any
+//! local i at fp + 8 * i
+//! fp ────────────────────────────────────── 16-byte aligned
+//! frame header, fp - FRAME_HEADER_SIZE up to fp (see FRAME_*)
+//! operand stack, empty at fp - FRAME_HEADER_SIZE, growing down; a v128 takes two slots
+//! headroom for the deepest operand stack, then the spill area of the handlers (SPILL_AREA_*)
+//! sp ────────────────────────────────────── fp - FunctionHeader::frame_size, 16-byte aligned
+//! ```
+//!
+//! A v128 local has a scalar slot at fp + 8 * i too, which stays unused, so that every local's scalar slot is at a
+//! fixed offset. A future JIT uses the same frames, so that calls between the tiers need no adapters and entering
+//! compiled code at a loop header only loads the slots.
+
+#![allow(dead_code)]
+
+use std::mem::offset_of;
+
+/// The frame header. All fields are 8 bytes, at `fp + FRAME_*`.
+pub const FRAME_SAVED_FP: isize = -8;
+/// The caller's instruction pointer after its call instruction.
+pub const FRAME_RETURN_IP: isize = -16;
+pub const FRAME_SAVED_STP: isize = -24;
+/// The `FunctionHeader` of the function running in the frame.
+pub const FRAME_FUNCTION: isize = -32;
+/// Where the caller's operand stack continues once the arguments are popped. Results are pushed from there.
+pub const FRAME_RETURN_VSP: isize = -40;
+/// The caller's `memory_base`.
+pub const FRAME_SAVED_MEMORY_BASE: isize = -48;
+/// The `InstanceData` of the function running in the frame.
+pub const FRAME_INSTANCE: isize = -56;
+/// The `ExecutionContext` the frame runs in.
+pub const FRAME_CONTEXT: isize = -64;
+pub const FRAME_HEADER_SIZE: usize = 64;
+
+/// The slots handlers spill values to, at the bottom of every frame, just above the stack pointer.
+pub const SPILL_AREA_OFFSET: usize = 0;
+pub const SPILL_AREA_SLOTS: usize = 32;
+pub const SPILL_AREA_SIZE: usize = SPILL_AREA_SLOTS * 8;
+
+pub const FUNCTION_KIND_WASM: u32 = 0;
+pub const FUNCTION_KIND_HOST: u32 = 1;
+/// A WebAssembly function with v128 parameters or locals, whose frame has storage for them.
+pub const FUNCTION_KIND_WASM_VECTOR: u32 = 2;
+
+/// One function, as the interpreter sees it. Function references point at these.
+#[repr(C)]
+pub struct FunctionHeader {
+ /// The function's first instruction.
+ pub code: *const u8,
+ /// The function's final `end` instruction.
+ pub code_end: *const u8,
+ pub side_table: *const u8,
+ pub instance: *const InstanceData,
+ pub kind: u32,
+ pub param_slots: u32,
+ pub result_slots: u32,
+ /// The number of locals, parameters included.
+ pub local_count: u32,
+ /// The bytes of locals above fp, 16-byte aligned.
+ pub locals_size: u32,
+ /// The padding that keeps the pointers below aligned.
+ pub reserved: u32,
+ /// The bytes below fp the frame needs, operand stack and red zone included.
+ pub frame_size: u32,
+ /// The store-wide identity of the function's type, equal exactly for equal types.
+ pub type_identity: u32,
+ /// For host functions, what the runtime needs to call them.
+ pub host: *const u8,
+ /// For functions with v128 parameters or locals (FUNCTION_KIND_WASM_VECTOR), the offset from fp of each local's
+ /// 16-byte storage, or zero for scalar locals. Null otherwise.
+ pub vector_storage: *const u32,
+}
+
+/// A memory, as the interpreter sees it.
+#[repr(C)]
+pub struct MemoryData {
+ pub base: *mut u8,
+ /// The accessible size, in bytes.
+ pub size: u64,
+ /// Nonzero for a memory64, whose addresses and sizes are i64 values.
+ pub address64: u64,
+ /// Nonzero for a shared memory, which atomic waits may block on.
+ pub shared: u64,
+}
+
+/// A table, as the interpreter sees it. Elements are 8-byte references, zero for null.
+#[repr(C)]
+pub struct TableData {
+ pub elements: *mut u64,
+ pub size: u64,
+ /// Nonzero for a table64, whose indices and sizes are i64 values.
+ pub address64: u64,
+}
+
+/// A module instance, as the interpreter sees it.
+#[repr(C)]
+pub struct InstanceData {
+ /// The base of memory 0, or null if the instance has none.
+ pub memory0_base: *mut u8,
+ pub memories: *const *mut MemoryData,
+ /// The storage of every global: 8 bytes, or 16 for v128 globals.
+ pub globals: *const *mut u64,
+ pub functions: *const *const FunctionHeader,
+ pub tables: *const *mut TableData,
+ /// The store-wide identity of each of the module's types.
+ pub type_identities: *const u32,
+ /// The bytes of each data segment, empty once dropped.
+ pub data_segments: *const Segment,
+ /// The references of each element segment, empty once dropped.
+ pub element_segments: *const Segment,
+ /// The identity of each of the instance's tags: the address of its TagInstance.
+ pub tags: *const u64,
+ pub function_count: u32,
+ pub memory_count: u32,
+}
+
+/// A passive segment: its contents and their length, in bytes for data and in elements for element segments.
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct Segment {
+ pub contents: *const u8,
+ pub length: u64,
+}
+
+pub const TRAP_NONE: u32 = 0;
+pub const TRAP_UNREACHABLE: u32 = 1;
+pub const TRAP_STACK_EXHAUSTED: u32 = 2;
+pub const TRAP_MEMORY_OUT_OF_BOUNDS: u32 = 3;
+pub const TRAP_INTEGER_DIVIDE_BY_ZERO: u32 = 4;
+pub const TRAP_INTEGER_OVERFLOW: u32 = 5;
+pub const TRAP_INVALID_CONVERSION: u32 = 6;
+pub const TRAP_UNDEFINED_ELEMENT: u32 = 7;
+pub const TRAP_UNINITIALIZED_ELEMENT: u32 = 8;
+pub const TRAP_INDIRECT_CALL_TYPE_MISMATCH: u32 = 9;
+pub const TRAP_TABLE_OUT_OF_BOUNDS: u32 = 10;
+pub const TRAP_NULL_REFERENCE: u32 = 11;
+pub const TRAP_CAST_FAILURE: u32 = 12;
+pub const TRAP_ARRAY_OUT_OF_BOUNDS: u32 = 13;
+/// The runtime reported a trap of its own, whose details it keeps.
+pub const TRAP_RUNTIME: u32 = 14;
+pub const TRAP_UNCAUGHT_EXCEPTION: u32 = 15;
+pub const TRAP_UNALIGNED_ATOMIC: u32 = 16;
+pub const TRAP_EXPECTED_SHARED_MEMORY: u32 = 17;
+
+/// The state one thread executes WebAssembly with.
+#[repr(C)]
+pub struct ExecutionContext {
+ /// The lowest address a frame may reach.
+ pub stack_limit: u64,
+ /// The fp of the innermost entry into the interpreter.
+ pub entry_fp: u64,
+ /// The `EntryRecord` of the innermost entry into the interpreter.
+ pub entry_record: *mut EntryRecord,
+ pub store: *mut u8,
+ /// Where the interpreter passes operands to the runtime functions it calls, which take the context alone.
+ pub arguments: [u64; 6],
+ /// The runtime type of each store-wide type identity.
+ pub rtts: *const *const Rtt,
+}
+
+/// What the interpreter knows about a type at runtime: how to check subtyping against it, and how objects of it are
+/// laid out. A GC object starts with the address of its type's Rtt; an array continues with its length, then its
+/// elements, and a struct with its fields.
+#[repr(C)]
+pub struct Rtt {
+ pub kind: u32,
+ /// The number of supertypes above this type.
+ pub depth: u32,
+ /// The identities of this type's supertypes, from the root down, and of this type last: `depth + 1` of them.
+ pub display: *const u32,
+ /// For structs, the byte offset of each field from the start of the object.
+ pub field_offsets: *const u32,
+ /// The STORAGE_* kind of each field of a struct, or of the elements of an array.
+ pub field_kinds: *const u8,
+ /// For structs, the size of an object; for arrays, the size of an element.
+ pub size: u32,
+ pub field_count: u32,
+}
+
+pub const RTT_KIND_FUNCTION: u32 = 0;
+pub const RTT_KIND_STRUCT: u32 = 1;
+pub const RTT_KIND_ARRAY: u32 = 2;
+
+/// How a struct field or array element is stored: one 8-byte word, with packed and 32-bit values zero-extended
+/// in it, or 16 bytes for a v128.
+pub const STORAGE_64: u8 = 0;
+pub const STORAGE_I8: u8 = 1;
+pub const STORAGE_I16: u8 = 2;
+pub const STORAGE_V128: u8 = 3;
+pub const STORAGE_32: u8 = 4;
+
+/// Where an array's elements start.
+pub const ARRAY_ELEMENTS_OFFSET: usize = 16;
+/// Where a struct's fields start.
+pub const STRUCT_FIELDS_OFFSET: usize = 8;
+
+/// What the runtime enters the interpreter with, and what it gets back.
+#[repr(C)]
+pub struct EntryRecord {
+ pub function: *const FunctionHeader,
+ /// The slots of the arguments as the operand stack holds them: the last argument at the lowest address.
+ pub arguments: *const u64,
+ /// Where the slots of the results go, laid out as the operand stack holds them.
+ pub results: *mut u64,
+ pub context: *mut ExecutionContext,
+ /// The `TRAP_*` code the call ended with.
+ pub trap: u32,
+ pub padding: u32,
+ pub saved_entry_fp: u64,
+ pub saved_entry_record: *mut EntryRecord,
+}
+
+/// The pseudo-instructions the interpreter starts and ends at, behind the 0xFF opcode no WebAssembly instruction uses.
+pub const INTERNAL_OPCODE: u8 = 0xff;
+pub const INTERNAL_ENTER: u8 = 0;
+pub const INTERNAL_EXIT: u8 = 1;
+pub const INTERNAL_MEMORY_FAULT: u8 = 2;
+
+/// The layout constants of everything above, in the format flapc reads.
+pub fn layout_constants() -> String {
+ let mut text = String::from("# Generated by the libwasm_engine build script -- DO NOT EDIT\n");
+ let mut signed_constant = |name: &str, value: isize| {
+ text.push_str(&format!("const {name} = {value}\n"));
+ };
+ signed_constant("FRAME_SAVED_FP", FRAME_SAVED_FP);
+ signed_constant("FRAME_RETURN_IP", FRAME_RETURN_IP);
+ signed_constant("FRAME_SAVED_STP", FRAME_SAVED_STP);
+ signed_constant("FRAME_FUNCTION", FRAME_FUNCTION);
+ signed_constant("FRAME_RETURN_VSP", FRAME_RETURN_VSP);
+ signed_constant("FRAME_SAVED_MEMORY_BASE", FRAME_SAVED_MEMORY_BASE);
+ signed_constant("FRAME_INSTANCE", FRAME_INSTANCE);
+ signed_constant("FRAME_CONTEXT", FRAME_CONTEXT);
+ let mut constant = |name: &str, value: usize| signed_constant(name, value as isize);
+ constant("FRAME_HEADER_SIZE", FRAME_HEADER_SIZE);
+ constant("SPILL_AREA_OFFSET", SPILL_AREA_OFFSET);
+ constant("SPILL_AREA_SLOTS", SPILL_AREA_SLOTS);
+ constant("SPILL_AREA_SIZE", SPILL_AREA_SIZE);
+ constant("FUNCTION_KIND_WASM", FUNCTION_KIND_WASM as usize);
+ constant("FUNCTION_KIND_HOST", FUNCTION_KIND_HOST as usize);
+ constant("FUNCTION_KIND_WASM_VECTOR", FUNCTION_KIND_WASM_VECTOR as usize);
+ macro_rules! field {
+ ($name:literal, $type:ty, $field:ident) => {
+ constant($name, offset_of!($type, $field));
+ };
+ }
+ field!("FUNCTION_CODE", FunctionHeader, code);
+ field!("FUNCTION_CODE_END", FunctionHeader, code_end);
+ field!("FUNCTION_SIDE_TABLE", FunctionHeader, side_table);
+ field!("FUNCTION_INSTANCE", FunctionHeader, instance);
+ field!("FUNCTION_KIND", FunctionHeader, kind);
+ field!("FUNCTION_PARAM_SLOTS", FunctionHeader, param_slots);
+ field!("FUNCTION_RESULT_SLOTS", FunctionHeader, result_slots);
+ field!("FUNCTION_LOCAL_COUNT", FunctionHeader, local_count);
+ field!("FUNCTION_LOCALS_SIZE", FunctionHeader, locals_size);
+ field!("FUNCTION_VECTOR_STORAGE", FunctionHeader, vector_storage);
+ field!("FUNCTION_FRAME_SIZE", FunctionHeader, frame_size);
+ field!("FUNCTION_TYPE_IDENTITY", FunctionHeader, type_identity);
+ field!("FUNCTION_HOST", FunctionHeader, host);
+ field!("MEMORY_BASE", MemoryData, base);
+ field!("MEMORY_SIZE", MemoryData, size);
+ field!("MEMORY_ADDRESS64", MemoryData, address64);
+ field!("MEMORY_SHARED", MemoryData, shared);
+ field!("TABLE_ELEMENTS", TableData, elements);
+ field!("TABLE_SIZE", TableData, size);
+ field!("TABLE_ADDRESS64", TableData, address64);
+ field!("INSTANCE_MEMORY0_BASE", InstanceData, memory0_base);
+ field!("INSTANCE_MEMORIES", InstanceData, memories);
+ field!("INSTANCE_GLOBALS", InstanceData, globals);
+ field!("INSTANCE_FUNCTIONS", InstanceData, functions);
+ field!("INSTANCE_TABLES", InstanceData, tables);
+ field!("INSTANCE_TYPE_IDENTITIES", InstanceData, type_identities);
+ field!("INSTANCE_DATA_SEGMENTS", InstanceData, data_segments);
+ field!("INSTANCE_ELEMENT_SEGMENTS", InstanceData, element_segments);
+ field!("INSTANCE_MEMORY_COUNT", InstanceData, memory_count);
+ field!("INSTANCE_TAGS", InstanceData, tags);
+ field!("SEGMENT_CONTENTS", Segment, contents);
+ field!("SEGMENT_LENGTH", Segment, length);
+ field!("CONTEXT_STACK_LIMIT", ExecutionContext, stack_limit);
+ field!("CONTEXT_ENTRY_FP", ExecutionContext, entry_fp);
+ field!("CONTEXT_ENTRY_RECORD", ExecutionContext, entry_record);
+ field!("CONTEXT_ARGUMENTS", ExecutionContext, arguments);
+ field!("CONTEXT_RTTS", ExecutionContext, rtts);
+ field!("RTT_KIND", Rtt, kind);
+ field!("RTT_DEPTH", Rtt, depth);
+ field!("RTT_DISPLAY", Rtt, display);
+ field!("RTT_FIELD_OFFSETS", Rtt, field_offsets);
+ field!("RTT_FIELD_KINDS", Rtt, field_kinds);
+ field!("RTT_SIZE", Rtt, size);
+ field!("RTT_FIELD_COUNT", Rtt, field_count);
+ constant("RTT_KIND_FUNCTION", RTT_KIND_FUNCTION as usize);
+ constant("RTT_KIND_STRUCT", RTT_KIND_STRUCT as usize);
+ constant("RTT_KIND_ARRAY", RTT_KIND_ARRAY as usize);
+ constant("STORAGE_64", STORAGE_64 as usize);
+ constant("STORAGE_I8", STORAGE_I8 as usize);
+ constant("STORAGE_I16", STORAGE_I16 as usize);
+ constant("STORAGE_V128", STORAGE_V128 as usize);
+ constant("STORAGE_32", STORAGE_32 as usize);
+ constant("ARRAY_ELEMENTS_OFFSET", ARRAY_ELEMENTS_OFFSET);
+ constant("STRUCT_FIELDS_OFFSET", STRUCT_FIELDS_OFFSET);
+ constant("CONTEXT_ARGUMENT_1", offset_of!(ExecutionContext, arguments) + 8);
+ constant("CONTEXT_ARGUMENT_2", offset_of!(ExecutionContext, arguments) + 16);
+ constant("CONTEXT_ARGUMENT_3", offset_of!(ExecutionContext, arguments) + 24);
+ constant("CONTEXT_ARGUMENT_4", offset_of!(ExecutionContext, arguments) + 32);
+ field!("ENTRY_FUNCTION", EntryRecord, function);
+ field!("ENTRY_ARGUMENTS", EntryRecord, arguments);
+ field!("ENTRY_RESULTS", EntryRecord, results);
+ field!("ENTRY_CONTEXT", EntryRecord, context);
+ field!("ENTRY_TRAP", EntryRecord, trap);
+ field!("ENTRY_SAVED_ENTRY_FP", EntryRecord, saved_entry_fp);
+ field!("ENTRY_SAVED_ENTRY_RECORD", EntryRecord, saved_entry_record);
+ for (name, value) in [
+ ("TRAP_UNREACHABLE", TRAP_UNREACHABLE),
+ ("TRAP_STACK_EXHAUSTED", TRAP_STACK_EXHAUSTED),
+ ("TRAP_MEMORY_OUT_OF_BOUNDS", TRAP_MEMORY_OUT_OF_BOUNDS),
+ ("TRAP_INTEGER_DIVIDE_BY_ZERO", TRAP_INTEGER_DIVIDE_BY_ZERO),
+ ("TRAP_INTEGER_OVERFLOW", TRAP_INTEGER_OVERFLOW),
+ ("TRAP_INVALID_CONVERSION", TRAP_INVALID_CONVERSION),
+ ("TRAP_UNDEFINED_ELEMENT", TRAP_UNDEFINED_ELEMENT),
+ ("TRAP_UNINITIALIZED_ELEMENT", TRAP_UNINITIALIZED_ELEMENT),
+ ("TRAP_INDIRECT_CALL_TYPE_MISMATCH", TRAP_INDIRECT_CALL_TYPE_MISMATCH),
+ ("TRAP_TABLE_OUT_OF_BOUNDS", TRAP_TABLE_OUT_OF_BOUNDS),
+ ("TRAP_NULL_REFERENCE", TRAP_NULL_REFERENCE),
+ ("TRAP_CAST_FAILURE", TRAP_CAST_FAILURE),
+ ("TRAP_ARRAY_OUT_OF_BOUNDS", TRAP_ARRAY_OUT_OF_BOUNDS),
+ ("TRAP_RUNTIME", TRAP_RUNTIME),
+ ("TRAP_UNCAUGHT_EXCEPTION", TRAP_UNCAUGHT_EXCEPTION),
+ ("TRAP_UNALIGNED_ATOMIC", TRAP_UNALIGNED_ATOMIC),
+ ("TRAP_EXPECTED_SHARED_MEMORY", TRAP_EXPECTED_SHARED_MEMORY),
+ ] {
+ constant(name, value as usize);
+ }
+ text
+}
diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rs
new file mode 100644
index 00000000000..ea1051ccda5
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/capi.rs
@@ -0,0 +1,1073 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The C ABI the embedders use: compiling modules, and a store to instantiate them in, call their functions, and
+//! access their memories, tables, and globals.
+//!
+//! Modules are reference counted and immutable, so they can be shared across threads. A store and everything in it
+//! belongs to one thread. Addresses index the store's functions, tables, memories, globals, and instances.
+
+use crate::module::{ExternalKind, ImportDescription, Module};
+use crate::runtime::{
+ ExternValue, FunctionAddress, GlobalAddress, InstanceAddress, InstantiationError, MemoryAddress, Store,
+ TableAddress, TagAddress, Trap, Value,
+};
+use crate::types::{AddressType, FuncType, GlobalType, HeapType, Limits, MemoryType, RefType, TableType, ValType};
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// An owned string, which the embedder releases with `wasm_string_release()`.
+#[repr(C)]
+pub struct WasmString {
+ pub data: *mut u8,
+ pub length: usize,
+}
+
+/// A string borrowed from a module or store, valid while it is.
+#[repr(C)]
+pub struct WasmStringView {
+ pub data: *const u8,
+ pub length: usize,
+}
+
+impl WasmStringView {
+ fn of(text: &str) -> Self {
+ Self {
+ data: text.as_ptr(),
+ length: text.len(),
+ }
+ }
+}
+
+fn write_string(destination: *mut WasmString, text: &str) {
+ if destination.is_null() {
+ return;
+ }
+ let bytes: Box<[u8]> = text.as_bytes().into();
+ let length = bytes.len();
+ unsafe {
+ *destination = WasmString {
+ data: Box::into_raw(bytes).cast(),
+ length,
+ };
+ }
+}
+
+/// Create a string the engine takes ownership of, as a host function's error message.
+///
+/// # Safety
+///
+/// `data` must point at `length` readable bytes, and `string` must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_string_create(data: *const u8, length: usize, string: *mut WasmString) {
+ let text = String::from_utf8_lossy(unsafe { ak::slice_from_raw_parts(data, length) }).into_owned();
+ write_string(string, &text);
+}
+
+/// Release a string the engine returned.
+///
+/// # Safety
+///
+/// The string must come from the engine and not have been released.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_string_release(string: WasmString) {
+ if string.data.is_null() {
+ return;
+ }
+ unsafe {
+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
+ string.data,
+ string.length,
+ )));
+ }
+}
+
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WasmValueKind {
+ I32,
+ I64,
+ F32,
+ F64,
+ V128,
+ Reference,
+}
+
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WasmHeapKind {
+ Function,
+ NoFunction,
+ Extern,
+ NoExtern,
+ Any,
+ Eq,
+ I31,
+ Struct,
+ Array,
+ None,
+ Exception,
+ NoException,
+ /// A type the module defines; `type_index` is its index in the module.
+ Concrete,
+}
+
+/// A value type. `heap`, `nullable`, and `type_index` only matter for references.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct WasmValueType {
+ pub kind: WasmValueKind,
+ pub heap: WasmHeapKind,
+ pub nullable: bool,
+ pub type_index: u32,
+}
+
+impl WasmValueType {
+ fn of(ty: ValType) -> Self {
+ let scalar = |kind| Self {
+ kind,
+ heap: WasmHeapKind::Function,
+ nullable: false,
+ type_index: 0,
+ };
+ match ty {
+ ValType::I32 => scalar(WasmValueKind::I32),
+ ValType::I64 => scalar(WasmValueKind::I64),
+ ValType::F32 => scalar(WasmValueKind::F32),
+ ValType::F64 => scalar(WasmValueKind::F64),
+ ValType::V128 => scalar(WasmValueKind::V128),
+ ValType::Ref(reference) => {
+ let (heap, type_index) = match reference.heap {
+ HeapType::Func => (WasmHeapKind::Function, 0),
+ HeapType::NoFunc => (WasmHeapKind::NoFunction, 0),
+ HeapType::Extern => (WasmHeapKind::Extern, 0),
+ HeapType::NoExtern => (WasmHeapKind::NoExtern, 0),
+ HeapType::Any => (WasmHeapKind::Any, 0),
+ HeapType::Eq => (WasmHeapKind::Eq, 0),
+ HeapType::I31 => (WasmHeapKind::I31, 0),
+ HeapType::Struct => (WasmHeapKind::Struct, 0),
+ HeapType::Array => (WasmHeapKind::Array, 0),
+ HeapType::None | HeapType::Bottom => (WasmHeapKind::None, 0),
+ HeapType::Exn => (WasmHeapKind::Exception, 0),
+ HeapType::NoExn => (WasmHeapKind::NoException, 0),
+ HeapType::Concrete(index) => (WasmHeapKind::Concrete, index),
+ };
+ Self {
+ kind: WasmValueKind::Reference,
+ heap,
+ nullable: reference.nullable,
+ type_index,
+ }
+ }
+ }
+ }
+
+ fn to_value_type(self) -> ValType {
+ match self.kind {
+ WasmValueKind::I32 => ValType::I32,
+ WasmValueKind::I64 => ValType::I64,
+ WasmValueKind::F32 => ValType::F32,
+ WasmValueKind::F64 => ValType::F64,
+ WasmValueKind::V128 => ValType::V128,
+ WasmValueKind::Reference => ValType::Ref(RefType {
+ nullable: self.nullable,
+ heap: match self.heap {
+ WasmHeapKind::Function => HeapType::Func,
+ WasmHeapKind::NoFunction => HeapType::NoFunc,
+ WasmHeapKind::Extern => HeapType::Extern,
+ WasmHeapKind::NoExtern => HeapType::NoExtern,
+ WasmHeapKind::Any => HeapType::Any,
+ WasmHeapKind::Eq => HeapType::Eq,
+ WasmHeapKind::I31 => HeapType::I31,
+ WasmHeapKind::Struct => HeapType::Struct,
+ WasmHeapKind::Array => HeapType::Array,
+ WasmHeapKind::None => HeapType::None,
+ WasmHeapKind::Exception => HeapType::Exn,
+ WasmHeapKind::NoException => HeapType::NoExn,
+ WasmHeapKind::Concrete => HeapType::Concrete(self.type_index),
+ },
+ }),
+ }
+ }
+}
+
+/// A value: i32 and f32 bits in the low 32 bits of `low`, v128 in `low` and `high`, references as their bits (zero
+/// for null).
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct WasmValue {
+ pub kind: WasmValueKind,
+ pub low: u64,
+ pub high: u64,
+}
+
+impl WasmValue {
+ fn of(value: Value) -> Self {
+ let (kind, low, high) = match value {
+ Value::I32(value) => (WasmValueKind::I32, u64::from(value as u32), 0),
+ Value::I64(value) => (WasmValueKind::I64, value as u64, 0),
+ Value::F32(bits) => (WasmValueKind::F32, u64::from(bits), 0),
+ Value::F64(bits) => (WasmValueKind::F64, bits, 0),
+ Value::V128(bits) => (WasmValueKind::V128, bits as u64, (bits >> 64) as u64),
+ Value::Ref(bits) => (WasmValueKind::Reference, bits, 0),
+ };
+ Self { kind, low, high }
+ }
+
+ fn to_value(self) -> Value {
+ match self.kind {
+ WasmValueKind::I32 => Value::I32(self.low as u32 as i32),
+ WasmValueKind::I64 => Value::I64(self.low as i64),
+ WasmValueKind::F32 => Value::F32(self.low as u32),
+ WasmValueKind::F64 => Value::F64(self.low),
+ WasmValueKind::V128 => Value::V128(u128::from(self.low) | (u128::from(self.high) << 64)),
+ WasmValueKind::Reference => Value::Ref(self.low),
+ }
+ }
+}
+
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WasmExternKind {
+ Function,
+ Table,
+ Memory,
+ Global,
+ Tag,
+}
+
+impl WasmExternKind {
+ fn of(kind: ExternalKind) -> Self {
+ match kind {
+ ExternalKind::Function => Self::Function,
+ ExternalKind::Table => Self::Table,
+ ExternalKind::Memory => Self::Memory,
+ ExternalKind::Global => Self::Global,
+ ExternalKind::Tag => Self::Tag,
+ }
+ }
+}
+
+/// A function, table, memory, or global of a store.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct WasmExtern {
+ pub kind: WasmExternKind,
+ pub address: u32,
+}
+
+impl WasmExtern {
+ fn of(value: ExternValue) -> Self {
+ let (kind, address) = match value {
+ ExternValue::Function(address) => (WasmExternKind::Function, address.0),
+ ExternValue::Table(address) => (WasmExternKind::Table, address.0),
+ ExternValue::Memory(address) => (WasmExternKind::Memory, address.0),
+ ExternValue::Global(address) => (WasmExternKind::Global, address.0),
+ ExternValue::Tag(address) => (WasmExternKind::Tag, address.0),
+ };
+ Self { kind, address }
+ }
+
+ fn to_extern_value(self) -> ExternValue {
+ match self.kind {
+ WasmExternKind::Function => ExternValue::Function(FunctionAddress(self.address)),
+ WasmExternKind::Table => ExternValue::Table(TableAddress(self.address)),
+ WasmExternKind::Memory => ExternValue::Memory(MemoryAddress(self.address)),
+ WasmExternKind::Global => ExternValue::Global(GlobalAddress(self.address)),
+ WasmExternKind::Tag => ExternValue::Tag(TagAddress(self.address)),
+ }
+ }
+}
+
+/// The limits of a memory or table. `maximum` only matters if `has_maximum` is set.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct WasmLimits {
+ pub minimum: u64,
+ pub maximum: u64,
+ pub has_maximum: bool,
+ pub address64: bool,
+ pub shared: bool,
+}
+
+impl WasmLimits {
+ fn of(limits: &Limits) -> Self {
+ Self {
+ minimum: limits.min,
+ maximum: limits.max.unwrap_or(0),
+ has_maximum: limits.max.is_some(),
+ address64: limits.address_type == AddressType::I64,
+ shared: limits.shared,
+ }
+ }
+
+ fn to_limits(self) -> Limits {
+ Limits {
+ min: self.minimum,
+ max: self.has_maximum.then_some(self.maximum),
+ address_type: if self.address64 {
+ AddressType::I64
+ } else {
+ AddressType::I32
+ },
+ shared: self.shared,
+ }
+ }
+}
+
+/// What an import or export is, beyond its kind: the type index of a function or tag, the limits of a memory or
+/// table, the element type of a table, and the value type and mutability of a global.
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct WasmExternType {
+ pub kind: WasmExternKind,
+ pub type_index: u32,
+ pub limits: WasmLimits,
+ pub value_type: WasmValueType,
+ pub mutable: bool,
+}
+
+fn extern_type_of_import(description: &ImportDescription) -> WasmExternType {
+ let mut ty = WasmExternType {
+ kind: WasmExternKind::Function,
+ type_index: 0,
+ limits: WasmLimits::of(&Limits {
+ min: 0,
+ max: None,
+ address_type: AddressType::I32,
+ shared: false,
+ }),
+ value_type: WasmValueType::of(ValType::I32),
+ mutable: false,
+ };
+ match description {
+ ImportDescription::Function(index) => ty.type_index = *index,
+ ImportDescription::Table(table) => {
+ ty.kind = WasmExternKind::Table;
+ ty.limits = WasmLimits::of(&table.limits);
+ ty.value_type = WasmValueType::of(ValType::Ref(table.element));
+ }
+ ImportDescription::Memory(memory) => {
+ ty.kind = WasmExternKind::Memory;
+ ty.limits = WasmLimits::of(&memory.limits);
+ }
+ ImportDescription::Global(global) => {
+ ty.kind = WasmExternKind::Global;
+ ty.value_type = WasmValueType::of(global.value);
+ ty.mutable = global.mutable;
+ }
+ ImportDescription::Tag(tag) => {
+ ty.kind = WasmExternKind::Tag;
+ ty.type_index = tag.type_index;
+ }
+ }
+ ty
+}
+
+// Modules.
+
+/// A compiled module. The embedder holds it through `wasm_module_retain()` and `wasm_module_release()`.
+pub struct WasmModule(Arc<Module>);
+
+/// Decode and validate a module. Returns null and sets `error` if the module is malformed or invalid.
+///
+/// # Safety
+///
+/// `bytes` must point at `length` readable bytes, and `error` must be null or writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_compile(
+ bytes: *const u8,
+ length: usize,
+ error: *mut WasmString,
+) -> *const WasmModule {
+ let bytes = unsafe { ak::slice_from_raw_parts(bytes, length) };
+ match crate::compile(bytes) {
+ Ok(module) => Arc::into_raw(Arc::new(WasmModule(Arc::new(module)))),
+ Err(compile_error) => {
+ write_string(error, &compile_error.to_string());
+ std::ptr::null()
+ }
+ }
+}
+
+/// # Safety
+///
+/// `module` must be a live module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_retain(module: *const WasmModule) {
+ unsafe { Arc::increment_strong_count(module) };
+}
+
+/// # Safety
+///
+/// `module` must be a live module, which this releases one reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_release(module: *const WasmModule) {
+ unsafe { Arc::decrement_strong_count(module) };
+}
+
+fn module_of<'a>(module: *const WasmModule) -> &'a Module {
+ unsafe { &(*module).0 }
+}
+
+/// # Safety
+///
+/// `module` must be a live module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_import_count(module: *const WasmModule) -> usize {
+ module_of(module).imports.len()
+}
+
+/// The names and type of an import.
+///
+/// # Safety
+///
+/// `module` must be a live module with an import at `index`, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_import(
+ module: *const WasmModule,
+ index: usize,
+ module_name: *mut WasmStringView,
+ name: *mut WasmStringView,
+ ty: *mut WasmExternType,
+) {
+ let import = &module_of(module).imports[index];
+ unsafe {
+ *module_name = WasmStringView::of(&import.module);
+ *name = WasmStringView::of(&import.name);
+ *ty = extern_type_of_import(&import.description);
+ }
+}
+
+/// # Safety
+///
+/// `module` must be a live module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_export_count(module: *const WasmModule) -> usize {
+ module_of(module).exports.len()
+}
+
+/// The name and type of an export.
+///
+/// # Safety
+///
+/// `module` must be a live module with an export at `index`, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_export(
+ module: *const WasmModule,
+ index: usize,
+ name: *mut WasmStringView,
+ ty: *mut WasmExternType,
+) {
+ let module = module_of(module);
+ let export = &module.exports[index];
+ let description = match export.kind {
+ ExternalKind::Function => ImportDescription::Function(module.function_space[export.index as usize]),
+ ExternalKind::Table => ImportDescription::Table(module.table_space[export.index as usize]),
+ ExternalKind::Memory => ImportDescription::Memory(module.memory_space[export.index as usize]),
+ ExternalKind::Global => ImportDescription::Global(module.global_space[export.index as usize]),
+ ExternalKind::Tag => ImportDescription::Tag(module.tag_space[export.index as usize]),
+ };
+ unsafe {
+ *name = WasmStringView::of(&export.name);
+ *ty = extern_type_of_import(&description);
+ (*ty).kind = WasmExternKind::of(export.kind);
+ }
+}
+
+/// The parameter and result counts of the function type at `type_index`, or false if it is not a function type.
+///
+/// # Safety
+///
+/// `module` must be a live module, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_function_type(
+ module: *const WasmModule,
+ type_index: u32,
+ parameter_count: *mut usize,
+ result_count: *mut usize,
+) -> bool {
+ let Some(function) = module_of(module)
+ .types
+ .get(type_index as usize)
+ .and_then(|ty| ty.as_func())
+ else {
+ return false;
+ };
+ unsafe {
+ *parameter_count = function.params.len();
+ *result_count = function.results.len();
+ }
+ true
+}
+
+/// Copy the parameter and result types of the function type at `type_index`.
+///
+/// # Safety
+///
+/// `module` must be a live module with a function type at `type_index`, and the out arrays must have room for its
+/// parameters and results.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_function_type_values(
+ module: *const WasmModule,
+ type_index: u32,
+ parameters: *mut WasmValueType,
+ results: *mut WasmValueType,
+) {
+ let function = module_of(module).types[type_index as usize]
+ .as_func()
+ .expect("the embedder checks for a function type");
+ unsafe { write_function_type(function, parameters, results) };
+}
+
+unsafe fn write_function_type(function: &FuncType, parameters: *mut WasmValueType, results: *mut WasmValueType) {
+ for (index, &ty) in function.params.iter().enumerate() {
+ unsafe { *parameters.add(index) = WasmValueType::of(ty) };
+ }
+ for (index, &ty) in function.results.iter().enumerate() {
+ unsafe { *results.add(index) = WasmValueType::of(ty) };
+ }
+}
+
+// Stores.
+
+/// A store, which belongs to the thread that created it.
+pub struct WasmStore(Store);
+
+/// Create a store for the current thread.
+#[unsafe(no_mangle)]
+pub extern "C" fn wasm_store_create() -> *mut WasmStore {
+ Box::into_raw(Box::new(WasmStore(Store::new())))
+}
+
+/// # Safety
+///
+/// `store` must be a live store that no call is running in.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_destroy(store: *mut WasmStore) {
+ unsafe { drop(Box::from_raw(store)) };
+}
+
+fn store_of<'a>(store: *mut WasmStore) -> &'a mut Store {
+ unsafe { &mut (*store).0 }
+}
+
+#[repr(u8)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WasmStatus {
+ Ok,
+ /// Linking failed: an import is missing or has the wrong type.
+ LinkError,
+ /// Execution trapped.
+ Trap,
+}
+
+/// A function the embedder implements. It reads the arguments and writes the results, in the order of the function
+/// type, and returns false with a message in `error` to trap.
+pub type WasmHostCallback = unsafe extern "C" fn(
+ user_data: *mut std::ffi::c_void,
+ store: *mut WasmStore,
+ arguments: *const WasmValue,
+ argument_count: usize,
+ results: *mut WasmValue,
+ result_count: usize,
+ error: *mut WasmString,
+) -> bool;
+
+/// Releases the user data of a host function when the store is destroyed.
+pub type WasmReleaseCallback = unsafe extern "C" fn(user_data: *mut std::ffi::c_void);
+
+struct HostFunctionData {
+ callback: WasmHostCallback,
+ user_data: *mut std::ffi::c_void,
+ release: WasmReleaseCallback,
+}
+
+impl Drop for HostFunctionData {
+ fn drop(&mut self) {
+ unsafe { (self.release)(self.user_data) };
+ }
+}
+
+/// Add a host function of the given type to the store, and return its address.
+///
+/// # Safety
+///
+/// `store` must be a live store, and the type arrays must hold the given numbers of types.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_host_function(
+ store: *mut WasmStore,
+ parameters: *const WasmValueType,
+ parameter_count: usize,
+ results: *const WasmValueType,
+ result_count: usize,
+ callback: WasmHostCallback,
+ user_data: *mut std::ffi::c_void,
+ release: WasmReleaseCallback,
+) -> u32 {
+ let to_types = |types: *const WasmValueType, count: usize| -> Vec<ValType> {
+ unsafe { ak::slice_from_raw_parts(types, count) }
+ .iter()
+ .map(|ty| ty.to_value_type())
+ .collect()
+ };
+ let ty = FuncType {
+ params: to_types(parameters, parameter_count),
+ results: to_types(results, result_count),
+ };
+ let wasm_store = store;
+ let data = Rc::new(HostFunctionData {
+ callback,
+ user_data,
+ release,
+ });
+ let result_count = ty.results.len();
+ let address = store_of(store).allocate_host_function(
+ ty,
+ // The callback gets the store it runs in, which is this one.
+ Rc::new(move |_: &mut Store, arguments: &[Value]| {
+ let arguments: Vec<WasmValue> = arguments.iter().map(|&value| WasmValue::of(value)).collect();
+ let mut results = vec![
+ WasmValue {
+ kind: WasmValueKind::I32,
+ low: 0,
+ high: 0,
+ };
+ result_count
+ ];
+ let mut error = WasmString {
+ data: std::ptr::null_mut(),
+ length: 0,
+ };
+ let succeeded = unsafe {
+ (data.callback)(
+ data.user_data,
+ wasm_store,
+ arguments.as_ptr(),
+ arguments.len(),
+ results.as_mut_ptr(),
+ results.len(),
+ &raw mut error,
+ )
+ };
+ if !succeeded {
+ let message = if error.data.is_null() {
+ String::new()
+ } else {
+ let bytes = unsafe { ak::slice_from_raw_parts(error.data, error.length) };
+ let message = String::from_utf8_lossy(bytes).into_owned();
+ unsafe { wasm_string_release(error) };
+ message
+ };
+ return Err(Trap::Host(message));
+ }
+ Ok(results.into_iter().map(WasmValue::to_value).collect())
+ }),
+ );
+ address.0
+}
+
+/// Add a memory to the store. Returns false if it cannot be allocated.
+///
+/// # Safety
+///
+/// `store` must be a live store, and `address` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_memory(
+ store: *mut WasmStore,
+ limits: WasmLimits,
+ address: *mut u32,
+) -> bool {
+ let Some(allocated) = store_of(store).allocate_memory(MemoryType {
+ limits: limits.to_limits(),
+ }) else {
+ return false;
+ };
+ unsafe { *address = allocated.0 };
+ true
+}
+
+/// Add a table to the store, with every element set to `initial`.
+///
+/// # Safety
+///
+/// `store` must be a live store.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_table(
+ store: *mut WasmStore,
+ element: WasmValueType,
+ limits: WasmLimits,
+ initial: u64,
+) -> u32 {
+ let ValType::Ref(element) = element.to_value_type() else {
+ panic!("table elements are references");
+ };
+ store_of(store)
+ .allocate_table(
+ TableType {
+ element,
+ limits: limits.to_limits(),
+ },
+ initial,
+ )
+ .0
+}
+
+/// Add a global to the store.
+///
+/// # Safety
+///
+/// `store` must be a live store.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_global(
+ store: *mut WasmStore,
+ ty: WasmValueType,
+ mutable: bool,
+ value: WasmValue,
+) -> u32 {
+ store_of(store)
+ .allocate_global(
+ GlobalType {
+ value: ty.to_value_type(),
+ mutable,
+ },
+ value.to_value(),
+ )
+ .0
+}
+
+/// Instantiate `module` with `imports`, one for each of its imports in order. On success, writes the instance's
+/// address; otherwise writes a message to `error`.
+///
+/// # Safety
+///
+/// `store` and `module` must be live, `imports` must hold `import_count` externs, and the out parameters must be
+/// writable (`error` may be null).
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_instantiate(
+ store: *mut WasmStore,
+ module: *const WasmModule,
+ imports: *const WasmExtern,
+ import_count: usize,
+ instance: *mut u32,
+ error: *mut WasmString,
+) -> WasmStatus {
+ let mut values = Vec::with_capacity(import_count);
+ for import in unsafe { ak::slice_from_raw_parts(imports, import_count) } {
+ values.push(import.to_extern_value());
+ }
+ let module = unsafe { (*module).0.clone() };
+ match store_of(store).instantiate(module, &values) {
+ Ok(address) => {
+ unsafe { *instance = address.0 };
+ WasmStatus::Ok
+ }
+ Err(InstantiationError::Link(message)) => {
+ write_string(error, &message);
+ WasmStatus::LinkError
+ }
+ Err(InstantiationError::Trap(trap)) => {
+ write_string(error, &trap.message());
+ WasmStatus::Trap
+ }
+ }
+}
+
+/// The number of exports of an instance.
+///
+/// # Safety
+///
+/// `store` must be a live store with an instance at `instance`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_instance_export_count(store: *mut WasmStore, instance: u32) -> usize {
+ store_of(store).instance(InstanceAddress(instance)).module.exports.len()
+}
+
+/// The name and value of an instance's export, in the module's order.
+///
+/// # Safety
+///
+/// `store` must be a live store with an instance at `instance` that has an export at `index`, and the out parameters
+/// must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_instance_export(
+ store: *mut WasmStore,
+ instance: u32,
+ index: usize,
+ name: *mut WasmStringView,
+ value: *mut WasmExtern,
+) -> bool {
+ let instance = store_of(store).instance(InstanceAddress(instance));
+ let export = &instance.module.exports[index];
+ unsafe { *name = WasmStringView::of(&export.name) };
+ let Some(extern_value) = instance.export(&export.name) else {
+ return false;
+ };
+ unsafe { *value = WasmExtern::of(extern_value) };
+ true
+}
+
+/// Find an instance's export by name.
+///
+/// # Safety
+///
+/// `store` must be a live store with an instance at `instance`, `name` must hold `length` bytes, and `value` must be
+/// writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_instance_find_export(
+ store: *mut WasmStore,
+ instance: u32,
+ name: *const u8,
+ length: usize,
+ value: *mut WasmExtern,
+) -> bool {
+ let name = unsafe { ak::slice_from_raw_parts(name, length) };
+ let Ok(name) = std::str::from_utf8(name) else {
+ return false;
+ };
+ let Some(extern_value) = store_of(store).instance(InstanceAddress(instance)).export(name) else {
+ return false;
+ };
+ unsafe { *value = WasmExtern::of(extern_value) };
+ true
+}
+
+/// The parameter and result counts of a function.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_function_type(
+ store: *mut WasmStore,
+ function: u32,
+ parameter_count: *mut usize,
+ result_count: *mut usize,
+) {
+ let ty = &store_of(store).function(FunctionAddress(function)).ty;
+ unsafe {
+ *parameter_count = ty.params.len();
+ *result_count = ty.results.len();
+ }
+}
+
+/// Copy the parameter and result types of a function.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`, and the out arrays must have room for its parameters
+/// and results.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_function_type_values(
+ store: *mut WasmStore,
+ function: u32,
+ parameters: *mut WasmValueType,
+ results: *mut WasmValueType,
+) {
+ let ty = &store_of(store).function(FunctionAddress(function)).ty;
+ unsafe { write_function_type(ty, parameters, results) };
+}
+
+/// Call a function. On a trap, writes its message to `error`.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`, `arguments` must hold one value for each parameter,
+/// `results` must have room for one value for each result, and `error` must be null or writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_invoke(
+ store: *mut WasmStore,
+ function: u32,
+ arguments: *const WasmValue,
+ argument_count: usize,
+ results: *mut WasmValue,
+ result_count: usize,
+ error: *mut WasmString,
+) -> WasmStatus {
+ let arguments: Vec<Value> = unsafe { ak::slice_from_raw_parts(arguments, argument_count) }
+ .iter()
+ .map(|value| value.to_value())
+ .collect();
+ match store_of(store).invoke(FunctionAddress(function), &arguments) {
+ Ok(values) => {
+ for (index, value) in values.into_iter().take(result_count).enumerate() {
+ unsafe { *results.add(index) = WasmValue::of(value) };
+ }
+ WasmStatus::Ok
+ }
+ Err(trap) => {
+ write_string(error, &trap.message());
+ WasmStatus::Trap
+ }
+ }
+}
+
+/// The reference to a function, as tables and reference values hold it.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_function_reference(store: *mut WasmStore, function: u32) -> u64 {
+ store_of(store).function_reference(FunctionAddress(function))
+}
+
+/// The function a function reference refers to. Returns false for null.
+///
+/// # Safety
+///
+/// `store` must be a live store, `reference` a function reference of it, and `function` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_function_from_reference(
+ store: *mut WasmStore,
+ reference: u64,
+ function: *mut u32,
+) -> bool {
+ let Some(address) = store_of(store).function_from_reference(reference) else {
+ return false;
+ };
+ unsafe { *function = address.0 };
+ true
+}
+
+/// The bytes of a memory, which move when it grows.
+///
+/// # Safety
+///
+/// `store` must be a live store with a memory at `memory`, and `size` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_memory_data(store: *mut WasmStore, memory: u32, size: *mut usize) -> *mut u8 {
+ let memory = store_of(store).memory_mut(MemoryAddress(memory));
+ unsafe { *size = memory.size() };
+ memory.bytes_mut().as_mut_ptr()
+}
+
+/// Grow a memory by `delta` pages. Returns the previous size in pages, or -1 if it cannot grow.
+///
+/// # Safety
+///
+/// `store` must be a live store with a memory at `memory`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_memory_grow(store: *mut WasmStore, memory: u32, delta: u64) -> i64 {
+ store_of(store)
+ .memory_mut(MemoryAddress(memory))
+ .grow(delta)
+ .map_or(-1, |previous| previous as i64)
+}
+
+/// The limits a memory was created with.
+///
+/// # Safety
+///
+/// `store` must be a live store with a memory at `memory`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_memory_limits(store: *mut WasmStore, memory: u32) -> WasmLimits {
+ WasmLimits::of(&store_of(store).memory(MemoryAddress(memory)).ty.limits)
+}
+
+/// # Safety
+///
+/// `store` must be a live store with a table at `table`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_table_size(store: *mut WasmStore, table: u32) -> u64 {
+ store_of(store).table(TableAddress(table)).elements.len() as u64
+}
+
+/// The element type and limits a table was created with.
+///
+/// # Safety
+///
+/// `store` must be a live store with a table at `table`, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_table_type(
+ store: *mut WasmStore,
+ table: u32,
+ element: *mut WasmValueType,
+ limits: *mut WasmLimits,
+) {
+ let table = store_of(store).table(TableAddress(table));
+ unsafe {
+ *element = WasmValueType::of(ValType::Ref(table.ty.element));
+ *limits = WasmLimits::of(&table.ty.limits);
+ }
+}
+
+/// Read a table element. Returns false if `index` is out of bounds.
+///
+/// # Safety
+///
+/// `store` must be a live store with a table at `table`, and `value` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_table_get(store: *mut WasmStore, table: u32, index: u64, value: *mut u64) -> bool {
+ let Some(&element) = store_of(store).table(TableAddress(table)).elements.get(index as usize) else {
+ return false;
+ };
+ unsafe { *value = element };
+ true
+}
+
+/// Write a table element. Returns false if `index` is out of bounds.
+///
+/// # Safety
+///
+/// `store` must be a live store with a table at `table`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_table_set(store: *mut WasmStore, table: u32, index: u64, value: u64) -> bool {
+ let Some(element) = store_of(store)
+ .table_mut(TableAddress(table))
+ .elements
+ .get_mut(index as usize)
+ else {
+ return false;
+ };
+ *element = value;
+ true
+}
+
+/// Grow a table by `delta` elements set to `initial`. Returns the previous size, or -1 if it cannot grow.
+///
+/// # Safety
+///
+/// `store` must be a live store with a table at `table`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_table_grow(store: *mut WasmStore, table: u32, delta: u64, initial: u64) -> i64 {
+ store_of(store)
+ .table_mut(TableAddress(table))
+ .grow(delta, initial)
+ .map_or(-1, |previous| previous as i64)
+}
+
+/// The type of a global.
+///
+/// # Safety
+///
+/// `store` must be a live store with a global at `global`, and `mutable` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_global_type(
+ store: *mut WasmStore,
+ global: u32,
+ mutable: *mut bool,
+) -> WasmValueType {
+ let ty = store_of(store).global(GlobalAddress(global)).ty;
+ unsafe { *mutable = ty.mutable };
+ WasmValueType::of(ty.value)
+}
+
+/// # Safety
+///
+/// `store` must be a live store with a global at `global`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_global_get(store: *mut WasmStore, global: u32) -> WasmValue {
+ WasmValue::of(store_of(store).global(GlobalAddress(global)).get())
+}
+
+/// # Safety
+///
+/// `store` must be a live store with a global at `global`, and `value` must have the global's type.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_global_set(store: *mut WasmStore, global: u32, value: WasmValue) {
+ store_of(store).global_mut(GlobalAddress(global)).set(value.to_value());
+}
diff --git a/Libraries/LibWasm/Engine/src/error.rs b/Libraries/LibWasm/Engine/src/error.rs
new file mode 100644
index 00000000000..b11380e911b
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/error.rs
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::fmt;
+
+/// Why a module was rejected: its bytes do not follow the binary format, or it breaks a validation rule.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Error {
+ Malformed(String),
+ Invalid(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+impl Error {
+ pub fn malformed(message: impl Into<String>) -> Self {
+ Self::Malformed(message.into())
+ }
+
+ pub fn invalid(message: impl Into<String>) -> Self {
+ Self::Invalid(message.into())
+ }
+
+ pub fn message(&self) -> &str {
+ match self {
+ Self::Malformed(message) | Self::Invalid(message) => message,
+ }
+ }
+
+ pub fn is_malformed(&self) -> bool {
+ matches!(self, Self::Malformed(_))
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Malformed(message) => write!(formatter, "malformed module: {message}"),
+ Self::Invalid(message) => write!(formatter, "invalid module: {message}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
diff --git a/Libraries/LibWasm/Engine/src/instruction_tables.rs b/Libraries/LibWasm/Engine/src/instruction_tables.rs
new file mode 100644
index 00000000000..2dcbc07680d
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/instruction_tables.rs
@@ -0,0 +1,622 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! How the vector and atomic instructions are typed, by sub-opcode.
+
+use crate::types::ValType;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SimdKind {
+ /// Loads `size` bytes from memory into a vector.
+ Load {
+ size: u32,
+ },
+ Store {
+ size: u32,
+ },
+ /// Loads `size` bytes into one lane of a vector operand.
+ LoadLane {
+ size: u32,
+ },
+ StoreLane {
+ size: u32,
+ },
+ Const,
+ Shuffle,
+ ExtractLane {
+ lanes: u8,
+ result: ValType,
+ },
+ ReplaceLane {
+ lanes: u8,
+ operand: ValType,
+ },
+ Splat(ValType),
+ /// A vector and an i32 shift count.
+ Shift,
+ /// A vector reduced to an i32.
+ Test,
+ Unary,
+ Binary,
+ Ternary,
+}
+
+pub fn simd_kind(sub_opcode: u32) -> Option<SimdKind> {
+ Some(match sub_opcode {
+ 0x0 => SimdKind::Load { size: 16 }, // v128_load
+ 0x1 => SimdKind::Load { size: 8 }, // v128_load8x8_s
+ 0x2 => SimdKind::Load { size: 8 }, // v128_load8x8_u
+ 0x3 => SimdKind::Load { size: 8 }, // v128_load16x4_s
+ 0x4 => SimdKind::Load { size: 8 }, // v128_load16x4_u
+ 0x5 => SimdKind::Load { size: 8 }, // v128_load32x2_s
+ 0x6 => SimdKind::Load { size: 8 }, // v128_load32x2_u
+ 0x7 => SimdKind::Load { size: 1 }, // v128_load8_splat
+ 0x8 => SimdKind::Load { size: 2 }, // v128_load16_splat
+ 0x9 => SimdKind::Load { size: 4 }, // v128_load32_splat
+ 0xa => SimdKind::Load { size: 8 }, // v128_load64_splat
+ 0xb => SimdKind::Store { size: 16 }, // v128_store
+ 0xc => SimdKind::Const, // v128_const
+ 0xd => SimdKind::Shuffle, // i8x16_shuffle
+ 0xe => SimdKind::Binary, // i8x16_swizzle
+ 0xf => SimdKind::Splat(ValType::I32), // i8x16_splat
+ 0x10 => SimdKind::Splat(ValType::I32), // i16x8_splat
+ 0x11 => SimdKind::Splat(ValType::I32), // i32x4_splat
+ 0x12 => SimdKind::Splat(ValType::I64), // i64x2_splat
+ 0x13 => SimdKind::Splat(ValType::F32), // f32x4_splat
+ 0x14 => SimdKind::Splat(ValType::F64), // f64x2_splat
+ 0x15 => SimdKind::ExtractLane {
+ lanes: 16,
+ result: ValType::I32,
+ }, // i8x16_extract_lane_s
+ 0x16 => SimdKind::ExtractLane {
+ lanes: 16,
+ result: ValType::I32,
+ }, // i8x16_extract_lane_u
+ 0x17 => SimdKind::ReplaceLane {
+ lanes: 16,
+ operand: ValType::I32,
+ }, // i8x16_replace_lane
+ 0x18 => SimdKind::ExtractLane {
+ lanes: 8,
+ result: ValType::I32,
+ }, // i16x8_extract_lane_s
+ 0x19 => SimdKind::ExtractLane {
+ lanes: 8,
+ result: ValType::I32,
+ }, // i16x8_extract_lane_u
+ 0x1a => SimdKind::ReplaceLane {
+ lanes: 8,
+ operand: ValType::I32,
+ }, // i16x8_replace_lane
+ 0x1b => SimdKind::ExtractLane {
+ lanes: 4,
+ result: ValType::I32,
+ }, // i32x4_extract_lane
+ 0x1c => SimdKind::ReplaceLane {
+ lanes: 4,
+ operand: ValType::I32,
+ }, // i32x4_replace_lane
+ 0x1d => SimdKind::ExtractLane {
+ lanes: 2,
+ result: ValType::I64,
+ }, // i64x2_extract_lane
+ 0x1e => SimdKind::ReplaceLane {
+ lanes: 2,
+ operand: ValType::I64,
+ }, // i64x2_replace_lane
+ 0x1f => SimdKind::ExtractLane {
+ lanes: 4,
+ result: ValType::F32,
+ }, // f32x4_extract_lane
+ 0x20 => SimdKind::ReplaceLane {
+ lanes: 4,
+ operand: ValType::F32,
+ }, // f32x4_replace_lane
+ 0x21 => SimdKind::ExtractLane {
+ lanes: 2,
+ result: ValType::F64,
+ }, // f64x2_extract_lane
+ 0x22 => SimdKind::ReplaceLane {
+ lanes: 2,
+ operand: ValType::F64,
+ }, // f64x2_replace_lane
+ 0x23 => SimdKind::Binary, // i8x16_eq
+ 0x24 => SimdKind::Binary, // i8x16_ne
+ 0x25 => SimdKind::Binary, // i8x16_lt_s
+ 0x26 => SimdKind::Binary, // i8x16_lt_u
+ 0x27 => SimdKind::Binary, // i8x16_gt_s
+ 0x28 => SimdKind::Binary, // i8x16_gt_u
+ 0x29 => SimdKind::Binary, // i8x16_le_s
+ 0x2a => SimdKind::Binary, // i8x16_le_u
+ 0x2b => SimdKind::Binary, // i8x16_ge_s
+ 0x2c => SimdKind::Binary, // i8x16_ge_u
+ 0x2d => SimdKind::Binary, // i16x8_eq
+ 0x2e => SimdKind::Binary, // i16x8_ne
+ 0x2f => SimdKind::Binary, // i16x8_lt_s
+ 0x30 => SimdKind::Binary, // i16x8_lt_u
+ 0x31 => SimdKind::Binary, // i16x8_gt_s
+ 0x32 => SimdKind::Binary, // i16x8_gt_u
+ 0x33 => SimdKind::Binary, // i16x8_le_s
+ 0x34 => SimdKind::Binary, // i16x8_le_u
+ 0x35 => SimdKind::Binary, // i16x8_ge_s
+ 0x36 => SimdKind::Binary, // i16x8_ge_u
+ 0x37 => SimdKind::Binary, // i32x4_eq
+ 0x38 => SimdKind::Binary, // i32x4_ne
+ 0x39 => SimdKind::Binary, // i32x4_lt_s
+ 0x3a => SimdKind::Binary, // i32x4_lt_u
+ 0x3b => SimdKind::Binary, // i32x4_gt_s
+ 0x3c => SimdKind::Binary, // i32x4_gt_u
+ 0x3d => SimdKind::Binary, // i32x4_le_s
+ 0x3e => SimdKind::Binary, // i32x4_le_u
+ 0x3f => SimdKind::Binary, // i32x4_ge_s
+ 0x40 => SimdKind::Binary, // i32x4_ge_u
+ 0x41 => SimdKind::Binary, // f32x4_eq
+ 0x42 => SimdKind::Binary, // f32x4_ne
+ 0x43 => SimdKind::Binary, // f32x4_lt
+ 0x44 => SimdKind::Binary, // f32x4_gt
+ 0x45 => SimdKind::Binary, // f32x4_le
+ 0x46 => SimdKind::Binary, // f32x4_ge
+ 0x47 => SimdKind::Binary, // f64x2_eq
+ 0x48 => SimdKind::Binary, // f64x2_ne
+ 0x49 => SimdKind::Binary, // f64x2_lt
+ 0x4a => SimdKind::Binary, // f64x2_gt
+ 0x4b => SimdKind::Binary, // f64x2_le
+ 0x4c => SimdKind::Binary, // f64x2_ge
+ 0x4d => SimdKind::Unary, // v128_not
+ 0x4e => SimdKind::Binary, // v128_and
+ 0x4f => SimdKind::Binary, // v128_andnot
+ 0x50 => SimdKind::Binary, // v128_or
+ 0x51 => SimdKind::Binary, // v128_xor
+ 0x52 => SimdKind::Ternary, // v128_bitselect
+ 0x53 => SimdKind::Test, // v128_any_true
+ 0x54 => SimdKind::LoadLane { size: 1 }, // v128_load8_lane
+ 0x55 => SimdKind::LoadLane { size: 2 }, // v128_load16_lane
+ 0x56 => SimdKind::LoadLane { size: 4 }, // v128_load32_lane
+ 0x57 => SimdKind::LoadLane { size: 8 }, // v128_load64_lane
+ 0x58 => SimdKind::StoreLane { size: 1 }, // v128_store8_lane
+ 0x59 => SimdKind::StoreLane { size: 2 }, // v128_store16_lane
+ 0x5a => SimdKind::StoreLane { size: 4 }, // v128_store32_lane
+ 0x5b => SimdKind::StoreLane { size: 8 }, // v128_store64_lane
+ 0x5c => SimdKind::Load { size: 4 }, // v128_load32_zero
+ 0x5d => SimdKind::Load { size: 8 }, // v128_load64_zero
+ 0x5e => SimdKind::Unary, // f32x4_demote_f64x2_zero
+ 0x5f => SimdKind::Unary, // f64x2_promote_low_f32x4
+ 0x60 => SimdKind::Unary, // i8x16_abs
+ 0x61 => SimdKind::Unary, // i8x16_neg
+ 0x62 => SimdKind::Unary, // i8x16_popcnt
+ 0x63 => SimdKind::Test, // i8x16_all_true
+ 0x64 => SimdKind::Test, // i8x16_bitmask
+ 0x65 => SimdKind::Binary, // i8x16_narrow_i16x8_s
+ 0x66 => SimdKind::Binary, // i8x16_narrow_i16x8_u
+ 0x67 => SimdKind::Unary, // f32x4_ceil
+ 0x68 => SimdKind::Unary, // f32x4_floor
+ 0x69 => SimdKind::Unary, // f32x4_trunc
+ 0x6a => SimdKind::Unary, // f32x4_nearest
+ 0x6b => SimdKind::Shift, // i8x16_shl
+ 0x6c => SimdKind::Shift, // i8x16_shr_s
+ 0x6d => SimdKind::Shift, // i8x16_shr_u
+ 0x6e => SimdKind::Binary, // i8x16_add
+ 0x6f => SimdKind::Binary, // i8x16_add_sat_s
+ 0x70 => SimdKind::Binary, // i8x16_add_sat_u
+ 0x71 => SimdKind::Binary, // i8x16_sub
+ 0x72 => SimdKind::Binary, // i8x16_sub_sat_s
+ 0x73 => SimdKind::Binary, // i8x16_sub_sat_u
+ 0x74 => SimdKind::Unary, // f64x2_ceil
+ 0x75 => SimdKind::Unary, // f64x2_floor
+ 0x76 => SimdKind::Binary, // i8x16_min_s
+ 0x77 => SimdKind::Binary, // i8x16_min_u
+ 0x78 => SimdKind::Binary, // i8x16_max_s
+ 0x79 => SimdKind::Binary, // i8x16_max_u
+ 0x7a => SimdKind::Unary, // f64x2_trunc
+ 0x7b => SimdKind::Binary, // i8x16_avgr_u
+ 0x7c => SimdKind::Unary, // i16x8_extadd_pairwise_i8x16_s
+ 0x7d => SimdKind::Unary, // i16x8_extadd_pairwise_i8x16_u
+ 0x7e => SimdKind::Unary, // i32x4_extadd_pairwise_i16x8_s
+ 0x7f => SimdKind::Unary, // i32x4_extadd_pairwise_i16x8_u
+ 0x80 => SimdKind::Unary, // i16x8_abs
+ 0x81 => SimdKind::Unary, // i16x8_neg
+ 0x82 => SimdKind::Binary, // i16x8_q15mulr_sat_s
+ 0x83 => SimdKind::Test, // i16x8_all_true
+ 0x84 => SimdKind::Test, // i16x8_bitmask
+ 0x85 => SimdKind::Binary, // i16x8_narrow_i32x4_s
+ 0x86 => SimdKind::Binary, // i16x8_narrow_i32x4_u
+ 0x87 => SimdKind::Unary, // i16x8_extend_low_i8x16_s
+ 0x88 => SimdKind::Unary, // i16x8_extend_high_i8x16_s
+ 0x89 => SimdKind::Unary, // i16x8_extend_low_i8x16_u
+ 0x8a => SimdKind::Unary, // i16x8_extend_high_i8x16_u
+ 0x8b => SimdKind::Shift, // i16x8_shl
+ 0x8c => SimdKind::Shift, // i16x8_shr_s
+ 0x8d => SimdKind::Shift, // i16x8_shr_u
+ 0x8e => SimdKind::Binary, // i16x8_add
+ 0x8f => SimdKind::Binary, // i16x8_add_sat_s
+ 0x90 => SimdKind::Binary, // i16x8_add_sat_u
+ 0x91 => SimdKind::Binary, // i16x8_sub
+ 0x92 => SimdKind::Binary, // i16x8_sub_sat_s
+ 0x93 => SimdKind::Binary, // i16x8_sub_sat_u
+ 0x94 => SimdKind::Unary, // f64x2_nearest
+ 0x95 => SimdKind::Binary, // i16x8_mul
+ 0x96 => SimdKind::Binary, // i16x8_min_s
+ 0x97 => SimdKind::Binary, // i16x8_min_u
+ 0x98 => SimdKind::Binary, // i16x8_max_s
+ 0x99 => SimdKind::Binary, // i16x8_max_u
+ 0x9b => SimdKind::Binary, // i16x8_avgr_u
+ 0x9c => SimdKind::Binary, // i16x8_extmul_low_i8x16_s
+ 0x9d => SimdKind::Binary, // i16x8_extmul_high_i8x16_s
+ 0x9e => SimdKind::Binary, // i16x8_extmul_low_i8x16_u
+ 0x9f => SimdKind::Binary, // i16x8_extmul_high_i8x16_u
+ 0xa0 => SimdKind::Unary, // i32x4_abs
+ 0xa1 => SimdKind::Unary, // i32x4_neg
+ 0xa3 => SimdKind::Test, // i32x4_all_true
+ 0xa4 => SimdKind::Test, // i32x4_bitmask
+ 0xa7 => SimdKind::Unary, // i32x4_extend_low_i16x8_s
+ 0xa8 => SimdKind::Unary, // i32x4_extend_high_i16x8_s
+ 0xa9 => SimdKind::Unary, // i32x4_extend_low_i16x8_u
+ 0xaa => SimdKind::Unary, // i32x4_extend_high_i16x8_u
+ 0xab => SimdKind::Shift, // i32x4_shl
+ 0xac => SimdKind::Shift, // i32x4_shr_s
+ 0xad => SimdKind::Shift, // i32x4_shr_u
+ 0xae => SimdKind::Binary, // i32x4_add
+ 0xb1 => SimdKind::Binary, // i32x4_sub
+ 0xb5 => SimdKind::Binary, // i32x4_mul
+ 0xb6 => SimdKind::Binary, // i32x4_min_s
+ 0xb7 => SimdKind::Binary, // i32x4_min_u
+ 0xb8 => SimdKind::Binary, // i32x4_max_s
+ 0xb9 => SimdKind::Binary, // i32x4_max_u
+ 0xba => SimdKind::Binary, // i32x4_dot_i16x8_s
+ 0xbc => SimdKind::Binary, // i32x4_extmul_low_i16x8_s
+ 0xbd => SimdKind::Binary, // i32x4_extmul_high_i16x8_s
+ 0xbe => SimdKind::Binary, // i32x4_extmul_low_i16x8_u
+ 0xbf => SimdKind::Binary, // i32x4_extmul_high_i16x8_u
+ 0xc0 => SimdKind::Unary, // i64x2_abs
+ 0xc1 => SimdKind::Unary, // i64x2_neg
+ 0xc3 => SimdKind::Test, // i64x2_all_true
+ 0xc4 => SimdKind::Test, // i64x2_bitmask
+ 0xc7 => SimdKind::Unary, // i64x2_extend_low_i32x4_s
+ 0xc8 => SimdKind::Unary, // i64x2_extend_high_i32x4_s
+ 0xc9 => SimdKind::Unary, // i64x2_extend_low_i32x4_u
+ 0xca => SimdKind::Unary, // i64x2_extend_high_i32x4_u
+ 0xcb => SimdKind::Shift, // i64x2_shl
+ 0xcc => SimdKind::Shift, // i64x2_shr_s
+ 0xcd => SimdKind::Shift, // i64x2_shr_u
+ 0xce => SimdKind::Binary, // i64x2_add
+ 0xd1 => SimdKind::Binary, // i64x2_sub
+ 0xd5 => SimdKind::Binary, // i64x2_mul
+ 0xd6 => SimdKind::Binary, // i64x2_eq
+ 0xd7 => SimdKind::Binary, // i64x2_ne
+ 0xd8 => SimdKind::Binary, // i64x2_lt_s
+ 0xd9 => SimdKind::Binary, // i64x2_gt_s
+ 0xda => SimdKind::Binary, // i64x2_le_s
+ 0xdb => SimdKind::Binary, // i64x2_ge_s
+ 0xdc => SimdKind::Binary, // i64x2_extmul_low_i32x4_s
+ 0xdd => SimdKind::Binary, // i64x2_extmul_high_i32x4_s
+ 0xde => SimdKind::Binary, // i64x2_extmul_low_i32x4_u
+ 0xdf => SimdKind::Binary, // i64x2_extmul_high_i32x4_u
+ 0xe0 => SimdKind::Unary, // f32x4_abs
+ 0xe1 => SimdKind::Unary, // f32x4_neg
+ 0xe3 => SimdKind::Unary, // f32x4_sqrt
+ 0xe4 => SimdKind::Binary, // f32x4_add
+ 0xe5 => SimdKind::Binary, // f32x4_sub
+ 0xe6 => SimdKind::Binary, // f32x4_mul
+ 0xe7 => SimdKind::Binary, // f32x4_div
+ 0xe8 => SimdKind::Binary, // f32x4_min
+ 0xe9 => SimdKind::Binary, // f32x4_max
+ 0xea => SimdKind::Binary, // f32x4_pmin
+ 0xeb => SimdKind::Binary, // f32x4_pmax
+ 0xec => SimdKind::Unary, // f64x2_abs
+ 0xed => SimdKind::Unary, // f64x2_neg
+ 0xef => SimdKind::Unary, // f64x2_sqrt
+ 0xf0 => SimdKind::Binary, // f64x2_add
+ 0xf1 => SimdKind::Binary, // f64x2_sub
+ 0xf2 => SimdKind::Binary, // f64x2_mul
+ 0xf3 => SimdKind::Binary, // f64x2_div
+ 0xf4 => SimdKind::Binary, // f64x2_min
+ 0xf5 => SimdKind::Binary, // f64x2_max
+ 0xf6 => SimdKind::Binary, // f64x2_pmin
+ 0xf7 => SimdKind::Binary, // f64x2_pmax
+ 0xf8 => SimdKind::Unary, // i32x4_trunc_sat_f32x4_s
+ 0xf9 => SimdKind::Unary, // i32x4_trunc_sat_f32x4_u
+ 0xfa => SimdKind::Unary, // f32x4_convert_i32x4_s
+ 0xfb => SimdKind::Unary, // f32x4_convert_i32x4_u
+ 0xfc => SimdKind::Unary, // i32x4_trunc_sat_f64x2_s_zero
+ 0xfd => SimdKind::Unary, // i32x4_trunc_sat_f64x2_u_zero
+ 0xfe => SimdKind::Unary, // f64x2_convert_low_i32x4_s
+ 0xff => SimdKind::Unary, // f64x2_convert_low_i32x4_u
+ 0x100 => SimdKind::Binary, // i8x16_relaxed_swizzle
+ 0x101 => SimdKind::Unary, // i32x4_relaxed_trunc_f32x4_s
+ 0x102 => SimdKind::Unary, // i32x4_relaxed_trunc_f32x4_u
+ 0x103 => SimdKind::Unary, // i32x4_relaxed_trunc_f64x2_s_zero
+ 0x104 => SimdKind::Unary, // i32x4_relaxed_trunc_f64x2_u_zero
+ 0x105 => SimdKind::Ternary, // f32x4_relaxed_madd
+ 0x106 => SimdKind::Ternary, // f32x4_relaxed_nmadd
+ 0x107 => SimdKind::Ternary, // f64x2_relaxed_madd
+ 0x108 => SimdKind::Ternary, // f64x2_relaxed_nmadd
+ 0x109 => SimdKind::Ternary, // i8x16_relaxed_laneselect
+ 0x10a => SimdKind::Ternary, // i16x8_relaxed_laneselect
+ 0x10b => SimdKind::Ternary, // i32x4_relaxed_laneselect
+ 0x10c => SimdKind::Ternary, // i64x2_relaxed_laneselect
+ 0x10d => SimdKind::Binary, // f32x4_relaxed_min
+ 0x10e => SimdKind::Binary, // f32x4_relaxed_max
+ 0x10f => SimdKind::Binary, // f64x2_relaxed_min
+ 0x110 => SimdKind::Binary, // f64x2_relaxed_max
+ 0x111 => SimdKind::Binary, // i16x8_relaxed_q15mulr_s
+ 0x112 => SimdKind::Binary, // i16x8_relaxed_dot_i8x16_i7x16_s
+ 0x113 => SimdKind::Ternary, // i32x4_relaxed_dot_i8x16_i7x16_add_s
+ _ => return None,
+ })
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AtomicKind {
+ Notify,
+ Wait { value: ValType },
+ Fence,
+ Load { value: ValType, size: u32 },
+ Store { value: ValType, size: u32 },
+ ReadModifyWrite { value: ValType, size: u32 },
+ CompareExchange { value: ValType, size: u32 },
+}
+
+pub fn atomic_kind(sub_opcode: u32) -> Option<AtomicKind> {
+ Some(match sub_opcode {
+ 0x0 => AtomicKind::Notify,
+ 0x1 => AtomicKind::Wait { value: ValType::I32 },
+ 0x2 => AtomicKind::Wait { value: ValType::I64 },
+ 0x3 => AtomicKind::Fence,
+ 0x10 => AtomicKind::Load {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x11 => AtomicKind::Load {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x12 => AtomicKind::Load {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x13 => AtomicKind::Load {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x14 => AtomicKind::Load {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x15 => AtomicKind::Load {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x16 => AtomicKind::Load {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x17 => AtomicKind::Store {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x18 => AtomicKind::Store {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x19 => AtomicKind::Store {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x1a => AtomicKind::Store {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x1b => AtomicKind::Store {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x1c => AtomicKind::Store {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x1d => AtomicKind::Store {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x1e => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x1f => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x20 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x21 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x22 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x23 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x24 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x25 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x26 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x27 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x28 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x29 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x2a => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x2b => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x2c => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x2d => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x2e => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x2f => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x30 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x31 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x32 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x33 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x34 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x35 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x36 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x37 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x38 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x39 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x3a => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x3b => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x3c => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x3d => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x3e => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x3f => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x40 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x41 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x42 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x43 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x44 => AtomicKind::ReadModifyWrite {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x45 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x46 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x47 => AtomicKind::ReadModifyWrite {
+ value: ValType::I64,
+ size: 4,
+ },
+ 0x48 => AtomicKind::CompareExchange {
+ value: ValType::I32,
+ size: 4,
+ },
+ 0x49 => AtomicKind::CompareExchange {
+ value: ValType::I64,
+ size: 8,
+ },
+ 0x4a => AtomicKind::CompareExchange {
+ value: ValType::I32,
+ size: 1,
+ },
+ 0x4b => AtomicKind::CompareExchange {
+ value: ValType::I32,
+ size: 2,
+ },
+ 0x4c => AtomicKind::CompareExchange {
+ value: ValType::I64,
+ size: 1,
+ },
+ 0x4d => AtomicKind::CompareExchange {
+ value: ValType::I64,
+ size: 2,
+ },
+ 0x4e => AtomicKind::CompareExchange {
+ value: ValType::I64,
+ size: 4,
+ },
+ _ => return None,
+ })
+}
diff --git a/Libraries/LibWasm/Engine/src/lib.rs b/Libraries/LibWasm/Engine/src/lib.rs
new file mode 100644
index 00000000000..004ce2f0628
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/lib.rs
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! # LibWasm
+//!
+//! A WebAssembly engine: the binary format decoder, the validator, which also builds the side tables the in-place
+//! interpreter branches with, and (in later steps) the runtime, the interpreter, and the JIT.
+
+#[cfg(feature = "allocator")]
+extern crate ladybird_allocator;
+
+#[path = "../../../RustDemangle.rs"]
+mod rust_demangle;
+
+#[path = "../../../RustPanic.rs"]
+mod rust_panic;
+
+pub mod abi;
+pub mod capi;
+pub mod error;
+pub mod instruction_tables;
+pub mod module;
+pub mod opcode;
+pub mod parser;
+pub mod quickening;
+pub mod reader;
+pub mod runtime;
+pub mod types;
+pub mod validator;
+
+pub use error::{Error, Result};
+pub use module::Module;
+
+/// Decode and validate a binary module.
+pub fn compile(bytes: &[u8]) -> Result<Module> {
+ let mut module = parser::parse(bytes)?;
+ validator::validate(&mut module)?;
+ Ok(module)
+}
diff --git a/Libraries/LibWasm/Engine/src/module.rs b/Libraries/LibWasm/Engine/src/module.rs
new file mode 100644
index 00000000000..bf0fea400b8
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/module.rs
@@ -0,0 +1,182 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A decoded module. Function bodies and constant expressions are not decoded into another form: they are byte
+//! ranges into the module's binary, which the validator checks and the interpreter executes in place.
+
+use crate::types::{FuncType, GlobalType, MemoryType, RefType, SubType, TableType, TagType, ValType};
+use crate::validator::FunctionInfo;
+use std::ops::Range;
+
+/// A byte range of the module's binary.
+pub type ByteRange = Range<u32>;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExternalKind {
+ Function,
+ Table,
+ Memory,
+ Global,
+ Tag,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ImportDescription {
+ Function(u32),
+ Table(TableType),
+ Memory(MemoryType),
+ Global(GlobalType),
+ Tag(TagType),
+}
+
+#[derive(Debug, Clone)]
+pub struct Import {
+ pub module: String,
+ pub name: String,
+ pub description: ImportDescription,
+}
+
+#[derive(Debug, Clone)]
+pub struct Export {
+ pub name: String,
+ pub kind: ExternalKind,
+ pub index: u32,
+}
+
+/// A constant expression: the bytes of its instructions, including the final `end`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConstantExpression {
+ pub code: ByteRange,
+}
+
+#[derive(Debug, Clone)]
+pub struct Table {
+ pub ty: TableType,
+ pub initializer: Option<ConstantExpression>,
+}
+
+#[derive(Debug, Clone)]
+pub struct Global {
+ pub ty: GlobalType,
+ pub initializer: ConstantExpression,
+}
+
+#[derive(Debug, Clone)]
+pub enum ElementMode {
+ Passive,
+ Declarative,
+ Active { table: u32, offset: ConstantExpression },
+}
+
+#[derive(Debug, Clone)]
+pub enum ElementItems {
+ Functions(Vec<u32>),
+ Expressions(Vec<ConstantExpression>),
+}
+
+impl ElementItems {
+ pub fn len(&self) -> usize {
+ match self {
+ Self::Functions(functions) => functions.len(),
+ Self::Expressions(expressions) => expressions.len(),
+ }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Element {
+ pub ty: RefType,
+ pub mode: ElementMode,
+ pub items: ElementItems,
+}
+
+#[derive(Debug, Clone)]
+pub enum DataMode {
+ Passive,
+ Active { memory: u32, offset: ConstantExpression },
+}
+
+#[derive(Debug, Clone)]
+pub struct Data {
+ pub mode: DataMode,
+ pub bytes: ByteRange,
+}
+
+/// The body of a defined function.
+#[derive(Debug, Clone)]
+pub struct FunctionBody {
+ /// The declared locals after the parameters, as (count, type) runs.
+ pub locals: Vec<(u32, ValType)>,
+ /// The total number of locals after the parameters.
+ pub declared_local_count: u32,
+ /// The function's instructions, starting at the first instruction and ending after its final `end`.
+ pub code: ByteRange,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RecursionGroup {
+ pub start: u32,
+ pub count: u32,
+}
+
+#[derive(Debug, Default)]
+pub struct Module {
+ pub bytes: Box<[u8]>,
+ pub types: Vec<SubType>,
+ pub recursion_groups: Vec<RecursionGroup>,
+ pub imports: Vec<Import>,
+ /// The type index of each defined function.
+ pub functions: Vec<u32>,
+ pub tables: Vec<Table>,
+ pub memories: Vec<MemoryType>,
+ pub globals: Vec<Global>,
+ pub tags: Vec<TagType>,
+ pub exports: Vec<Export>,
+ pub start: Option<u32>,
+ pub elements: Vec<Element>,
+ pub data_count: Option<u32>,
+ pub code: Vec<FunctionBody>,
+ pub data: Vec<Data>,
+
+ // Index spaces, imports first.
+ pub imported_function_count: u32,
+ pub imported_table_count: u32,
+ pub imported_memory_count: u32,
+ pub imported_global_count: u32,
+ pub imported_tag_count: u32,
+ /// The type index of every function.
+ pub function_space: Vec<u32>,
+ pub table_space: Vec<TableType>,
+ pub memory_space: Vec<MemoryType>,
+ pub global_space: Vec<GlobalType>,
+ pub tag_space: Vec<TagType>,
+
+ /// Filled in by validation: the canonical identity of each type, equal exactly for equal types, assigned by a
+ /// canonicalizer local to this module.
+ pub type_identities: Vec<u32>,
+ /// Filled in by validation: what the interpreter needs to run each defined function.
+ pub function_infos: Vec<FunctionInfo>,
+}
+
+impl Module {
+ pub fn bytes_of(&self, range: &ByteRange) -> &[u8] {
+ &self.bytes[range.start as usize..range.end as usize]
+ }
+
+ pub fn function_type(&self, function: u32) -> Option<&FuncType> {
+ self.types
+ .get(*self.function_space.get(function as usize)? as usize)?
+ .as_func()
+ }
+
+ pub fn total_function_count(&self) -> u32 {
+ self.function_space.len() as u32
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/opcode.rs b/Libraries/LibWasm/Engine/src/opcode.rs
new file mode 100644
index 00000000000..015e79a909d
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/opcode.rs
@@ -0,0 +1,594 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! WebAssembly opcodes. Single-byte opcodes are `u8`s; the `0xFB`, `0xFC`, `0xFD`, and `0xFE` prefixes are followed by
+//! a LEB128 `u32` sub-opcode, whose values live in the module named after the prefix.
+
+#![allow(dead_code)]
+
+pub const PREFIX_GC: u8 = 0xfb;
+pub const PREFIX_MISC: u8 = 0xfc;
+pub const PREFIX_SIMD: u8 = 0xfd;
+pub const PREFIX_ATOMIC: u8 = 0xfe;
+
+pub const UNREACHABLE: u8 = 0x00;
+pub const NOP: u8 = 0x01;
+pub const BLOCK: u8 = 0x02;
+pub const LOOP: u8 = 0x03;
+pub const IF: u8 = 0x04;
+pub const ELSE: u8 = 0x05;
+pub const THROW: u8 = 0x08;
+pub const THROW_REF: u8 = 0x0a;
+pub const END: u8 = 0x0b;
+pub const BR: u8 = 0x0c;
+pub const BR_IF: u8 = 0x0d;
+pub const BR_TABLE: u8 = 0x0e;
+pub const RETURN: u8 = 0x0f;
+pub const CALL: u8 = 0x10;
+pub const CALL_INDIRECT: u8 = 0x11;
+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 DROP: u8 = 0x1a;
+pub const SELECT: u8 = 0x1b;
+pub const SELECT_TYPED: u8 = 0x1c;
+pub const TRY_TABLE: u8 = 0x1f;
+pub const LOCAL_GET: u8 = 0x20;
+pub const LOCAL_SET: u8 = 0x21;
+pub const LOCAL_TEE: u8 = 0x22;
+pub const GLOBAL_GET: u8 = 0x23;
+pub const GLOBAL_SET: u8 = 0x24;
+pub const TABLE_GET: u8 = 0x25;
+pub const TABLE_SET: u8 = 0x26;
+pub const I32_LOAD: u8 = 0x28;
+pub const I64_LOAD: u8 = 0x29;
+pub const F32_LOAD: u8 = 0x2a;
+pub const F64_LOAD: u8 = 0x2b;
+pub const I32_LOAD8_S: u8 = 0x2c;
+pub const I32_LOAD8_U: u8 = 0x2d;
+pub const I32_LOAD16_S: u8 = 0x2e;
+pub const I32_LOAD16_U: u8 = 0x2f;
+pub const I64_LOAD8_S: u8 = 0x30;
+pub const I64_LOAD8_U: u8 = 0x31;
+pub const I64_LOAD16_S: u8 = 0x32;
+pub const I64_LOAD16_U: u8 = 0x33;
+pub const I64_LOAD32_S: u8 = 0x34;
+pub const I64_LOAD32_U: u8 = 0x35;
+pub const I32_STORE: u8 = 0x36;
+pub const I64_STORE: u8 = 0x37;
+pub const F32_STORE: u8 = 0x38;
+pub const F64_STORE: u8 = 0x39;
+pub const I32_STORE8: u8 = 0x3a;
+pub const I32_STORE16: u8 = 0x3b;
+pub const I64_STORE8: u8 = 0x3c;
+pub const I64_STORE16: u8 = 0x3d;
+pub const I64_STORE32: u8 = 0x3e;
+pub const MEMORY_SIZE: u8 = 0x3f;
+pub const MEMORY_GROW: u8 = 0x40;
+pub const I32_CONST: u8 = 0x41;
+pub const I64_CONST: u8 = 0x42;
+pub const F32_CONST: u8 = 0x43;
+pub const F64_CONST: u8 = 0x44;
+pub const I32_EQZ: u8 = 0x45;
+pub const I32_EQ: u8 = 0x46;
+pub const I32_NE: u8 = 0x47;
+pub const I32_LTS: u8 = 0x48;
+pub const I32_LTU: u8 = 0x49;
+pub const I32_GTS: u8 = 0x4a;
+pub const I32_GTU: u8 = 0x4b;
+pub const I32_LES: u8 = 0x4c;
+pub const I32_LEU: u8 = 0x4d;
+pub const I32_GES: u8 = 0x4e;
+pub const I32_GEU: u8 = 0x4f;
+pub const I64_EQZ: u8 = 0x50;
+pub const I64_EQ: u8 = 0x51;
+pub const I64_NE: u8 = 0x52;
+pub const I64_LTS: u8 = 0x53;
+pub const I64_LTU: u8 = 0x54;
+pub const I64_GTS: u8 = 0x55;
+pub const I64_GTU: u8 = 0x56;
+pub const I64_LES: u8 = 0x57;
+pub const I64_LEU: u8 = 0x58;
+pub const I64_GES: u8 = 0x59;
+pub const I64_GEU: u8 = 0x5a;
+pub const F32_EQ: u8 = 0x5b;
+pub const F32_NE: u8 = 0x5c;
+pub const F32_LT: u8 = 0x5d;
+pub const F32_GT: u8 = 0x5e;
+pub const F32_LE: u8 = 0x5f;
+pub const F32_GE: u8 = 0x60;
+pub const F64_EQ: u8 = 0x61;
+pub const F64_NE: u8 = 0x62;
+pub const F64_LT: u8 = 0x63;
+pub const F64_GT: u8 = 0x64;
+pub const F64_LE: u8 = 0x65;
+pub const F64_GE: u8 = 0x66;
+pub const I32_CLZ: u8 = 0x67;
+pub const I32_CTZ: u8 = 0x68;
+pub const I32_POPCNT: u8 = 0x69;
+pub const I32_ADD: u8 = 0x6a;
+pub const I32_SUB: u8 = 0x6b;
+pub const I32_MUL: u8 = 0x6c;
+pub const I32_DIVS: u8 = 0x6d;
+pub const I32_DIVU: u8 = 0x6e;
+pub const I32_REMS: u8 = 0x6f;
+pub const I32_REMU: u8 = 0x70;
+pub const I32_AND: u8 = 0x71;
+pub const I32_OR: u8 = 0x72;
+pub const I32_XOR: u8 = 0x73;
+pub const I32_SHL: u8 = 0x74;
+pub const I32_SHRS: u8 = 0x75;
+pub const I32_SHRU: u8 = 0x76;
+pub const I32_ROTL: u8 = 0x77;
+pub const I32_ROTR: u8 = 0x78;
+pub const I64_CLZ: u8 = 0x79;
+pub const I64_CTZ: u8 = 0x7a;
+pub const I64_POPCNT: u8 = 0x7b;
+pub const I64_ADD: u8 = 0x7c;
+pub const I64_SUB: u8 = 0x7d;
+pub const I64_MUL: u8 = 0x7e;
+pub const I64_DIVS: u8 = 0x7f;
+pub const I64_DIVU: u8 = 0x80;
+pub const I64_REMS: u8 = 0x81;
+pub const I64_REMU: u8 = 0x82;
+pub const I64_AND: u8 = 0x83;
+pub const I64_OR: u8 = 0x84;
+pub const I64_XOR: u8 = 0x85;
+pub const I64_SHL: u8 = 0x86;
+pub const I64_SHRS: u8 = 0x87;
+pub const I64_SHRU: u8 = 0x88;
+pub const I64_ROTL: u8 = 0x89;
+pub const I64_ROTR: u8 = 0x8a;
+pub const F32_ABS: u8 = 0x8b;
+pub const F32_NEG: u8 = 0x8c;
+pub const F32_CEIL: u8 = 0x8d;
+pub const F32_FLOOR: u8 = 0x8e;
+pub const F32_TRUNC: u8 = 0x8f;
+pub const F32_NEAREST: u8 = 0x90;
+pub const F32_SQRT: u8 = 0x91;
+pub const F32_ADD: u8 = 0x92;
+pub const F32_SUB: u8 = 0x93;
+pub const F32_MUL: u8 = 0x94;
+pub const F32_DIV: u8 = 0x95;
+pub const F32_MIN: u8 = 0x96;
+pub const F32_MAX: u8 = 0x97;
+pub const F32_COPYSIGN: u8 = 0x98;
+pub const F64_ABS: u8 = 0x99;
+pub const F64_NEG: u8 = 0x9a;
+pub const F64_CEIL: u8 = 0x9b;
+pub const F64_FLOOR: u8 = 0x9c;
+pub const F64_TRUNC: u8 = 0x9d;
+pub const F64_NEAREST: u8 = 0x9e;
+pub const F64_SQRT: u8 = 0x9f;
+pub const F64_ADD: u8 = 0xa0;
+pub const F64_SUB: u8 = 0xa1;
+pub const F64_MUL: u8 = 0xa2;
+pub const F64_DIV: u8 = 0xa3;
+pub const F64_MIN: u8 = 0xa4;
+pub const F64_MAX: u8 = 0xa5;
+pub const F64_COPYSIGN: u8 = 0xa6;
+pub const I32_WRAP_I64: u8 = 0xa7;
+pub const I32_TRUNC_F32_S: u8 = 0xa8;
+pub const I32_TRUNC_F32_U: u8 = 0xa9;
+pub const I32_TRUNC_F64_S: u8 = 0xaa;
+pub const I32_TRUNC_F64_U: u8 = 0xab;
+pub const I64_EXTEND_I32_S: u8 = 0xac;
+pub const I64_EXTEND_I32_U: u8 = 0xad;
+pub const I64_TRUNC_F32_S: u8 = 0xae;
+pub const I64_TRUNC_F32_U: u8 = 0xaf;
+pub const I64_TRUNC_F64_S: u8 = 0xb0;
+pub const I64_TRUNC_F64_U: u8 = 0xb1;
+pub const F32_CONVERT_I32_S: u8 = 0xb2;
+pub const F32_CONVERT_I32_U: u8 = 0xb3;
+pub const F32_CONVERT_I64_S: u8 = 0xb4;
+pub const F32_CONVERT_I64_U: u8 = 0xb5;
+pub const F32_DEMOTE_F64: u8 = 0xb6;
+pub const F64_CONVERT_I32_S: u8 = 0xb7;
+pub const F64_CONVERT_I32_U: u8 = 0xb8;
+pub const F64_CONVERT_I64_S: u8 = 0xb9;
+pub const F64_CONVERT_I64_U: u8 = 0xba;
+pub const F64_PROMOTE_F32: u8 = 0xbb;
+pub const I32_REINTERPRET_F32: u8 = 0xbc;
+pub const I64_REINTERPRET_F64: u8 = 0xbd;
+pub const F32_REINTERPRET_I32: u8 = 0xbe;
+pub const F64_REINTERPRET_I64: u8 = 0xbf;
+pub const I32_EXTEND8_S: u8 = 0xc0;
+pub const I32_EXTEND16_S: u8 = 0xc1;
+pub const I64_EXTEND8_S: u8 = 0xc2;
+pub const I64_EXTEND16_S: u8 = 0xc3;
+pub const I64_EXTEND32_S: u8 = 0xc4;
+pub const REF_NULL: u8 = 0xd0;
+pub const REF_IS_NULL: u8 = 0xd1;
+pub const REF_FUNC: u8 = 0xd2;
+pub const REF_EQ: u8 = 0xd3;
+pub const REF_AS_NON_NULL: u8 = 0xd4;
+pub const BR_ON_NULL: u8 = 0xd5;
+pub const BR_ON_NON_NULL: u8 = 0xd6;
+
+pub mod gc {
+ pub const STRUCT_NEW: u32 = 0x0;
+ pub const STRUCT_NEW_DEFAULT: u32 = 0x1;
+ pub const STRUCT_GET: u32 = 0x2;
+ pub const STRUCT_GET_S: u32 = 0x3;
+ pub const STRUCT_GET_U: u32 = 0x4;
+ pub const STRUCT_SET: u32 = 0x5;
+ pub const ARRAY_NEW: u32 = 0x6;
+ pub const ARRAY_NEW_DEFAULT: u32 = 0x7;
+ pub const ARRAY_NEW_FIXED: u32 = 0x8;
+ pub const ARRAY_NEW_DATA: u32 = 0x9;
+ pub const ARRAY_NEW_ELEM: u32 = 0xa;
+ pub const ARRAY_GET: u32 = 0xb;
+ pub const ARRAY_GET_S: u32 = 0xc;
+ pub const ARRAY_GET_U: u32 = 0xd;
+ pub const ARRAY_SET: u32 = 0xe;
+ pub const ARRAY_LEN: u32 = 0xf;
+ pub const ARRAY_FILL: u32 = 0x10;
+ pub const ARRAY_COPY: u32 = 0x11;
+ pub const ARRAY_INIT_DATA: u32 = 0x12;
+ pub const ARRAY_INIT_ELEM: u32 = 0x13;
+ pub const REF_TEST: u32 = 0x14;
+ pub const REF_TEST_NULL: u32 = 0x15;
+ pub const REF_CAST: u32 = 0x16;
+ pub const REF_CAST_NULL: u32 = 0x17;
+ pub const BR_ON_CAST: u32 = 0x18;
+ pub const BR_ON_CAST_FAIL: u32 = 0x19;
+ pub const ANY_CONVERT_EXTERN: u32 = 0x1a;
+ pub const EXTERN_CONVERT_ANY: u32 = 0x1b;
+ pub const REF_I31: u32 = 0x1c;
+ pub const I31_GET_S: u32 = 0x1d;
+ pub const I31_GET_U: u32 = 0x1e;
+}
+
+pub mod misc {
+ pub const I32_TRUNC_SAT_F32_S: u32 = 0x0;
+ pub const I32_TRUNC_SAT_F32_U: u32 = 0x1;
+ pub const I32_TRUNC_SAT_F64_S: u32 = 0x2;
+ pub const I32_TRUNC_SAT_F64_U: u32 = 0x3;
+ pub const I64_TRUNC_SAT_F32_S: u32 = 0x4;
+ pub const I64_TRUNC_SAT_F32_U: u32 = 0x5;
+ pub const I64_TRUNC_SAT_F64_S: u32 = 0x6;
+ pub const I64_TRUNC_SAT_F64_U: u32 = 0x7;
+ pub const MEMORY_INIT: u32 = 0x8;
+ pub const DATA_DROP: u32 = 0x9;
+ pub const MEMORY_COPY: u32 = 0xa;
+ pub const MEMORY_FILL: u32 = 0xb;
+ pub const TABLE_INIT: u32 = 0xc;
+ pub const ELEM_DROP: u32 = 0xd;
+ pub const TABLE_COPY: u32 = 0xe;
+ pub const TABLE_GROW: u32 = 0xf;
+ pub const TABLE_SIZE: u32 = 0x10;
+ pub const TABLE_FILL: u32 = 0x11;
+}
+
+pub mod simd {
+ pub const V128_LOAD: u32 = 0x0;
+ pub const V128_LOAD8X8_S: u32 = 0x1;
+ pub const V128_LOAD8X8_U: u32 = 0x2;
+ pub const V128_LOAD16X4_S: u32 = 0x3;
+ pub const V128_LOAD16X4_U: u32 = 0x4;
+ pub const V128_LOAD32X2_S: u32 = 0x5;
+ pub const V128_LOAD32X2_U: u32 = 0x6;
+ pub const V128_LOAD8_SPLAT: u32 = 0x7;
+ pub const V128_LOAD16_SPLAT: u32 = 0x8;
+ pub const V128_LOAD32_SPLAT: u32 = 0x9;
+ pub const V128_LOAD64_SPLAT: u32 = 0xa;
+ pub const V128_STORE: u32 = 0xb;
+ pub const V128_CONST: u32 = 0xc;
+ pub const I8X16_SHUFFLE: u32 = 0xd;
+ pub const I8X16_SWIZZLE: u32 = 0xe;
+ pub const I8X16_SPLAT: u32 = 0xf;
+ pub const I16X8_SPLAT: u32 = 0x10;
+ pub const I32X4_SPLAT: u32 = 0x11;
+ pub const I64X2_SPLAT: u32 = 0x12;
+ pub const F32X4_SPLAT: u32 = 0x13;
+ pub const F64X2_SPLAT: u32 = 0x14;
+ pub const I8X16_EXTRACT_LANE_S: u32 = 0x15;
+ pub const I8X16_EXTRACT_LANE_U: u32 = 0x16;
+ pub const I8X16_REPLACE_LANE: u32 = 0x17;
+ pub const I16X8_EXTRACT_LANE_S: u32 = 0x18;
+ pub const I16X8_EXTRACT_LANE_U: u32 = 0x19;
+ pub const I16X8_REPLACE_LANE: u32 = 0x1a;
+ pub const I32X4_EXTRACT_LANE: u32 = 0x1b;
+ pub const I32X4_REPLACE_LANE: u32 = 0x1c;
+ pub const I64X2_EXTRACT_LANE: u32 = 0x1d;
+ pub const I64X2_REPLACE_LANE: u32 = 0x1e;
+ pub const F32X4_EXTRACT_LANE: u32 = 0x1f;
+ pub const F32X4_REPLACE_LANE: u32 = 0x20;
+ pub const F64X2_EXTRACT_LANE: u32 = 0x21;
+ pub const F64X2_REPLACE_LANE: u32 = 0x22;
+ pub const I8X16_EQ: u32 = 0x23;
+ pub const I8X16_NE: u32 = 0x24;
+ pub const I8X16_LT_S: u32 = 0x25;
+ pub const I8X16_LT_U: u32 = 0x26;
+ pub const I8X16_GT_S: u32 = 0x27;
+ pub const I8X16_GT_U: u32 = 0x28;
+ pub const I8X16_LE_S: u32 = 0x29;
+ pub const I8X16_LE_U: u32 = 0x2a;
+ pub const I8X16_GE_S: u32 = 0x2b;
+ pub const I8X16_GE_U: u32 = 0x2c;
+ pub const I16X8_EQ: u32 = 0x2d;
+ pub const I16X8_NE: u32 = 0x2e;
+ pub const I16X8_LT_S: u32 = 0x2f;
+ pub const I16X8_LT_U: u32 = 0x30;
+ pub const I16X8_GT_S: u32 = 0x31;
+ pub const I16X8_GT_U: u32 = 0x32;
+ pub const I16X8_LE_S: u32 = 0x33;
+ pub const I16X8_LE_U: u32 = 0x34;
+ pub const I16X8_GE_S: u32 = 0x35;
+ pub const I16X8_GE_U: u32 = 0x36;
+ pub const I32X4_EQ: u32 = 0x37;
+ pub const I32X4_NE: u32 = 0x38;
+ pub const I32X4_LT_S: u32 = 0x39;
+ pub const I32X4_LT_U: u32 = 0x3a;
+ pub const I32X4_GT_S: u32 = 0x3b;
+ pub const I32X4_GT_U: u32 = 0x3c;
+ pub const I32X4_LE_S: u32 = 0x3d;
+ pub const I32X4_LE_U: u32 = 0x3e;
+ pub const I32X4_GE_S: u32 = 0x3f;
+ pub const I32X4_GE_U: u32 = 0x40;
+ pub const F32X4_EQ: u32 = 0x41;
+ pub const F32X4_NE: u32 = 0x42;
+ pub const F32X4_LT: u32 = 0x43;
+ pub const F32X4_GT: u32 = 0x44;
+ pub const F32X4_LE: u32 = 0x45;
+ pub const F32X4_GE: u32 = 0x46;
+ pub const F64X2_EQ: u32 = 0x47;
+ pub const F64X2_NE: u32 = 0x48;
+ pub const F64X2_LT: u32 = 0x49;
+ pub const F64X2_GT: u32 = 0x4a;
+ pub const F64X2_LE: u32 = 0x4b;
+ pub const F64X2_GE: u32 = 0x4c;
+ pub const V128_NOT: u32 = 0x4d;
+ pub const V128_AND: u32 = 0x4e;
+ pub const V128_ANDNOT: u32 = 0x4f;
+ pub const V128_OR: u32 = 0x50;
+ pub const V128_XOR: u32 = 0x51;
+ pub const V128_BITSELECT: u32 = 0x52;
+ pub const V128_ANY_TRUE: u32 = 0x53;
+ pub const V128_LOAD8_LANE: u32 = 0x54;
+ pub const V128_LOAD16_LANE: u32 = 0x55;
+ pub const V128_LOAD32_LANE: u32 = 0x56;
+ pub const V128_LOAD64_LANE: u32 = 0x57;
+ pub const V128_STORE8_LANE: u32 = 0x58;
+ pub const V128_STORE16_LANE: u32 = 0x59;
+ pub const V128_STORE32_LANE: u32 = 0x5a;
+ pub const V128_STORE64_LANE: u32 = 0x5b;
+ pub const V128_LOAD32_ZERO: u32 = 0x5c;
+ pub const V128_LOAD64_ZERO: u32 = 0x5d;
+ pub const F32X4_DEMOTE_F64X2_ZERO: u32 = 0x5e;
+ pub const F64X2_PROMOTE_LOW_F32X4: u32 = 0x5f;
+ pub const I8X16_ABS: u32 = 0x60;
+ pub const I8X16_NEG: u32 = 0x61;
+ pub const I8X16_POPCNT: u32 = 0x62;
+ pub const I8X16_ALL_TRUE: u32 = 0x63;
+ pub const I8X16_BITMASK: u32 = 0x64;
+ pub const I8X16_NARROW_I16X8_S: u32 = 0x65;
+ pub const I8X16_NARROW_I16X8_U: u32 = 0x66;
+ pub const F32X4_CEIL: u32 = 0x67;
+ pub const F32X4_FLOOR: u32 = 0x68;
+ pub const F32X4_TRUNC: u32 = 0x69;
+ pub const F32X4_NEAREST: u32 = 0x6a;
+ pub const I8X16_SHL: u32 = 0x6b;
+ pub const I8X16_SHR_S: u32 = 0x6c;
+ pub const I8X16_SHR_U: u32 = 0x6d;
+ pub const I8X16_ADD: u32 = 0x6e;
+ pub const I8X16_ADD_SAT_S: u32 = 0x6f;
+ pub const I8X16_ADD_SAT_U: u32 = 0x70;
+ pub const I8X16_SUB: u32 = 0x71;
+ pub const I8X16_SUB_SAT_S: u32 = 0x72;
+ pub const I8X16_SUB_SAT_U: u32 = 0x73;
+ pub const F64X2_CEIL: u32 = 0x74;
+ pub const F64X2_FLOOR: u32 = 0x75;
+ pub const I8X16_MIN_S: u32 = 0x76;
+ pub const I8X16_MIN_U: u32 = 0x77;
+ pub const I8X16_MAX_S: u32 = 0x78;
+ pub const I8X16_MAX_U: u32 = 0x79;
+ pub const F64X2_TRUNC: u32 = 0x7a;
+ pub const I8X16_AVGR_U: u32 = 0x7b;
+ pub const I16X8_EXTADD_PAIRWISE_I8X16_S: u32 = 0x7c;
+ pub const I16X8_EXTADD_PAIRWISE_I8X16_U: u32 = 0x7d;
+ pub const I32X4_EXTADD_PAIRWISE_I16X8_S: u32 = 0x7e;
+ pub const I32X4_EXTADD_PAIRWISE_I16X8_U: u32 = 0x7f;
+ pub const I16X8_ABS: u32 = 0x80;
+ pub const I16X8_NEG: u32 = 0x81;
+ pub const I16X8_Q15MULR_SAT_S: u32 = 0x82;
+ pub const I16X8_ALL_TRUE: u32 = 0x83;
+ pub const I16X8_BITMASK: u32 = 0x84;
+ pub const I16X8_NARROW_I32X4_S: u32 = 0x85;
+ pub const I16X8_NARROW_I32X4_U: u32 = 0x86;
+ pub const I16X8_EXTEND_LOW_I8X16_S: u32 = 0x87;
+ pub const I16X8_EXTEND_HIGH_I8X16_S: u32 = 0x88;
+ pub const I16X8_EXTEND_LOW_I8X16_U: u32 = 0x89;
+ pub const I16X8_EXTEND_HIGH_I8X16_U: u32 = 0x8a;
+ pub const I16X8_SHL: u32 = 0x8b;
+ pub const I16X8_SHR_S: u32 = 0x8c;
+ pub const I16X8_SHR_U: u32 = 0x8d;
+ pub const I16X8_ADD: u32 = 0x8e;
+ pub const I16X8_ADD_SAT_S: u32 = 0x8f;
+ pub const I16X8_ADD_SAT_U: u32 = 0x90;
+ pub const I16X8_SUB: u32 = 0x91;
+ pub const I16X8_SUB_SAT_S: u32 = 0x92;
+ pub const I16X8_SUB_SAT_U: u32 = 0x93;
+ pub const F64X2_NEAREST: u32 = 0x94;
+ pub const I16X8_MUL: u32 = 0x95;
+ pub const I16X8_MIN_S: u32 = 0x96;
+ pub const I16X8_MIN_U: u32 = 0x97;
+ pub const I16X8_MAX_S: u32 = 0x98;
+ pub const I16X8_MAX_U: u32 = 0x99;
+ pub const I16X8_AVGR_U: u32 = 0x9b;
+ pub const I16X8_EXTMUL_LOW_I8X16_S: u32 = 0x9c;
+ pub const I16X8_EXTMUL_HIGH_I8X16_S: u32 = 0x9d;
+ pub const I16X8_EXTMUL_LOW_I8X16_U: u32 = 0x9e;
+ pub const I16X8_EXTMUL_HIGH_I8X16_U: u32 = 0x9f;
+ pub const I32X4_ABS: u32 = 0xa0;
+ pub const I32X4_NEG: u32 = 0xa1;
+ pub const I32X4_ALL_TRUE: u32 = 0xa3;
+ pub const I32X4_BITMASK: u32 = 0xa4;
+ pub const I32X4_EXTEND_LOW_I16X8_S: u32 = 0xa7;
+ pub const I32X4_EXTEND_HIGH_I16X8_S: u32 = 0xa8;
+ pub const I32X4_EXTEND_LOW_I16X8_U: u32 = 0xa9;
+ pub const I32X4_EXTEND_HIGH_I16X8_U: u32 = 0xaa;
+ pub const I32X4_SHL: u32 = 0xab;
+ pub const I32X4_SHR_S: u32 = 0xac;
+ pub const I32X4_SHR_U: u32 = 0xad;
+ pub const I32X4_ADD: u32 = 0xae;
+ pub const I32X4_SUB: u32 = 0xb1;
+ pub const I32X4_MUL: u32 = 0xb5;
+ pub const I32X4_MIN_S: u32 = 0xb6;
+ pub const I32X4_MIN_U: u32 = 0xb7;
+ pub const I32X4_MAX_S: u32 = 0xb8;
+ pub const I32X4_MAX_U: u32 = 0xb9;
+ pub const I32X4_DOT_I16X8_S: u32 = 0xba;
+ pub const I32X4_EXTMUL_LOW_I16X8_S: u32 = 0xbc;
+ pub const I32X4_EXTMUL_HIGH_I16X8_S: u32 = 0xbd;
+ pub const I32X4_EXTMUL_LOW_I16X8_U: u32 = 0xbe;
+ pub const I32X4_EXTMUL_HIGH_I16X8_U: u32 = 0xbf;
+ pub const I64X2_ABS: u32 = 0xc0;
+ pub const I64X2_NEG: u32 = 0xc1;
+ pub const I64X2_ALL_TRUE: u32 = 0xc3;
+ pub const I64X2_BITMASK: u32 = 0xc4;
+ pub const I64X2_EXTEND_LOW_I32X4_S: u32 = 0xc7;
+ pub const I64X2_EXTEND_HIGH_I32X4_S: u32 = 0xc8;
+ pub const I64X2_EXTEND_LOW_I32X4_U: u32 = 0xc9;
+ pub const I64X2_EXTEND_HIGH_I32X4_U: u32 = 0xca;
+ pub const I64X2_SHL: u32 = 0xcb;
+ pub const I64X2_SHR_S: u32 = 0xcc;
+ pub const I64X2_SHR_U: u32 = 0xcd;
+ pub const I64X2_ADD: u32 = 0xce;
+ pub const I64X2_SUB: u32 = 0xd1;
+ pub const I64X2_MUL: u32 = 0xd5;
+ pub const I64X2_EQ: u32 = 0xd6;
+ pub const I64X2_NE: u32 = 0xd7;
+ pub const I64X2_LT_S: u32 = 0xd8;
+ pub const I64X2_GT_S: u32 = 0xd9;
+ pub const I64X2_LE_S: u32 = 0xda;
+ pub const I64X2_GE_S: u32 = 0xdb;
+ pub const I64X2_EXTMUL_LOW_I32X4_S: u32 = 0xdc;
+ pub const I64X2_EXTMUL_HIGH_I32X4_S: u32 = 0xdd;
+ pub const I64X2_EXTMUL_LOW_I32X4_U: u32 = 0xde;
+ pub const I64X2_EXTMUL_HIGH_I32X4_U: u32 = 0xdf;
+ pub const F32X4_ABS: u32 = 0xe0;
+ pub const F32X4_NEG: u32 = 0xe1;
+ pub const F32X4_SQRT: u32 = 0xe3;
+ pub const F32X4_ADD: u32 = 0xe4;
+ pub const F32X4_SUB: u32 = 0xe5;
+ pub const F32X4_MUL: u32 = 0xe6;
+ pub const F32X4_DIV: u32 = 0xe7;
+ pub const F32X4_MIN: u32 = 0xe8;
+ pub const F32X4_MAX: u32 = 0xe9;
+ pub const F32X4_PMIN: u32 = 0xea;
+ pub const F32X4_PMAX: u32 = 0xeb;
+ pub const F64X2_ABS: u32 = 0xec;
+ pub const F64X2_NEG: u32 = 0xed;
+ pub const F64X2_SQRT: u32 = 0xef;
+ pub const F64X2_ADD: u32 = 0xf0;
+ pub const F64X2_SUB: u32 = 0xf1;
+ pub const F64X2_MUL: u32 = 0xf2;
+ pub const F64X2_DIV: u32 = 0xf3;
+ pub const F64X2_MIN: u32 = 0xf4;
+ pub const F64X2_MAX: u32 = 0xf5;
+ pub const F64X2_PMIN: u32 = 0xf6;
+ pub const F64X2_PMAX: u32 = 0xf7;
+ pub const I32X4_TRUNC_SAT_F32X4_S: u32 = 0xf8;
+ pub const I32X4_TRUNC_SAT_F32X4_U: u32 = 0xf9;
+ pub const F32X4_CONVERT_I32X4_S: u32 = 0xfa;
+ pub const F32X4_CONVERT_I32X4_U: u32 = 0xfb;
+ pub const I32X4_TRUNC_SAT_F64X2_S_ZERO: u32 = 0xfc;
+ pub const I32X4_TRUNC_SAT_F64X2_U_ZERO: u32 = 0xfd;
+ pub const F64X2_CONVERT_LOW_I32X4_S: u32 = 0xfe;
+ pub const F64X2_CONVERT_LOW_I32X4_U: u32 = 0xff;
+ pub const I8X16_RELAXED_SWIZZLE: u32 = 0x100;
+ pub const I32X4_RELAXED_TRUNC_F32X4_S: u32 = 0x101;
+ pub const I32X4_RELAXED_TRUNC_F32X4_U: u32 = 0x102;
+ pub const I32X4_RELAXED_TRUNC_F64X2_S_ZERO: u32 = 0x103;
+ pub const I32X4_RELAXED_TRUNC_F64X2_U_ZERO: u32 = 0x104;
+ pub const F32X4_RELAXED_MADD: u32 = 0x105;
+ pub const F32X4_RELAXED_NMADD: u32 = 0x106;
+ pub const F64X2_RELAXED_MADD: u32 = 0x107;
+ pub const F64X2_RELAXED_NMADD: u32 = 0x108;
+ pub const I8X16_RELAXED_LANESELECT: u32 = 0x109;
+ pub const I16X8_RELAXED_LANESELECT: u32 = 0x10a;
+ pub const I32X4_RELAXED_LANESELECT: u32 = 0x10b;
+ pub const I64X2_RELAXED_LANESELECT: u32 = 0x10c;
+ pub const F32X4_RELAXED_MIN: u32 = 0x10d;
+ pub const F32X4_RELAXED_MAX: u32 = 0x10e;
+ pub const F64X2_RELAXED_MIN: u32 = 0x10f;
+ pub const F64X2_RELAXED_MAX: u32 = 0x110;
+ pub const I16X8_RELAXED_Q15MULR_S: u32 = 0x111;
+ pub const I16X8_RELAXED_DOT_I8X16_I7X16_S: u32 = 0x112;
+ pub const I32X4_RELAXED_DOT_I8X16_I7X16_ADD_S: u32 = 0x113;
+}
+
+pub mod atomic {
+ pub const MEMORY_ATOMIC_NOTIFY: u32 = 0x0;
+ pub const MEMORY_ATOMIC_WAIT32: u32 = 0x1;
+ pub const MEMORY_ATOMIC_WAIT64: u32 = 0x2;
+ pub const ATOMIC_FENCE: u32 = 0x3;
+ pub const I32_ATOMIC_LOAD: u32 = 0x10;
+ pub const I64_ATOMIC_LOAD: u32 = 0x11;
+ pub const I32_ATOMIC_LOAD8_U: u32 = 0x12;
+ pub const I32_ATOMIC_LOAD16_U: u32 = 0x13;
+ pub const I64_ATOMIC_LOAD8_U: u32 = 0x14;
+ pub const I64_ATOMIC_LOAD16_U: u32 = 0x15;
+ pub const I64_ATOMIC_LOAD32_U: u32 = 0x16;
+ pub const I32_ATOMIC_STORE: u32 = 0x17;
+ pub const I64_ATOMIC_STORE: u32 = 0x18;
+ pub const I32_ATOMIC_STORE8: u32 = 0x19;
+ pub const I32_ATOMIC_STORE16: u32 = 0x1a;
+ pub const I64_ATOMIC_STORE8: u32 = 0x1b;
+ pub const I64_ATOMIC_STORE16: u32 = 0x1c;
+ pub const I64_ATOMIC_STORE32: u32 = 0x1d;
+ pub const I32_ATOMIC_RMW_ADD: u32 = 0x1e;
+ pub const I64_ATOMIC_RMW_ADD: u32 = 0x1f;
+ pub const I32_ATOMIC_RMW8_ADD_U: u32 = 0x20;
+ pub const I32_ATOMIC_RMW16_ADD_U: u32 = 0x21;
+ pub const I64_ATOMIC_RMW8_ADD_U: u32 = 0x22;
+ pub const I64_ATOMIC_RMW16_ADD_U: u32 = 0x23;
+ pub const I64_ATOMIC_RMW32_ADD_U: u32 = 0x24;
+ pub const I32_ATOMIC_RMW_SUB: u32 = 0x25;
+ pub const I64_ATOMIC_RMW_SUB: u32 = 0x26;
+ pub const I32_ATOMIC_RMW8_SUB_U: u32 = 0x27;
+ pub const I32_ATOMIC_RMW16_SUB_U: u32 = 0x28;
+ pub const I64_ATOMIC_RMW8_SUB_U: u32 = 0x29;
+ pub const I64_ATOMIC_RMW16_SUB_U: u32 = 0x2a;
+ pub const I64_ATOMIC_RMW32_SUB_U: u32 = 0x2b;
+ pub const I32_ATOMIC_RMW_AND: u32 = 0x2c;
+ pub const I64_ATOMIC_RMW_AND: u32 = 0x2d;
+ pub const I32_ATOMIC_RMW8_AND_U: u32 = 0x2e;
+ pub const I32_ATOMIC_RMW16_AND_U: u32 = 0x2f;
+ pub const I64_ATOMIC_RMW8_AND_U: u32 = 0x30;
+ pub const I64_ATOMIC_RMW16_AND_U: u32 = 0x31;
+ pub const I64_ATOMIC_RMW32_AND_U: u32 = 0x32;
+ pub const I32_ATOMIC_RMW_OR: u32 = 0x33;
+ pub const I64_ATOMIC_RMW_OR: u32 = 0x34;
+ pub const I32_ATOMIC_RMW8_OR_U: u32 = 0x35;
+ pub const I32_ATOMIC_RMW16_OR_U: u32 = 0x36;
+ pub const I64_ATOMIC_RMW8_OR_U: u32 = 0x37;
+ pub const I64_ATOMIC_RMW16_OR_U: u32 = 0x38;
+ pub const I64_ATOMIC_RMW32_OR_U: u32 = 0x39;
+ pub const I32_ATOMIC_RMW_XOR: u32 = 0x3a;
+ pub const I64_ATOMIC_RMW_XOR: u32 = 0x3b;
+ pub const I32_ATOMIC_RMW8_XOR_U: u32 = 0x3c;
+ pub const I32_ATOMIC_RMW16_XOR_U: u32 = 0x3d;
+ pub const I64_ATOMIC_RMW8_XOR_U: u32 = 0x3e;
+ pub const I64_ATOMIC_RMW16_XOR_U: u32 = 0x3f;
+ pub const I64_ATOMIC_RMW32_XOR_U: u32 = 0x40;
+ pub const I32_ATOMIC_RMW_XCHG: u32 = 0x41;
+ pub const I64_ATOMIC_RMW_XCHG: u32 = 0x42;
+ pub const I32_ATOMIC_RMW8_XCHG_U: u32 = 0x43;
+ pub const I32_ATOMIC_RMW16_XCHG_U: u32 = 0x44;
+ pub const I64_ATOMIC_RMW8_XCHG_U: u32 = 0x45;
+ pub const I64_ATOMIC_RMW16_XCHG_U: u32 = 0x46;
+ pub const I64_ATOMIC_RMW32_XCHG_U: u32 = 0x47;
+ pub const I32_ATOMIC_RMW_CMPXCHG: u32 = 0x48;
+ pub const I64_ATOMIC_RMW_CMPXCHG: u32 = 0x49;
+ pub const I32_ATOMIC_RMW8_CMPXCHG_U: u32 = 0x4a;
+ pub const I32_ATOMIC_RMW16_CMPXCHG_U: u32 = 0x4b;
+ pub const I64_ATOMIC_RMW8_CMPXCHG_U: u32 = 0x4c;
+ pub const I64_ATOMIC_RMW16_CMPXCHG_U: u32 = 0x4d;
+ pub const I64_ATOMIC_RMW32_CMPXCHG_U: u32 = 0x4e;
+}
diff --git a/Libraries/LibWasm/Engine/src/parser.rs b/Libraries/LibWasm/Engine/src/parser.rs
new file mode 100644
index 00000000000..dcbb83117b4
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/parser.rs
@@ -0,0 +1,674 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The binary format decoder. It decodes the module structure and leaves function bodies and constant expressions as
+//! byte ranges, which validation decodes as it checks them.
+
+use crate::error::{Error, Result};
+use crate::module::{
+ ConstantExpression, Data, DataMode, Element, ElementItems, ElementMode, Export, ExternalKind, FunctionBody, Global,
+ Import, ImportDescription, Module, RecursionGroup, Table,
+};
+use crate::opcode;
+use crate::reader::Reader;
+use crate::types::{
+ AddressType, CompositeType, FieldType, FuncType, GlobalType, HeapType, Limits, MemoryType, RefType, StorageType,
+ SubType, TableType, TagType, ValType,
+};
+
+/// The most locals one (count, type) run of a function may declare. Every local takes a slot of the function's
+/// machine stack frame, so this bounds the frame size a module can ask for.
+pub const MAX_LOCALS_PER_RUN: u32 = 42069;
+
+const SECTION_CUSTOM: u8 = 0;
+const SECTION_TYPE: u8 = 1;
+const SECTION_IMPORT: u8 = 2;
+const SECTION_FUNCTION: u8 = 3;
+const SECTION_TABLE: u8 = 4;
+const SECTION_MEMORY: u8 = 5;
+const SECTION_GLOBAL: u8 = 6;
+const SECTION_EXPORT: u8 = 7;
+const SECTION_START: u8 = 8;
+const SECTION_ELEMENT: u8 = 9;
+const SECTION_CODE: u8 = 10;
+const SECTION_DATA: u8 = 11;
+const SECTION_DATA_COUNT: u8 = 12;
+const SECTION_TAG: u8 = 13;
+
+/// The position of each non-custom section in the order the binary format requires.
+fn section_order(id: u8) -> Option<u8> {
+ Some(match id {
+ SECTION_TYPE => 1,
+ SECTION_IMPORT => 2,
+ SECTION_FUNCTION => 3,
+ SECTION_TABLE => 4,
+ SECTION_MEMORY => 5,
+ SECTION_TAG => 6,
+ SECTION_GLOBAL => 7,
+ SECTION_EXPORT => 8,
+ SECTION_START => 9,
+ SECTION_ELEMENT => 10,
+ SECTION_DATA_COUNT => 11,
+ SECTION_CODE => 12,
+ SECTION_DATA => 13,
+ _ => return None,
+ })
+}
+
+pub fn parse(bytes: &[u8]) -> Result<Module> {
+ let mut module = Module {
+ bytes: bytes.into(),
+ ..Module::default()
+ };
+ let mut reader = Reader::new(bytes);
+ let magic = reader.read_bytes(4).map_err(|_| Error::malformed("unexpected end"))?;
+ if magic != b"\0asm" {
+ return Err(Error::malformed("magic header not detected"));
+ }
+ let version = reader.read_bytes(4).map_err(|_| Error::malformed("unexpected end"))?;
+ if version != [1, 0, 0, 0] {
+ return Err(Error::malformed("unknown binary version"));
+ }
+
+ let mut last_order = 0;
+ let mut function_count = None;
+ while !reader.is_at_end() {
+ let id = reader.read_u8()?;
+ let size = reader.read_u32()?;
+ let mut section = reader.sub_reader(size as usize)?;
+ if id != SECTION_CUSTOM {
+ let order = section_order(id).ok_or_else(|| Error::malformed("malformed section id"))?;
+ if order <= last_order {
+ return Err(Error::malformed("unexpected content after last section"));
+ }
+ last_order = order;
+ }
+ match id {
+ SECTION_CUSTOM => {
+ section.read_name()?;
+ continue;
+ }
+ SECTION_TYPE => parse_type_section(&mut section, &mut module)?,
+ SECTION_IMPORT => parse_import_section(&mut section, &mut module)?,
+ SECTION_FUNCTION => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let type_index = section.read_u32()?;
+ module.functions.push(type_index);
+ module.function_space.push(type_index);
+ }
+ function_count = Some(count);
+ }
+ SECTION_TABLE => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let table = parse_table(&mut section)?;
+ module.table_space.push(table.ty);
+ module.tables.push(table);
+ }
+ }
+ SECTION_MEMORY => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let memory = parse_memory_type(&mut section)?;
+ module.memory_space.push(memory);
+ module.memories.push(memory);
+ }
+ }
+ SECTION_TAG => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let tag = parse_tag_type(&mut section)?;
+ module.tag_space.push(tag);
+ module.tags.push(tag);
+ }
+ }
+ SECTION_GLOBAL => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let ty = parse_global_type(&mut section)?;
+ let initializer = parse_constant_expression(&mut section)?;
+ module.global_space.push(ty);
+ module.globals.push(Global { ty, initializer });
+ }
+ }
+ SECTION_EXPORT => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let name = section.read_name()?.to_string();
+ let kind = match section.read_u8()? {
+ 0x00 => ExternalKind::Function,
+ 0x01 => ExternalKind::Table,
+ 0x02 => ExternalKind::Memory,
+ 0x03 => ExternalKind::Global,
+ 0x04 => ExternalKind::Tag,
+ _ => return Err(Error::malformed("malformed export kind")),
+ };
+ let index = section.read_u32()?;
+ module.exports.push(Export { name, kind, index });
+ }
+ }
+ SECTION_START => module.start = Some(section.read_u32()?),
+ SECTION_ELEMENT => {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ module.elements.push(parse_element(&mut section)?);
+ }
+ }
+ SECTION_DATA_COUNT => module.data_count = Some(section.read_u32()?),
+ SECTION_CODE => {
+ let count = section.read_vector_length()?;
+ if function_count.unwrap_or(0) != count {
+ return Err(Error::malformed("function and code section have inconsistent lengths"));
+ }
+ for _ in 0..count {
+ module.code.push(parse_function_body(&mut section)?);
+ }
+ }
+ SECTION_DATA => {
+ let count = section.read_vector_length()?;
+ if let Some(data_count) = module.data_count
+ && data_count != count
+ {
+ return Err(Error::malformed(
+ "data count and data section have inconsistent lengths",
+ ));
+ }
+ for _ in 0..count {
+ module.data.push(parse_data(&mut section)?);
+ }
+ }
+ _ => unreachable!("section ids are checked above"),
+ }
+ if !section.is_at_end() {
+ return Err(Error::malformed("section size mismatch"));
+ }
+ }
+ if function_count.unwrap_or(0) != 0 && module.code.is_empty() {
+ return Err(Error::malformed("function and code section have inconsistent lengths"));
+ }
+ if module.data_count.is_some_and(|count| count != 0) && module.data.is_empty() {
+ return Err(Error::malformed(
+ "data count and data section have inconsistent lengths",
+ ));
+ }
+ Ok(module)
+}
+
+fn parse_type_section(section: &mut Reader<'_>, module: &mut Module) -> Result<()> {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let start = module.types.len() as u32;
+ if section.peek_u8()? == 0x4e {
+ section.read_u8()?;
+ let group_size = section.read_vector_length()?;
+ for _ in 0..group_size {
+ module.types.push(parse_sub_type(section)?);
+ }
+ } else {
+ module.types.push(parse_sub_type(section)?);
+ }
+ let count = module.types.len() as u32 - start;
+ module.recursion_groups.push(RecursionGroup { start, count });
+ }
+ Ok(())
+}
+
+fn parse_sub_type(reader: &mut Reader<'_>) -> Result<SubType> {
+ let (is_final, supertypes) = match reader.peek_u8()? {
+ byte @ (0x50 | 0x4f) => {
+ reader.read_u8()?;
+ let count = reader.read_vector_length()?;
+ let mut supertypes = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ supertypes.push(reader.read_u32()?);
+ }
+ (byte == 0x4f, supertypes)
+ }
+ _ => (true, Vec::new()),
+ };
+ let composite = match reader.read_u8()? {
+ 0x60 => {
+ let params = parse_value_types(reader)?;
+ let results = parse_value_types(reader)?;
+ CompositeType::Func(FuncType { params, results })
+ }
+ 0x5f => {
+ let count = reader.read_vector_length()?;
+ let mut fields = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ fields.push(parse_field_type(reader)?);
+ }
+ CompositeType::Struct(fields)
+ }
+ 0x5e => CompositeType::Array(parse_field_type(reader)?),
+ _ => return Err(Error::malformed("integer representation too long")),
+ };
+ Ok(SubType {
+ is_final,
+ supertypes,
+ composite,
+ })
+}
+
+fn parse_field_type(reader: &mut Reader<'_>) -> Result<FieldType> {
+ let storage = match reader.peek_u8()? {
+ 0x78 => {
+ reader.read_u8()?;
+ StorageType::I8
+ }
+ 0x77 => {
+ reader.read_u8()?;
+ StorageType::I16
+ }
+ _ => StorageType::Val(parse_value_type(reader)?),
+ };
+ let mutable = match reader.read_u8()? {
+ 0 => false,
+ 1 => true,
+ _ => return Err(Error::malformed("malformed mutability")),
+ };
+ Ok(FieldType { storage, mutable })
+}
+
+fn parse_value_types(reader: &mut Reader<'_>) -> Result<Vec<ValType>> {
+ let count = reader.read_vector_length()?;
+ let mut types = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ types.push(parse_value_type(reader)?);
+ }
+ Ok(types)
+}
+
+/// The abstract heap type a single byte encodes, both as a shorthand reference type (nullable) and as a heap type.
+fn abstract_heap_type(byte: u8) -> Option<HeapType> {
+ Some(match byte {
+ 0x70 => HeapType::Func,
+ 0x73 => HeapType::NoFunc,
+ 0x6f => HeapType::Extern,
+ 0x72 => HeapType::NoExtern,
+ 0x6e => HeapType::Any,
+ 0x6d => HeapType::Eq,
+ 0x6c => HeapType::I31,
+ 0x6b => HeapType::Struct,
+ 0x6a => HeapType::Array,
+ 0x71 => HeapType::None,
+ 0x69 => HeapType::Exn,
+ 0x74 => HeapType::NoExn,
+ _ => return None,
+ })
+}
+
+pub fn parse_heap_type(reader: &mut Reader<'_>) -> Result<HeapType> {
+ if let Some(heap) = abstract_heap_type(reader.peek_u8()?) {
+ reader.read_u8()?;
+ return Ok(heap);
+ }
+ let index = reader.read_s33()?;
+ if index < 0 {
+ return Err(Error::malformed("malformed reference type"));
+ }
+ u32::try_from(index)
+ .map(HeapType::Concrete)
+ .map_err(|_| Error::malformed("malformed reference type"))
+}
+
+pub fn parse_reference_type(reader: &mut Reader<'_>) -> Result<RefType> {
+ let byte = reader.read_u8()?;
+ match byte {
+ 0x63 => Ok(RefType::new(true, parse_heap_type(reader)?)),
+ 0x64 => Ok(RefType::new(false, parse_heap_type(reader)?)),
+ _ => abstract_heap_type(byte)
+ .map(|heap| RefType::new(true, heap))
+ .ok_or_else(|| Error::malformed("malformed reference type")),
+ }
+}
+
+pub fn parse_value_type(reader: &mut Reader<'_>) -> Result<ValType> {
+ let value = match reader.peek_u8()? {
+ 0x7f => ValType::I32,
+ 0x7e => ValType::I64,
+ 0x7d => ValType::F32,
+ 0x7c => ValType::F64,
+ 0x7b => ValType::V128,
+ _ => return Ok(ValType::Ref(parse_reference_type(reader)?)),
+ };
+ reader.read_u8()?;
+ Ok(value)
+}
+
+fn parse_limits(reader: &mut Reader<'_>, is_memory: bool) -> Result<Limits> {
+ let flags = reader.read_u8()?;
+ let valid_flags = if is_memory { 0x07 } else { 0x05 };
+ if flags & !valid_flags != 0 {
+ return Err(Error::malformed(if is_memory {
+ "malformed memory limits flags"
+ } else {
+ "malformed table limits flags"
+ }));
+ }
+ let address_type = if flags & 0x04 != 0 {
+ AddressType::I64
+ } else {
+ AddressType::I32
+ };
+ let read = |reader: &mut Reader<'_>| match address_type {
+ AddressType::I32 => reader.read_u32().map(u64::from),
+ AddressType::I64 => reader.read_u64(),
+ };
+ let min = read(reader)?;
+ let max = if flags & 0x01 != 0 { Some(read(reader)?) } else { None };
+ Ok(Limits {
+ min,
+ max,
+ address_type,
+ shared: flags & 0x02 != 0,
+ })
+}
+
+fn parse_table_type(reader: &mut Reader<'_>) -> Result<TableType> {
+ let element = parse_reference_type(reader)?;
+ let limits = parse_limits(reader, false)?;
+ Ok(TableType { element, limits })
+}
+
+fn parse_table(reader: &mut Reader<'_>) -> Result<Table> {
+ if reader.peek_u8()? == 0x40 {
+ reader.read_u8()?;
+ if reader.read_u8()? != 0x00 {
+ return Err(Error::malformed("malformed table"));
+ }
+ let ty = parse_table_type(reader)?;
+ let initializer = parse_constant_expression(reader)?;
+ return Ok(Table {
+ ty,
+ initializer: Some(initializer),
+ });
+ }
+ Ok(Table {
+ ty: parse_table_type(reader)?,
+ initializer: None,
+ })
+}
+
+fn parse_memory_type(reader: &mut Reader<'_>) -> Result<MemoryType> {
+ Ok(MemoryType {
+ limits: parse_limits(reader, true)?,
+ })
+}
+
+fn parse_global_type(reader: &mut Reader<'_>) -> Result<GlobalType> {
+ let value = parse_value_type(reader)?;
+ let mutable = match reader.read_u8()? {
+ 0 => false,
+ 1 => true,
+ _ => return Err(Error::malformed("malformed mutability")),
+ };
+ Ok(GlobalType { value, mutable })
+}
+
+fn parse_tag_type(reader: &mut Reader<'_>) -> Result<TagType> {
+ if reader.read_u8()? != 0x00 {
+ return Err(Error::malformed("malformed tag attribute"));
+ }
+ Ok(TagType {
+ type_index: reader.read_u32()?,
+ })
+}
+
+fn parse_import_section(section: &mut Reader<'_>, module: &mut Module) -> Result<()> {
+ let count = section.read_vector_length()?;
+ for _ in 0..count {
+ let module_name = section.read_name()?.to_string();
+ let name = section.read_name()?.to_string();
+ let description = match section.read_u8()? {
+ 0x00 => {
+ let type_index = section.read_u32()?;
+ module.function_space.push(type_index);
+ module.imported_function_count += 1;
+ ImportDescription::Function(type_index)
+ }
+ 0x01 => {
+ let table = parse_table_type(section)?;
+ module.table_space.push(table);
+ module.imported_table_count += 1;
+ ImportDescription::Table(table)
+ }
+ 0x02 => {
+ let memory = parse_memory_type(section)?;
+ module.memory_space.push(memory);
+ module.imported_memory_count += 1;
+ ImportDescription::Memory(memory)
+ }
+ 0x03 => {
+ let global = parse_global_type(section)?;
+ module.global_space.push(global);
+ module.imported_global_count += 1;
+ ImportDescription::Global(global)
+ }
+ 0x04 => {
+ let tag = parse_tag_type(section)?;
+ module.tag_space.push(tag);
+ module.imported_tag_count += 1;
+ ImportDescription::Tag(tag)
+ }
+ _ => return Err(Error::malformed("malformed import kind")),
+ };
+ module.imports.push(Import {
+ module: module_name,
+ name,
+ description,
+ });
+ }
+ Ok(())
+}
+
+/// Skip over the instructions of a constant expression up to and including its `end`. Only the instructions a
+/// constant expression may contain are decoded; anything else is left for validation to reject.
+pub fn parse_constant_expression(reader: &mut Reader<'_>) -> Result<ConstantExpression> {
+ let start = reader.position() as u32;
+ loop {
+ let opcode = reader.read_u8()?;
+ match opcode {
+ opcode::END => break,
+ opcode::I32_CONST => {
+ reader.read_i32()?;
+ }
+ opcode::I64_CONST => {
+ reader.read_i64()?;
+ }
+ opcode::F32_CONST => {
+ reader.read_bytes(4)?;
+ }
+ opcode::F64_CONST => {
+ reader.read_bytes(8)?;
+ }
+ opcode::REF_NULL => {
+ parse_heap_type(reader)?;
+ }
+ opcode::REF_FUNC | opcode::GLOBAL_GET => {
+ reader.read_u32()?;
+ }
+ opcode::I32_ADD
+ | opcode::I32_SUB
+ | opcode::I32_MUL
+ | opcode::I64_ADD
+ | opcode::I64_SUB
+ | opcode::I64_MUL => {}
+ opcode::PREFIX_SIMD => {
+ let sub_opcode = reader.read_u32()?;
+ if sub_opcode != opcode::simd::V128_CONST {
+ return Err(Error::invalid("constant expression required"));
+ }
+ reader.read_bytes(16)?;
+ }
+ opcode::PREFIX_GC => {
+ let sub_opcode = reader.read_u32()?;
+ match sub_opcode {
+ opcode::gc::STRUCT_NEW
+ | opcode::gc::STRUCT_NEW_DEFAULT
+ | opcode::gc::ARRAY_NEW
+ | opcode::gc::ARRAY_NEW_DEFAULT => {
+ reader.read_u32()?;
+ }
+ opcode::gc::ARRAY_NEW_FIXED => {
+ reader.read_u32()?;
+ reader.read_u32()?;
+ }
+ opcode::gc::REF_I31 | opcode::gc::ANY_CONVERT_EXTERN | opcode::gc::EXTERN_CONVERT_ANY => {}
+ _ => return Err(Error::invalid("constant expression required")),
+ }
+ }
+ _ => return Err(Error::invalid("constant expression required")),
+ }
+ }
+ Ok(ConstantExpression {
+ code: start..reader.position() as u32,
+ })
+}
+
+fn parse_function_indices(reader: &mut Reader<'_>) -> Result<ElementItems> {
+ let count = reader.read_vector_length()?;
+ let mut functions = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ functions.push(reader.read_u32()?);
+ }
+ Ok(ElementItems::Functions(functions))
+}
+
+fn parse_element_expressions(reader: &mut Reader<'_>) -> Result<ElementItems> {
+ let count = reader.read_vector_length()?;
+ let mut expressions = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ expressions.push(parse_constant_expression(reader)?);
+ }
+ Ok(ElementItems::Expressions(expressions))
+}
+
+/// Segments of function indices hold non-null function references.
+const FUNCTION_INDEX_ELEMENT_TYPE: RefType = RefType {
+ nullable: false,
+ heap: HeapType::Func,
+};
+
+fn parse_element_kind(reader: &mut Reader<'_>) -> Result<RefType> {
+ if reader.read_u8()? != 0x00 {
+ return Err(Error::malformed("malformed element kind"));
+ }
+ Ok(FUNCTION_INDEX_ELEMENT_TYPE)
+}
+
+fn parse_element(reader: &mut Reader<'_>) -> Result<Element> {
+ let flags = reader.read_u32()?;
+ let (ty, mode, items) = match flags {
+ 0 => {
+ let offset = parse_constant_expression(reader)?;
+ let items = parse_function_indices(reader)?;
+ (
+ FUNCTION_INDEX_ELEMENT_TYPE,
+ ElementMode::Active { table: 0, offset },
+ items,
+ )
+ }
+ 1 => {
+ let ty = parse_element_kind(reader)?;
+ (ty, ElementMode::Passive, parse_function_indices(reader)?)
+ }
+ 2 => {
+ let table = reader.read_u32()?;
+ let offset = parse_constant_expression(reader)?;
+ let ty = parse_element_kind(reader)?;
+ (
+ ty,
+ ElementMode::Active { table, offset },
+ parse_function_indices(reader)?,
+ )
+ }
+ 3 => {
+ let ty = parse_element_kind(reader)?;
+ (ty, ElementMode::Declarative, parse_function_indices(reader)?)
+ }
+ 4 => {
+ let offset = parse_constant_expression(reader)?;
+ let items = parse_element_expressions(reader)?;
+ (RefType::FUNCREF, ElementMode::Active { table: 0, offset }, items)
+ }
+ 5 => {
+ let ty = parse_reference_type(reader)?;
+ (ty, ElementMode::Passive, parse_element_expressions(reader)?)
+ }
+ 6 => {
+ let table = reader.read_u32()?;
+ let offset = parse_constant_expression(reader)?;
+ let ty = parse_reference_type(reader)?;
+ (
+ ty,
+ ElementMode::Active { table, offset },
+ parse_element_expressions(reader)?,
+ )
+ }
+ 7 => {
+ let ty = parse_reference_type(reader)?;
+ (ty, ElementMode::Declarative, parse_element_expressions(reader)?)
+ }
+ _ => return Err(Error::malformed("malformed elements segment kind")),
+ };
+ Ok(Element { ty, mode, items })
+}
+
+fn parse_data(reader: &mut Reader<'_>) -> Result<Data> {
+ let flags = reader.read_u32()?;
+ let mode = match flags {
+ 0 => DataMode::Active {
+ memory: 0,
+ offset: parse_constant_expression(reader)?,
+ },
+ 1 => DataMode::Passive,
+ 2 => {
+ let memory = reader.read_u32()?;
+ DataMode::Active {
+ memory,
+ offset: parse_constant_expression(reader)?,
+ }
+ }
+ _ => return Err(Error::malformed("malformed data segment kind")),
+ };
+ let length = reader.read_u32()?;
+ let start = reader.position() as u32;
+ reader.read_bytes(length as usize)?;
+ Ok(Data {
+ mode,
+ bytes: start..start + length,
+ })
+}
+
+fn parse_function_body(section: &mut Reader<'_>) -> Result<FunctionBody> {
+ let size = section.read_u32()?;
+ let mut body = section.sub_reader(size as usize)?;
+ let run_count = body.read_u32()?;
+ let mut locals = Vec::new();
+ let mut declared_local_count = 0u32;
+ for _ in 0..run_count {
+ let count = body.read_u32()?;
+ if count > MAX_LOCALS_PER_RUN {
+ return Err(Error::malformed("too many locals"));
+ }
+ declared_local_count = declared_local_count
+ .checked_add(count)
+ .ok_or_else(|| Error::malformed("too many locals"))?;
+ let ty = parse_value_type(&mut body)?;
+ locals.push((count, ty));
+ }
+ let start = body.position() as u32;
+ if body.is_at_end() {
+ return Err(Error::malformed("unexpected end of section or function"));
+ }
+ Ok(FunctionBody {
+ locals,
+ declared_local_count,
+ code: start..body.end() as u32,
+ })
+}
diff --git a/Libraries/LibWasm/Engine/src/quickening.rs b/Libraries/LibWasm/Engine/src/quickening.rs
new file mode 100644
index 00000000000..954a8995287
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/quickening.rs
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Quickening: the validator rewrites some instructions in the engine's own copy of a module's code into forms that
+//! say what validation found out about them, so that the interpreter's handlers for the common forms need no checks.
+//! These rules are a contract between the validator and everything that executes code: the interpreter and the JIT.
+//!
+//! A rewrite never changes the length of an instruction or moves any other one, so branch targets and side-table
+//! entries stay valid. Quickened forms use bytes WebAssembly leaves unused:
+//!
+//! - The prefix 0xFF, followed by a one-byte sub-opcode, for instructions with an immediate byte to spare.
+//! - Single-byte opcodes from 0xF4 to 0xFA, for instructions with none (0xF0 to 0xF3 are the runtime's entry and exit
+//! pseudo-instructions).
+//!
+//! The rules:
+//!
+//! 1. A core load or store (opcodes 0x28 to 0x3E) that cannot use the guard pages of memory 0, because it accesses
+//! another memory or memory 0 is a memory64, becomes an explicitly bounds-checked access:
+//!
+//! `op align [memory] offset` becomes `0xFF sub [memory] offset 0x01*`, where sub is the original opcode, plus 0x40
+//! if a memory index follows. The memory index and offset keep their original encodings. The alignment, which only
+//! matters to validation, is dropped; if it took more than one byte, `nop` instructions (0x01) fill the bytes it
+//! leaves over, after the access.
+//!
+//! A SIMD load or store (0xFD followed by sub-opcode 0x00 to 0x0B or 0x54 to 0x5D) on such a memory works the same
+//! way, with its own sub-opcode: 0x80 plus the position of its SIMD sub-opcode in `SIMD_ACCESSES`, plus 0x20 if a
+//! memory index follows. A lane index, if the instruction has one, comes after the offset, and `nop` instructions
+//! fill what the SIMD sub-opcode and alignment leave over.
+//!
+//! 2. An instruction whose operand or local type is v128, where the plain form assumes a single 8-byte slot, becomes
+//! its v128 form with the same immediates (see `V128_FORMS`).
+//!
+//! Executing code may assume these rules have been applied: plain loads and stores access memory 0, which is a
+//! memory32 with guard pages, and the plain forms of the instructions in rule 2 never see v128 values.
+
+pub const QUICK_PREFIX: u8 = 0xff;
+
+/// The sub-opcode bit that says a memory index follows.
+pub const CHECKED_ACCESS_HAS_MEMORY_INDEX: u8 = 0x40;
+
+/// The first sub-opcode of checked SIMD accesses, and the bit that says a memory index follows.
+pub const CHECKED_SIMD_ACCESS: u8 = 0x80;
+pub const CHECKED_SIMD_ACCESS_HAS_MEMORY_INDEX: u8 = 0x20;
+
+/// The SIMD sub-opcodes of the loads and stores, in the order of their checked sub-opcodes.
+pub const SIMD_ACCESSES: [u32; 22] = [
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,
+ 0x5b, 0x5c, 0x5d,
+];
+
+pub const LOCAL_GET_V128: u8 = 0xf4;
+pub const LOCAL_SET_V128: u8 = 0xf5;
+pub const LOCAL_TEE_V128: u8 = 0xf6;
+pub const GLOBAL_GET_V128: u8 = 0xf7;
+pub const GLOBAL_SET_V128: u8 = 0xf8;
+pub const DROP_V128: u8 = 0xf9;
+pub const SELECT_V128: u8 = 0xfa;
+
+/// Each plain opcode with a v128 form, and that form.
+pub const V128_FORMS: [(u8, u8); 7] = [
+ (crate::opcode::LOCAL_GET, LOCAL_GET_V128),
+ (crate::opcode::LOCAL_SET, LOCAL_SET_V128),
+ (crate::opcode::LOCAL_TEE, LOCAL_TEE_V128),
+ (crate::opcode::GLOBAL_GET, GLOBAL_GET_V128),
+ (crate::opcode::GLOBAL_SET, GLOBAL_SET_V128),
+ (crate::opcode::DROP, DROP_V128),
+ (crate::opcode::SELECT, SELECT_V128),
+];
+
+/// The v128 form of a plain opcode.
+pub fn v128_form(opcode: u8) -> Option<u8> {
+ V128_FORMS
+ .iter()
+ .find_map(|&(plain, quickened)| (plain == opcode).then_some(quickened))
+}
+
+/// Bytes to write over a module's code, starting at `position`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Rewrite {
+ pub position: u32,
+ pub bytes: Vec<u8>,
+}
+
+/// The rewrite of rule 1, for the access whose opcode is at `position`, with the alignment, memory index (if any),
+/// and offset immediates encoded in the given byte ranges of `code`.
+pub fn checked_access(
+ code: &[u8],
+ position: usize,
+ alignment: std::ops::Range<usize>,
+ memory: Option<std::ops::Range<usize>>,
+ offset: std::ops::Range<usize>,
+) -> Rewrite {
+ let opcode = code[position];
+ let mut bytes = vec![
+ QUICK_PREFIX,
+ opcode
+ | if memory.is_some() {
+ CHECKED_ACCESS_HAS_MEMORY_INDEX
+ } else {
+ 0
+ },
+ ];
+ if let Some(memory) = memory {
+ bytes.extend_from_slice(&code[memory]);
+ }
+ bytes.extend_from_slice(&code[offset]);
+ bytes.extend(std::iter::repeat_n(crate::opcode::NOP, alignment.len() - 1));
+ Rewrite {
+ position: position as u32,
+ bytes,
+ }
+}
+
+/// The rewrite of rule 1 for the SIMD access whose prefix is at `position`, its sub-opcode `sub_opcode`, its
+/// alignment, memory index, and offset immediates in the given ranges of `code`, and a lane index at `lane` if it has
+/// one. `end` is where the instruction ends.
+pub fn checked_simd_access(
+ code: &[u8],
+ position: usize,
+ sub_opcode: u32,
+ memory: Option<std::ops::Range<usize>>,
+ offset: std::ops::Range<usize>,
+ end: usize,
+) -> Rewrite {
+ let index = SIMD_ACCESSES
+ .iter()
+ .position(|&access| access == sub_opcode)
+ .expect("only SIMD accesses are rewritten") as u8;
+ let mut bytes = vec![
+ QUICK_PREFIX,
+ CHECKED_SIMD_ACCESS
+ + index
+ + if memory.is_some() {
+ CHECKED_SIMD_ACCESS_HAS_MEMORY_INDEX
+ } else {
+ 0
+ },
+ ];
+ if let Some(memory) = memory {
+ bytes.extend_from_slice(&code[memory]);
+ }
+ bytes.extend_from_slice(&code[offset.start..end]);
+ let length = end - position;
+ bytes.resize(length, crate::opcode::NOP);
+ Rewrite {
+ position: position as u32,
+ bytes,
+ }
+}
+
+/// Apply rewrites to a module's code.
+pub fn apply(code: &mut [u8], rewrites: &[Rewrite]) {
+ for rewrite in rewrites {
+ let start = rewrite.position as usize;
+ code[start..start + rewrite.bytes.len()].copy_from_slice(&rewrite.bytes);
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/reader.rs b/Libraries/LibWasm/Engine/src/reader.rs
new file mode 100644
index 00000000000..a90cafeb185
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/reader.rs
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! A cursor over the bytes of a binary module.
+
+use crate::error::{Error, Result};
+
+#[derive(Clone)]
+pub struct Reader<'a> {
+ bytes: &'a [u8],
+ position: usize,
+ end: usize,
+}
+
+impl<'a> Reader<'a> {
+ pub fn new(bytes: &'a [u8]) -> Self {
+ Self {
+ bytes,
+ position: 0,
+ end: bytes.len(),
+ }
+ }
+
+ /// A reader over `bytes[start..end]` that reports positions relative to the start of `bytes`.
+ pub fn with_range(bytes: &'a [u8], start: usize, end: usize) -> Self {
+ Self {
+ bytes,
+ position: start,
+ end,
+ }
+ }
+
+ pub fn bytes(&self) -> &'a [u8] {
+ self.bytes
+ }
+
+ pub fn position(&self) -> usize {
+ self.position
+ }
+
+ pub fn end(&self) -> usize {
+ self.end
+ }
+
+ pub fn is_at_end(&self) -> bool {
+ self.position >= self.end
+ }
+
+ pub fn remaining(&self) -> usize {
+ self.end - self.position
+ }
+
+ /// A reader over the next `length` bytes, which this reader skips.
+ pub fn sub_reader(&mut self, length: usize) -> Result<Reader<'a>> {
+ if length > self.remaining() {
+ return Err(Error::malformed("unexpected end of section or function"));
+ }
+ let reader = Reader::with_range(self.bytes, self.position, self.position + length);
+ self.position += length;
+ Ok(reader)
+ }
+
+ pub fn read_u8(&mut self) -> Result<u8> {
+ if self.position >= self.end {
+ return Err(Error::malformed("unexpected end"));
+ }
+ let byte = self.bytes[self.position];
+ self.position += 1;
+ Ok(byte)
+ }
+
+ pub fn peek_u8(&self) -> Result<u8> {
+ if self.position >= self.end {
+ return Err(Error::malformed("unexpected end"));
+ }
+ Ok(self.bytes[self.position])
+ }
+
+ pub fn read_bytes(&mut self, length: usize) -> Result<&'a [u8]> {
+ if length > self.remaining() {
+ return Err(Error::malformed("unexpected end"));
+ }
+ let bytes = &self.bytes[self.position..self.position + length];
+ self.position += length;
+ Ok(bytes)
+ }
+
+ pub fn read_fixed_u32(&mut self) -> Result<u32> {
+ let bytes = self.read_bytes(4)?;
+ Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
+ }
+
+ pub fn read_fixed_u64(&mut self) -> Result<u64> {
+ let bytes = self.read_bytes(8)?;
+ let mut array = [0; 8];
+ array.copy_from_slice(bytes);
+ Ok(u64::from_le_bytes(array))
+ }
+
+ fn read_unsigned_leb(&mut self, bits: u32) -> Result<u64> {
+ let mut result = 0u64;
+ let mut shift = 0;
+ loop {
+ let byte = self.read_u8().map_err(|_| Error::malformed("unexpected end"))?;
+ let payload = u64::from(byte & 0x7f);
+ let remaining_bits = bits - shift;
+ if remaining_bits < 7 {
+ // The final byte may not set bits beyond the integer's width.
+ if byte & 0x80 != 0 || payload >> remaining_bits != 0 {
+ return Err(Error::malformed(if byte & 0x80 != 0 {
+ "integer representation too long"
+ } else {
+ "integer too large"
+ }));
+ }
+ }
+ result |= payload << shift;
+ if byte & 0x80 == 0 {
+ return Ok(result);
+ }
+ shift += 7;
+ }
+ }
+
+ fn read_signed_leb(&mut self, bits: u32) -> Result<i64> {
+ let mut result = 0i64;
+ let mut shift = 0;
+ loop {
+ let byte = self.read_u8().map_err(|_| Error::malformed("unexpected end"))?;
+ let payload = i64::from(byte & 0x7f);
+ let remaining_bits = bits - shift;
+ if remaining_bits < 7 {
+ // The unused bits of the final byte must all equal its sign bit.
+ let sign_and_unused = (byte & 0x7f) >> (remaining_bits - 1);
+ let expected = if byte & 0x40 != 0 {
+ 0x7f >> (remaining_bits - 1)
+ } else {
+ 0
+ };
+ if byte & 0x80 != 0 {
+ return Err(Error::malformed("integer representation too long"));
+ }
+ if sign_and_unused != expected {
+ return Err(Error::malformed("integer too large"));
+ }
+ }
+ result |= payload << shift;
+ shift += 7;
+ if byte & 0x80 == 0 {
+ if shift < 64 && byte & 0x40 != 0 {
+ result |= -1i64 << shift;
+ }
+ return Ok(result);
+ }
+ }
+ }
+
+ pub fn read_u32(&mut self) -> Result<u32> {
+ Ok(self.read_unsigned_leb(32)? as u32)
+ }
+
+ pub fn read_u64(&mut self) -> Result<u64> {
+ self.read_unsigned_leb(64)
+ }
+
+ pub fn read_i32(&mut self) -> Result<i32> {
+ Ok(self.read_signed_leb(32)? as i32)
+ }
+
+ pub fn read_i64(&mut self) -> Result<i64> {
+ self.read_signed_leb(64)
+ }
+
+ pub fn read_s33(&mut self) -> Result<i64> {
+ self.read_signed_leb(33)
+ }
+
+ pub fn read_name(&mut self) -> Result<&'a str> {
+ let length = self.read_u32()? as usize;
+ let bytes = self.read_bytes(length)?;
+ std::str::from_utf8(bytes).map_err(|_| Error::malformed("malformed UTF-8 encoding"))
+ }
+
+ /// The length of a vector, rejected early if it cannot fit in the remaining bytes, given that every element
+ /// takes at least one byte.
+ pub fn read_vector_length(&mut self) -> Result<u32> {
+ let length = self.read_u32()?;
+ if length as usize > self.remaining() {
+ return Err(Error::malformed("unexpected end of section or function"));
+ }
+ Ok(length)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn decodes_leb128() {
+ assert_eq!(Reader::new(&[0x7f]).read_u32().unwrap(), 127);
+ assert_eq!(Reader::new(&[0x80, 0x01]).read_u32().unwrap(), 128);
+ assert_eq!(
+ Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x0f]).read_u32().unwrap(),
+ u32::MAX
+ );
+ assert!(Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x1f]).read_u32().is_err());
+ assert!(Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x00]).read_u32().is_err());
+ assert_eq!(Reader::new(&[0x7f]).read_i32().unwrap(), -1);
+ assert_eq!(Reader::new(&[0x80, 0x7f]).read_i32().unwrap(), -128);
+ assert_eq!(
+ Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x07]).read_i32().unwrap(),
+ i32::MAX
+ );
+ assert_eq!(
+ Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x78]).read_i32().unwrap(),
+ i32::MIN
+ );
+ assert!(Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x0f]).read_i32().is_err());
+ assert!(Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x70]).read_i32().is_err());
+ assert_eq!(
+ Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f])
+ .read_i64()
+ .unwrap(),
+ i64::MIN
+ );
+ assert_eq!(Reader::new(&[0x40]).read_s33().unwrap(), -64);
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/constant.rs b/Libraries/LibWasm/Engine/src/runtime/constant.rs
new file mode 100644
index 00000000000..a68220aa9aa
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/constant.rs
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Evaluating the constant expressions that initialize globals, tables, and segments.
+
+use super::{FunctionAddress, GlobalAddress, Store, Trap, Value};
+use crate::module::{ConstantExpression, Module};
+use crate::opcode;
+use crate::parser::parse_heap_type;
+use crate::reader::Reader;
+use crate::types::CompositeType;
+
+pub fn evaluate(
+ store: &mut Store,
+ globals: &[GlobalAddress],
+ functions: &[FunctionAddress],
+ type_identities: &[u32],
+ module: &Module,
+ expression: &ConstantExpression,
+) -> Result<Value, Trap> {
+ let mut reader = Reader::with_range(
+ &module.bytes,
+ expression.code.start as usize,
+ expression.code.end as usize,
+ );
+ let mut stack: Vec<Value> = Vec::new();
+ let malformed = || Trap::Host("malformed constant expression".to_string());
+ let read = |result: crate::Result<u64>| result.map_err(|_| malformed());
+ loop {
+ let opcode = reader.read_u8().map_err(|_| malformed())?;
+ match opcode {
+ opcode::END => break,
+ opcode::I32_CONST => stack.push(Value::I32(reader.read_i32().map_err(|_| malformed())?)),
+ opcode::I64_CONST => stack.push(Value::I64(reader.read_i64().map_err(|_| malformed())?)),
+ opcode::F32_CONST => stack.push(Value::F32(reader.read_fixed_u32().map_err(|_| malformed())?)),
+ opcode::F64_CONST => stack.push(Value::F64(reader.read_fixed_u64().map_err(|_| malformed())?)),
+ opcode::REF_NULL => {
+ parse_heap_type(&mut reader).map_err(|_| malformed())?;
+ stack.push(Value::Ref(0));
+ }
+ opcode::REF_FUNC => {
+ let index = read(reader.read_u32().map(u64::from))?;
+ stack.push(Value::Ref(store.function_reference(functions[index as usize])));
+ }
+ opcode::GLOBAL_GET => {
+ let index = read(reader.read_u32().map(u64::from))?;
+ stack.push(store.global(globals[index as usize]).get());
+ }
+ opcode::I32_ADD | opcode::I32_SUB | opcode::I32_MUL => {
+ let (Some(Value::I32(rhs)), Some(Value::I32(lhs))) = (stack.pop(), stack.pop()) else {
+ return Err(malformed());
+ };
+ stack.push(Value::I32(match opcode {
+ opcode::I32_ADD => lhs.wrapping_add(rhs),
+ opcode::I32_SUB => lhs.wrapping_sub(rhs),
+ _ => lhs.wrapping_mul(rhs),
+ }));
+ }
+ opcode::I64_ADD | opcode::I64_SUB | opcode::I64_MUL => {
+ let (Some(Value::I64(rhs)), Some(Value::I64(lhs))) = (stack.pop(), stack.pop()) else {
+ return Err(malformed());
+ };
+ stack.push(Value::I64(match opcode {
+ opcode::I64_ADD => lhs.wrapping_add(rhs),
+ opcode::I64_SUB => lhs.wrapping_sub(rhs),
+ _ => lhs.wrapping_mul(rhs),
+ }));
+ }
+ opcode::PREFIX_SIMD => {
+ read(reader.read_u32().map(u64::from))?;
+ let bytes = reader.read_bytes(16).map_err(|_| malformed())?;
+ let mut array = [0u8; 16];
+ array.copy_from_slice(bytes);
+ stack.push(Value::V128(u128::from_le_bytes(array)));
+ }
+ opcode::PREFIX_GC => {
+ let sub_opcode = reader.read_u32().map_err(|_| malformed())?;
+ let mut immediate = || reader.read_u32().map_err(|_| malformed());
+ match sub_opcode {
+ opcode::gc::STRUCT_NEW | opcode::gc::STRUCT_NEW_DEFAULT => {
+ let type_index = immediate()?;
+ let identity = type_identities[type_index as usize];
+ let CompositeType::Struct(fields) = &store.types[identity as usize].composite else {
+ return Err(malformed());
+ };
+ let count = fields.len();
+ let values = if sub_opcode == opcode::gc::STRUCT_NEW {
+ stack.split_off(stack.len().checked_sub(count).ok_or_else(malformed)?)
+ } else {
+ fields
+ .iter()
+ .map(|field| Value::default_for(field.storage.unpacked()))
+ .collect()
+ };
+ stack.push(Value::Ref(store.allocate_struct(identity, &values)));
+ }
+ opcode::gc::ARRAY_NEW | opcode::gc::ARRAY_NEW_DEFAULT | opcode::gc::ARRAY_NEW_FIXED => {
+ let type_index = immediate()?;
+ let identity = type_identities[type_index as usize];
+ let CompositeType::Array(element) = &store.types[identity as usize].composite else {
+ return Err(malformed());
+ };
+ let element = element.storage.unpacked();
+ let values = match sub_opcode {
+ opcode::gc::ARRAY_NEW_FIXED => {
+ let count = immediate()? as usize;
+ stack.split_off(stack.len().checked_sub(count).ok_or_else(malformed)?)
+ }
+ _ => {
+ let Some(Value::I32(length)) = stack.pop() else {
+ return Err(malformed());
+ };
+ let value = if sub_opcode == opcode::gc::ARRAY_NEW {
+ stack.pop().ok_or_else(malformed)?
+ } else {
+ Value::default_for(element)
+ };
+ vec![value; length as u32 as usize]
+ }
+ };
+ let array = store.allocate_array(identity, &values);
+ if array == 0 {
+ return Err(Trap::Host("out of memory".to_string()));
+ }
+ stack.push(Value::Ref(array));
+ }
+ opcode::gc::REF_I31 => {
+ let Some(Value::I32(value)) = stack.pop() else {
+ return Err(malformed());
+ };
+ stack.push(Value::Ref(super::gc::i31_reference(value)));
+ }
+ // A reference keeps its bits when it moves between the any and extern hierarchies.
+ opcode::gc::ANY_CONVERT_EXTERN | opcode::gc::EXTERN_CONVERT_ANY => {}
+ _ => return Err(malformed()),
+ }
+ }
+ _ => return Err(Trap::Host("unsupported constant expression".to_string())),
+ }
+ }
+ stack.pop().ok_or_else(malformed)
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rs
new file mode 100644
index 00000000000..aadb19709d9
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! GC objects: their runtime types, layout, and allocation (see `Rtt` in abi.rs for the layout).
+//!
+//! References in the any hierarchy are encoded so that their kind shows in their low bits: zero is null, an i31 has
+//! bit 0 set (its value is in the bits above), a host value converted from an externref has bits 1:0 equal to 0b10,
+//! and GC objects are 8-byte aligned addresses. Converting between externref and anyref keeps the bits.
+
+use super::{Store, Value};
+use crate::abi::{
+ ARRAY_ELEMENTS_OFFSET, RTT_KIND_ARRAY, RTT_KIND_FUNCTION, RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_I8,
+ STORAGE_I16, STORAGE_V128, STRUCT_FIELDS_OFFSET,
+};
+use crate::types::{CompositeType, StorageType, ValType};
+
+/// An Rtt and the arrays it points at.
+pub struct RttStorage {
+ pub rtt: Rtt,
+ display: Box<[u32]>,
+ _field_offsets: Box<[u32]>,
+ _field_kinds: Box<[u8]>,
+}
+
+pub fn storage_kind(storage: StorageType) -> u8 {
+ match storage {
+ StorageType::I8 => STORAGE_I8,
+ StorageType::I16 => STORAGE_I16,
+ StorageType::Val(ValType::V128) => STORAGE_V128,
+ StorageType::Val(ValType::I32 | ValType::F32) => STORAGE_32,
+ StorageType::Val(_) => STORAGE_64,
+ }
+}
+
+fn storage_size(kind: u8) -> u32 {
+ if kind == STORAGE_V128 { 16 } else { 8 }
+}
+
+impl RttStorage {
+ /// The runtime type of the store type `identity`, whose supertypes have runtime types already.
+ pub fn new(store: &Store, identity: u32) -> Box<Self> {
+ let sub_type = &store.types[identity as usize];
+ let mut display = match sub_type.supertypes.first() {
+ Some(&supertype) => store.rtts[supertype as usize].display.to_vec(),
+ None => Vec::new(),
+ };
+ display.push(identity);
+ let (kind, field_kinds, field_offsets, size) = match &sub_type.composite {
+ CompositeType::Func(_) => (RTT_KIND_FUNCTION, Vec::new(), Vec::new(), 0),
+ CompositeType::Struct(fields) => {
+ let kinds: Vec<u8> = fields.iter().map(|field| storage_kind(field.storage)).collect();
+ let mut offsets = Vec::with_capacity(kinds.len());
+ let mut offset = STRUCT_FIELDS_OFFSET as u32;
+ for &kind in &kinds {
+ offsets.push(offset);
+ offset += storage_size(kind);
+ }
+ (RTT_KIND_STRUCT, kinds, offsets, offset)
+ }
+ CompositeType::Array(element) => {
+ let kind = storage_kind(element.storage);
+ (RTT_KIND_ARRAY, vec![kind], Vec::new(), storage_size(kind))
+ }
+ };
+ let display = display.into_boxed_slice();
+ let field_offsets = field_offsets.into_boxed_slice();
+ let field_kinds = field_kinds.into_boxed_slice();
+ Box::new(Self {
+ rtt: Rtt {
+ kind,
+ depth: display.len() as u32 - 1,
+ display: display.as_ptr(),
+ field_offsets: field_offsets.as_ptr(),
+ field_kinds: field_kinds.as_ptr(),
+ size,
+ field_count: field_offsets.len() as u32,
+ },
+ display,
+ _field_offsets: field_offsets,
+ _field_kinds: field_kinds,
+ })
+ }
+}
+
+/// The largest object the runtime allocates.
+const MAX_OBJECT_SIZE: u64 = 1 << 31;
+
+impl Store {
+ pub fn rtt(&self, identity: u32) -> &Rtt {
+ &self.rtts[identity as usize].rtt
+ }
+
+ /// Allocate a zeroed object of `size` bytes whose type is `rtt`, or return zero if it is too large.
+ pub fn allocate_object(&mut self, rtt: *const Rtt, size: u64) -> u64 {
+ if size > MAX_OBJECT_SIZE {
+ return 0;
+ }
+ let mut words = vec![0u64; size.div_ceil(8) as usize].into_boxed_slice();
+ words[0] = rtt as u64;
+ let object = words.as_mut_ptr() as u64;
+ self.objects.push(words);
+ object
+ }
+
+ /// Allocate a struct of the type `identity` with the given field values.
+ pub fn allocate_struct(&mut self, identity: u32, fields: &[Value]) -> u64 {
+ let rtt: *const Rtt = self.rtt(identity);
+ let size = u64::from(unsafe { (*rtt).size });
+ let object = self.allocate_object(rtt, size);
+ for (index, value) in fields.iter().enumerate() {
+ unsafe {
+ let offset = *(*rtt).field_offsets.add(index);
+ let kind = *(*rtt).field_kinds.add(index);
+ store_field(object + u64::from(offset), kind, *value);
+ }
+ }
+ object
+ }
+
+ /// Allocate an array of the type `identity` with `values` as its elements, or return zero if it is too large.
+ pub fn allocate_array(&mut self, identity: u32, values: &[Value]) -> u64 {
+ let rtt: *const Rtt = self.rtt(identity);
+ let (element_size, kind) = unsafe { (u64::from((*rtt).size), *(*rtt).field_kinds) };
+ let size = ARRAY_ELEMENTS_OFFSET as u64 + values.len() as u64 * element_size;
+ let object = self.allocate_object(rtt, size);
+ if object == 0 {
+ return 0;
+ }
+ unsafe {
+ *((object + 8) as *mut u64) = values.len() as u64;
+ for (index, value) in values.iter().enumerate() {
+ store_field(
+ object + ARRAY_ELEMENTS_OFFSET as u64 + index as u64 * element_size,
+ kind,
+ *value,
+ );
+ }
+ }
+ object
+ }
+}
+
+unsafe fn store_field(address: u64, kind: u8, value: Value) {
+ let mut slots = Vec::with_capacity(2);
+ value.push_slots(&mut slots);
+ let mask = match kind {
+ STORAGE_I8 => 0xff,
+ STORAGE_I16 => 0xffff,
+ _ => u64::MAX,
+ };
+ unsafe {
+ *(address as *mut u64) = slots[0] & mask;
+ if kind == STORAGE_V128 {
+ *((address + 8) as *mut u64) = slots[1];
+ }
+ }
+}
+
+/// The i31 reference of a value.
+pub fn i31_reference(value: i32) -> u64 {
+ (u64::from(value as u32 & 0x7fff_ffff) << 1) | 1
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
new file mode 100644
index 00000000000..e6433ada6f4
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
@@ -0,0 +1,340 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The runtime services the interpreter calls for what needs the runtime: growing memories and tables, and calling
+//! host functions. Each takes the execution context, whose `arguments` hold the operands.
+
+use super::{FunctionInstance, FunctionKind, Store, Trap, Value};
+use crate::abi::{
+ ExecutionContext, FRAME_FUNCTION, FRAME_HEADER_SIZE, FRAME_INSTANCE, FRAME_RETURN_IP, FRAME_SAVED_FP, MemoryData,
+ TableData,
+};
+use crate::validator::CatchKind;
+
+unsafe fn store_of(context: *mut ExecutionContext) -> &'static mut Store {
+ unsafe { &mut *(*context).store.cast::<Store>() }
+}
+
+/// Grow the memory of `arguments[0]` (a `MemoryData`) by `arguments[1]` pages. Returns the previous size in pages, or
+/// u64::MAX if the memory cannot grow.
+///
+/// # 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 {
+ let data = (*context).arguments[0] as *const MemoryData;
+ let delta = (*context).arguments[1];
+ let store = store_of(context);
+ store
+ .memories
+ .iter_mut()
+ .find(|memory| std::ptr::eq(&raw const *memory.data, data))
+ .and_then(|memory| memory.grow(delta))
+ .unwrap_or(u64::MAX)
+ }
+}
+
+/// Grow the table of `arguments[0]` (a `TableData`) by `arguments[1]` elements initialized to `arguments[2]`. Returns
+/// the previous size, or u64::MAX if the table cannot grow.
+///
+/// # 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 {
+ let data = (*context).arguments[0] as *const TableData;
+ let delta = (*context).arguments[1];
+ let initial = (*context).arguments[2];
+ let store = store_of(context);
+ store
+ .tables
+ .iter_mut()
+ .find(|table| std::ptr::eq(&raw const *table.data, data))
+ .and_then(|table| table.grow(delta, initial))
+ .unwrap_or(u64::MAX)
+ }
+}
+
+/// Call the host function whose header is `arguments[0]` with the arguments on the operand stack at `arguments[1]`,
+/// replacing them with its results. `arguments[2]` is the address the call returns to and `arguments[3]` the caller's
+/// frame, which an exception the host function throws unwinds from. Returns the new top of the operand stack, 1 if
+/// the call threw an exception that a handler caught (see `wasm_runtime_throw`), or 0 if it trapped.
+///
+/// # 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 {
+ let function = &*((*context).arguments[0] as *const FunctionInstance);
+ let top = (*context).arguments[1] as *mut u64;
+ let return_ip = (*context).arguments[2];
+ let frame = (*context).arguments[3];
+ let store = store_of(context);
+ let FunctionKind::Host(callback) = &function.kind else {
+ return 0;
+ };
+ let callback = callback.clone();
+ let parameter_slots = function.header.param_slots as usize;
+ let slots = ak::slice_from_raw_parts(top, parameter_slots);
+ // The operand stack grows down, so the first argument is in the highest slots.
+ let mut arguments = Vec::with_capacity(function.ty.params.len());
+ let mut slot = parameter_slots;
+ for &ty in &function.ty.params {
+ slot -= ty.slot_count() as usize;
+ arguments.push(Value::from_slots(ty, &slots[slot..]));
+ }
+ let results = match callback(store, &arguments) {
+ Ok(results) => results,
+ Err(Trap::UncaughtException(exception)) => {
+ // The exception continues in the caller, as if the call instruction had thrown it.
+ if unwind(context, store, exception, frame, return_ip - 1) {
+ return 1;
+ }
+ store.pending_trap = Some(Trap::UncaughtException(exception));
+ return 0;
+ }
+ Err(trap) => {
+ store.pending_trap = Some(trap);
+ return 0;
+ }
+ };
+ let mut result_slots = Vec::new();
+ for result in results.iter().rev() {
+ result.push_slots(&mut result_slots);
+ }
+ let return_top = top.add(parameter_slots).sub(result_slots.len());
+ for (index, value) in result_slots.iter().enumerate() {
+ *return_top.add(index) = *value;
+ }
+ return_top as u64
+ }
+}
+
+/// Allocate a zeroed GC object of `arguments[1]` bytes whose runtime type is `arguments[0]`. Returns zero if it is
+/// too large.
+///
+/// # 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 {
+ let store = store_of(context);
+ let rtt = (*context).arguments[0] as *const crate::abi::Rtt;
+ let size = (*context).arguments[1];
+ let object = store.allocate_object(rtt, size);
+ if object == 0 {
+ store.pending_trap = Some(Trap::Host("out of memory".to_string()));
+ }
+ object
+ }
+}
+
+/// Throw an exception: a new one with the tag whose identity is `arguments[0]` and the values on the operand stack
+/// at `arguments[1]`, or the existing one `arguments[4]` refers to if that is not zero. `arguments[2]` is the
+/// throwing instruction and `arguments[3]` its frame. Returns 1 if a handler caught the exception, with the frame,
+/// instruction pointer, side-table pointer, and operand stack top to continue with in `arguments[0..4]`, or 0 if it
+/// left the interpreter uncaught.
+///
+/// # 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 {
+ let store = store_of(context);
+ let pc = (*context).arguments[2];
+ let frame = (*context).arguments[3];
+ let mut exception = (*context).arguments[4];
+ if exception == 0 {
+ let tag = store.tag_from_identity((*context).arguments[0]);
+ let slot_count: u32 = store.tag(tag).ty.params.iter().map(|param| param.slot_count()).sum();
+ let top = (*context).arguments[1] as *const u64;
+ let payload: Box<[u64]> = ak::slice_from_raw_parts(top, slot_count as usize).into();
+ exception = store.allocate_exception(tag, payload);
+ }
+ if unwind(context, store, exception, frame, pc) {
+ return 1;
+ }
+ store.pending_trap = Some(Trap::UncaughtException(exception));
+ 0
+ }
+}
+
+/// Find the handler of `exception`, thrown by the instruction at `pc` in the frame `frame`, in that frame or the ones
+/// it was called from, up to where the runtime entered the interpreter. If there is one, push what the handler
+/// receives and put where it continues into the context's arguments.
+unsafe fn unwind(context: *mut ExecutionContext, store: &Store, exception: u64, mut frame: u64, mut pc: u64) -> bool {
+ let read = |address: u64| unsafe { *(address as *const u64) };
+ let thrown_tag = store.exception(exception).tag;
+ loop {
+ // The frame the runtime enters the interpreter with has no instance.
+ if read(frame.wrapping_add_signed(FRAME_INSTANCE as i64)) == 0 {
+ return false;
+ }
+ let function = unsafe { &*(read(frame.wrapping_add_signed(FRAME_FUNCTION as i64)) as *const FunctionInstance) };
+ if let FunctionKind::Wasm {
+ module,
+ index,
+ instance,
+ } = &function.kind
+ {
+ 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.
+ for region in info.try_regions.iter().rev() {
+ if offset < u64::from(region.start) || offset >= u64::from(region.end) {
+ continue;
+ }
+ let clauses = &info.catch_clauses
+ [region.first_clause as usize..(region.first_clause + region.clause_count) as usize];
+ for clause in clauses {
+ let catches = match clause.kind {
+ CatchKind::Catch | CatchKind::CatchRef => {
+ store.instance(*instance).tags[clause.tag as usize] == thrown_tag
+ }
+ CatchKind::CatchAll | CatchKind::CatchAllRef => true,
+ };
+ if !catches {
+ continue;
+ }
+ let payload: &[u64] = match clause.kind {
+ CatchKind::Catch | CatchKind::CatchRef => &store.exception(exception).payload,
+ CatchKind::CatchAll | CatchKind::CatchAllRef => &[],
+ };
+ let pushes_reference = matches!(clause.kind, CatchKind::CatchRef | CatchKind::CatchAllRef);
+ let pushed = payload.len() as u64 + u64::from(pushes_reference);
+ let empty_stack = frame - FRAME_HEADER_SIZE as u64;
+ let top = empty_stack - (u64::from(clause.height) + pushed) * 8;
+ let mut slot = top as *mut u64;
+ unsafe {
+ if pushes_reference {
+ *slot = exception;
+ slot = slot.add(1);
+ }
+ for &value in payload {
+ *slot = value;
+ slot = slot.add(1);
+ }
+ (*context).arguments[0] = frame;
+ (*context).arguments[1] = module.bytes.as_ptr() as u64 + u64::from(clause.target_pc);
+ (*context).arguments[2] = info.side_table.as_ptr() as u64 + u64::from(clause.target_stp) * 16;
+ (*context).arguments[3] = top;
+ }
+ return true;
+ }
+ }
+ }
+ // Continue in the caller, inside the call instruction this frame returns past.
+ pc = read(frame.wrapping_add_signed(FRAME_RETURN_IP as i64)) - 1;
+ frame = read(frame.wrapping_add_signed(FRAME_SAVED_FP as i64));
+ }
+}
+
+/// The threads waiting in `memory.atomic.wait`, with the address they wait on, oldest first.
+static WAITERS: std::sync::Mutex<Vec<(u64, std::sync::Arc<Waiter>)>> = std::sync::Mutex::new(Vec::new());
+
+struct Waiter {
+ woken: std::sync::Mutex<bool>,
+ condition: std::sync::Condvar,
+}
+
+/// Wait on the shared memory location at address `arguments[0]` while it holds `arguments[1]` (compared at
+/// `arguments[3]` bytes), for at most `arguments[2]` nanoseconds if that is not negative. Returns 0 when woken, 1 if
+/// the location held another value, and 2 when the time ran out.
+///
+/// # 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 {
+ let (address, expected, timeout, size) = unsafe {
+ (
+ (*context).arguments[0],
+ (*context).arguments[1],
+ (*context).arguments[2] as i64,
+ (*context).arguments[3],
+ )
+ };
+ let waiter = {
+ let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");
+ // Notifies take the lock, so none can come between reading the value and waiting for it.
+ let current = unsafe {
+ if size == 4 {
+ u64::from((*(address as *const std::sync::atomic::AtomicU32)).load(std::sync::atomic::Ordering::SeqCst))
+ } else {
+ (*(address as *const std::sync::atomic::AtomicU64)).load(std::sync::atomic::Ordering::SeqCst)
+ }
+ };
+ if current != expected {
+ return 1;
+ }
+ let waiter = std::sync::Arc::new(Waiter {
+ woken: std::sync::Mutex::new(false),
+ condition: std::sync::Condvar::new(),
+ });
+ waiters.push((address, waiter.clone()));
+ waiter
+ };
+ let mut woken = waiter.woken.lock().expect("a waiter is never poisoned");
+ if timeout < 0 {
+ while !*woken {
+ woken = waiter.condition.wait(woken).expect("a waiter is never poisoned");
+ }
+ return 0;
+ }
+ let deadline = std::time::Instant::now() + std::time::Duration::from_nanos(timeout as u64);
+ while !*woken {
+ let now = std::time::Instant::now();
+ if now >= deadline {
+ break;
+ }
+ woken = waiter
+ .condition
+ .wait_timeout(woken, deadline - now)
+ .expect("a waiter is never poisoned")
+ .0;
+ }
+ if *woken {
+ return 0;
+ }
+ drop(woken);
+ let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");
+ waiters.retain(|(_, other)| !std::sync::Arc::ptr_eq(other, &waiter));
+ // A notify may have come in after the time ran out but before the waiter left the list.
+ if *waiter.woken.lock().expect("a waiter is never poisoned") {
+ 0
+ } else {
+ 2
+ }
+}
+
+/// Wake at most `arguments[1]` of the threads waiting on the shared memory location at address `arguments[0]`, and
+/// return how many it woke.
+///
+/// # Safety
+///
+/// Only the interpreter calls this.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_runtime_notify(context: *mut ExecutionContext) -> u64 {
+ let (address, count) = unsafe { ((*context).arguments[0], (*context).arguments[1]) };
+ let mut waiters = WAITERS.lock().expect("the waiter list is never poisoned");
+ let mut woken = 0;
+ waiters.retain(|(waiting_on, waiter)| {
+ if woken >= count || *waiting_on != address {
+ return true;
+ }
+ *waiter.woken.lock().expect("a waiter is never poisoned") = true;
+ waiter.condition.notify_one();
+ woken += 1;
+ false
+ });
+ woken
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/interpreter.rs b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
new file mode 100644
index 00000000000..842c63040a6
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/interpreter.rs
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Entering the interpreter, and turning faulting memory accesses inside it into traps.
+
+use crate::abi::EntryRecord;
+
+/// The pseudo-instructions the runtime enters the interpreter at: Enter pushes the arguments, CallEntry calls the
+/// function, and the function returns to Exit, which leaves the interpreter.
+static ENTRY_CODE: [u8; 3] = [0xf0, 0xf3, 0xf1];
+
+/// The opcode of the pseudo-instruction a faulting memory access continues at.
+#[cfg(wasm_interpreter)]
+const MEMORY_FAULT_OPCODE: usize = 0xf2;
+
+#[cfg(wasm_interpreter)]
+unsafe extern "C" {
+ fn wasm_interpreter(ip: *const u8, argument: u64);
+ static wasm_interpreter_end: u8;
+ static wasm_interpreter_dispatch_table: [usize; 256];
+}
+
+/// Run the function of `record` in the interpreter.
+///
+/// # Safety
+///
+/// The record must describe a function of a live instance, its arguments, and room for its results.
+pub unsafe fn enter(record: &mut EntryRecord) {
+ #[cfg(wasm_interpreter)]
+ unsafe {
+ wasm_interpreter(ENTRY_CODE.as_ptr(), (record as *mut EntryRecord) as u64);
+ }
+ #[cfg(not(wasm_interpreter))]
+ {
+ let _ = &ENTRY_CODE;
+ record.trap = crate::abi::TRAP_RUNTIME;
+ }
+}
+
+#[cfg(wasm_interpreter)]
+fn interpreter_code_range() -> (usize, usize) {
+ (
+ wasm_interpreter as *const () as usize,
+ &raw const wasm_interpreter_end as usize,
+ )
+}
+
+#[cfg(wasm_interpreter)]
+fn memory_fault_handler() -> usize {
+ unsafe { wasm_interpreter_dispatch_table[MEMORY_FAULT_OPCODE] }
+}
+
+/// The CPU features the interpreter's code uses and that the target's baseline guarantees: x86-64-v3 on x86-64, and
+/// ARMv8.2-A on AArch64. A CPU without them would not fault but compute wrong results (lzcnt runs as bsr on older
+/// CPUs), so the engine refuses to start instead.
+pub fn check_cpu_features() {
+ let missing = missing_cpu_features();
+ assert!(
+ missing.is_empty(),
+ "The WebAssembly engine needs CPU features this machine lacks: {}",
+ missing.join(", ")
+ );
+}
+
+#[cfg(target_arch = "x86_64")]
+fn missing_cpu_features() -> Vec<&'static str> {
+ let mut missing = Vec::new();
+ macro_rules! require {
+ ($($feature:tt),+) => {
+ $(if !std::arch::is_x86_feature_detected!($feature) {
+ missing.push($feature);
+ })+
+ };
+ }
+ require!(
+ "sse4.1", "sse4.2", "popcnt", "lzcnt", "bmi1", "bmi2", "avx2", "fma", "movbe"
+ );
+ missing
+}
+
+#[cfg(target_arch = "aarch64")]
+fn missing_cpu_features() -> Vec<&'static str> {
+ let mut missing = Vec::new();
+ macro_rules! require {
+ ($($feature:tt),+) => {
+ $(if !std::arch::is_aarch64_feature_detected!($feature) {
+ missing.push($feature);
+ })+
+ };
+ }
+ require!("neon", "lse", "rdm");
+ missing
+}
+
+#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
+fn missing_cpu_features() -> Vec<&'static str> {
+ Vec::new()
+}
+
+/// The lowest address the interpreter's frames may use on the current thread, leaving `reserve` bytes below it.
+pub fn stack_limit(reserve: usize) -> u64 {
+ let marker = 0u8;
+ let current = &raw const marker as usize;
+ let lowest = thread_stack_lowest_address().unwrap_or(current.saturating_sub(1024 * 1024));
+ (lowest + reserve) as u64
+}
+
+#[cfg(target_os = "linux")]
+fn thread_stack_lowest_address() -> Option<usize> {
+ unsafe {
+ let mut attributes: libc::pthread_attr_t = std::mem::zeroed();
+ if libc::pthread_getattr_np(libc::pthread_self(), &raw mut attributes) != 0 {
+ return None;
+ }
+ let mut address = std::ptr::null_mut();
+ let mut size = 0;
+ let result = libc::pthread_attr_getstack(&raw const attributes, &raw mut address, &raw mut size);
+ libc::pthread_attr_destroy(&raw mut attributes);
+ (result == 0).then_some(address as usize)
+ }
+}
+
+#[cfg(target_os = "macos")]
+#[allow(clippy::unnecessary_wraps)] // The other platforms' versions can fail.
+fn thread_stack_lowest_address() -> Option<usize> {
+ unsafe {
+ let thread = libc::pthread_self();
+ let top = libc::pthread_get_stackaddr_np(thread) as usize;
+ Some(top - libc::pthread_get_stacksize_np(thread))
+ }
+}
+
+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
+fn thread_stack_lowest_address() -> Option<usize> {
+ None
+}
+
+#[cfg(all(wasm_interpreter, unix))]
+mod fault {
+ use super::{interpreter_code_range, memory_fault_handler};
+ use crate::runtime::memory::is_in_any_reservation;
+ use std::sync::Once;
+
+ static INSTALL: Once = Once::new();
+ static mut PREVIOUS_SIGSEGV: libc::sigaction = unsafe { std::mem::zeroed() };
+ static mut PREVIOUS_SIGBUS: libc::sigaction = unsafe { std::mem::zeroed() };
+
+ #[cfg(target_os = "linux")]
+ unsafe fn instruction_pointer(context: *mut libc::c_void) -> *mut usize {
+ unsafe {
+ let context = context.cast::<libc::ucontext_t>();
+ (&raw mut (*context).uc_mcontext.gregs[libc::REG_RIP as usize]).cast()
+ }
+ }
+
+ #[cfg(target_os = "macos")]
+ 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.__rip).cast()
+ }
+ }
+
+ unsafe fn forward(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {
+ unsafe {
+ let previous = if signal == libc::SIGSEGV {
+ &raw const PREVIOUS_SIGSEGV
+ } else {
+ &raw const PREVIOUS_SIGBUS
+ };
+ let previous = &*previous;
+ if previous.sa_flags & libc::SA_SIGINFO != 0 && previous.sa_sigaction > libc::SIG_IGN {
+ let handler: extern "C" fn(i32, *mut libc::siginfo_t, *mut libc::c_void) =
+ std::mem::transmute(previous.sa_sigaction);
+ handler(signal, info, context);
+ return;
+ }
+ if previous.sa_sigaction > libc::SIG_IGN {
+ let handler: extern "C" fn(i32) = std::mem::transmute(previous.sa_sigaction);
+ handler(signal);
+ return;
+ }
+ // Return with the default action in place, so that the faulting access faults again and kills the
+ // process as it would have without us.
+ libc::signal(signal, libc::SIG_DFL);
+ }
+ }
+
+ extern "C" fn handle_fault(signal: i32, info: *mut libc::siginfo_t, context: *mut libc::c_void) {
+ unsafe {
+ let pc = instruction_pointer(context);
+ let (start, end) = interpreter_code_range();
+ let address = (*info).si_addr() as usize;
+ if (start..end).contains(&*pc) && is_in_any_reservation(address) {
+ // 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;
+ }
+ forward(signal, info, context);
+ }
+ }
+
+ pub fn install() {
+ INSTALL.call_once(|| unsafe {
+ let mut action: libc::sigaction = std::mem::zeroed();
+ action.sa_sigaction = handle_fault as *const () as usize;
+ action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;
+ libc::sigemptyset(&raw mut action.sa_mask);
+ libc::sigaction(libc::SIGSEGV, &raw const action, &raw mut PREVIOUS_SIGSEGV);
+ libc::sigaction(libc::SIGBUS, &raw const action, &raw mut PREVIOUS_SIGBUS);
+ });
+ }
+}
+
+pub fn install_fault_handler() {
+ #[cfg(all(wasm_interpreter, unix))]
+ fault::install();
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/memory.rs b/Libraries/LibWasm/Engine/src/runtime/memory.rs
new file mode 100644
index 00000000000..ce9fa118ab5
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/memory.rs
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Linear memories. A memory reserves the address range its accesses can form up front and only commits what it has
+//! grown to, so that its base never moves and accesses past its end fault into the guard region instead of needing a
+//! bounds check.
+
+use crate::abi::MemoryData;
+use crate::types::{AddressType, MemoryType};
+use std::sync::Mutex;
+
+pub const PAGE_SIZE: u64 = 64 * 1024;
+const MEMORY32_MAX_PAGES: u64 = 1 << 16;
+
+/// The most pages a memory64 reserves, and so can grow to: 16 GiB. Its accesses are bounds checked, so it needs no
+/// guard region.
+const MEMORY64_MAX_PAGES: u64 = 1 << 18;
+
+/// The bytes a memory32 memory reserves: every address (u32) plus every offset (u32), plus one page for the width of
+/// the access.
+pub const GUARDED_RESERVATION_SIZE: u64 = 2 * (MEMORY32_MAX_PAGES * PAGE_SIZE) + PAGE_SIZE;
+
+/// The address ranges all memories reserve, for the fault handler to recognize accesses that ran off a memory.
+static RESERVATIONS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+
+pub fn is_in_any_reservation(address: usize) -> bool {
+ // The fault handler cannot block, so a contended lock means the fault is not ours to handle.
+ let Ok(reservations) = RESERVATIONS.try_lock() else {
+ return false;
+ };
+ reservations
+ .iter()
+ .any(|&(start, length)| address >= start && address - start < length)
+}
+
+pub struct MemoryInstance {
+ /// What the interpreter reads. Boxed, so that its address stays put for the instances that refer to it.
+ pub data: Box<MemoryData>,
+ pub ty: MemoryType,
+ reservation: *mut u8,
+ reservation_size: usize,
+ pages: u64,
+ maximum_pages: u64,
+}
+
+// The reservation is only accessed through the memory that owns it.
+unsafe impl Send for MemoryInstance {}
+
+#[cfg(unix)]
+mod platform {
+ pub unsafe fn reserve(size: usize) -> *mut u8 {
+ let pointer = unsafe {
+ libc::mmap(
+ std::ptr::null_mut(),
+ size,
+ libc::PROT_NONE,
+ libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
+ -1,
+ 0,
+ )
+ };
+ if pointer == libc::MAP_FAILED {
+ std::ptr::null_mut()
+ } else {
+ pointer.cast()
+ }
+ }
+
+ pub unsafe fn commit(address: *mut u8, size: usize) -> bool {
+ unsafe { libc::mprotect(address.cast(), size, libc::PROT_READ | libc::PROT_WRITE) == 0 }
+ }
+
+ pub unsafe fn release(address: *mut u8, size: usize) {
+ unsafe {
+ libc::munmap(address.cast(), size);
+ }
+ }
+}
+
+#[cfg(windows)]
+mod platform {
+ use std::ffi::c_void;
+
+ const MEM_COMMIT: u32 = 0x1000;
+ const MEM_RESERVE: u32 = 0x2000;
+ const MEM_RELEASE: u32 = 0x8000;
+ const PAGE_NOACCESS: u32 = 0x01;
+ const PAGE_READWRITE: u32 = 0x04;
+
+ unsafe extern "system" {
+ fn VirtualAlloc(address: *mut c_void, size: usize, allocation_type: u32, protect: u32) -> *mut c_void;
+ fn VirtualFree(address: *mut c_void, size: usize, free_type: u32) -> i32;
+ }
+
+ pub unsafe fn reserve(size: usize) -> *mut u8 {
+ unsafe { VirtualAlloc(std::ptr::null_mut(), size, MEM_RESERVE, PAGE_NOACCESS).cast() }
+ }
+
+ pub unsafe fn commit(address: *mut u8, size: usize) -> bool {
+ unsafe { !VirtualAlloc(address.cast(), size, MEM_COMMIT, PAGE_READWRITE).is_null() }
+ }
+
+ pub unsafe fn release(address: *mut u8, _size: usize) {
+ unsafe {
+ VirtualFree(address.cast(), 0, MEM_RELEASE);
+ }
+ }
+}
+
+impl MemoryInstance {
+ pub fn new(ty: MemoryType) -> Option<Self> {
+ let (maximum_pages, reservation_size) = match ty.limits.address_type {
+ AddressType::I32 => (
+ ty.limits.max.unwrap_or(MEMORY32_MAX_PAGES).min(MEMORY32_MAX_PAGES),
+ GUARDED_RESERVATION_SIZE as usize,
+ ),
+ AddressType::I64 => {
+ let maximum_pages = ty.limits.max.unwrap_or(MEMORY64_MAX_PAGES).min(MEMORY64_MAX_PAGES);
+ // A memory that cannot grow still reserves a page, so that its base is a valid address.
+ (maximum_pages, (maximum_pages.max(1) * PAGE_SIZE) as usize)
+ }
+ };
+ if ty.limits.min > maximum_pages {
+ return None;
+ }
+ let reservation = unsafe { platform::reserve(reservation_size) };
+ if reservation.is_null() {
+ return None;
+ }
+ RESERVATIONS
+ .lock()
+ .expect("the reservation list is never poisoned")
+ .push((reservation as usize, reservation_size));
+ let mut memory = Self {
+ data: Box::new(MemoryData {
+ base: reservation,
+ size: 0,
+ address64: u64::from(ty.limits.address_type == AddressType::I64),
+ shared: u64::from(ty.limits.shared),
+ }),
+ ty,
+ reservation,
+ reservation_size,
+ pages: 0,
+ maximum_pages,
+ };
+ memory.grow(ty.limits.min)?;
+ Some(memory)
+ }
+
+ pub fn pages(&self) -> u64 {
+ self.pages
+ }
+
+ pub fn size(&self) -> usize {
+ (self.pages * PAGE_SIZE) as usize
+ }
+
+ pub fn maximum_pages(&self) -> u64 {
+ self.maximum_pages
+ }
+
+ /// Grow by `delta` pages, returning the previous size in pages.
+ pub fn grow(&mut self, delta: u64) -> Option<u64> {
+ let previous = self.pages;
+ let new_pages = previous.checked_add(delta)?;
+ if new_pages > self.maximum_pages {
+ return None;
+ }
+ if delta != 0 {
+ let start = unsafe { self.reservation.add(self.size()) };
+ if !unsafe { platform::commit(start, (delta * PAGE_SIZE) as usize) } {
+ return None;
+ }
+ }
+ self.pages = new_pages;
+ self.data.size = new_pages * PAGE_SIZE;
+ Some(previous)
+ }
+
+ pub fn bytes(&self) -> &[u8] {
+ unsafe { ak::slice_from_raw_parts(self.reservation, self.size()) }
+ }
+
+ pub fn bytes_mut(&mut self) -> &mut [u8] {
+ unsafe { ak::slice_from_raw_parts_mut(self.reservation, self.size()) }
+ }
+}
+
+impl Drop for MemoryInstance {
+ fn drop(&mut self) {
+ let start = self.reservation as usize;
+ RESERVATIONS
+ .lock()
+ .expect("the reservation list is never poisoned")
+ .retain(|&(reservation, _)| reservation != start);
+ unsafe { platform::release(self.reservation, self.reservation_size) };
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
new file mode 100644
index 00000000000..3358eb9a763
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -0,0 +1,1033 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The runtime: the store of functions, memories, tables, and globals that instances share, instantiation, and
+//! calling into the interpreter.
+
+pub mod constant;
+pub mod gc;
+pub mod helpers;
+pub mod interpreter;
+pub mod memory;
+
+use crate::abi::{
+ EntryRecord, ExecutionContext, FRAME_HEADER_SIZE, FUNCTION_KIND_HOST, FUNCTION_KIND_WASM,
+ 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 memory::MemoryInstance;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+/// A value as the runtime's API sees it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Value {
+ I32(i32),
+ I64(i64),
+ /// The bits of an f32.
+ F32(u32),
+ /// The bits of an f64.
+ F64(u64),
+ V128(u128),
+ /// A reference: zero for null, otherwise its encoded bits.
+ Ref(u64),
+}
+
+impl Value {
+ pub fn default_for(ty: ValType) -> Self {
+ match ty {
+ ValType::I32 => Self::I32(0),
+ ValType::I64 => Self::I64(0),
+ ValType::F32 => Self::F32(0),
+ ValType::F64 => Self::F64(0),
+ ValType::V128 => Self::V128(0),
+ ValType::Ref(_) => Self::Ref(0),
+ }
+ }
+
+ /// Append the slots of this value in memory order: a v128's low half first.
+ pub fn push_slots(self, slots: &mut Vec<u64>) {
+ match self {
+ Self::I32(value) => slots.push(u64::from(value as u32)),
+ Self::I64(value) => slots.push(value as u64),
+ Self::F32(bits) => slots.push(u64::from(bits)),
+ Self::F64(bits) | Self::Ref(bits) => slots.push(bits),
+ Self::V128(bits) => {
+ slots.push(bits as u64);
+ slots.push((bits >> 64) as u64);
+ }
+ }
+ }
+
+ pub fn from_slots(ty: ValType, slots: &[u64]) -> Self {
+ match ty {
+ ValType::I32 => Self::I32(slots[0] as u32 as i32),
+ ValType::I64 => Self::I64(slots[0] as i64),
+ ValType::F32 => Self::F32(slots[0] as u32),
+ ValType::F64 => Self::F64(slots[0]),
+ ValType::Ref(_) => Self::Ref(slots[0]),
+ ValType::V128 => Self::V128(u128::from(slots[0]) | (u128::from(slots[1]) << 64)),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Trap {
+ Unreachable,
+ StackExhausted,
+ MemoryOutOfBounds,
+ IntegerDivideByZero,
+ IntegerOverflow,
+ InvalidConversion,
+ UndefinedElement,
+ UninitializedElement,
+ IndirectCallTypeMismatch,
+ TableOutOfBounds,
+ NullReference,
+ CastFailure,
+ ArrayOutOfBounds,
+ UnalignedAtomic,
+ ExpectedSharedMemory,
+ Host(String),
+ UncaughtException(u64),
+}
+
+impl Trap {
+ fn from_code(code: u32, pending: Option<Trap>) -> Self {
+ use crate::abi::*;
+ match code {
+ TRAP_UNREACHABLE => Self::Unreachable,
+ TRAP_STACK_EXHAUSTED => Self::StackExhausted,
+ TRAP_MEMORY_OUT_OF_BOUNDS => Self::MemoryOutOfBounds,
+ TRAP_INTEGER_DIVIDE_BY_ZERO => Self::IntegerDivideByZero,
+ TRAP_INTEGER_OVERFLOW => Self::IntegerOverflow,
+ TRAP_INVALID_CONVERSION => Self::InvalidConversion,
+ TRAP_UNDEFINED_ELEMENT => Self::UndefinedElement,
+ TRAP_UNINITIALIZED_ELEMENT => Self::UninitializedElement,
+ TRAP_INDIRECT_CALL_TYPE_MISMATCH => Self::IndirectCallTypeMismatch,
+ TRAP_TABLE_OUT_OF_BOUNDS => Self::TableOutOfBounds,
+ TRAP_NULL_REFERENCE => Self::NullReference,
+ TRAP_CAST_FAILURE => Self::CastFailure,
+ TRAP_ARRAY_OUT_OF_BOUNDS => Self::ArrayOutOfBounds,
+ TRAP_UNALIGNED_ATOMIC => Self::UnalignedAtomic,
+ TRAP_EXPECTED_SHARED_MEMORY => Self::ExpectedSharedMemory,
+ _ => pending.unwrap_or_else(|| Self::Host("the runtime reported a trap without details".to_string())),
+ }
+ }
+
+ pub fn message(&self) -> String {
+ match self {
+ Self::Unreachable => "unreachable".to_string(),
+ Self::StackExhausted => "call stack exhausted".to_string(),
+ Self::MemoryOutOfBounds => "Memory access out of bounds".to_string(),
+ Self::IntegerDivideByZero => "integer divide by zero".to_string(),
+ Self::IntegerOverflow => "integer overflow".to_string(),
+ Self::InvalidConversion => "invalid conversion to integer".to_string(),
+ Self::UndefinedElement => "undefined element".to_string(),
+ Self::UninitializedElement => "uninitialized element".to_string(),
+ Self::IndirectCallTypeMismatch => "indirect call type mismatch".to_string(),
+ Self::TableOutOfBounds => "out of bounds table access".to_string(),
+ Self::NullReference => "null reference".to_string(),
+ Self::CastFailure => "cast failure".to_string(),
+ Self::ArrayOutOfBounds => "out of bounds array access".to_string(),
+ Self::Host(message) => message.clone(),
+ Self::UncaughtException(_) => "uncaught exception".to_string(),
+ Self::UnalignedAtomic => "Unaligned atomic memory access".to_string(),
+ Self::ExpectedSharedMemory => "Expected shared memory".to_string(),
+ }
+ }
+}
+
+macro_rules! define_address {
+ ($name:ident) => {
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+ pub struct $name(pub u32);
+ };
+}
+define_address!(FunctionAddress);
+define_address!(TableAddress);
+define_address!(MemoryAddress);
+define_address!(GlobalAddress);
+define_address!(InstanceAddress);
+define_address!(TagAddress);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExternValue {
+ Function(FunctionAddress),
+ Table(TableAddress),
+ Memory(MemoryAddress),
+ Global(GlobalAddress),
+ Tag(TagAddress),
+}
+
+/// A tag, which exceptions are thrown with. Its address is its identity.
+pub struct TagInstance {
+ pub address: TagAddress,
+ /// The types of the values an exception with this tag carries.
+ pub ty: FuncType,
+ pub type_identity: u32,
+}
+
+/// An exception: a tag and the values thrown with it, in operand stack order (the last value in the lowest slot).
+/// An exception reference is the address of its ExceptionInstance.
+pub struct ExceptionInstance {
+ pub tag: TagAddress,
+ pub payload: Box<[u64]>,
+}
+
+/// A function the embedder implements. It gets the arguments and returns the results, in the function type's order.
+pub type HostCallback = Rc<dyn Fn(&mut Store, &[Value]) -> Result<Vec<Value>, Trap>>;
+
+pub enum FunctionKind {
+ Wasm {
+ module: Arc<Module>,
+ index: u32,
+ instance: InstanceAddress,
+ },
+ Host(HostCallback),
+}
+
+/// A function. The interpreter sees its header, which is its first field, so that a function reference, which points
+/// at the header, also points at the function.
+#[repr(C)]
+pub struct FunctionInstance {
+ pub header: FunctionHeader,
+ pub address: FunctionAddress,
+ pub ty: FuncType,
+ /// What `header.vector_storage` points at.
+ pub vector_storage: Box<[u32]>,
+ pub kind: FunctionKind,
+}
+
+pub struct TableInstance {
+ pub data: Box<TableData>,
+ pub ty: TableType,
+ pub elements: Vec<u64>,
+}
+
+impl TableInstance {
+ fn new(ty: TableType, initial: u64) -> Self {
+ let mut elements = vec![initial; ty.limits.min as usize];
+ let data = Box::new(TableData {
+ elements: elements.as_mut_ptr(),
+ size: elements.len() as u64,
+ address64: u64::from(ty.limits.address_type == crate::types::AddressType::I64),
+ });
+ Self { data, ty, elements }
+ }
+
+ fn sync(&mut self) {
+ self.data.elements = self.elements.as_mut_ptr();
+ self.data.size = self.elements.len() as u64;
+ }
+
+ pub fn grow(&mut self, delta: u64, initial: u64) -> Option<u64> {
+ let previous = self.elements.len() as u64;
+ let new_size = previous.checked_add(delta)?;
+ let maximum = self.ty.limits.max.unwrap_or(u64::from(u32::MAX));
+ if new_size > maximum || new_size > MAX_TABLE_SIZE {
+ return None;
+ }
+ self.elements.resize(new_size as usize, initial);
+ self.sync();
+ Some(previous)
+ }
+}
+
+/// The largest number of elements a table may grow to.
+const MAX_TABLE_SIZE: u64 = 10_000_000;
+
+#[repr(C, align(16))]
+pub struct GlobalInstance {
+ /// The value's slots: one, or two for v128.
+ pub value: [u64; 2],
+ pub ty: GlobalType,
+}
+
+impl GlobalInstance {
+ pub fn get(&self) -> Value {
+ Value::from_slots(self.ty.value, &self.value)
+ }
+
+ pub fn set(&mut self, value: Value) {
+ let mut slots = Vec::with_capacity(2);
+ value.push_slots(&mut slots);
+ self.value[..slots.len()].copy_from_slice(&slots);
+ }
+}
+
+/// An instance. The interpreter sees its `data`.
+pub struct Instance {
+ pub data: Box<InstanceData>,
+ pub module: Arc<Module>,
+ pub functions: Vec<FunctionAddress>,
+ pub tables: Vec<TableAddress>,
+ pub memories: Vec<MemoryAddress>,
+ pub globals: Vec<GlobalAddress>,
+ pub tags: Vec<TagAddress>,
+ pub exports: HashMap<String, ExternValue>,
+ pub type_identities: Vec<u32>,
+ /// The references of each passive element segment. The interpreter sees them through `element_segments`.
+ pub element_storage: Vec<Vec<u64>>,
+ /// Each element segment, empty once dropped or used by instantiation.
+ pub element_segments: Vec<Segment>,
+ /// Each data segment, empty once dropped or used by instantiation.
+ pub data_segments: Vec<Segment>,
+ function_headers: Vec<*const FunctionHeader>,
+ global_slots: Vec<*mut u64>,
+ table_datas: Vec<*mut TableData>,
+ memory_datas: Vec<*mut MemoryData>,
+ tag_identities: Vec<u64>,
+}
+
+impl Instance {
+ pub fn export(&self, name: &str) -> Option<ExternValue> {
+ self.exports.get(name).copied()
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum InstantiationError {
+ Link(String),
+ Trap(Trap),
+}
+
+/// The bytes of stack a call into WebAssembly leaves free for the runtime functions it calls.
+const STACK_RESERVE: usize = 256 * 1024;
+
+pub struct Store {
+ context: Box<ExecutionContext>,
+ pub functions: Vec<Box<FunctionInstance>>,
+ pub tables: Vec<Box<TableInstance>>,
+ pub memories: Vec<Box<MemoryInstance>>,
+ pub globals: Vec<Box<GlobalInstance>>,
+ pub instances: Vec<Box<Instance>>,
+ pub tags: Vec<Box<TagInstance>>,
+ /// The runtime type of each type identity, and the addresses the interpreter sees them by.
+ #[allow(clippy::vec_box)] // The interpreter holds the addresses of the Rtts, which must not move.
+ rtts: Vec<Box<gc::RttStorage>>,
+ rtt_pointers: Vec<*const crate::abi::Rtt>,
+ // FIXME: Collect objects nothing refers to anymore.
+ objects: Vec<Box<[u64]>>,
+ // FIXME: Collect exceptions nothing refers to anymore.
+ pub exceptions: Vec<Box<ExceptionInstance>>,
+ canonicalizer: TypeCanonicalizer,
+ /// The type of each store-wide type identity, with its type indices replaced by identities, so that types of
+ /// different modules can be compared.
+ types: Vec<crate::types::SubType>,
+ /// The identity of each type in `types`: its index. This makes `types` usable as a type context.
+ identities: Vec<u32>,
+ /// A trap a runtime function reported, which the interpreter only knows as TRAP_RUNTIME.
+ pending_trap: Option<Trap>,
+}
+
+impl Default for Store {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Store {
+ pub fn new() -> Self {
+ interpreter::check_cpu_features();
+ interpreter::install_fault_handler();
+ Self {
+ context: Box::new(ExecutionContext {
+ stack_limit: 0,
+ entry_fp: 0,
+ entry_record: std::ptr::null_mut(),
+ store: std::ptr::null_mut(),
+ arguments: [0; 6],
+ rtts: std::ptr::null(),
+ }),
+ functions: Vec::new(),
+ tables: Vec::new(),
+ memories: Vec::new(),
+ globals: Vec::new(),
+ instances: Vec::new(),
+ canonicalizer: TypeCanonicalizer::new(),
+ types: Vec::new(),
+ identities: Vec::new(),
+ pending_trap: None,
+ tags: Vec::new(),
+ exceptions: Vec::new(),
+ rtts: Vec::new(),
+ rtt_pointers: Vec::new(),
+ objects: Vec::new(),
+ }
+ }
+
+ pub fn function(&self, address: FunctionAddress) -> &FunctionInstance {
+ &self.functions[address.0 as usize]
+ }
+
+ pub fn memory(&self, address: MemoryAddress) -> &MemoryInstance {
+ &self.memories[address.0 as usize]
+ }
+
+ pub fn memory_mut(&mut self, address: MemoryAddress) -> &mut MemoryInstance {
+ &mut self.memories[address.0 as usize]
+ }
+
+ pub fn table(&self, address: TableAddress) -> &TableInstance {
+ &self.tables[address.0 as usize]
+ }
+
+ pub fn table_mut(&mut self, address: TableAddress) -> &mut TableInstance {
+ &mut self.tables[address.0 as usize]
+ }
+
+ pub fn global(&self, address: GlobalAddress) -> &GlobalInstance {
+ &self.globals[address.0 as usize]
+ }
+
+ pub fn global_mut(&mut self, address: GlobalAddress) -> &mut GlobalInstance {
+ &mut self.globals[address.0 as usize]
+ }
+
+ pub fn instance(&self, address: InstanceAddress) -> &Instance {
+ &self.instances[address.0 as usize]
+ }
+
+ /// The store-wide identity of a function type that is not part of a recursion group.
+ fn identity_of_function_type(&mut self, ty: &FuncType) -> u32 {
+ let sub_type = crate::types::SubType {
+ is_final: true,
+ supertypes: Vec::new(),
+ composite: crate::types::CompositeType::Func(ty.clone()),
+ };
+ let identities = self
+ .canonicalizer
+ .canonicalize_group(std::slice::from_ref(&sub_type), 0, |_| 0);
+ self.register_types(&[sub_type], &identities);
+ identities[0]
+ }
+
+ /// Remember the store-wide form of a canonicalized group the first time it is seen. Its types must already have
+ /// identities in place of their type indices.
+ fn register_types(&mut self, group: &[crate::types::SubType], identities: &[u32]) {
+ if identities
+ .first()
+ .is_none_or(|&first| first as usize != self.types.len())
+ {
+ return;
+ }
+ for sub_type in group {
+ let identity = self.types.len() as u32;
+ self.identities.push(identity);
+ self.types.push(sub_type.clone());
+ let rtt = gc::RttStorage::new(self, identity);
+ self.rtt_pointers.push(&raw const rtt.rtt);
+ self.rtts.push(rtt);
+ }
+ self.context.rtts = self.rtt_pointers.as_ptr();
+ }
+
+ /// The types of the store, where concrete heap types are identities.
+ fn type_context(&self) -> crate::validator::TypeContext<'_> {
+ crate::validator::TypeContext {
+ types: &self.types,
+ identities: &self.identities,
+ }
+ }
+
+ pub fn allocate_host_function(&mut self, ty: FuncType, callback: HostCallback) -> FunctionAddress {
+ let address = FunctionAddress(self.functions.len() as u32);
+ let type_identity = self.identity_of_function_type(&ty);
+ let mut function = Box::new(FunctionInstance {
+ header: FunctionHeader {
+ code: std::ptr::null(),
+ code_end: std::ptr::null(),
+ side_table: std::ptr::null(),
+ instance: std::ptr::null(),
+ kind: FUNCTION_KIND_HOST,
+ param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
+ result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
+ local_count: 0,
+ locals_size: 0,
+ reserved: 0,
+ frame_size: 0,
+ type_identity,
+ host: std::ptr::null(),
+ vector_storage: std::ptr::null(),
+ },
+ address,
+ ty,
+ vector_storage: Box::new([]),
+ kind: FunctionKind::Host(callback),
+ });
+ function.header.host = (&raw const *function).cast();
+ self.functions.push(function);
+ address
+ }
+
+ pub fn allocate_memory(&mut self, ty: crate::types::MemoryType) -> Option<MemoryAddress> {
+ let memory = MemoryInstance::new(ty)?;
+ self.memories.push(Box::new(memory));
+ Some(MemoryAddress(self.memories.len() as u32 - 1))
+ }
+
+ pub fn allocate_table(&mut self, ty: TableType, initial: u64) -> TableAddress {
+ self.tables.push(Box::new(TableInstance::new(ty, initial)));
+ TableAddress(self.tables.len() as u32 - 1)
+ }
+
+ pub fn allocate_global(&mut self, ty: GlobalType, value: Value) -> GlobalAddress {
+ let mut global = Box::new(GlobalInstance { value: [0; 2], ty });
+ global.set(value);
+ self.globals.push(global);
+ GlobalAddress(self.globals.len() as u32 - 1)
+ }
+
+ pub fn instantiate(
+ &mut self,
+ module: Arc<Module>,
+ imports: &[ExternValue],
+ ) -> Result<InstanceAddress, InstantiationError> {
+ let link_error = |message: &str| Err(InstantiationError::Link(message.to_string()));
+ if imports.len() != module.imports.len() {
+ 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);
+ }
+
+ // 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 mut functions = Vec::new();
+ let mut tables = Vec::new();
+ let mut memories = Vec::new();
+ let mut globals = Vec::new();
+ let mut tags = Vec::new();
+ for (import, value) in module.imports.iter().zip(imports) {
+ match (&import.description, value) {
+ (ImportDescription::Function(type_index), ExternValue::Function(address)) => {
+ let expected = type_identities[*type_index as usize];
+ let actual = self.function(*address).header.type_identity;
+ if !self
+ .type_context()
+ .heap_subtype(HeapType::Concrete(actual), HeapType::Concrete(expected))
+ {
+ return link_error("incompatible import type");
+ }
+ functions.push(*address);
+ }
+ (ImportDescription::Table(ty), ExternValue::Table(address)) => {
+ let table = self.table(*address);
+ if !limits_match(table.elements.len() as u64, table.ty.limits.max, &ty.limits)
+ || table.ty.limits.address_type != ty.limits.address_type
+ || ValType::Ref(table.ty.element) != canonical(ValType::Ref(ty.element))
+ {
+ return link_error("incompatible import type");
+ }
+ tables.push(*address);
+ }
+ (ImportDescription::Memory(ty), ExternValue::Memory(address)) => {
+ let memory = self.memory(*address);
+ if !limits_match(memory.pages(), memory.ty.limits.max, &ty.limits)
+ || memory.ty.limits.address_type != ty.limits.address_type
+ || memory.ty.limits.shared != ty.limits.shared
+ {
+ return link_error("incompatible import type");
+ }
+ memories.push(*address);
+ }
+ (ImportDescription::Global(ty), ExternValue::Global(address)) => {
+ let global = self.global(*address);
+ let expected = canonical(ty.value);
+ let matches = if ty.mutable {
+ global.ty.mutable && global.ty.value == expected
+ } else {
+ !global.ty.mutable && self.type_context().value_subtype(global.ty.value, expected)
+ };
+ if !matches {
+ return link_error("incompatible import type");
+ }
+ globals.push(*address);
+ }
+ (ImportDescription::Tag(ty), ExternValue::Tag(address)) => {
+ if self.tag(*address).type_identity != type_identities[ty.type_index as usize] {
+ return link_error("incompatible import type");
+ }
+ tags.push(*address);
+ }
+ _ => return link_error("incompatible import type"),
+ }
+ }
+
+ // The instance is allocated before its contents, so that its functions can point at its data.
+ let instance_address = InstanceAddress(self.instances.len() as u32);
+ let mut instance = Box::new(Instance {
+ data: Box::new(InstanceData {
+ memory0_base: std::ptr::null_mut(),
+ memories: std::ptr::null(),
+ globals: std::ptr::null(),
+ functions: std::ptr::null(),
+ tables: std::ptr::null(),
+ type_identities: std::ptr::null(),
+ data_segments: std::ptr::null(),
+ element_segments: std::ptr::null(),
+ tags: std::ptr::null(),
+ function_count: 0,
+ memory_count: 0,
+ }),
+ module: module.clone(),
+ functions: Vec::new(),
+ tables: Vec::new(),
+ memories: Vec::new(),
+ globals: Vec::new(),
+ exports: HashMap::new(),
+ type_identities,
+ element_storage: Vec::new(),
+ element_segments: Vec::new(),
+ data_segments: module
+ .data
+ .iter()
+ .map(|data| Segment {
+ contents: module.bytes.as_ptr().wrapping_add(data.bytes.start as usize),
+ length: u64::from(data.bytes.end - data.bytes.start),
+ })
+ .collect(),
+ function_headers: Vec::new(),
+ global_slots: Vec::new(),
+ tags: Vec::new(),
+ tag_identities: Vec::new(),
+ table_datas: Vec::new(),
+ memory_datas: Vec::new(),
+ });
+ let instance_data: *const InstanceData = &raw const *instance.data;
+
+ 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 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)),
+ );
+ let mut vector_storage = Vec::new();
+ let mut locals_size = scalar_size;
+ for local in local_types {
+ if local == ValType::V128 {
+ vector_storage.push(locals_size);
+ locals_size += 16;
+ } else {
+ vector_storage.push(0);
+ }
+ }
+ let has_v128_locals = locals_size != scalar_size;
+ if !has_v128_locals {
+ vector_storage.clear();
+ }
+ let vector_storage = vector_storage.into_boxed_slice();
+ let frame_size =
+ (FRAME_HEADER_SIZE as u32 + info.max_stack_slots * 8 + SPILL_AREA_SIZE as u32).next_multiple_of(16);
+ let address = FunctionAddress(self.functions.len() as u32);
+ let code = module.bytes.as_ptr().wrapping_add(body.code.start as usize);
+ let code_end = module.bytes.as_ptr().wrapping_add(body.code.end as usize - 1);
+ self.functions.push(Box::new(FunctionInstance {
+ header: FunctionHeader {
+ code,
+ code_end,
+ side_table: info.side_table.as_ptr().cast(),
+ instance: instance_data,
+ kind: if has_v128_locals {
+ FUNCTION_KIND_WASM_VECTOR
+ } else {
+ FUNCTION_KIND_WASM
+ },
+ param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
+ result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
+ local_count,
+ locals_size,
+ reserved: 0,
+ frame_size,
+ type_identity: instance.type_identities[type_index as usize],
+ host: std::ptr::null(),
+ vector_storage: if has_v128_locals {
+ vector_storage.as_ptr()
+ } else {
+ std::ptr::null()
+ },
+ },
+ address,
+ ty,
+ vector_storage,
+ kind: FunctionKind::Wasm {
+ module: module.clone(),
+ index: module.imported_function_count + offset as u32,
+ instance: instance_address,
+ },
+ }));
+ functions.push(address);
+ }
+ instance.functions = functions;
+ instance.function_headers = instance
+ .functions
+ .iter()
+ .map(|address| &raw const self.function(*address).header)
+ .collect();
+
+ for memory in &module.memories {
+ let address = self
+ .allocate_memory(*memory)
+ .ok_or_else(|| InstantiationError::Link("cannot allocate memory".to_string()))?;
+ memories.push(address);
+ }
+ instance.memories = memories;
+
+ // Globals are initialized in order, and an initializer may read the globals before its own.
+ for global in &module.globals {
+ let value = constant::evaluate(
+ self,
+ &globals,
+ &instance.functions,
+ &instance.type_identities,
+ &module,
+ &global.initializer,
+ )
+ .map_err(InstantiationError::Trap)?;
+ let ty = GlobalType {
+ value: canonical(global.ty.value),
+ mutable: global.ty.mutable,
+ };
+ globals.push(self.allocate_global(ty, value));
+ }
+ instance.globals = globals;
+
+ for table in &module.tables {
+ let initial = match &table.initializer {
+ Some(initializer) => {
+ match constant::evaluate(
+ self,
+ &instance.globals,
+ &instance.functions,
+ &instance.type_identities,
+ &module,
+ initializer,
+ )
+ .map_err(InstantiationError::Trap)?
+ {
+ Value::Ref(bits) => bits,
+ _ => 0,
+ }
+ }
+ None => 0,
+ };
+ let ValType::Ref(element) = canonical(ValType::Ref(table.ty.element)) else {
+ unreachable!("table elements are references");
+ };
+ tables.push(self.allocate_table(TableType { element, ..table.ty }, initial));
+ }
+ 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 type_identity = instance.type_identities[tag.type_index as usize];
+ tags.push(self.allocate_tag_with_identity(ty, type_identity));
+ }
+ instance.tags = tags;
+ self.refresh_instance_data(&mut instance);
+
+ for export in &module.exports {
+ let value = match export.kind {
+ ExternalKind::Function => ExternValue::Function(instance.functions[export.index as usize]),
+ ExternalKind::Table => ExternValue::Table(instance.tables[export.index as usize]),
+ ExternalKind::Memory => ExternValue::Memory(instance.memories[export.index as usize]),
+ ExternalKind::Global => ExternValue::Global(instance.globals[export.index as usize]),
+ ExternalKind::Tag => ExternValue::Tag(instance.tags[export.index as usize]),
+ };
+ instance.exports.insert(export.name.clone(), value);
+ }
+
+ // Element segments.
+ let mut element_values = Vec::with_capacity(module.elements.len());
+ for element in &module.elements {
+ let values = match &element.items {
+ ElementItems::Functions(indices) => indices
+ .iter()
+ .map(|&index| self.function_reference(instance.functions[index as usize]))
+ .collect::<Vec<_>>(),
+ ElementItems::Expressions(expressions) => {
+ let mut values = Vec::with_capacity(expressions.len());
+ for expression in expressions {
+ match constant::evaluate(
+ self,
+ &instance.globals,
+ &instance.functions,
+ &instance.type_identities,
+ &module,
+ expression,
+ )
+ .map_err(InstantiationError::Trap)?
+ {
+ Value::Ref(bits) => values.push(bits),
+ _ => values.push(0),
+ }
+ }
+ values
+ }
+ };
+ element_values.push(values);
+ }
+ instance.element_storage = element_values;
+ instance.element_segments = instance
+ .element_storage
+ .iter()
+ .zip(&module.elements)
+ .map(|(values, element)| Segment {
+ contents: values.as_ptr().cast(),
+ length: if matches!(element.mode, ElementMode::Passive) {
+ values.len() as u64
+ } else {
+ 0
+ },
+ })
+ .collect();
+ instance.data.element_segments = instance.element_segments.as_ptr();
+ instance.data.data_segments = instance.data_segments.as_ptr();
+ self.instances.push(instance);
+ let instance_index = instance_address.0 as usize;
+
+ for (index, element) in module.elements.iter().enumerate() {
+ if let ElementMode::Active { table, offset } = &element.mode {
+ let offset = self.evaluate_offset(instance_index, &module, offset)?;
+ let table_address = self.instances[instance_index].tables[*table as usize];
+ let values = std::mem::take(&mut self.instances[instance_index].element_storage[index]);
+ let table = self.table_mut(table_address);
+ let end = offset.checked_add(values.len() as u64);
+ if end.is_none_or(|end| end > table.elements.len() as u64) {
+ return Err(InstantiationError::Trap(Trap::TableOutOfBounds));
+ }
+ table.elements[offset as usize..offset as usize + values.len()].copy_from_slice(&values);
+ }
+ }
+
+ for (index, data) in module.data.iter().enumerate() {
+ if let DataMode::Active { memory, offset } = &data.mode {
+ let offset = self.evaluate_offset(instance_index, &module, offset)?;
+ let memory_address = self.instances[instance_index].memories[*memory as usize];
+ let bytes = module.bytes_of(&data.bytes);
+ let memory = self.memory_mut(memory_address);
+ let end = offset.checked_add(bytes.len() as u64);
+ if end.is_none_or(|end| end > memory.size() as u64) {
+ return Err(InstantiationError::Trap(Trap::MemoryOutOfBounds));
+ }
+ memory.bytes_mut()[offset as usize..offset as usize + bytes.len()].copy_from_slice(bytes);
+ self.instances[instance_index].data_segments[index].length = 0;
+ }
+ }
+
+ if let Some(start) = module.start {
+ let function = self.instances[instance_index].functions[start as usize];
+ self.invoke(function, &[]).map_err(InstantiationError::Trap)?;
+ }
+ Ok(instance_address)
+ }
+
+ fn evaluate_offset(
+ &mut self,
+ instance_index: usize,
+ module: &Module,
+ expression: &crate::module::ConstantExpression,
+ ) -> Result<u64, InstantiationError> {
+ let instance = &self.instances[instance_index];
+ let (globals, functions, type_identities) = (
+ instance.globals.clone(),
+ instance.functions.clone(),
+ instance.type_identities.clone(),
+ );
+ match constant::evaluate(self, &globals, &functions, &type_identities, module, expression)
+ .map_err(InstantiationError::Trap)?
+ {
+ Value::I32(value) => Ok(u64::from(value as u32)),
+ Value::I64(value) => Ok(value as u64),
+ _ => Ok(0),
+ }
+ }
+
+ /// Point the instance's interpreter-visible data at its current contents.
+ fn refresh_instance_data(&self, instance: &mut Instance) {
+ instance.function_headers = instance
+ .functions
+ .iter()
+ .map(|address| &raw const self.function(*address).header)
+ .collect();
+ instance.global_slots = instance
+ .globals
+ .iter()
+ .map(|address| self.globals[address.0 as usize].value.as_ptr().cast_mut())
+ .collect();
+ instance.table_datas = instance
+ .tables
+ .iter()
+ .map(|address| (&raw const *self.tables[address.0 as usize].data).cast_mut())
+ .collect();
+ instance.memory_datas = instance
+ .memories
+ .iter()
+ .map(|address| (&raw const *self.memories[address.0 as usize].data).cast_mut())
+ .collect();
+ let data = &mut instance.data;
+ data.functions = instance.function_headers.as_ptr();
+ data.function_count = instance.function_headers.len() as u32;
+ data.globals = instance.global_slots.as_ptr();
+ data.tables = instance.table_datas.as_ptr();
+ data.memories = instance.memory_datas.as_ptr();
+ data.memory_count = instance.memory_datas.len() as u32;
+ data.memory0_base = instance
+ .memories
+ .first()
+ .map_or(std::ptr::null_mut(), |address| self.memory(*address).data.base);
+ data.type_identities = instance.type_identities.as_ptr();
+ instance.tag_identities = instance
+ .tags
+ .iter()
+ .map(|address| (&raw const *self.tags[address.0 as usize]) as u64)
+ .collect();
+ instance.data.tags = instance.tag_identities.as_ptr();
+ }
+
+ pub fn tag(&self, address: TagAddress) -> &TagInstance {
+ &self.tags[address.0 as usize]
+ }
+
+ /// Add a tag for exceptions that carry values of the parameter types of `ty`.
+ pub fn allocate_tag(&mut self, ty: FuncType) -> TagAddress {
+ let type_identity = self.identity_of_function_type(&ty);
+ self.allocate_tag_with_identity(ty, type_identity)
+ }
+
+ fn allocate_tag_with_identity(&mut self, ty: FuncType, type_identity: u32) -> TagAddress {
+ let address = TagAddress(self.tags.len() as u32);
+ self.tags.push(Box::new(TagInstance {
+ address,
+ ty,
+ type_identity,
+ }));
+ address
+ }
+
+ /// The tag of an exception reference's identity.
+ pub fn tag_from_identity(&self, identity: u64) -> TagAddress {
+ unsafe { (*(identity as *const TagInstance)).address }
+ }
+
+ /// Make an exception with `tag` and the values of `payload`, and return its reference.
+ pub fn allocate_exception(&mut self, tag: TagAddress, payload: Box<[u64]>) -> u64 {
+ let exception = Box::new(ExceptionInstance { tag, payload });
+ let reference = (&raw const *exception) as u64;
+ self.exceptions.push(exception);
+ reference
+ }
+
+ /// The exception an exception reference refers to.
+ pub fn exception(&self, reference: u64) -> &ExceptionInstance {
+ unsafe { &*(reference as *const ExceptionInstance) }
+ }
+
+ pub fn function_reference(&self, address: FunctionAddress) -> u64 {
+ (&raw const self.function(address).header) as u64
+ }
+
+ /// The function a non-null function reference refers to.
+ pub fn function_from_reference(&self, reference: u64) -> Option<FunctionAddress> {
+ if reference == 0 {
+ return None;
+ }
+ let function = unsafe { &*(reference as *const FunctionInstance) };
+ Some(function.address)
+ }
+
+ pub fn invoke(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ let function = self.function(address);
+ if let FunctionKind::Host(_) = function.kind {
+ return self.call_host(address, arguments);
+ }
+ let ty = function.ty.clone();
+ let header: *const FunctionHeader = &raw const function.header;
+ // The arguments are laid out as they will be on the operand stack, which grows down: the last one first.
+ let mut argument_slots = Vec::new();
+ for argument in arguments.iter().rev() {
+ argument.push_slots(&mut argument_slots);
+ }
+ let mut result_slots = vec![0u64; function.header.result_slots as usize];
+ let is_outermost = self.context.entry_record.is_null();
+ if is_outermost {
+ self.context.stack_limit = interpreter::stack_limit(STACK_RESERVE);
+ }
+ self.context.store = (self as *mut Store).cast();
+ let mut record = EntryRecord {
+ function: header,
+ arguments: argument_slots.as_ptr(),
+ results: result_slots.as_mut_ptr(),
+ context: &raw mut *self.context,
+ trap: 0,
+ padding: 0,
+ saved_entry_fp: 0,
+ saved_entry_record: std::ptr::null_mut(),
+ };
+ unsafe { interpreter::enter(&mut record) };
+ if record.trap != 0 {
+ return Err(Trap::from_code(record.trap, self.pending_trap.take()));
+ }
+ // The results are laid out as the operand stack holds them, the first one in the highest slots.
+ let mut results = Vec::with_capacity(ty.results.len());
+ let mut slot = result_slots.len();
+ for &result in &ty.results {
+ slot -= result.slot_count() as usize;
+ results.push(Value::from_slots(result, &result_slots[slot..]));
+ }
+ Ok(results)
+ }
+
+ fn call_host(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ let FunctionKind::Host(callback) = &self.functions[address.0 as usize].kind else {
+ unreachable!("only host functions are called through call_host")
+ };
+ let callback = callback.clone();
+ callback(self, arguments)
+ }
+}
+
+fn limits_match(current: u64, current_max: Option<u64>, expected: &crate::types::Limits) -> bool {
+ if current < expected.min {
+ return false;
+ }
+ match expected.max {
+ None => true,
+ Some(max) => current_max.is_some_and(|current_max| current_max <= max),
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/types.rs b/Libraries/LibWasm/Engine/src/types.rs
new file mode 100644
index 00000000000..80f37861548
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/types.rs
@@ -0,0 +1,368 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The WebAssembly type language, and the canonicalization that decides when two type indices denote the same type.
+
+use std::collections::HashMap;
+
+/// A heap type. `Concrete` names a type by its index in the module's type section.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum HeapType {
+ Func,
+ NoFunc,
+ Extern,
+ NoExtern,
+ Any,
+ Eq,
+ I31,
+ Struct,
+ Array,
+ None,
+ Exn,
+ NoExn,
+ Concrete(u32),
+ /// The bottom of every hierarchy. Validation only produces it for values popped from an unreachable stack.
+ Bottom,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct RefType {
+ pub nullable: bool,
+ pub heap: HeapType,
+}
+
+impl RefType {
+ pub const FUNCREF: RefType = RefType {
+ nullable: true,
+ heap: HeapType::Func,
+ };
+ pub const EXTERNREF: RefType = RefType {
+ nullable: true,
+ heap: HeapType::Extern,
+ };
+ pub const EXNREF: RefType = RefType {
+ nullable: true,
+ heap: HeapType::Exn,
+ };
+
+ pub fn new(nullable: bool, heap: HeapType) -> Self {
+ Self { nullable, heap }
+ }
+
+ pub fn as_non_null(self) -> Self {
+ Self {
+ nullable: false,
+ heap: self.heap,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ValType {
+ I32,
+ I64,
+ F32,
+ F64,
+ V128,
+ Ref(RefType),
+}
+
+impl ValType {
+ pub const FUNCREF: ValType = ValType::Ref(RefType::FUNCREF);
+ pub const EXTERNREF: ValType = ValType::Ref(RefType::EXTERNREF);
+
+ pub fn is_reference(self) -> bool {
+ matches!(self, Self::Ref(_))
+ }
+
+ pub fn is_numeric(self) -> bool {
+ matches!(self, Self::I32 | Self::I64 | Self::F32 | Self::F64)
+ }
+
+ /// Whether a local of this type has a default value, so that it can be used before it is set.
+ pub fn is_defaultable(self) -> bool {
+ match self {
+ Self::Ref(reference) => reference.nullable,
+ _ => true,
+ }
+ }
+
+ /// The number of 8-byte slots a value of this type takes on the operand stack.
+ pub fn slot_count(self) -> u32 {
+ match self {
+ Self::V128 => 2,
+ _ => 1,
+ }
+ }
+
+ /// This type with the type index of a concrete heap type replaced by `map` of it.
+ pub fn map_type_indices(self, map: &impl Fn(u32) -> u32) -> Self {
+ match self {
+ Self::Ref(RefType {
+ nullable,
+ heap: HeapType::Concrete(index),
+ }) => Self::Ref(RefType {
+ nullable,
+ heap: HeapType::Concrete(map(index)),
+ }),
+ other => other,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum StorageType {
+ Val(ValType),
+ I8,
+ I16,
+}
+
+impl StorageType {
+ pub fn is_packed(self) -> bool {
+ matches!(self, Self::I8 | Self::I16)
+ }
+
+ /// The type a field of this storage type has once it is read.
+ pub fn unpacked(self) -> ValType {
+ match self {
+ Self::Val(value) => value,
+ Self::I8 | Self::I16 => ValType::I32,
+ }
+ }
+
+ pub fn byte_size(self) -> u32 {
+ match self {
+ Self::I8 => 1,
+ Self::I16 => 2,
+ Self::Val(ValType::I32 | ValType::F32) => 4,
+ Self::Val(ValType::V128) => 16,
+ Self::Val(_) => 8,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct FieldType {
+ pub storage: StorageType,
+ pub mutable: bool,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
+pub struct FuncType {
+ pub params: Vec<ValType>,
+ pub results: Vec<ValType>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum CompositeType {
+ Func(FuncType),
+ Struct(Vec<FieldType>),
+ Array(FieldType),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct SubType {
+ pub is_final: bool,
+ pub supertypes: Vec<u32>,
+ pub composite: CompositeType,
+}
+
+impl SubType {
+ /// This type with every type index in it replaced by `map` of it.
+ pub fn map_type_indices(&self, map: &impl Fn(u32) -> u32) -> Self {
+ let storage = |storage: StorageType| match storage {
+ StorageType::Val(value) => StorageType::Val(value.map_type_indices(map)),
+ packed => packed,
+ };
+ let field = |field: &FieldType| FieldType {
+ storage: storage(field.storage),
+ mutable: field.mutable,
+ };
+ Self {
+ is_final: self.is_final,
+ supertypes: self.supertypes.iter().map(|&supertype| map(supertype)).collect(),
+ composite: match &self.composite {
+ CompositeType::Func(function) => CompositeType::Func(FuncType {
+ params: function
+ .params
+ .iter()
+ .map(|param| param.map_type_indices(map))
+ .collect(),
+ results: function
+ .results
+ .iter()
+ .map(|result| result.map_type_indices(map))
+ .collect(),
+ }),
+ CompositeType::Struct(fields) => CompositeType::Struct(fields.iter().map(field).collect()),
+ CompositeType::Array(element) => CompositeType::Array(field(element)),
+ },
+ }
+ }
+
+ pub fn as_func(&self) -> Option<&FuncType> {
+ match &self.composite {
+ CompositeType::Func(function) => Some(function),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AddressType {
+ I32,
+ I64,
+}
+
+impl AddressType {
+ pub fn value_type(self) -> ValType {
+ match self {
+ Self::I32 => ValType::I32,
+ Self::I64 => ValType::I64,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Limits {
+ pub min: u64,
+ pub max: Option<u64>,
+ pub address_type: AddressType,
+ pub shared: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MemoryType {
+ pub limits: Limits,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TableType {
+ pub element: RefType,
+ pub limits: Limits,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct GlobalType {
+ pub value: ValType,
+ pub mutable: bool,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TagType {
+ pub type_index: u32,
+}
+
+/// A type index inside a canonicalization key: either relative to the start of the recursion group it appears in,
+/// or the canonical identity of a type outside of it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum KeyIndex {
+ Recursive(u32),
+ Canonical(u32),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum KeyHeap {
+ Abstract(HeapType),
+ Index(KeyIndex),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum KeyValue {
+ Plain(ValType),
+ Ref(bool, KeyHeap),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum KeyStorage {
+ Value(KeyValue),
+ I8,
+ I16,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum KeyComposite {
+ Func(Vec<KeyValue>, Vec<KeyValue>),
+ Struct(Vec<(KeyStorage, bool)>),
+ Array(KeyStorage, bool),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct KeySubType {
+ is_final: bool,
+ supertypes: Vec<KeyIndex>,
+ composite: KeyComposite,
+}
+
+/// Assigns every type a canonical identity, such that two types are equal exactly when their identities are. Types are
+/// equal when their recursion groups are structurally identical and they sit at the same position in them, so a whole
+/// group is canonicalized at once, with references to types of earlier groups replaced by their identities.
+#[derive(Default)]
+pub struct TypeCanonicalizer {
+ groups: HashMap<Vec<KeySubType>, u32>,
+ next_identity: u32,
+}
+
+impl TypeCanonicalizer {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Canonicalize a recursion group whose first type has index `start`. `identity_of` gives the identities of the
+ /// types before `start`. Returns the identity of each type in the group.
+ pub fn canonicalize_group(&mut self, group: &[SubType], start: u32, identity_of: impl Fn(u32) -> u32) -> Vec<u32> {
+ let index = |type_index: u32| {
+ if type_index >= start {
+ KeyIndex::Recursive(type_index - start)
+ } else {
+ KeyIndex::Canonical(identity_of(type_index))
+ }
+ };
+ let value = |value: ValType| match value {
+ ValType::Ref(reference) => KeyValue::Ref(
+ reference.nullable,
+ match reference.heap {
+ HeapType::Concrete(type_index) => KeyHeap::Index(index(type_index)),
+ heap => KeyHeap::Abstract(heap),
+ },
+ ),
+ plain => KeyValue::Plain(plain),
+ };
+ let storage = |storage: StorageType| match storage {
+ StorageType::Val(inner) => KeyStorage::Value(value(inner)),
+ StorageType::I8 => KeyStorage::I8,
+ StorageType::I16 => KeyStorage::I16,
+ };
+ let key = group
+ .iter()
+ .map(|sub_type| KeySubType {
+ is_final: sub_type.is_final,
+ supertypes: sub_type.supertypes.iter().map(|&supertype| index(supertype)).collect(),
+ composite: match &sub_type.composite {
+ CompositeType::Func(function) => KeyComposite::Func(
+ function.params.iter().map(|&param| value(param)).collect(),
+ function.results.iter().map(|&result| value(result)).collect(),
+ ),
+ CompositeType::Struct(fields) => KeyComposite::Struct(
+ fields
+ .iter()
+ .map(|field| (storage(field.storage), field.mutable))
+ .collect(),
+ ),
+ CompositeType::Array(field) => KeyComposite::Array(storage(field.storage), field.mutable),
+ },
+ })
+ .collect::<Vec<_>>();
+ let count = group.len() as u32;
+ let next_identity = &mut self.next_identity;
+ let first = *self.groups.entry(key).or_insert_with(|| {
+ let first = *next_identity;
+ *next_identity += count;
+ first
+ });
+ (first..first + count).collect()
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/validator.rs b/Libraries/LibWasm/Engine/src/validator.rs
new file mode 100644
index 00000000000..046cb85ef38
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/validator.rs
@@ -0,0 +1,2258 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Module validation. Function bodies are checked in one pass over their bytes, which also builds the side table the
+//! in-place interpreter branches with.
+//!
+//! # Side tables
+//!
+//! The interpreter executes a function's original bytes, so it cannot find branch targets in the code itself. Every
+//! instruction that may transfer control to somewhere other than the next instruction owns entries of the function's
+//! side table, in the order the instructions appear. The interpreter keeps a pointer to the next entry (`stp`) next
+//! to the instruction pointer and advances it as it executes those instructions, so a branch finds its entry without
+//! a search:
+//!
+//! - `br`, `br_if`, `br_on_null`, `br_on_non_null`, `br_on_cast`, and `br_on_cast_fail` own one entry, for the taken
+//! branch. Not taking a conditional branch steps over it.
+//! - `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.
+//!
+//! 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
+//! drop the `drop` slots below them. Branches to blocks target the instruction after their `end`; branches to loops
+//! target the `loop` instruction, which is where back edges are counted; branches to the function's label target its
+//! final `end`, which returns.
+//!
+//! Exceptions are not linear, so `try_table` handlers live in a separate table of the regions they protect.
+
+use crate::error::{Error, Result};
+use crate::instruction_tables::{AtomicKind, SimdKind, atomic_kind, simd_kind};
+use crate::module::{ConstantExpression, DataMode, ElementItems, ElementMode, ExternalKind, ImportDescription, Module};
+use crate::opcode;
+use crate::parser::{parse_heap_type, parse_value_type};
+use crate::quickening::Rewrite;
+use crate::reader::Reader;
+use crate::types::{
+ AddressType, CompositeType, FieldType, FuncType, HeapType, Limits, RefType, StorageType, SubType,
+ TypeCanonicalizer, ValType,
+};
+use std::collections::HashSet;
+
+/// One side-table entry. See the module documentation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+#[repr(C)]
+pub struct SideTableEntry {
+ /// The target's offset from the branching instruction, in bytes.
+ pub pc_delta: i32,
+ /// The target's next entry's offset from this entry, in entries.
+ pub stp_delta: i32,
+ /// The number of slots at the top of the operand stack the branch keeps.
+ pub keep: u32,
+ /// The number of slots below them the branch drops.
+ pub drop: u32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CatchKind {
+ Catch,
+ CatchRef,
+ CatchAll,
+ CatchAllRef,
+}
+
+/// One catch clause of a `try_table`: which exceptions it catches and where the handler continues.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CatchClause {
+ pub kind: CatchKind,
+ /// The tag index of `catch` and `catch_ref` clauses.
+ pub tag: u32,
+ /// The module offset of the instruction the handler continues at.
+ pub target_pc: u32,
+ /// The index of the side-table entry the handler continues with.
+ pub target_stp: u32,
+ /// The height of the operand stack, in slots, below the values the handler pushes.
+ pub height: u32,
+}
+
+/// The instructions of one `try_table`, 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,
+}
+
+/// What validation learned about a defined function that running it needs.
+#[derive(Debug, Clone, Default)]
+pub struct FunctionInfo {
+ pub side_table: Box<[SideTableEntry]>,
+ /// `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.
+ pub local_count: u32,
+ /// The most slots the operand stack ever holds.
+ pub max_stack_slots: u32,
+}
+
+impl FunctionInfo {
+ /// The bytes this function's validation results take beyond the module's own bytes.
+ pub fn metadata_size(&self) -> usize {
+ size_of::<Self>()
+ + self.side_table.len() * size_of::<SideTableEntry>()
+ + self.try_regions.len() * size_of::<TryRegion>()
+ + self.catch_clauses.len() * size_of::<CatchClause>()
+ }
+}
+
+/// The largest number of pages a memory may declare.
+const MEMORY32_MAX_PAGES: u64 = 1 << 16;
+const MEMORY64_MAX_PAGES: u64 = 1 << 48;
+
+fn invalid<T>(message: impl Into<String>) -> Result<T> {
+ Err(Error::invalid(message))
+}
+
+fn type_mismatch<T>() -> Result<T> {
+ invalid("type mismatch")
+}
+
+/// The type-level view of a module that validation checks against.
+pub struct TypeContext<'a> {
+ pub types: &'a [SubType],
+ pub identities: &'a [u32],
+}
+
+impl TypeContext<'_> {
+ fn sub_type(&self, index: u32) -> &SubType {
+ &self.types[index as usize]
+ }
+
+ fn is_func(&self, index: u32) -> bool {
+ matches!(self.sub_type(index).composite, CompositeType::Func(_))
+ }
+
+ fn top(&self, heap: HeapType) -> HeapType {
+ match heap {
+ HeapType::Func | HeapType::NoFunc => HeapType::Func,
+ HeapType::Extern | HeapType::NoExtern => HeapType::Extern,
+ HeapType::Exn | HeapType::NoExn => HeapType::Exn,
+ HeapType::Any | HeapType::Eq | HeapType::I31 | HeapType::Struct | HeapType::Array | HeapType::None => {
+ HeapType::Any
+ }
+ HeapType::Concrete(index) => match self.sub_type(index).composite {
+ CompositeType::Func(_) => HeapType::Func,
+ _ => HeapType::Any,
+ },
+ HeapType::Bottom => HeapType::Bottom,
+ }
+ }
+
+ pub fn heap_subtype(&self, sub: HeapType, sup: HeapType) -> bool {
+ use HeapType::*;
+ if sub == sup || sub == Bottom {
+ return true;
+ }
+ match (sub, sup) {
+ (Concrete(a), Concrete(b)) => {
+ if self.identities[a as usize] == self.identities[b as usize] {
+ return true;
+ }
+ self.sub_type(a)
+ .supertypes
+ .iter()
+ .any(|&supertype| self.heap_subtype(Concrete(supertype), sup))
+ }
+ (Concrete(a), _) => match self.sub_type(a).composite {
+ CompositeType::Func(_) => sup == Func,
+ CompositeType::Struct(_) => matches!(sup, Struct | Eq | Any),
+ CompositeType::Array(_) => matches!(sup, Array | Eq | Any),
+ },
+ (None, Concrete(b)) => !self.is_func(b),
+ (NoFunc, Concrete(b)) => self.is_func(b),
+ (_, Concrete(_)) => false,
+ (None, Any | Eq | I31 | Struct | Array) => true,
+ (I31 | Struct | Array, Eq | Any) => true,
+ (Eq, Any) => true,
+ (NoFunc, Func) | (NoExtern, Extern) | (NoExn, Exn) => true,
+ _ => false,
+ }
+ }
+
+ pub fn ref_subtype(&self, sub: RefType, sup: RefType) -> bool {
+ (!sub.nullable || sup.nullable) && self.heap_subtype(sub.heap, sup.heap)
+ }
+
+ pub fn value_subtype(&self, sub: ValType, sup: ValType) -> bool {
+ match (sub, sup) {
+ (ValType::Ref(sub), ValType::Ref(sup)) => self.ref_subtype(sub, sup),
+ _ => sub == sup,
+ }
+ }
+
+ fn storage_subtype(&self, sub: StorageType, sup: StorageType) -> bool {
+ match (sub, sup) {
+ (StorageType::Val(sub), StorageType::Val(sup)) => self.value_subtype(sub, sup),
+ _ => sub == sup,
+ }
+ }
+
+ fn field_subtype(&self, sub: FieldType, sup: FieldType) -> bool {
+ if sub.mutable != sup.mutable {
+ return false;
+ }
+ if sub.mutable {
+ self.storage_subtype(sub.storage, sup.storage) && self.storage_subtype(sup.storage, sub.storage)
+ } else {
+ self.storage_subtype(sub.storage, sup.storage)
+ }
+ }
+
+ fn values_subtype(&self, sub: &[ValType], sup: &[ValType]) -> bool {
+ sub.len() == sup.len() && sub.iter().zip(sup).all(|(&sub, &sup)| self.value_subtype(sub, sup))
+ }
+
+ fn function_subtype(&self, sub: &FuncType, sup: &FuncType) -> bool {
+ self.values_subtype(&sup.params, &sub.params) && self.values_subtype(&sub.results, &sup.results)
+ }
+
+ fn composite_subtype(&self, sub: &CompositeType, sup: &CompositeType) -> bool {
+ match (sub, sup) {
+ (CompositeType::Func(sub), CompositeType::Func(sup)) => self.function_subtype(sub, sup),
+ (CompositeType::Struct(sub), CompositeType::Struct(sup)) => {
+ sub.len() >= sup.len() && sub.iter().zip(sup).all(|(&sub, &sup)| self.field_subtype(sub, sup))
+ }
+ (CompositeType::Array(sub), CompositeType::Array(sup)) => self.field_subtype(*sub, *sup),
+ _ => false,
+ }
+ }
+}
+
+/// An operand stack entry. `None` is a value of unknown type, which only unreachable code produces.
+type Operand = Option<ValType>;
+
+fn operand_slots(operand: Operand) -> u32 {
+ operand.map_or(1, ValType::slot_count)
+}
+
+fn slots_of(types: &[ValType]) -> u32 {
+ types.iter().map(|ty| ty.slot_count()).sum()
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum FrameKind {
+ Block,
+ Loop,
+ If,
+ Else,
+ TryTable,
+ Function,
+}
+
+/// A side-table entry or catch clause whose target is the end of a frame that has not been reached yet.
+#[derive(Debug, Clone, Copy)]
+enum Fixup {
+ Entry { entry: usize, branch_pc: u32 },
+ Clause(usize),
+}
+
+struct Frame {
+ kind: FrameKind,
+ params: Vec<ValType>,
+ results: Vec<ValType>,
+ height: usize,
+ slot_height: u32,
+ unreachable: bool,
+ initialization_height: usize,
+ /// The module offset of the frame's first instruction: the `loop` instruction of a loop, which back edges target.
+ start_pc: u32,
+ /// The side-table index a branch to a loop continues with.
+ start_stp: u32,
+ fixups: Vec<Fixup>,
+ /// The entry of an `if` that jumps to its `else` arm.
+ if_entry: Option<(usize, u32)>,
+ /// The index of the `try_table` region this frame protects.
+ try_region: Option<usize>,
+}
+
+impl Frame {
+ fn label_types(&self) -> &[ValType] {
+ if self.kind == FrameKind::Loop {
+ &self.params
+ } else {
+ &self.results
+ }
+ }
+}
+
+struct FunctionValidator<'a> {
+ module: &'a Module,
+ types: TypeContext<'a>,
+ declared_functions: &'a HashSet<u32>,
+ locals: Vec<ValType>,
+ local_initialized: Vec<bool>,
+ initialization_log: Vec<u32>,
+ operands: Vec<Operand>,
+ slot_height: u32,
+ max_slot_height: u32,
+ frames: Vec<Frame>,
+ side_table: Vec<SideTableEntry>,
+ try_regions: Vec<TryRegion>,
+ catch_clauses: Vec<CatchClause>,
+ results: Vec<ValType>,
+ /// Where the instruction being validated starts.
+ instruction_start: u32,
+ /// The quickened forms of this function's instructions (see quickening.rs).
+ rewrites: Vec<Rewrite>,
+ /// The memory index and offset immediates of the last memory argument read, if its access needs bounds checks.
+ checked_access: Option<(Option<std::ops::Range<usize>>, std::ops::Range<usize>)>,
+}
+
+impl FunctionValidator<'_> {
+ /// Quicken the instruction being validated into its v128 form if its value is a v128.
+ fn quicken_for_v128(&mut self, value: Operand) {
+ if value != Some(ValType::V128) {
+ return;
+ }
+ let opcode = self.module.bytes[self.instruction_start as usize];
+ let quickened = crate::quickening::v128_form(opcode).expect("only instructions with a v128 form get here");
+ self.rewrites.push(Rewrite {
+ position: self.instruction_start,
+ bytes: vec![quickened],
+ });
+ }
+
+ fn push(&mut self, operand: Operand) {
+ self.slot_height += operand_slots(operand);
+ self.max_slot_height = self.max_slot_height.max(self.slot_height);
+ self.operands.push(operand);
+ }
+
+ fn push_value(&mut self, value: ValType) {
+ self.push(Some(value));
+ }
+
+ fn push_values(&mut self, values: &[ValType]) {
+ for &value in values {
+ self.push_value(value);
+ }
+ }
+
+ fn pop(&mut self) -> Result<Operand> {
+ let frame = self.frames.last().expect("validation always has a frame");
+ if self.operands.len() == frame.height {
+ if frame.unreachable {
+ return Ok(None);
+ }
+ return type_mismatch();
+ }
+ let operand = self.operands.pop().expect("the stack is above the frame's height");
+ self.slot_height -= operand_slots(operand);
+ Ok(operand)
+ }
+
+ fn pop_expecting(&mut self, expected: ValType) -> Result<Operand> {
+ let actual = self.pop()?;
+ if let Some(actual) = actual
+ && !self.types.value_subtype(actual, expected)
+ {
+ return type_mismatch();
+ }
+ Ok(actual.or(Some(expected)))
+ }
+
+ fn pop_values(&mut self, values: &[ValType]) -> Result<()> {
+ for &value in values.iter().rev() {
+ self.pop_expecting(value)?;
+ }
+ Ok(())
+ }
+
+ /// Pop a reference of any type, and return it unless it is of unknown type.
+ fn pop_reference(&mut self) -> Result<Option<RefType>> {
+ match self.pop()? {
+ None => Ok(None),
+ Some(ValType::Ref(reference)) => Ok(Some(reference)),
+ Some(_) => type_mismatch(),
+ }
+ }
+
+ fn set_unreachable(&mut self) {
+ let frame = self.frames.last_mut().expect("validation always has a frame");
+ let height = frame.height;
+ frame.unreachable = true;
+ while self.operands.len() > height {
+ let operand = self.operands.pop().expect("the stack is above the frame's height");
+ self.slot_height -= operand_slots(operand);
+ }
+ }
+
+ fn push_frame(&mut self, kind: FrameKind, params: Vec<ValType>, results: Vec<ValType>, start_pc: u32) {
+ let height = self.operands.len();
+ let slot_height = self.slot_height;
+ self.frames.push(Frame {
+ kind,
+ params: params.clone(),
+ results,
+ height,
+ slot_height,
+ unreachable: false,
+ initialization_height: self.initialization_log.len(),
+ start_pc,
+ start_stp: self.side_table.len() as u32,
+ fixups: Vec::new(),
+ if_entry: None,
+ try_region: None,
+ });
+ self.push_values(&params);
+ }
+
+ fn pop_frame(&mut self) -> Result<Frame> {
+ let frame = self.frames.last().expect("validation always has a frame");
+ let results = frame.results.clone();
+ self.pop_values(&results)?;
+ let frame = self.frames.last().expect("validation always has a frame");
+ if self.operands.len() != frame.height {
+ return type_mismatch();
+ }
+ let frame = self.frames.pop().expect("validation always has a frame");
+ for local in self.initialization_log.drain(frame.initialization_height..) {
+ self.local_initialized[local as usize] = false;
+ }
+ Ok(frame)
+ }
+
+ fn label(&self, depth: u32) -> Result<&Frame> {
+ let count = self.frames.len();
+ if depth as usize >= count {
+ return invalid("unknown label");
+ }
+ Ok(&self.frames[count - 1 - depth as usize])
+ }
+
+ fn label_types(&self, depth: u32) -> Result<Vec<ValType>> {
+ Ok(self.label(depth)?.label_types().to_vec())
+ }
+
+ /// Add the side-table entry of a branch at `branch_pc` to the label at `depth`, taken with the current operand
+ /// stack.
+ fn add_branch_entry(&mut self, depth: u32, branch_pc: u32) {
+ let entry_index = self.side_table.len();
+ let frame_index = self.frames.len() - 1 - depth as usize;
+ let frame = &self.frames[frame_index];
+ let keep = slots_of(frame.label_types());
+ let drop = self.slot_height.saturating_sub(frame.slot_height + keep);
+ let reachable = !self.frames.last().expect("validation always has a frame").unreachable;
+ let mut entry = SideTableEntry {
+ pc_delta: 0,
+ stp_delta: 0,
+ keep,
+ drop: if reachable { drop } else { 0 },
+ };
+ if frame.kind == FrameKind::Loop {
+ entry.pc_delta = frame.start_pc as i32 - branch_pc as i32;
+ entry.stp_delta = frame.start_stp as i32 - entry_index as i32;
+ } else {
+ self.frames[frame_index].fixups.push(Fixup::Entry {
+ entry: entry_index,
+ branch_pc,
+ });
+ }
+ self.side_table.push(entry);
+ }
+
+ /// Point the pending branches of a frame at `target_pc`, continuing with the next side-table entry.
+ fn resolve_fixups(&mut self, fixups: &[Fixup], target_pc: u32) {
+ let target_stp = self.side_table.len();
+ for fixup in fixups {
+ match *fixup {
+ Fixup::Entry { entry, branch_pc } => {
+ self.side_table[entry].pc_delta = target_pc as i32 - branch_pc as i32;
+ self.side_table[entry].stp_delta = target_stp as i32 - entry as i32;
+ }
+ Fixup::Clause(clause) => {
+ self.catch_clauses[clause].target_pc = target_pc;
+ self.catch_clauses[clause].target_stp = target_stp as u32;
+ }
+ }
+ }
+ }
+
+ fn local(&self, index: u32) -> Result<ValType> {
+ self.locals
+ .get(index as usize)
+ .copied()
+ .ok_or_else(|| Error::invalid("unknown local"))
+ }
+
+ fn initialize_local(&mut self, index: u32) {
+ if !self.local_initialized[index as usize] {
+ self.local_initialized[index as usize] = true;
+ self.initialization_log.push(index);
+ }
+ }
+
+ fn global(&self, index: u32) -> Result<crate::types::GlobalType> {
+ self.module
+ .global_space
+ .get(index as usize)
+ .copied()
+ .ok_or_else(|| Error::invalid("unknown global"))
+ }
+
+ fn table(&self, index: u32) -> Result<crate::types::TableType> {
+ self.module
+ .table_space
+ .get(index as usize)
+ .copied()
+ .ok_or_else(|| Error::invalid("unknown table"))
+ }
+
+ fn memory_address_type(&self, index: u32) -> Result<AddressType> {
+ self.module
+ .memory_space
+ .get(index as usize)
+ .map(|memory| memory.limits.address_type)
+ .ok_or_else(|| Error::invalid("unknown memory"))
+ }
+
+ fn function_type(&self, index: u32) -> Result<FuncType> {
+ let type_index = *self
+ .module
+ .function_space
+ .get(index as usize)
+ .ok_or_else(|| Error::invalid("unknown function"))?;
+ Ok(self.module.types[type_index as usize]
+ .as_func()
+ .expect("function types are checked first")
+ .clone())
+ }
+
+ fn func_type_at(&self, type_index: u32) -> Result<FuncType> {
+ match self.module.types.get(type_index as usize) {
+ None => invalid("unknown type"),
+ Some(sub_type) => sub_type
+ .as_func()
+ .cloned()
+ .ok_or_else(|| Error::invalid("type mismatch")),
+ }
+ }
+
+ fn struct_type(&self, type_index: u32) -> Result<Vec<FieldType>> {
+ match self
+ .module
+ .types
+ .get(type_index as usize)
+ .map(|sub_type| &sub_type.composite)
+ {
+ None => invalid("unknown type"),
+ Some(CompositeType::Struct(fields)) => Ok(fields.clone()),
+ Some(_) => type_mismatch(),
+ }
+ }
+
+ fn array_type(&self, type_index: u32) -> Result<FieldType> {
+ match self
+ .module
+ .types
+ .get(type_index as usize)
+ .map(|sub_type| &sub_type.composite)
+ {
+ None => invalid("unknown type"),
+ Some(CompositeType::Array(field)) => Ok(*field),
+ Some(_) => type_mismatch(),
+ }
+ }
+
+ fn tag_params(&self, index: u32) -> Result<Vec<ValType>> {
+ let tag = self
+ .module
+ .tag_space
+ .get(index as usize)
+ .ok_or_else(|| Error::invalid("unknown tag"))?;
+ Ok(self.func_type_at(tag.type_index)?.params)
+ }
+
+ fn check_data_index(&self, index: u32) -> Result<()> {
+ let Some(count) = self.module.data_count else {
+ return invalid("data count section required");
+ };
+ if index >= count {
+ return invalid("unknown data segment");
+ }
+ Ok(())
+ }
+
+ fn element_type(&self, index: u32) -> Result<RefType> {
+ self.module
+ .elements
+ .get(index as usize)
+ .map(|element| element.ty)
+ .ok_or_else(|| Error::invalid("unknown elem segment"))
+ }
+
+ fn check_heap_type(&self, heap: HeapType) -> Result<()> {
+ check_heap_type(self.module, heap)
+ }
+
+ fn check_value_type(&self, value: ValType) -> Result<()> {
+ check_value_type(self.module, value)
+ }
+
+ fn read_block_type(&self, reader: &mut Reader<'_>) -> Result<(Vec<ValType>, Vec<ValType>)> {
+ match reader.peek_u8()? {
+ 0x40 => {
+ reader.read_u8()?;
+ Ok((Vec::new(), Vec::new()))
+ }
+ 0x7f | 0x7e | 0x7d | 0x7c | 0x7b | 0x63 | 0x64 | 0x70 | 0x6f | 0x6e | 0x6d | 0x6c | 0x6b | 0x6a | 0x69
+ | 0x71 | 0x72 | 0x73 | 0x74 => {
+ let value = parse_value_type(reader)?;
+ self.check_value_type(value)?;
+ Ok((Vec::new(), vec![value]))
+ }
+ _ => {
+ let index = reader.read_s33()?;
+ if index < 0 {
+ return Err(Error::malformed("malformed block type"));
+ }
+ let function = self.func_type_at(u32::try_from(index).map_err(|_| Error::invalid("unknown type"))?)?;
+ Ok((function.params, function.results))
+ }
+ }
+ }
+
+ fn read_memory_argument(&mut self, reader: &mut Reader<'_>, natural_size: u32) -> Result<AddressType> {
+ let alignment_start = reader.position();
+ let mut align = reader.read_u32()?;
+ let alignment_end = reader.position();
+ let mut memory = 0;
+ let mut memory_bytes = None;
+ if align & 0x40 != 0 {
+ align &= !0x40;
+ let start = reader.position();
+ memory = reader.read_u32()?;
+ memory_bytes = Some(start..reader.position());
+ }
+ let address_type = self.memory_address_type(memory)?;
+ let offset_start = reader.position();
+ let offset = reader.read_u64()?;
+ let opcode = self.module.bytes[self.instruction_start as usize];
+ let is_core_access = (crate::opcode::I32_LOAD..=crate::opcode::I64_STORE32).contains(&opcode);
+ self.checked_access = None;
+ if memory != 0 || address_type == AddressType::I64 {
+ if is_core_access {
+ self.rewrites.push(crate::quickening::checked_access(
+ &self.module.bytes,
+ self.instruction_start as usize,
+ alignment_start..alignment_end,
+ memory_bytes,
+ offset_start..reader.position(),
+ ));
+ } else {
+ self.checked_access = Some((memory_bytes, offset_start..reader.position()));
+ }
+ }
+ if align >= 64 {
+ return Err(Error::malformed("malformed memop flags"));
+ }
+ if address_type == AddressType::I32 && offset > u64::from(u32::MAX) {
+ return invalid("offset out of range");
+ }
+ if 1u64 << align > u64::from(natural_size) {
+ return invalid("alignment must not be larger than natural");
+ }
+ Ok(address_type)
+ }
+
+ fn read_atomic_memory_argument(&self, reader: &mut Reader<'_>, natural_size: u32) -> Result<AddressType> {
+ let mut align = reader.read_u32()?;
+ let mut memory = 0;
+ if align & 0x40 != 0 {
+ align &= !0x40;
+ memory = reader.read_u32()?;
+ }
+ let address_type = self.memory_address_type(memory)?;
+ let offset = reader.read_u64()?;
+ if address_type == AddressType::I32 && offset > u64::from(u32::MAX) {
+ return invalid("offset out of range");
+ }
+ if align >= 64 || 1u64 << align != u64::from(natural_size) {
+ return invalid("atomic memory op alignment must be equal to natural");
+ }
+ Ok(address_type)
+ }
+
+ fn load(&mut self, reader: &mut Reader<'_>, natural_size: u32, result: ValType) -> Result<()> {
+ let address_type = self.read_memory_argument(reader, natural_size)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.push_value(result);
+ Ok(())
+ }
+
+ fn store(&mut self, reader: &mut Reader<'_>, natural_size: u32, value: ValType) -> Result<()> {
+ let address_type = self.read_memory_argument(reader, natural_size)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(address_type.value_type())?;
+ Ok(())
+ }
+
+ fn unary(&mut self, operand: ValType, result: ValType) -> Result<()> {
+ self.pop_expecting(operand)?;
+ self.push_value(result);
+ Ok(())
+ }
+
+ fn binary(&mut self, operand: ValType, result: ValType) -> Result<()> {
+ self.pop_expecting(operand)?;
+ self.pop_expecting(operand)?;
+ self.push_value(result);
+ Ok(())
+ }
+
+ fn check_call_results(&self, results: &[ValType]) -> Result<()> {
+ if !self.types.values_subtype(results, &self.results) {
+ return type_mismatch();
+ }
+ Ok(())
+ }
+
+ fn validate_body(&mut self, reader: &mut Reader<'_>) -> Result<()> {
+ while !self.frames.is_empty() {
+ if reader.is_at_end() {
+ return Err(Error::malformed("unexpected end of section or function"));
+ }
+ self.validate_instruction(reader)?;
+ }
+ if !reader.is_at_end() {
+ return Err(Error::malformed("section size mismatch"));
+ }
+ Ok(())
+ }
+
+ fn validate_instruction(&mut self, reader: &mut Reader<'_>) -> Result<()> {
+ use ValType::{F32, F64, I32, I64, V128};
+
+ let pc = reader.position() as u32;
+ self.instruction_start = pc;
+ let opcode = reader.read_u8()?;
+ match opcode {
+ opcode::UNREACHABLE => self.set_unreachable(),
+ opcode::NOP => {}
+ opcode::BLOCK | opcode::LOOP => {
+ let (params, results) = self.read_block_type(reader)?;
+ self.pop_values(&params)?;
+ let kind = if opcode == opcode::BLOCK {
+ FrameKind::Block
+ } else {
+ FrameKind::Loop
+ };
+ self.push_frame(kind, params, results, pc);
+ }
+ opcode::IF => {
+ let (params, results) = self.read_block_type(reader)?;
+ self.pop_expecting(I32)?;
+ self.pop_values(&params)?;
+ let entry = self.side_table.len();
+ self.side_table.push(SideTableEntry {
+ keep: slots_of(&params),
+ ..SideTableEntry::default()
+ });
+ self.push_frame(FrameKind::If, params, results, pc);
+ self.frames.last_mut().expect("the frame was just pushed").if_entry = Some((entry, pc));
+ }
+ opcode::ELSE => {
+ if self.frames.last().is_none_or(|frame| frame.kind != FrameKind::If) {
+ return invalid("else without if");
+ }
+ let frame = self.pop_frame()?;
+ // The first arm jumps past the `end`.
+ let else_entry = self.side_table.len();
+ self.side_table.push(SideTableEntry {
+ keep: slots_of(&frame.results),
+ ..SideTableEntry::default()
+ });
+ // The condition jumps to the second arm, which starts after this instruction and its entry.
+ let (if_entry, if_pc) = frame.if_entry.expect("an if frame has an if entry");
+ self.side_table[if_entry].pc_delta = (pc + 1) as i32 - if_pc as i32;
+ self.side_table[if_entry].stp_delta = self.side_table.len() as i32 - if_entry as i32;
+ let mut fixups = frame.fixups;
+ fixups.push(Fixup::Entry {
+ entry: else_entry,
+ branch_pc: pc,
+ });
+ self.push_frame(FrameKind::Else, frame.params, frame.results, frame.start_pc);
+ self.frames.last_mut().expect("the frame was just pushed").fixups = fixups;
+ }
+ opcode::END => {
+ let frame = self.pop_frame()?;
+ if frame.kind == FrameKind::If && !self.types.values_subtype(&frame.params, &frame.results) {
+ return type_mismatch();
+ }
+ let target_pc = if frame.kind == FrameKind::Function { pc } else { pc + 1 };
+ if let Some((if_entry, if_pc)) = frame.if_entry {
+ self.side_table[if_entry].pc_delta = target_pc as i32 - if_pc as i32;
+ self.side_table[if_entry].stp_delta = self.side_table.len() as i32 - if_entry as i32;
+ }
+ if let Some(region) = frame.try_region {
+ self.try_regions[region].end = pc;
+ }
+ self.resolve_fixups(&frame.fixups, target_pc);
+ if frame.kind != FrameKind::Function {
+ self.push_values(&frame.results);
+ }
+ }
+ opcode::BR => {
+ let depth = reader.read_u32()?;
+ let label = self.label_types(depth)?;
+ self.pop_values(&label)?;
+ self.push_values(&label);
+ self.add_branch_entry(depth, pc);
+ self.set_unreachable();
+ }
+ opcode::BR_IF => {
+ let depth = reader.read_u32()?;
+ self.pop_expecting(I32)?;
+ let label = self.label_types(depth)?;
+ self.pop_values(&label)?;
+ self.push_values(&label);
+ self.add_branch_entry(depth, pc);
+ }
+ opcode::BR_TABLE => {
+ let count = reader.read_vector_length()?;
+ let mut depths = Vec::with_capacity(count as usize + 1);
+ for _ in 0..=count {
+ depths.push(reader.read_u32()?);
+ }
+ self.pop_expecting(I32)?;
+ let default_depth = *depths.last().expect("there is a default label");
+ let arity = self.label_types(default_depth)?.len();
+ for &depth in &depths {
+ let label = self.label_types(depth)?;
+ if label.len() != arity {
+ return type_mismatch();
+ }
+ // Check the operands against each label without committing to one label's types.
+ let mut popped = Vec::with_capacity(arity);
+ for &value in label.iter().rev() {
+ let operand = self.pop()?;
+ if let Some(operand) = operand
+ && !self.types.value_subtype(operand, value)
+ {
+ return type_mismatch();
+ }
+ popped.push(operand);
+ }
+ for operand in popped.into_iter().rev() {
+ self.push(operand);
+ }
+ }
+ for &depth in &depths {
+ self.add_branch_entry(depth, pc);
+ }
+ self.set_unreachable();
+ }
+ opcode::RETURN => {
+ let results = self.results.clone();
+ self.pop_values(&results)?;
+ self.set_unreachable();
+ }
+ opcode::CALL => {
+ let function = self.function_type(reader.read_u32()?)?;
+ self.pop_values(&function.params)?;
+ self.push_values(&function.results);
+ }
+ opcode::RETURN_CALL => {
+ let function = self.function_type(reader.read_u32()?)?;
+ self.check_call_results(&function.results)?;
+ self.pop_values(&function.params)?;
+ self.set_unreachable();
+ }
+ opcode::CALL_INDIRECT | opcode::RETURN_CALL_INDIRECT => {
+ let type_index = reader.read_u32()?;
+ let table_index = reader.read_u32()?;
+ let table = self.table(table_index)?;
+ let function = self.func_type_at(type_index)?;
+ if !self.types.ref_subtype(table.element, RefType::FUNCREF) {
+ return type_mismatch();
+ }
+ self.pop_expecting(table.limits.address_type.value_type())?;
+ if opcode == opcode::RETURN_CALL_INDIRECT {
+ self.check_call_results(&function.results)?;
+ self.pop_values(&function.params)?;
+ self.set_unreachable();
+ } else {
+ self.pop_values(&function.params)?;
+ self.push_values(&function.results);
+ }
+ }
+ opcode::CALL_REF | opcode::RETURN_CALL_REF => {
+ let type_index = reader.read_u32()?;
+ let function = self.func_type_at(type_index)?;
+ self.pop_expecting(ValType::Ref(RefType::new(true, HeapType::Concrete(type_index))))?;
+ if opcode == opcode::RETURN_CALL_REF {
+ self.check_call_results(&function.results)?;
+ self.pop_values(&function.params)?;
+ self.set_unreachable();
+ } else {
+ self.pop_values(&function.params)?;
+ self.push_values(&function.results);
+ }
+ }
+ opcode::THROW => {
+ let params = self.tag_params(reader.read_u32()?)?;
+ self.pop_values(&params)?;
+ self.set_unreachable();
+ }
+ opcode::THROW_REF => {
+ self.pop_expecting(ValType::Ref(RefType::EXNREF))?;
+ self.set_unreachable();
+ }
+ opcode::TRY_TABLE => {
+ let (params, results) = self.read_block_type(reader)?;
+ let count = reader.read_vector_length()?;
+ let first_clause = self.catch_clauses.len();
+ let mut clause_labels = Vec::with_capacity(count as usize);
+ for _ in 0..count {
+ let kind = match reader.read_u8()? {
+ 0x00 => CatchKind::Catch,
+ 0x01 => CatchKind::CatchRef,
+ 0x02 => CatchKind::CatchAll,
+ 0x03 => CatchKind::CatchAllRef,
+ _ => return Err(Error::malformed("malformed catch clause")),
+ };
+ let tag = if matches!(kind, CatchKind::Catch | CatchKind::CatchRef) {
+ reader.read_u32()?
+ } else {
+ 0
+ };
+ let depth = reader.read_u32()?;
+ let mut pushed = if matches!(kind, CatchKind::Catch | CatchKind::CatchRef) {
+ self.tag_params(tag)?
+ } else {
+ Vec::new()
+ };
+ if matches!(kind, CatchKind::CatchRef | CatchKind::CatchAllRef) {
+ pushed.push(ValType::Ref(RefType::new(false, HeapType::Exn)));
+ }
+ let label = self.label_types(depth)?;
+ if !self.types.values_subtype(&pushed, &label) {
+ return type_mismatch();
+ }
+ clause_labels.push((kind, tag, depth));
+ }
+ self.pop_values(&params)?;
+ for (kind, tag, depth) in clause_labels {
+ let clause_index = self.catch_clauses.len();
+ let frame_index = self.frames.len() - 1 - depth as usize;
+ let frame = &self.frames[frame_index];
+ let mut clause = CatchClause {
+ kind,
+ tag,
+ target_pc: 0,
+ target_stp: 0,
+ height: frame.slot_height,
+ };
+ if frame.kind == FrameKind::Loop {
+ clause.target_pc = frame.start_pc;
+ clause.target_stp = frame.start_stp;
+ } else {
+ self.frames[frame_index].fixups.push(Fixup::Clause(clause_index));
+ }
+ self.catch_clauses.push(clause);
+ }
+ let region = self.try_regions.len();
+ self.try_regions.push(TryRegion {
+ start: reader.position() as u32,
+ end: 0,
+ first_clause: first_clause as u32,
+ clause_count: count,
+ });
+ self.push_frame(FrameKind::TryTable, params, results, pc);
+ self.frames.last_mut().expect("the frame was just pushed").try_region = Some(region);
+ }
+ opcode::DROP => {
+ let value = self.pop()?;
+ self.quicken_for_v128(value);
+ }
+ opcode::SELECT => {
+ self.pop_expecting(I32)?;
+ let first = self.pop()?;
+ let second = self.pop()?;
+ let is_numeric_or_vector =
+ |operand: Operand| operand.is_none_or(|value| value.is_numeric() || value == V128);
+ if !is_numeric_or_vector(first) || !is_numeric_or_vector(second) {
+ return type_mismatch();
+ }
+ match (first, second) {
+ (Some(first), Some(second)) if first != second => return type_mismatch(),
+ _ => {}
+ }
+ self.quicken_for_v128(first.or(second));
+ self.push(first.or(second));
+ }
+ opcode::SELECT_TYPED => {
+ let count = reader.read_u32()?;
+ if count != 1 {
+ return invalid("invalid result arity");
+ }
+ let value = parse_value_type(reader)?;
+ self.check_value_type(value)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(value)?;
+ self.push_value(value);
+ }
+ opcode::LOCAL_GET => {
+ let index = reader.read_u32()?;
+ let value = self.local(index)?;
+ if !self.local_initialized[index as usize] {
+ return invalid("uninitialized local");
+ }
+ self.quicken_for_v128(Some(value));
+ self.push_value(value);
+ }
+ opcode::LOCAL_SET => {
+ let index = reader.read_u32()?;
+ let value = self.local(index)?;
+ self.pop_expecting(value)?;
+ self.initialize_local(index);
+ self.quicken_for_v128(Some(value));
+ }
+ opcode::LOCAL_TEE => {
+ let index = reader.read_u32()?;
+ let value = self.local(index)?;
+ self.pop_expecting(value)?;
+ self.initialize_local(index);
+ self.quicken_for_v128(Some(value));
+ self.push_value(value);
+ }
+ opcode::GLOBAL_GET => {
+ let global = self.global(reader.read_u32()?)?;
+ self.quicken_for_v128(Some(global.value));
+ self.push_value(global.value);
+ }
+ opcode::GLOBAL_SET => {
+ let global = self.global(reader.read_u32()?)?;
+ if !global.mutable {
+ return invalid("global is immutable");
+ }
+ self.pop_expecting(global.value)?;
+ self.quicken_for_v128(Some(global.value));
+ }
+ opcode::TABLE_GET => {
+ let table = self.table(reader.read_u32()?)?;
+ self.pop_expecting(table.limits.address_type.value_type())?;
+ self.push_value(ValType::Ref(table.element));
+ }
+ opcode::TABLE_SET => {
+ let table = self.table(reader.read_u32()?)?;
+ self.pop_expecting(ValType::Ref(table.element))?;
+ self.pop_expecting(table.limits.address_type.value_type())?;
+ }
+ opcode::I32_LOAD => self.load(reader, 4, I32)?,
+ opcode::I64_LOAD => self.load(reader, 8, I64)?,
+ opcode::F32_LOAD => self.load(reader, 4, F32)?,
+ opcode::F64_LOAD => self.load(reader, 8, F64)?,
+ opcode::I32_LOAD8_S | opcode::I32_LOAD8_U => self.load(reader, 1, I32)?,
+ opcode::I32_LOAD16_S | opcode::I32_LOAD16_U => self.load(reader, 2, I32)?,
+ opcode::I64_LOAD8_S | opcode::I64_LOAD8_U => self.load(reader, 1, I64)?,
+ opcode::I64_LOAD16_S | opcode::I64_LOAD16_U => self.load(reader, 2, I64)?,
+ opcode::I64_LOAD32_S | opcode::I64_LOAD32_U => self.load(reader, 4, I64)?,
+ opcode::I32_STORE => self.store(reader, 4, I32)?,
+ opcode::I64_STORE => self.store(reader, 8, I64)?,
+ opcode::F32_STORE => self.store(reader, 4, F32)?,
+ opcode::F64_STORE => self.store(reader, 8, F64)?,
+ opcode::I32_STORE8 => self.store(reader, 1, I32)?,
+ opcode::I32_STORE16 => self.store(reader, 2, I32)?,
+ opcode::I64_STORE8 => self.store(reader, 1, I64)?,
+ opcode::I64_STORE16 => self.store(reader, 2, I64)?,
+ opcode::I64_STORE32 => self.store(reader, 4, I64)?,
+ opcode::MEMORY_SIZE => {
+ let address_type = self.memory_address_type(reader.read_u32()?)?;
+ self.push_value(address_type.value_type());
+ }
+ opcode::MEMORY_GROW => {
+ let address_type = self.memory_address_type(reader.read_u32()?)?;
+ self.unary(address_type.value_type(), address_type.value_type())?;
+ }
+ opcode::I32_CONST => {
+ reader.read_i32()?;
+ self.push_value(I32);
+ }
+ opcode::I64_CONST => {
+ reader.read_i64()?;
+ self.push_value(I64);
+ }
+ opcode::F32_CONST => {
+ reader.read_bytes(4)?;
+ self.push_value(F32);
+ }
+ opcode::F64_CONST => {
+ reader.read_bytes(8)?;
+ self.push_value(F64);
+ }
+ opcode::I32_EQZ => self.unary(I32, I32)?,
+ 0x46..=0x4f => self.binary(I32, I32)?,
+ opcode::I64_EQZ => self.unary(I64, I32)?,
+ 0x51..=0x5a => self.binary(I64, I32)?,
+ 0x5b..=0x60 => self.binary(F32, I32)?,
+ 0x61..=0x66 => self.binary(F64, I32)?,
+ 0x67..=0x69 => self.unary(I32, I32)?,
+ 0x6a..=0x78 => self.binary(I32, I32)?,
+ 0x79..=0x7b => self.unary(I64, I64)?,
+ 0x7c..=0x8a => self.binary(I64, I64)?,
+ 0x8b..=0x91 => self.unary(F32, F32)?,
+ 0x92..=0x98 => self.binary(F32, F32)?,
+ 0x99..=0x9f => self.unary(F64, F64)?,
+ 0xa0..=0xa6 => self.binary(F64, F64)?,
+ opcode::I32_WRAP_I64 => self.unary(I64, I32)?,
+ opcode::I32_TRUNC_F32_S | opcode::I32_TRUNC_F32_U => self.unary(F32, I32)?,
+ opcode::I32_TRUNC_F64_S | opcode::I32_TRUNC_F64_U => self.unary(F64, I32)?,
+ opcode::I64_EXTEND_I32_S | opcode::I64_EXTEND_I32_U => self.unary(I32, I64)?,
+ opcode::I64_TRUNC_F32_S | opcode::I64_TRUNC_F32_U => self.unary(F32, I64)?,
+ opcode::I64_TRUNC_F64_S | opcode::I64_TRUNC_F64_U => self.unary(F64, I64)?,
+ opcode::F32_CONVERT_I32_S | opcode::F32_CONVERT_I32_U => self.unary(I32, F32)?,
+ opcode::F32_CONVERT_I64_S | opcode::F32_CONVERT_I64_U => self.unary(I64, F32)?,
+ opcode::F32_DEMOTE_F64 => self.unary(F64, F32)?,
+ opcode::F64_CONVERT_I32_S | opcode::F64_CONVERT_I32_U => self.unary(I32, F64)?,
+ opcode::F64_CONVERT_I64_S | opcode::F64_CONVERT_I64_U => self.unary(I64, F64)?,
+ opcode::F64_PROMOTE_F32 => self.unary(F32, F64)?,
+ opcode::I32_REINTERPRET_F32 => self.unary(F32, I32)?,
+ opcode::I64_REINTERPRET_F64 => self.unary(F64, I64)?,
+ opcode::F32_REINTERPRET_I32 => self.unary(I32, F32)?,
+ opcode::F64_REINTERPRET_I64 => self.unary(I64, F64)?,
+ opcode::I32_EXTEND8_S | opcode::I32_EXTEND16_S => self.unary(I32, I32)?,
+ opcode::I64_EXTEND8_S | opcode::I64_EXTEND16_S | opcode::I64_EXTEND32_S => self.unary(I64, I64)?,
+ opcode::REF_NULL => {
+ let heap = parse_heap_type(reader)?;
+ self.check_heap_type(heap)?;
+ self.push_value(ValType::Ref(RefType::new(true, heap)));
+ }
+ opcode::REF_IS_NULL => {
+ self.pop_reference()?;
+ self.push_value(I32);
+ }
+ opcode::REF_FUNC => {
+ let index = reader.read_u32()?;
+ let type_index = *self
+ .module
+ .function_space
+ .get(index as usize)
+ .ok_or_else(|| Error::invalid("unknown function"))?;
+ if !self.declared_functions.contains(&index) {
+ return invalid("undeclared function reference");
+ }
+ self.push_value(ValType::Ref(RefType::new(false, HeapType::Concrete(type_index))));
+ }
+ opcode::REF_EQ => {
+ let eqref = ValType::Ref(RefType::new(true, HeapType::Eq));
+ self.pop_expecting(eqref)?;
+ self.pop_expecting(eqref)?;
+ self.push_value(I32);
+ }
+ opcode::REF_AS_NON_NULL => {
+ let reference = self.pop_reference()?;
+ self.push(reference.map(|reference| ValType::Ref(reference.as_non_null())));
+ }
+ opcode::BR_ON_NULL => {
+ let depth = reader.read_u32()?;
+ let reference = self.pop_reference()?;
+ let label = self.label_types(depth)?;
+ self.pop_values(&label)?;
+ self.push_values(&label);
+ self.add_branch_entry(depth, pc);
+ self.push(reference.map(|reference| ValType::Ref(reference.as_non_null())));
+ }
+ opcode::BR_ON_NON_NULL => {
+ let depth = reader.read_u32()?;
+ let mut label = self.label_types(depth)?;
+ let Some(ValType::Ref(label_reference)) = label.pop() else {
+ return type_mismatch();
+ };
+ let reference = self.pop_reference()?;
+ if let Some(reference) = reference
+ && !self.types.ref_subtype(reference.as_non_null(), label_reference)
+ {
+ return type_mismatch();
+ }
+ self.pop_values(&label)?;
+ self.push_values(&label);
+ // The taken branch keeps the label's values and the reference.
+ self.push_value(ValType::Ref(label_reference));
+ self.add_branch_entry(depth, pc);
+ self.pop()?;
+ }
+ opcode::PREFIX_MISC => self.validate_misc(reader)?,
+ opcode::PREFIX_GC => self.validate_gc(reader, pc)?,
+ opcode::PREFIX_SIMD => self.validate_simd(reader)?,
+ opcode::PREFIX_ATOMIC => self.validate_atomic(reader)?,
+ _ => return Err(Error::malformed(format!("illegal opcode {opcode:#x}"))),
+ }
+ Ok(())
+ }
+
+ fn validate_misc(&mut self, reader: &mut Reader<'_>) -> Result<()> {
+ use ValType::{F32, F64, I32, I64};
+ let sub_opcode = reader.read_u32()?;
+ match sub_opcode {
+ opcode::misc::I32_TRUNC_SAT_F32_S | opcode::misc::I32_TRUNC_SAT_F32_U => self.unary(F32, I32)?,
+ opcode::misc::I32_TRUNC_SAT_F64_S | opcode::misc::I32_TRUNC_SAT_F64_U => self.unary(F64, I32)?,
+ opcode::misc::I64_TRUNC_SAT_F32_S | opcode::misc::I64_TRUNC_SAT_F32_U => self.unary(F32, I64)?,
+ opcode::misc::I64_TRUNC_SAT_F64_S | opcode::misc::I64_TRUNC_SAT_F64_U => self.unary(F64, I64)?,
+ opcode::misc::MEMORY_INIT => {
+ let data = reader.read_u32()?;
+ let address_type = self.memory_address_type(reader.read_u32()?)?;
+ self.check_data_index(data)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(address_type.value_type())?;
+ }
+ opcode::misc::DATA_DROP => self.check_data_index(reader.read_u32()?)?,
+ opcode::misc::MEMORY_COPY => {
+ let destination = self.memory_address_type(reader.read_u32()?)?;
+ let source = self.memory_address_type(reader.read_u32()?)?;
+ let length = if destination == AddressType::I64 && source == AddressType::I64 {
+ I64
+ } else {
+ I32
+ };
+ self.pop_expecting(length)?;
+ self.pop_expecting(source.value_type())?;
+ self.pop_expecting(destination.value_type())?;
+ }
+ opcode::misc::MEMORY_FILL => {
+ let address_type = self.memory_address_type(reader.read_u32()?)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(address_type.value_type())?;
+ }
+ opcode::misc::TABLE_INIT => {
+ let element = self.element_type(reader.read_u32()?)?;
+ let table = self.table(reader.read_u32()?)?;
+ if !self.types.ref_subtype(element, table.element) {
+ return type_mismatch();
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(table.limits.address_type.value_type())?;
+ }
+ opcode::misc::ELEM_DROP => {
+ self.element_type(reader.read_u32()?)?;
+ }
+ opcode::misc::TABLE_COPY => {
+ let destination = self.table(reader.read_u32()?)?;
+ let source = self.table(reader.read_u32()?)?;
+ if !self.types.ref_subtype(source.element, destination.element) {
+ return type_mismatch();
+ }
+ let length = if destination.limits.address_type == AddressType::I64
+ && source.limits.address_type == AddressType::I64
+ {
+ I64
+ } else {
+ I32
+ };
+ self.pop_expecting(length)?;
+ self.pop_expecting(source.limits.address_type.value_type())?;
+ self.pop_expecting(destination.limits.address_type.value_type())?;
+ }
+ opcode::misc::TABLE_GROW => {
+ let table = self.table(reader.read_u32()?)?;
+ let address = table.limits.address_type.value_type();
+ self.pop_expecting(address)?;
+ self.pop_expecting(ValType::Ref(table.element))?;
+ self.push_value(address);
+ }
+ opcode::misc::TABLE_SIZE => {
+ let table = self.table(reader.read_u32()?)?;
+ self.push_value(table.limits.address_type.value_type());
+ }
+ opcode::misc::TABLE_FILL => {
+ let table = self.table(reader.read_u32()?)?;
+ let address = table.limits.address_type.value_type();
+ self.pop_expecting(address)?;
+ self.pop_expecting(ValType::Ref(table.element))?;
+ self.pop_expecting(address)?;
+ }
+ _ => return Err(Error::malformed(format!("illegal opcode 0xfc {sub_opcode:#x}"))),
+ }
+ Ok(())
+ }
+
+ fn read_cast_reference(&self, reader: &mut Reader<'_>, nullable: bool) -> Result<RefType> {
+ let heap = parse_heap_type(reader)?;
+ self.check_heap_type(heap)?;
+ Ok(RefType::new(nullable, heap))
+ }
+
+ fn validate_gc(&mut self, reader: &mut Reader<'_>, pc: u32) -> Result<()> {
+ use ValType::I32;
+ let sub_opcode = reader.read_u32()?;
+ let reference = |nullable, type_index| ValType::Ref(RefType::new(nullable, HeapType::Concrete(type_index)));
+ match sub_opcode {
+ opcode::gc::STRUCT_NEW => {
+ let type_index = reader.read_u32()?;
+ let fields = self.struct_type(type_index)?;
+ for field in fields.iter().rev() {
+ self.pop_expecting(field.storage.unpacked())?;
+ }
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::STRUCT_NEW_DEFAULT => {
+ let type_index = reader.read_u32()?;
+ let fields = self.struct_type(type_index)?;
+ if !fields.iter().all(|field| field.storage.unpacked().is_defaultable()) {
+ return invalid("field type is not defaultable");
+ }
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::STRUCT_GET | opcode::gc::STRUCT_GET_S | opcode::gc::STRUCT_GET_U => {
+ let type_index = reader.read_u32()?;
+ let field_index = reader.read_u32()?;
+ let fields = self.struct_type(type_index)?;
+ let field = *fields
+ .get(field_index as usize)
+ .ok_or_else(|| Error::invalid("unknown field"))?;
+ if field.storage.is_packed() != (sub_opcode != opcode::gc::STRUCT_GET) {
+ return invalid("type mismatch: field is packed or not as the instruction requires");
+ }
+ self.pop_expecting(reference(true, type_index))?;
+ self.push_value(field.storage.unpacked());
+ }
+ opcode::gc::STRUCT_SET => {
+ let type_index = reader.read_u32()?;
+ let field_index = reader.read_u32()?;
+ let fields = self.struct_type(type_index)?;
+ let field = *fields
+ .get(field_index as usize)
+ .ok_or_else(|| Error::invalid("unknown field"))?;
+ if !field.mutable {
+ return invalid("field is immutable");
+ }
+ self.pop_expecting(field.storage.unpacked())?;
+ self.pop_expecting(reference(true, type_index))?;
+ }
+ opcode::gc::ARRAY_NEW => {
+ let type_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(element.storage.unpacked())?;
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::ARRAY_NEW_DEFAULT => {
+ let type_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if !element.storage.unpacked().is_defaultable() {
+ return invalid("array type is not defaultable");
+ }
+ self.pop_expecting(I32)?;
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::ARRAY_NEW_FIXED => {
+ let type_index = reader.read_u32()?;
+ let count = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ for _ in 0..count {
+ self.pop_expecting(element.storage.unpacked())?;
+ }
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::ARRAY_NEW_DATA => {
+ let type_index = reader.read_u32()?;
+ let data = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if element.storage.unpacked().is_reference() {
+ return type_mismatch();
+ }
+ self.check_data_index(data)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::ARRAY_NEW_ELEM => {
+ let type_index = reader.read_u32()?;
+ let element_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ let segment = self.element_type(element_index)?;
+ if !self
+ .types
+ .value_subtype(ValType::Ref(segment), element.storage.unpacked())
+ || element.storage.is_packed()
+ {
+ return type_mismatch();
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.push_value(reference(false, type_index));
+ }
+ opcode::gc::ARRAY_GET | opcode::gc::ARRAY_GET_S | opcode::gc::ARRAY_GET_U => {
+ let type_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if element.storage.is_packed() != (sub_opcode != opcode::gc::ARRAY_GET) {
+ return invalid("type mismatch: element is packed or not as the instruction requires");
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, type_index))?;
+ self.push_value(element.storage.unpacked());
+ }
+ opcode::gc::ARRAY_SET => {
+ let type_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if !element.mutable {
+ return invalid("array is immutable");
+ }
+ self.pop_expecting(element.storage.unpacked())?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, type_index))?;
+ }
+ opcode::gc::ARRAY_LEN => {
+ self.pop_expecting(ValType::Ref(RefType::new(true, HeapType::Array)))?;
+ self.push_value(I32);
+ }
+ opcode::gc::ARRAY_FILL => {
+ let type_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if !element.mutable {
+ return invalid("array is immutable");
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(element.storage.unpacked())?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, type_index))?;
+ }
+ opcode::gc::ARRAY_COPY => {
+ let destination_index = reader.read_u32()?;
+ let source_index = reader.read_u32()?;
+ let destination = self.array_type(destination_index)?;
+ let source = self.array_type(source_index)?;
+ if !destination.mutable {
+ return invalid("array is immutable");
+ }
+ if !self.types.storage_subtype(source.storage, destination.storage) {
+ return type_mismatch();
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, source_index))?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, destination_index))?;
+ }
+ opcode::gc::ARRAY_INIT_DATA => {
+ let type_index = reader.read_u32()?;
+ let data = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if !element.mutable {
+ return invalid("array is immutable");
+ }
+ if element.storage.unpacked().is_reference() {
+ return type_mismatch();
+ }
+ self.check_data_index(data)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, type_index))?;
+ }
+ opcode::gc::ARRAY_INIT_ELEM => {
+ let type_index = reader.read_u32()?;
+ let element_index = reader.read_u32()?;
+ let element = self.array_type(type_index)?;
+ if !element.mutable {
+ return invalid("array is immutable");
+ }
+ let segment = self.element_type(element_index)?;
+ if !self
+ .types
+ .value_subtype(ValType::Ref(segment), element.storage.unpacked())
+ || element.storage.is_packed()
+ {
+ return type_mismatch();
+ }
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(reference(true, type_index))?;
+ }
+ opcode::gc::REF_TEST | opcode::gc::REF_TEST_NULL | opcode::gc::REF_CAST | opcode::gc::REF_CAST_NULL => {
+ let nullable = matches!(sub_opcode, opcode::gc::REF_TEST_NULL | opcode::gc::REF_CAST_NULL);
+ let target = self.read_cast_reference(reader, nullable)?;
+ let top = RefType::new(true, self.types.top(target.heap));
+ self.pop_expecting(ValType::Ref(top))?;
+ if matches!(sub_opcode, opcode::gc::REF_TEST | opcode::gc::REF_TEST_NULL) {
+ self.push_value(I32);
+ } else {
+ self.push_value(ValType::Ref(target));
+ }
+ }
+ opcode::gc::BR_ON_CAST | opcode::gc::BR_ON_CAST_FAIL => {
+ let flags = reader.read_u8()?;
+ if flags & !0x03 != 0 {
+ return Err(Error::malformed("malformed cast flags"));
+ }
+ let depth = reader.read_u32()?;
+ let source = self.read_cast_reference(reader, flags & 0x01 != 0)?;
+ let target = self.read_cast_reference(reader, flags & 0x02 != 0)?;
+ if !self.types.ref_subtype(target, source) {
+ return type_mismatch();
+ }
+ let difference = RefType::new(source.nullable && !target.nullable, source.heap);
+ let (taken, fallthrough) = if sub_opcode == opcode::gc::BR_ON_CAST {
+ (target, difference)
+ } else {
+ (difference, target)
+ };
+ let mut label = self.label_types(depth)?;
+ let Some(ValType::Ref(label_reference)) = label.pop() else {
+ return type_mismatch();
+ };
+ if !self.types.ref_subtype(taken, label_reference) {
+ return type_mismatch();
+ }
+ self.pop_expecting(ValType::Ref(source))?;
+ self.pop_values(&label)?;
+ self.push_values(&label);
+ self.push_value(ValType::Ref(taken));
+ self.add_branch_entry(depth, pc);
+ self.pop()?;
+ self.push_value(ValType::Ref(fallthrough));
+ }
+ opcode::gc::ANY_CONVERT_EXTERN | opcode::gc::EXTERN_CONVERT_ANY => {
+ let (from, to) = if sub_opcode == opcode::gc::ANY_CONVERT_EXTERN {
+ (HeapType::Extern, HeapType::Any)
+ } else {
+ (HeapType::Any, HeapType::Extern)
+ };
+ let operand = self.pop_expecting(ValType::Ref(RefType::new(true, from)))?;
+ let nullable = match operand {
+ Some(ValType::Ref(reference)) => reference.nullable,
+ _ => true,
+ };
+ self.push_value(ValType::Ref(RefType::new(nullable, to)));
+ }
+ opcode::gc::REF_I31 => self.unary(I32, ValType::Ref(RefType::new(false, HeapType::I31)))?,
+ opcode::gc::I31_GET_S | opcode::gc::I31_GET_U => {
+ self.unary(ValType::Ref(RefType::new(true, HeapType::I31)), I32)?;
+ }
+ _ => return Err(Error::malformed(format!("illegal opcode 0xfb {sub_opcode:#x}"))),
+ }
+ Ok(())
+ }
+
+ fn validate_simd(&mut self, reader: &mut Reader<'_>) -> Result<()> {
+ use ValType::{I32, V128};
+ let sub_opcode = reader.read_u32()?;
+ let kind =
+ simd_kind(sub_opcode).ok_or_else(|| Error::malformed(format!("illegal opcode 0xfd {sub_opcode:#x}")))?;
+ self.checked_access = None;
+ match kind {
+ SimdKind::Load { size } => self.load(reader, size, V128)?,
+ SimdKind::Store { size } => self.store(reader, size, V128)?,
+ SimdKind::LoadLane { size } | SimdKind::StoreLane { size } => {
+ let address_type = self.read_memory_argument(reader, size)?;
+ let lane = reader.read_u8()?;
+ if u32::from(lane) >= 16 / size {
+ return invalid("invalid lane index");
+ }
+ self.pop_expecting(V128)?;
+ self.pop_expecting(address_type.value_type())?;
+ if matches!(kind, SimdKind::LoadLane { .. }) {
+ self.push_value(V128);
+ }
+ }
+ _ => {}
+ }
+ if let Some((memory, offset)) = self.checked_access.take() {
+ self.rewrites.push(crate::quickening::checked_simd_access(
+ &self.module.bytes,
+ self.instruction_start as usize,
+ sub_opcode,
+ memory,
+ offset,
+ reader.position(),
+ ));
+ }
+ match kind {
+ SimdKind::Load { .. } | SimdKind::Store { .. } | SimdKind::LoadLane { .. } | SimdKind::StoreLane { .. } => {
+ }
+ SimdKind::Const => {
+ reader.read_bytes(16)?;
+ self.push_value(V128);
+ }
+ SimdKind::Shuffle => {
+ for _ in 0..16 {
+ if reader.read_u8()? >= 32 {
+ return invalid("invalid lane index");
+ }
+ }
+ self.binary(V128, V128)?;
+ }
+ SimdKind::ExtractLane { lanes, result } => {
+ if reader.read_u8()? >= lanes {
+ return invalid("invalid lane index");
+ }
+ self.unary(V128, result)?;
+ }
+ SimdKind::ReplaceLane { lanes, operand } => {
+ if reader.read_u8()? >= lanes {
+ return invalid("invalid lane index");
+ }
+ self.pop_expecting(operand)?;
+ self.unary(V128, V128)?;
+ }
+ SimdKind::Splat(operand) => self.unary(operand, V128)?,
+ SimdKind::Shift => {
+ self.pop_expecting(I32)?;
+ self.unary(V128, V128)?;
+ }
+ SimdKind::Test => self.unary(V128, I32)?,
+ SimdKind::Unary => self.unary(V128, V128)?,
+ SimdKind::Binary => self.binary(V128, V128)?,
+ SimdKind::Ternary => {
+ self.pop_expecting(V128)?;
+ self.binary(V128, V128)?;
+ }
+ }
+ Ok(())
+ }
+
+ fn validate_atomic(&mut self, reader: &mut Reader<'_>) -> Result<()> {
+ use ValType::{I32, I64};
+ let sub_opcode = reader.read_u32()?;
+ let kind =
+ atomic_kind(sub_opcode).ok_or_else(|| Error::malformed(format!("illegal opcode 0xfe {sub_opcode:#x}")))?;
+ match kind {
+ AtomicKind::Fence => {
+ if reader.read_u8()? != 0 {
+ return Err(Error::malformed("malformed atomic fence"));
+ }
+ }
+ AtomicKind::Notify => {
+ let address_type = self.read_atomic_memory_argument(reader, 4)?;
+ self.pop_expecting(I32)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.push_value(I32);
+ }
+ AtomicKind::Wait { value } => {
+ let size = if value == I32 { 4 } else { 8 };
+ let address_type = self.read_atomic_memory_argument(reader, size)?;
+ self.pop_expecting(I64)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.push_value(I32);
+ }
+ AtomicKind::Load { value, size } => {
+ let address_type = self.read_atomic_memory_argument(reader, size)?;
+ self.unary(address_type.value_type(), value)?;
+ }
+ AtomicKind::Store { value, size } => {
+ let address_type = self.read_atomic_memory_argument(reader, size)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(address_type.value_type())?;
+ }
+ AtomicKind::ReadModifyWrite { value, size } => {
+ let address_type = self.read_atomic_memory_argument(reader, size)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.push_value(value);
+ }
+ AtomicKind::CompareExchange { value, size } => {
+ let address_type = self.read_atomic_memory_argument(reader, size)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(value)?;
+ self.pop_expecting(address_type.value_type())?;
+ self.push_value(value);
+ }
+ }
+ Ok(())
+ }
+}
+
+fn check_heap_type(module: &Module, heap: HeapType) -> Result<()> {
+ if let HeapType::Concrete(index) = heap
+ && index as usize >= module.types.len()
+ {
+ return invalid("unknown type");
+ }
+ Ok(())
+}
+
+fn check_value_type(module: &Module, value: ValType) -> Result<()> {
+ match value {
+ ValType::Ref(reference) => check_heap_type(module, reference.heap),
+ _ => Ok(()),
+ }
+}
+
+fn check_limits(limits: &Limits, bound: u64) -> Result<()> {
+ if limits.min > bound {
+ return invalid("size minimum must not be greater than maximum");
+ }
+ if let Some(max) = limits.max {
+ if max > bound {
+ return invalid("size maximum must not be greater than bound");
+ }
+ if max < limits.min {
+ return invalid("size minimum must not be greater than maximum");
+ }
+ }
+ Ok(())
+}
+
+fn check_table_type(module: &Module, table: &crate::types::TableType) -> Result<()> {
+ check_heap_type(module, table.element.heap)?;
+ let bound = match table.limits.address_type {
+ AddressType::I32 => u64::from(u32::MAX),
+ AddressType::I64 => u64::MAX,
+ };
+ check_limits(&table.limits, bound)
+}
+
+fn check_memory_type(memory: &crate::types::MemoryType) -> Result<()> {
+ let bound = match memory.limits.address_type {
+ AddressType::I32 => MEMORY32_MAX_PAGES,
+ AddressType::I64 => MEMORY64_MAX_PAGES,
+ };
+ if memory.limits.min > bound {
+ return invalid("memory size must be at most 65536 pages (4GiB)");
+ }
+ if let Some(max) = memory.limits.max {
+ if max > bound {
+ return invalid("memory size must be at most 65536 pages (4GiB)");
+ }
+ if max < memory.limits.min {
+ return invalid("size minimum must not be greater than maximum");
+ }
+ }
+ if memory.limits.shared && memory.limits.max.is_none() {
+ return invalid("shared memory must have maximum");
+ }
+ Ok(())
+}
+
+fn check_tag_type(module: &Module, type_index: u32) -> Result<()> {
+ match module
+ .types
+ .get(type_index as usize)
+ .map(|sub_type| &sub_type.composite)
+ {
+ None => invalid("unknown type"),
+ Some(CompositeType::Func(function)) if function.results.is_empty() => Ok(()),
+ Some(CompositeType::Func(_)) => invalid("non-empty tag result type"),
+ Some(_) => type_mismatch(),
+ }
+}
+
+/// Validate a constant expression of type `expected`. `global_limit` is the number of globals it may read: the
+/// globals before the one it initializes, or all of them.
+fn validate_constant_expression(
+ module: &Module,
+ types: &TypeContext<'_>,
+ expression: &ConstantExpression,
+ expected: ValType,
+ global_limit: u32,
+) -> Result<()> {
+ use ValType::{F32, F64, I32, I64, V128};
+
+ let mut reader = Reader::with_range(
+ &module.bytes,
+ expression.code.start as usize,
+ expression.code.end as usize,
+ );
+ let mut stack: Vec<ValType> = Vec::new();
+ let pop = |stack: &mut Vec<ValType>, expected: ValType| -> Result<()> {
+ match stack.pop() {
+ Some(actual) if types.value_subtype(actual, expected) => Ok(()),
+ _ => type_mismatch(),
+ }
+ };
+ loop {
+ let opcode = reader.read_u8()?;
+ match opcode {
+ opcode::END => break,
+ opcode::I32_CONST => {
+ reader.read_i32()?;
+ stack.push(I32);
+ }
+ opcode::I64_CONST => {
+ reader.read_i64()?;
+ stack.push(I64);
+ }
+ opcode::F32_CONST => {
+ reader.read_bytes(4)?;
+ stack.push(F32);
+ }
+ opcode::F64_CONST => {
+ reader.read_bytes(8)?;
+ stack.push(F64);
+ }
+ opcode::REF_NULL => {
+ let heap = parse_heap_type(&mut reader)?;
+ check_heap_type(module, heap)?;
+ stack.push(ValType::Ref(RefType::new(true, heap)));
+ }
+ opcode::REF_FUNC => {
+ let index = reader.read_u32()?;
+ let type_index = *module
+ .function_space
+ .get(index as usize)
+ .ok_or_else(|| Error::invalid("unknown function"))?;
+ stack.push(ValType::Ref(RefType::new(false, HeapType::Concrete(type_index))));
+ }
+ opcode::GLOBAL_GET => {
+ let index = reader.read_u32()?;
+ let global = module
+ .global_space
+ .get(index as usize)
+ .ok_or_else(|| Error::invalid("unknown global"))?;
+ if index >= global_limit {
+ return invalid("unknown global");
+ }
+ if global.mutable {
+ return invalid("constant expression required");
+ }
+ stack.push(global.value);
+ }
+ opcode::I32_ADD | opcode::I32_SUB | opcode::I32_MUL => {
+ pop(&mut stack, I32)?;
+ pop(&mut stack, I32)?;
+ stack.push(I32);
+ }
+ opcode::I64_ADD | opcode::I64_SUB | opcode::I64_MUL => {
+ pop(&mut stack, I64)?;
+ pop(&mut stack, I64)?;
+ stack.push(I64);
+ }
+ opcode::PREFIX_SIMD => {
+ reader.read_u32()?;
+ reader.read_bytes(16)?;
+ stack.push(V128);
+ }
+ opcode::PREFIX_GC => {
+ let sub_opcode = reader.read_u32()?;
+ let concrete = |type_index| ValType::Ref(RefType::new(false, HeapType::Concrete(type_index)));
+ let composite = |type_index: u32| {
+ module
+ .types
+ .get(type_index as usize)
+ .map(|sub_type| sub_type.composite.clone())
+ .ok_or_else(|| Error::invalid("unknown type"))
+ };
+ match sub_opcode {
+ opcode::gc::STRUCT_NEW | opcode::gc::STRUCT_NEW_DEFAULT => {
+ let type_index = reader.read_u32()?;
+ let CompositeType::Struct(fields) = composite(type_index)? else {
+ return type_mismatch();
+ };
+ if sub_opcode == opcode::gc::STRUCT_NEW {
+ for field in fields.iter().rev() {
+ pop(&mut stack, field.storage.unpacked())?;
+ }
+ } else if !fields.iter().all(|field| field.storage.unpacked().is_defaultable()) {
+ return invalid("field type is not defaultable");
+ }
+ stack.push(concrete(type_index));
+ }
+ opcode::gc::ARRAY_NEW | opcode::gc::ARRAY_NEW_DEFAULT => {
+ let type_index = reader.read_u32()?;
+ let CompositeType::Array(element) = composite(type_index)? else {
+ return type_mismatch();
+ };
+ pop(&mut stack, I32)?;
+ if sub_opcode == opcode::gc::ARRAY_NEW {
+ pop(&mut stack, element.storage.unpacked())?;
+ } else if !element.storage.unpacked().is_defaultable() {
+ return invalid("array type is not defaultable");
+ }
+ stack.push(concrete(type_index));
+ }
+ opcode::gc::ARRAY_NEW_FIXED => {
+ let type_index = reader.read_u32()?;
+ let count = reader.read_u32()?;
+ let CompositeType::Array(element) = composite(type_index)? else {
+ return type_mismatch();
+ };
+ for _ in 0..count {
+ pop(&mut stack, element.storage.unpacked())?;
+ }
+ stack.push(concrete(type_index));
+ }
+ opcode::gc::REF_I31 => {
+ pop(&mut stack, I32)?;
+ stack.push(ValType::Ref(RefType::new(false, HeapType::I31)));
+ }
+ opcode::gc::ANY_CONVERT_EXTERN | opcode::gc::EXTERN_CONVERT_ANY => {
+ let (from, to) = if sub_opcode == opcode::gc::ANY_CONVERT_EXTERN {
+ (HeapType::Extern, HeapType::Any)
+ } else {
+ (HeapType::Any, HeapType::Extern)
+ };
+ let Some(ValType::Ref(operand)) = stack.pop() else {
+ return type_mismatch();
+ };
+ if !types.ref_subtype(operand, RefType::new(true, from)) {
+ return type_mismatch();
+ }
+ stack.push(ValType::Ref(RefType::new(operand.nullable, to)));
+ }
+ _ => return invalid("constant expression required"),
+ }
+ }
+ _ => return invalid("constant expression required"),
+ }
+ }
+ if !reader.is_at_end() {
+ return Err(Error::malformed("section size mismatch"));
+ }
+ match stack.as_slice() {
+ [actual] if types.value_subtype(*actual, expected) => Ok(()),
+ _ => type_mismatch(),
+ }
+}
+
+/// Collect the functions `ref.func` may refer to inside function bodies: those referenced anywhere else in the
+/// module.
+fn declared_functions(module: &Module) -> HashSet<u32> {
+ let mut functions = HashSet::new();
+ let mut scan = |expression: &ConstantExpression| {
+ let mut reader = Reader::with_range(
+ &module.bytes,
+ expression.code.start as usize,
+ expression.code.end as usize,
+ );
+ while let Ok(opcode) = reader.read_u8() {
+ match opcode {
+ opcode::REF_FUNC => {
+ if let Ok(index) = reader.read_u32() {
+ functions.insert(index);
+ }
+ }
+ opcode::I32_CONST => {
+ let _ = reader.read_i32();
+ }
+ opcode::I64_CONST => {
+ let _ = reader.read_i64();
+ }
+ opcode::F32_CONST => {
+ let _ = reader.read_bytes(4);
+ }
+ opcode::F64_CONST => {
+ let _ = reader.read_bytes(8);
+ }
+ opcode::REF_NULL => {
+ let _ = parse_heap_type(&mut reader);
+ }
+ opcode::GLOBAL_GET => {
+ let _ = reader.read_u32();
+ }
+ opcode::PREFIX_SIMD => {
+ let _ = reader.read_u32();
+ let _ = reader.read_bytes(16);
+ }
+ opcode::PREFIX_GC => match reader.read_u32() {
+ Ok(
+ opcode::gc::STRUCT_NEW
+ | opcode::gc::STRUCT_NEW_DEFAULT
+ | opcode::gc::ARRAY_NEW
+ | opcode::gc::ARRAY_NEW_DEFAULT,
+ ) => {
+ let _ = reader.read_u32();
+ }
+ Ok(opcode::gc::ARRAY_NEW_FIXED) => {
+ let _ = reader.read_u32();
+ let _ = reader.read_u32();
+ }
+ _ => {}
+ },
+ _ => {}
+ }
+ }
+ };
+ for global in &module.globals {
+ scan(&global.initializer);
+ }
+ for table in &module.tables {
+ if let Some(initializer) = &table.initializer {
+ scan(initializer);
+ }
+ }
+ let mut listed = Vec::new();
+ for element in &module.elements {
+ match &element.items {
+ ElementItems::Functions(indices) => listed.extend(indices.iter().copied()),
+ ElementItems::Expressions(expressions) => expressions.iter().for_each(&mut scan),
+ }
+ }
+ for export in &module.exports {
+ if export.kind == ExternalKind::Function {
+ listed.push(export.index);
+ }
+ }
+ functions.extend(listed);
+ functions
+}
+
+fn validate_types(module: &Module, identities: &mut Vec<u32>) -> Result<()> {
+ let mut canonicalizer = TypeCanonicalizer::new();
+ for group in &module.recursion_groups {
+ let end = group.start + group.count;
+ let sub_types = &module.types[group.start as usize..end as usize];
+ // Types may refer to any type of their own group, but only to earlier groups otherwise.
+ for sub_type in sub_types {
+ let check = |value: ValType| match value {
+ ValType::Ref(RefType {
+ heap: HeapType::Concrete(index),
+ ..
+ }) if index >= end => invalid("unknown type"),
+ _ => Ok(()),
+ };
+ let check_storage = |storage: StorageType| match storage {
+ StorageType::Val(value) => check(value),
+ _ => Ok(()),
+ };
+ match &sub_type.composite {
+ CompositeType::Func(function) => {
+ function
+ .params
+ .iter()
+ .chain(&function.results)
+ .try_for_each(|&value| check(value))?;
+ }
+ CompositeType::Struct(fields) => fields.iter().try_for_each(|field| check_storage(field.storage))?,
+ CompositeType::Array(field) => check_storage(field.storage)?,
+ }
+ if sub_type.supertypes.len() > 1 {
+ return invalid("multiple supertypes are not supported");
+ }
+ }
+ let group_identities =
+ canonicalizer.canonicalize_group(sub_types, group.start, |index| identities[index as usize]);
+ identities.extend(group_identities);
+ let types = TypeContext {
+ types: &module.types,
+ identities,
+ };
+ for (offset, sub_type) in sub_types.iter().enumerate() {
+ let index = group.start + offset as u32;
+ for &supertype in &sub_type.supertypes {
+ if supertype >= index {
+ return invalid("unknown type: supertypes must be declared before their subtypes");
+ }
+ let parent = &module.types[supertype as usize];
+ if parent.is_final {
+ return invalid("sub type of a final type");
+ }
+ if !types.composite_subtype(&sub_type.composite, &parent.composite) {
+ return invalid("sub type does not match its supertype");
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+pub fn validate(module: &mut Module) -> Result<()> {
+ let mut identities = Vec::with_capacity(module.types.len());
+ validate_types(module, &mut identities)?;
+ module.type_identities = identities;
+ let types = TypeContext {
+ types: &module.types,
+ identities: &module.type_identities,
+ };
+
+ for import in &module.imports {
+ match &import.description {
+ ImportDescription::Function(type_index) => match module.types.get(*type_index as usize) {
+ None => return invalid("unknown type"),
+ Some(sub_type) if sub_type.as_func().is_none() => return type_mismatch(),
+ _ => {}
+ },
+ ImportDescription::Table(table) => check_table_type(module, table)?,
+ ImportDescription::Memory(memory) => check_memory_type(memory)?,
+ ImportDescription::Global(global) => check_value_type(module, global.value)?,
+ ImportDescription::Tag(tag) => check_tag_type(module, tag.type_index)?,
+ }
+ }
+ for &type_index in &module.functions {
+ match module.types.get(type_index as usize) {
+ None => return invalid("unknown type"),
+ Some(sub_type) if sub_type.as_func().is_none() => return type_mismatch(),
+ _ => {}
+ }
+ }
+ let global_count = module.global_space.len() as u32;
+ for table in &module.tables {
+ check_table_type(module, &table.ty)?;
+ match &table.initializer {
+ Some(initializer) => {
+ validate_constant_expression(
+ module,
+ &types,
+ initializer,
+ ValType::Ref(table.ty.element),
+ module.imported_global_count,
+ )?;
+ }
+ None if !table.ty.element.nullable => return type_mismatch(),
+ None => {}
+ }
+ }
+ for memory in &module.memories {
+ check_memory_type(memory)?;
+ }
+ for tag in &module.tags {
+ check_tag_type(module, tag.type_index)?;
+ }
+ for (offset, global) in module.globals.iter().enumerate() {
+ check_value_type(module, global.ty.value)?;
+ let limit = module.imported_global_count + offset as u32;
+ validate_constant_expression(module, &types, &global.initializer, global.ty.value, limit)?;
+ }
+ let mut export_names = HashSet::new();
+ for export in &module.exports {
+ if !export_names.insert(export.name.as_str()) {
+ return invalid("duplicate export name");
+ }
+ let exists = match export.kind {
+ ExternalKind::Function => (export.index as usize) < module.function_space.len(),
+ ExternalKind::Table => (export.index as usize) < module.table_space.len(),
+ ExternalKind::Memory => (export.index as usize) < module.memory_space.len(),
+ ExternalKind::Global => (export.index as usize) < module.global_space.len(),
+ ExternalKind::Tag => (export.index as usize) < module.tag_space.len(),
+ };
+ if !exists {
+ return invalid(match export.kind {
+ ExternalKind::Function => "unknown function",
+ ExternalKind::Table => "unknown table",
+ ExternalKind::Memory => "unknown memory",
+ ExternalKind::Global => "unknown global",
+ ExternalKind::Tag => "unknown tag",
+ });
+ }
+ }
+ if let Some(start) = module.start {
+ let Some(&type_index) = module.function_space.get(start as usize) else {
+ return invalid("unknown function");
+ };
+ let function = module.types[type_index as usize]
+ .as_func()
+ .expect("function types are checked");
+ if !function.params.is_empty() || !function.results.is_empty() {
+ return invalid("start function");
+ }
+ }
+ for element in &module.elements {
+ check_heap_type(module, element.ty.heap)?;
+ match &element.items {
+ ElementItems::Functions(indices) => {
+ for &index in indices {
+ if index as usize >= module.function_space.len() {
+ return invalid("unknown function");
+ }
+ }
+ }
+ ElementItems::Expressions(expressions) => {
+ for expression in expressions {
+ validate_constant_expression(module, &types, expression, ValType::Ref(element.ty), global_count)?;
+ }
+ }
+ }
+ if let ElementMode::Active { table, offset } = &element.mode {
+ let table = module
+ .table_space
+ .get(*table as usize)
+ .ok_or_else(|| Error::invalid("unknown table"))?;
+ validate_constant_expression(
+ module,
+ &types,
+ offset,
+ table.limits.address_type.value_type(),
+ global_count,
+ )?;
+ if !types.ref_subtype(element.ty, table.element) {
+ return type_mismatch();
+ }
+ }
+ }
+ for data in &module.data {
+ if let DataMode::Active { memory, offset } = &data.mode {
+ let memory = module
+ .memory_space
+ .get(*memory as usize)
+ .ok_or_else(|| Error::invalid("unknown memory"))?;
+ validate_constant_expression(
+ module,
+ &types,
+ offset,
+ memory.limits.address_type.value_type(),
+ global_count,
+ )?;
+ }
+ }
+
+ let declared = declared_functions(module);
+ let mut infos = Vec::with_capacity(module.code.len());
+ let mut rewrites = Vec::new();
+ for (offset, body) in module.code.iter().enumerate() {
+ let type_index = module.functions[offset];
+ let function = module.types[type_index as usize]
+ .as_func()
+ .expect("function types are checked");
+ let mut locals = function.params.clone();
+ locals.reserve(body.declared_local_count as usize);
+ for &(count, ty) in &body.locals {
+ check_value_type(module, ty)?;
+ locals.extend(std::iter::repeat_n(ty, count as usize));
+ }
+ let mut local_initialized = vec![true; locals.len()];
+ for (index, local) in locals.iter().enumerate().skip(function.params.len()) {
+ local_initialized[index] = local.is_defaultable();
+ }
+ let mut validator = FunctionValidator {
+ module,
+ types: TypeContext {
+ types: &module.types,
+ identities: &module.type_identities,
+ },
+ declared_functions: &declared,
+ locals,
+ local_initialized,
+ initialization_log: Vec::new(),
+ operands: Vec::new(),
+ slot_height: 0,
+ max_slot_height: 0,
+ frames: Vec::new(),
+ side_table: Vec::new(),
+ try_regions: Vec::new(),
+ catch_clauses: Vec::new(),
+ results: function.results.clone(),
+ instruction_start: body.code.start,
+ rewrites: Vec::new(),
+ checked_access: None,
+ };
+ validator.push_frame(
+ FrameKind::Function,
+ Vec::new(),
+ function.results.clone(),
+ body.code.start,
+ );
+ let mut reader = Reader::with_range(&module.bytes, body.code.start as usize, body.code.end as usize);
+ validator.validate_body(&mut reader)?;
+ rewrites.append(&mut validator.rewrites);
+ infos.push(FunctionInfo {
+ 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,
+ max_stack_slots: validator.max_slot_height,
+ });
+ }
+ module.function_infos = infos;
+ crate::quickening::apply(&mut module.bytes, &rewrites);
+ Ok(())
+}
diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rs
new file mode 100644
index 00000000000..ed50bfcb1b7
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/execution.rs
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![cfg(all(target_arch = "x86_64", not(windows)))]
+
+use libwasm_engine::runtime::{ExternValue, InstanceAddress, Store, Trap, Value};
+use std::sync::Arc;
+
+fn instantiate(store: &mut Store, name: &str) -> InstanceAddress {
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("tests/fixtures")
+ .join(name);
+ let bytes = std::fs::read(path).unwrap();
+ let module = libwasm_engine::compile(&bytes).unwrap();
+ store.instantiate(Arc::new(module), &[]).unwrap()
+}
+
+fn call(store: &mut Store, instance: InstanceAddress, name: &str, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ let Some(ExternValue::Function(function)) = store.instance(instance).export(name) else {
+ panic!("no function export {name}");
+ };
+ store.invoke(function, arguments)
+}
+
+#[test]
+fn runs_control_flow_locals_calls_and_memory() {
+ let mut store = Store::new();
+ let instance = instantiate(&mut store, "basics.wasm");
+ assert_eq!(
+ call(&mut store, instance, "add", &[Value::I32(40), Value::I32(2)]),
+ Ok(vec![Value::I32(42)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "fib", &[Value::I64(20)]),
+ Ok(vec![Value::I64(6765)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "sum_to", &[Value::I32(100)]),
+ Ok(vec![Value::I32(5050)])
+ );
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "store_and_load",
+ &[Value::I32(16), Value::I32(0x1234_5678)]
+ ),
+ Ok(vec![Value::I32(0x56)])
+ );
+ for (input, output) in [(0, 100), (1, 200), (2, 300), (7, 300)] {
+ assert_eq!(
+ call(&mut store, instance, "classify", &[Value::I32(input)]),
+ Ok(vec![Value::I32(output)])
+ );
+ }
+ assert_eq!(call(&mut store, instance, "bump", &[]), Ok(vec![Value::I32(15)]));
+ assert_eq!(call(&mut store, instance, "bump", &[]), Ok(vec![Value::I32(20)]));
+ assert_eq!(
+ call(&mut store, instance, "multi", &[]),
+ Ok(vec![Value::I32(1), Value::I64(2), Value::I32(3)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "select", &[Value::I32(1)]),
+ Ok(vec![Value::I32(11)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "select", &[Value::I32(0)]),
+ Ok(vec![Value::I32(22)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "drop_in_block", &[]),
+ Ok(vec![Value::I32(3)])
+ );
+}
+
+#[test]
+fn traps() {
+ let mut store = Store::new();
+ let instance = instantiate(&mut store, "basics.wasm");
+ assert_eq!(call(&mut store, instance, "trap", &[]), Err(Trap::Unreachable));
+ assert_eq!(
+ call(&mut store, instance, "out_of_bounds", &[]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "recurse", &[Value::I32(0)]),
+ Err(Trap::StackExhausted)
+ );
+ // The store still works after a trap.
+ assert_eq!(
+ call(&mut store, instance, "add", &[Value::I32(1), Value::I32(2)]),
+ Ok(vec![Value::I32(3)])
+ );
+}
+
+#[test]
+fn checks_bounds_of_other_memories_and_memory64() {
+ let mut store = Store::new();
+ let instance = instantiate(&mut store, "checked_memories.wasm");
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "store_other",
+ &[Value::I32(100), Value::I32(0x1234)]
+ ),
+ Ok(vec![])
+ );
+ assert_eq!(
+ call(&mut store, instance, "load_other", &[Value::I32(100)]),
+ Ok(vec![Value::I32(0x1234)])
+ );
+ // The store went to the other memory, not to memory 0.
+ assert_eq!(
+ call(&mut store, instance, "load_small", &[Value::I32(100)]),
+ Ok(vec![Value::I32(0)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "load_other", &[Value::I32(65533)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "store_wide", &[Value::I64(16), Value::I64(-5)]),
+ Ok(vec![])
+ );
+ assert_eq!(
+ call(&mut store, instance, "load_wide", &[Value::I64(16)]),
+ Ok(vec![Value::I64(-5)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "load_wide", &[Value::I64(1 << 40)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ // An address and offset that wrap around 2^64 are out of bounds too.
+ assert_eq!(
+ call(&mut store, instance, "load_wide", &[Value::I64(-4)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "splat_other", &[Value::I32(100)]),
+ Ok(vec![Value::I32(0x1234)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "splat_other", &[Value::I32(65535)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "lane_wide", &[Value::I64(24)]),
+ Ok(vec![Value::I32(-5)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "lane_wide", &[Value::I64(65533)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "grow_wide", &[Value::I64(1)]),
+ Ok(vec![Value::I64(1)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "grow_wide", &[Value::I64(1 << 40)]),
+ Ok(vec![Value::I64(-1)])
+ );
+}
+
+#[test]
+fn catches_exceptions_from_webassembly_and_host_functions() {
+ use libwasm_engine::types::{FuncType, ValType};
+ let mut store = Store::new();
+ let tag = store.allocate_tag(FuncType {
+ params: vec![ValType::I32],
+ results: vec![],
+ });
+ let thrower = store.allocate_host_function(
+ FuncType {
+ params: vec![ValType::I32],
+ results: vec![],
+ },
+ std::rc::Rc::new(move |store: &mut Store, arguments: &[Value]| {
+ let Value::I32(value) = arguments[0] else {
+ unreachable!();
+ };
+ let exception = store.allocate_exception(tag, Box::new([u64::from((value * 2) as u32)]));
+ Err(Trap::UncaughtException(exception))
+ }),
+ );
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/exceptions.wasm");
+ let module = libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap();
+ let instance = store
+ .instantiate(
+ Arc::new(module),
+ &[ExternValue::Tag(tag), ExternValue::Function(thrower)],
+ )
+ .unwrap();
+ assert_eq!(
+ call(&mut store, instance, "catch_own", &[Value::I32(7)]),
+ Ok(vec![Value::I32(7)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "catch_host", &[Value::I32(7)]),
+ Ok(vec![Value::I32(14)])
+ );
+ let Err(Trap::UncaughtException(exception)) = call(&mut store, instance, "uncaught", &[Value::I32(5)]) else {
+ panic!("the exception should leave the interpreter");
+ };
+ assert_eq!(store.exception(exception).tag, tag);
+ assert_eq!(&*store.exception(exception).payload, &[5]);
+}
+
+#[test]
+fn waits_on_shared_memory() {
+ let mut store = Store::new();
+ let instance = instantiate(&mut store, "shared_waits.wasm");
+ // The location holds 0, not 1.
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "wait",
+ &[Value::I32(0), Value::I32(1), Value::I64(-1)]
+ ),
+ Ok(vec![Value::I32(1)])
+ );
+ // Nobody notifies, so the wait times out after a millisecond.
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "wait",
+ &[Value::I32(0), Value::I32(0), Value::I64(1_000_000)]
+ ),
+ Ok(vec![Value::I32(2)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "notify", &[Value::I32(0)]),
+ Ok(vec![Value::I32(0)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "or", &[Value::I32(8), Value::I32(6)]),
+ Ok(vec![Value::I32(0)])
+ );
+ assert_eq!(
+ call(&mut store, instance, "or", &[Value::I32(8), Value::I32(9)]),
+ Ok(vec![Value::I32(6)])
+ );
+}
diff --git a/Libraries/LibWasm/Engine/tests/fixtures.rs b/Libraries/LibWasm/Engine/tests/fixtures.rs
new file mode 100644
index 00000000000..aa30557d2e0
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures.rs
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use std::path::{Path, PathBuf};
+
+fn fixtures() -> Vec<PathBuf> {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");
+ let mut paths = Vec::new();
+ for directory in [
+ "Libraries/LibWasm/Tests/Fixtures/Modules",
+ "Libraries/LibWasm/Tests/CI",
+ "Tests/LibWasm/Fixtures",
+ ] {
+ for entry in std::fs::read_dir(root.join(directory)).unwrap() {
+ let path = entry.unwrap().path();
+ if path.extension().is_some_and(|extension| extension == "wasm") {
+ paths.push(path);
+ }
+ }
+ }
+ paths.sort();
+ paths
+}
+
+#[test]
+fn validates_the_fixture_modules() {
+ let paths = fixtures();
+ assert!(paths.len() >= 20);
+ for path in paths {
+ let bytes = std::fs::read(&path).unwrap();
+ let result = libwasm_engine::compile(&bytes);
+ let name = path.file_name().unwrap().to_str().unwrap();
+ if name == "atomics-misaligned.wasm" {
+ assert_eq!(
+ result.unwrap_err(),
+ libwasm_engine::Error::invalid("atomic memory op alignment must be equal to natural")
+ );
+ } else {
+ result.unwrap_or_else(|error| panic!("{name}: {error}"));
+ }
+ }
+}
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/basics.wasm b/Libraries/LibWasm/Engine/tests/fixtures/basics.wasm
new file mode 100644
index 00000000000..c2da03bb336
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/basics.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/basics.wat b/Libraries/LibWasm/Engine/tests/fixtures/basics.wat
new file mode 100644
index 00000000000..338b8221f03
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/basics.wat
@@ -0,0 +1,95 @@
+(module
+ (memory (export "memory") 1)
+ (global $counter (mut i32) (i32.const 10))
+ (func (export "add") (param i32 i32) (result i32)
+ local.get 0
+ local.get 1
+ i32.add)
+ (func $fib (export "fib") (param i64) (result i64)
+ local.get 0
+ i64.const 2
+ i64.lt_u
+ if (result i64)
+ local.get 0
+ else
+ local.get 0
+ i64.const 1
+ i64.sub
+ call $fib
+ local.get 0
+ i64.const 2
+ i64.sub
+ call $fib
+ i64.add
+ end)
+ (func (export "sum_to") (param i32) (result i32)
+ (local i32 i32)
+ block
+ loop
+ local.get 1
+ local.get 0
+ i32.ge_s
+ br_if 1
+ local.get 1
+ i32.const 1
+ i32.add
+ local.tee 1
+ local.get 2
+ i32.add
+ local.set 2
+ br 0
+ end
+ end
+ local.get 2)
+ (func (export "store_and_load") (param i32 i32) (result i32)
+ local.get 0
+ local.get 1
+ i32.store offset=4
+ local.get 0
+ i32.load8_u offset=5)
+ (func (export "classify") (param i32) (result i32)
+ block
+ block
+ block
+ local.get 0
+ br_table 0 1 2
+ end
+ i32.const 100
+ return
+ end
+ i32.const 200
+ return
+ end
+ i32.const 300)
+ (func (export "bump") (result i32)
+ global.get $counter
+ i32.const 5
+ i32.add
+ global.set $counter
+ global.get $counter)
+ (func (export "trap") (result i32)
+ unreachable)
+ (func (export "out_of_bounds") (result i32)
+ i32.const 65536
+ i32.load)
+ (func $recurse (export "recurse") (param i32) (result i32)
+ local.get 0
+ i32.const 1
+ i32.add
+ call $recurse)
+ (func (export "multi") (result i32 i64 i32)
+ i32.const 1
+ i64.const 2
+ i32.const 3)
+ (func (export "select") (param i32) (result i32)
+ i32.const 11
+ i32.const 22
+ local.get 0
+ select)
+ (func (export "drop_in_block") (result i32)
+ block (result i32)
+ i32.const 1
+ i32.const 2
+ i32.const 3
+ br 0
+ end))
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wasm b/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wasm
new file mode 100644
index 00000000000..43dd6ce64fa
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wat b/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wat
new file mode 100644
index 00000000000..8fe2d26f185
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/checked_memories.wat
@@ -0,0 +1,22 @@
+;; Accesses that cannot rely on the guard pages of memory 0: another memory, and a memory64.
+(module
+ (memory $small 1)
+ (memory $other 1)
+ (memory $wide i64 1)
+ (func (export "store_other") (param i32 i32)
+ (i32.store $other (local.get 0) (local.get 1)))
+ (func (export "load_other") (param i32) (result i32)
+ (i32.load $other (local.get 0)))
+ (func (export "load_small") (param i32) (result i32)
+ (i32.load $small (local.get 0)))
+ (func (export "store_wide") (param i64 i64)
+ (i64.store $wide offset=8 (local.get 0) (local.get 1)))
+ (func (export "load_wide") (param i64) (result i64)
+ (i64.load $wide offset=8 (local.get 0)))
+ (func (export "splat_other") (param i32) (result i32)
+ (i32x4.extract_lane 3 (v128.load32_splat $other (local.get 0))))
+ (func (export "lane_wide") (param i64) (result i32)
+ (i32x4.extract_lane 2 (v128.load32_lane $wide 2 (local.get 0) (v128.const i32x4 1 2 3 4))))
+ (func (export "grow_wide") (param i64) (result i64)
+ (memory.grow $wide (local.get 0)))
+)
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wasm b/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wasm
new file mode 100644
index 00000000000..a0b300cfb7a
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wat b/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wat
new file mode 100644
index 00000000000..e658667be00
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/exceptions.wat
@@ -0,0 +1,19 @@
+;; Exceptions thrown by WebAssembly and by host functions, caught by WebAssembly.
+(module
+ (tag $error (import "host" "error") (param i32))
+ (func $host_throw (import "host" "throw") (param i32))
+ (func $thrower (param i32)
+ (throw $error (local.get 0)))
+ (func (export "catch_own") (param i32) (result i32)
+ (block $caught (result i32)
+ (try_table (catch $error $caught)
+ (call $thrower (local.get 0)))
+ (i32.const -1)))
+ (func (export "catch_host") (param i32) (result i32)
+ (block $caught (result i32)
+ (try_table (catch $error $caught)
+ (call $host_throw (local.get 0)))
+ (i32.const -1)))
+ (func (export "uncaught") (param i32)
+ (call $thrower (local.get 0)))
+)
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wasm b/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wasm
new file mode 100644
index 00000000000..a4b2d75d48b
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wat b/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wat
new file mode 100644
index 00000000000..8b83348f027
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/shared_waits.wat
@@ -0,0 +1,10 @@
+;; Waits and notifies on a shared memory that no other thread uses.
+(module
+ (memory 1 1 shared)
+ (func (export "wait") (param i32 i32 i64) (result i32)
+ (memory.atomic.wait32 (local.get 0) (local.get 1) (local.get 2)))
+ (func (export "notify") (param i32) (result i32)
+ (memory.atomic.notify (local.get 0) (i32.const 1)))
+ (func (export "or") (param i32 i32) (result i32)
+ (i32.atomic.rmw.or (local.get 0) (local.get 1)))
+)
diff --git a/Libraries/LibWasm/Engine/tests/side_table.rs b/Libraries/LibWasm/Engine/tests/side_table.rs
new file mode 100644
index 00000000000..f98378e6e22
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/side_table.rs
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use libwasm_engine::validator::{CatchKind, SideTableEntry};
+use libwasm_engine::{Error, Module, compile};
+
+fn leb(mut value: u32, out: &mut Vec<u8>) {
+ loop {
+ let byte = (value & 0x7f) as u8;
+ value >>= 7;
+ if value == 0 {
+ out.push(byte);
+ return;
+ }
+ out.push(byte | 0x80);
+ }
+}
+
+fn section(id: u8, contents: &[u8], out: &mut Vec<u8>) {
+ out.push(id);
+ leb(contents.len() as u32, out);
+ out.extend_from_slice(contents);
+}
+
+/// A module with one function of type `params -> results` (value type bytes), with no declared locals and the given
+/// instructions, which must end with the function's `end`. Tag 0 has type [i32] -> [].
+fn module(params: &[u8], results: &[u8], code: &[u8]) -> Vec<u8> {
+ let mut bytes = b"\0asm\x01\0\0\0".to_vec();
+ let mut types = vec![2, 0x60];
+ leb(params.len() as u32, &mut types);
+ types.extend_from_slice(params);
+ leb(results.len() as u32, &mut types);
+ types.extend_from_slice(results);
+ types.extend_from_slice(&[0x60, 1, 0x7f, 0]);
+ section(1, &types, &mut bytes);
+ section(3, &[1, 0], &mut bytes);
+ section(13, &[1, 0, 1], &mut bytes);
+ let mut body = vec![0];
+ body.extend_from_slice(code);
+ let mut function = Vec::new();
+ leb(body.len() as u32, &mut function);
+ function.extend_from_slice(&body);
+ let mut code_section = vec![1];
+ code_section.extend_from_slice(&function);
+ section(10, &code_section, &mut bytes);
+ bytes
+}
+
+fn compile_function(params: &[u8], results: &[u8], code: &[u8]) -> (Module, u32) {
+ let bytes = module(params, results, code);
+ let module = compile(&bytes).unwrap_or_else(|error| panic!("{error}"));
+ let start = module.code[0].code.start;
+ (module, start)
+}
+
+fn entries(module: &Module) -> &[SideTableEntry] {
+ &module.function_infos[0].side_table
+}
+
+const I32: u8 = 0x7f;
+
+#[test]
+fn branches_out_of_blocks_past_their_end() {
+ // block (result i32) i32.const 1 i32.const 2 br 0 end drop end
+ let code = [0x02, I32, 0x41, 1, 0x41, 2, 0x0c, 0, 0x0b, 0x1a, 0x0b];
+ let (module, start) = compile_function(&[], &[], &code);
+ let branch = 6;
+ let after_end = 9;
+ assert_eq!(
+ entries(&module),
+ [SideTableEntry {
+ pc_delta: after_end - branch,
+ stp_delta: 1,
+ keep: 1,
+ drop: 1,
+ }]
+ );
+ assert_eq!(module.function_infos[0].max_stack_slots, 2);
+ assert_eq!(module.bytes[(start as usize) + after_end as usize], 0x1a);
+}
+
+#[test]
+fn branches_back_to_the_loop_instruction() {
+ // loop local.get 0 br_if 0 end end, with param i32
+ let code = [0x03, 0x40, 0x20, 0, 0x0d, 0, 0x0b, 0x0b];
+ let (module, _) = compile_function(&[I32], &[], &code);
+ assert_eq!(
+ entries(&module),
+ [SideTableEntry {
+ pc_delta: -4,
+ stp_delta: 0,
+ keep: 0,
+ drop: 0,
+ }]
+ );
+}
+
+#[test]
+fn if_jumps_to_its_else_arm_and_the_first_arm_jumps_past_the_end() {
+ // local.get 0 if (result i32) i32.const 1 else i32.const 2 end drop end
+ let code = [0x20, 0, 0x04, I32, 0x41, 1, 0x05, 0x41, 2, 0x0b, 0x1a, 0x0b];
+ let (module, _) = compile_function(&[I32], &[], &code);
+ let if_pc = 2;
+ let else_pc = 6;
+ let end_pc = 9;
+ assert_eq!(
+ entries(&module),
+ [
+ SideTableEntry {
+ pc_delta: else_pc + 1 - if_pc,
+ stp_delta: 2,
+ keep: 0,
+ drop: 0,
+ },
+ SideTableEntry {
+ pc_delta: end_pc + 1 - else_pc,
+ stp_delta: 1,
+ keep: 1,
+ drop: 0,
+ },
+ ]
+ );
+}
+
+#[test]
+fn if_without_else_jumps_past_its_end() {
+ // local.get 0 if nop end end
+ let code = [0x20, 0, 0x04, 0x40, 0x01, 0x0b, 0x0b];
+ let (module, _) = compile_function(&[I32], &[], &code);
+ assert_eq!(entries(&module)[0].pc_delta, 6 - 2);
+ assert_eq!(entries(&module)[0].stp_delta, 1);
+}
+
+#[test]
+fn br_table_has_an_entry_per_label_with_the_default_last() {
+ // block block local.get 0 br_table 0 1 0 end end end
+ let code = [0x02, 0x40, 0x02, 0x40, 0x20, 0, 0x0e, 2, 0, 1, 0, 0x0b, 0x0b, 0x0b];
+ let (module, _) = compile_function(&[I32], &[], &code);
+ let branch = 6;
+ let inner_end = 11;
+ let outer_end = 12;
+ let table = entries(&module);
+ assert_eq!(table.len(), 3);
+ assert_eq!(table[0].pc_delta, inner_end + 1 - branch);
+ assert_eq!(table[1].pc_delta, outer_end + 1 - branch);
+ assert_eq!(table[2].pc_delta, inner_end + 1 - branch);
+ for (index, entry) in table.iter().enumerate() {
+ assert_eq!(entry.stp_delta, 3 - index as i32);
+ }
+}
+
+#[test]
+fn branches_to_the_function_label_target_its_final_end() {
+ // i32.const 7 br 0 end, returning i32
+ let code = [0x41, 7, 0x0c, 0, 0x0b];
+ let (module, _) = compile_function(&[], &[I32], &code);
+ assert_eq!(
+ entries(&module),
+ [SideTableEntry {
+ pc_delta: 2,
+ stp_delta: 1,
+ keep: 1,
+ drop: 0,
+ }]
+ );
+}
+
+#[test]
+fn counts_vector_values_as_two_slots() {
+ // v128.const 0 v128.const 0 drop drop end
+ let mut code = vec![0xfd, 0x0c];
+ code.extend_from_slice(&[0; 16]);
+ code.extend_from_slice(&[0xfd, 0x0c]);
+ code.extend_from_slice(&[0; 16]);
+ code.extend_from_slice(&[0x1a, 0x1a, 0x0b]);
+ let (module, _) = compile_function(&[], &[], &code);
+ assert_eq!(module.function_infos[0].max_stack_slots, 4);
+}
+
+#[test]
+fn records_try_table_handlers() {
+ // block (result i32) try_table (catch 0 0) i32.const 1 throw 0 end unreachable end drop end
+ let code = [
+ 0x02, I32, 0x1f, 0x40, 1, 0x00, 0, 0, 0x41, 1, 0x08, 0, 0x0b, 0x00, 0x0b, 0x1a, 0x0b,
+ ];
+ let (module, start) = compile_function(&[], &[], &code);
+ let info = &module.function_infos[0];
+ assert_eq!(info.try_regions.len(), 1);
+ let region = info.try_regions[0];
+ assert_eq!(region.start - start, 8);
+ assert_eq!(region.end - start, 12);
+ assert_eq!(region.clause_count, 1);
+ let clause = info.catch_clauses[0];
+ assert_eq!(clause.kind, CatchKind::Catch);
+ assert_eq!(clause.tag, 0);
+ assert_eq!(clause.target_pc - start, 15);
+ assert_eq!(clause.height, 0);
+}
+
+#[test]
+fn rejects_malformed_and_invalid_functions() {
+ // i32.add on an empty stack
+ let error = compile(&module(&[], &[], &[0x6a, 0x0b])).unwrap_err();
+ assert_eq!(error, Error::invalid("type mismatch"));
+ // a missing end
+ let error = compile(&module(&[], &[], &[0x01])).unwrap_err();
+ assert!(error.is_malformed(), "{error}");
+ // br to a label that does not exist
+ let error = compile(&module(&[], &[], &[0x0c, 1, 0x0b])).unwrap_err();
+ assert_eq!(error, Error::invalid("unknown label"));
+}
diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flap
new file mode 100644
index 00000000000..8d65ea50958
--- /dev/null
+++ b/Libraries/LibWasm/Interpreter/interpreter.flap
@@ -0,0 +1,8581 @@
+# Copyright (c) 2026-present, the Ladybird developers.
+# SPDX-License-Identifier: BSD-2-Clause
+
+# The in-place WebAssembly interpreter. Handlers run on a function's original code bytes: `ip` points at the
+# current instruction, whose immediates the handler decodes itself, and `stp` points at the next entry of the
+# function's side table, which branches read their targets from (see validator.rs). Frames live on the machine
+# stack (see abi.rs): locals at fp + 8 * i, the frame header below fp, and the operand stack below the header in
+# 8-byte slots, with `vsp` pointing at the top slot.
+#
+# Slots hold i32 and f32 values zero-extended, i64 and f64 values and references in full, and v128 values in two
+# slots, low half at the lower address.
+
+# Decoding immediates. The validator guarantees they are well-formed, so only their lengths and values matter.
+
+# An unsigned LEB128 value and its length. Most immediates are a single byte, so the loop over the others is out of
+# line.
+inline fn read_leb(bytes: Sequence<u8>) -> (u64, u64) {
+ let first: u64 = alias(bytes[0]);
+ let mut result: u64 = first;
+ let mut length: u64 = 1;
+ if first >= 128 @cold {
+ result = first & 127;
+ let mut shift: u64 = 7;
+ let mut byte: u64 = first;
+ do {
+ byte = alias(bytes[length]);
+ let bits = (byte & 127) << shift;
+ result = result | bits;
+ shift = shift + 7;
+ length = length + 1;
+ } while byte >= 128;
+ }
+ (result, length)
+}
+
+# A signed LEB128 value, sign-extended to 64 bits, and its length.
+inline fn read_signed_leb(bytes: Sequence<u8>) -> (u64, u64) {
+ let first: u64 = alias(bytes[0]);
+ let moved = first << 57;
+ let signed: i64 = alias(moved);
+ let extended = signed >> 57;
+ let mut result: u64 = alias(extended);
+ let mut length: u64 = 1;
+ if first >= 128 @cold {
+ result = first & 127;
+ let mut shift: u64 = 7;
+ let mut byte: u64 = first;
+ do {
+ byte = alias(bytes[length]);
+ let bits = (byte & 127) << shift;
+ result = result | bits;
+ shift = shift + 7;
+ length = length + 1;
+ } while byte >= 128;
+ if shift < 64 {
+ if byte & 64 != 0 {
+ let all_ones: u64 = 0xffffffffffffffff;
+ let extension = all_ones << shift;
+ result = result | extension;
+ }
+ }
+ }
+ (result, length)
+}
+
+# The length of a LEB128 value.
+inline fn leb_length(bytes: Sequence<u8>) -> u64 {
+ let first: u64 = alias(bytes[0]);
+ let mut length: u64 = 1;
+ if first >= 128 @cold {
+ let mut byte: u64 = first;
+ while byte >= 128 {
+ byte = alias(bytes[length]);
+ length = length + 1;
+ }
+ }
+ length
+}
+
+# The length of a block type immediate: a value type, which takes one byte unless it is a reference type with a heap
+# type, the empty type, or a type index.
+inline fn block_type_length(bytes: Sequence<u8>) -> u64 {
+ let first: u64 = alias(bytes[0]);
+ let mut length: u64 = 1;
+ if first >= 0x63 @cold {
+ if first <= 0x64 {
+ let start: u64 = alias(bytes);
+ let heap_bytes: Sequence<u8> = alias(start + 1);
+ let heap_length = leb_length(heap_bytes);
+ length = heap_length + 1;
+ }
+ if first >= 128 {
+ length = leb_length(bytes);
+ }
+ }
+ length
+}
+
+inline fn immediates() -> Sequence<u8> {
+ let current: u64 = ip;
+ let bytes: Sequence<u8> = alias(current + 1);
+ bytes
+}
+
+# The immediates after a prefix opcode and its LEB128 sub-opcode, and the offset from the instruction to them.
+inline fn prefixed_immediates() -> (Sequence<u8>, u64) {
+ let length = leb_length(immediates());
+ let current: u64 = ip;
+ let offset = length + 1;
+ let bytes: Sequence<u8> = alias(current + offset);
+ (bytes, offset)
+}
+
+inline fn advance(length: u64) {
+ let current: u64 = ip;
+ let next = current + length;
+ ip = next;
+ dispatch;
+}
+
+# The operand stack.
+
+inline fn stack() -> Sequence<u64> {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ slots
+}
+
+inline fn push(value: u64) {
+ let top: u64 = vsp;
+ let next = top - 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = value;
+}
+
+inline fn pop() -> u64 {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let value = slots[0];
+ let next = top + 8;
+ vsp = next;
+ value
+}
+
+inline fn pop32() -> u32 {
+ let value = pop();
+ u32(value)
+}
+
+inline fn drop_slots(count: u64) {
+ let top: u64 = vsp;
+ let next = top + (count << 3);
+ vsp = next;
+}
+
+# Operand helpers for numeric instructions: the two operands of a binary instruction, whose result replaces the
+# first of them, and the operand of a unary instruction, whose result replaces it.
+
+inline fn binary_operands() -> (u64, u64) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let rhs = slots[0];
+ let lhs = slots[1];
+ let next = top + 8;
+ vsp = next;
+ (lhs, rhs)
+}
+
+inline fn binary32() -> (u32, u32) {
+ let [lhs, rhs] = binary_operands();
+ let narrow_lhs = u32(lhs);
+ let narrow_rhs = u32(rhs);
+ (narrow_lhs, narrow_rhs)
+}
+
+inline fn unary_operand() -> u64 {
+ let slots = stack();
+ slots[0]
+}
+
+inline fn unary32() -> u32 {
+ let value = unary_operand();
+ u32(value)
+}
+
+inline fn set_top(value: u64) {
+ let slots = stack();
+ slots[0] = value;
+}
+
+inline fn result(value: u64) {
+ set_top(value);
+ dispatch_next;
+}
+
+inline fn result32(value: u32) {
+ let wide: u64 = alias(value);
+ set_top(wide);
+ dispatch_next;
+}
+
+inline fn signed64(value: u64) -> i64 {
+ let signed: i64 = alias(value);
+ signed
+}
+
+inline fn unsigned64(value: u64) -> u64 {
+ value
+}
+
+# The frame.
+
+inline fn frame_word(offset: u64) -> u64 {
+ let frame: u64 = fp;
+ let mut value: u64;
+ load64(value, [frame, offset]);
+ value
+}
+
+inline fn context() -> u64 {
+ let frame: u64 = fp;
+ let mut value: u64;
+ load64(value, [frame, FRAME_CONTEXT]);
+ value
+}
+
+inline fn instance() -> u64 {
+ let frame: u64 = fp;
+ let mut value: u64;
+ load64(value, [frame, FRAME_INSTANCE]);
+ value
+}
+
+# Leave the interpreter with a trap: return to the entry the runtime made, with the trap code in its record.
+inline fn trap_with(code: u64, context_pointer: u64) {
+ let mut record: u64;
+ load64(record, [context_pointer, CONTEXT_ENTRY_RECORD]);
+ store32([record, ENTRY_TRAP], code);
+ leave(context_pointer, record);
+}
+
+inline fn trap(code: u64) {
+ trap_with(code, context());
+}
+
+# Restore the state of the entry that `record` describes and leave the interpreter.
+inline fn leave(context_pointer: u64, record: u64) {
+ let mut entry_fp: u64;
+ load64(entry_fp, [context_pointer, CONTEXT_ENTRY_FP]);
+ let mut saved_fp: u64;
+ load64(saved_fp, [record, ENTRY_SAVED_ENTRY_FP]);
+ let mut saved_record: u64;
+ load64(saved_record, [record, ENTRY_SAVED_ENTRY_RECORD]);
+ store64([context_pointer, CONTEXT_ENTRY_FP], saved_fp);
+ store64([context_pointer, CONTEXT_ENTRY_RECORD], saved_record);
+ fp = entry_fp;
+ exit();
+}
+
+# Calls and returns.
+
+# OPTIMIZATION: Shifts align without the scratch registers a 64-bit `and` with an immediate reserves, which the call
+# handlers do not have to spare.
+inline fn align_down_16(address: u64) -> u64 {
+ let shifted = address >> 4;
+ shifted << 4
+}
+
+# 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);
+ let top: u64 = vsp;
+ store64([context_pointer, CONTEXT_ARGUMENT_1], top);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], return_ip);
+ store64([context_pointer, CONTEXT_ARGUMENT_3], fp);
+ # The helper may clobber every allocatable register, so nothing but its result is kept across it.
+ ip = return_ip;
+ let new_top: u64 = call_helper(wasm_runtime_call_host, context_pointer);
+ guard new_top != 0 else @cold {
+ trap(TRAP_RUNTIME);
+ };
+ if new_top == 1 @cold {
+ resume_at_handler();
+ }
+ vsp = new_top;
+ dispatch;
+}
+
+# Continue at the exception handler the runtime found, which it left in the context's arguments.
+inline fn resume_at_handler() {
+ let context_pointer = context();
+ let mut handler_fp: u64;
+ load64(handler_fp, [context_pointer, CONTEXT_ARGUMENTS]);
+ let mut handler_ip: u64;
+ load64(handler_ip, [context_pointer, CONTEXT_ARGUMENT_1]);
+ let mut handler_stp: u64;
+ load64(handler_stp, [context_pointer, CONTEXT_ARGUMENT_2]);
+ let mut handler_vsp: u64;
+ load64(handler_vsp, [context_pointer, CONTEXT_ARGUMENT_3]);
+ let mut handler_instance: u64;
+ load64(handler_instance, [handler_fp, FRAME_INSTANCE]);
+ let mut handler_memory_base: u64;
+ load64(handler_memory_base, [handler_instance, INSTANCE_MEMORY0_BASE]);
+ fp = handler_fp;
+ ip = handler_ip;
+ stp = handler_stp;
+ vsp = handler_vsp;
+ memory_base = handler_memory_base;
+ dispatch;
+}
+
+# Throw the exception `exception` refers to, or a new one with `tag` and the values on top of the operand stack.
+inline fn throw_exception(tag: u64, exception: u64) {
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], tag);
+ let top: u64 = vsp;
+ store64([context_pointer, CONTEXT_ARGUMENT_1], top);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], ip);
+ store64([context_pointer, CONTEXT_ARGUMENT_3], fp);
+ store64([context_pointer, CONTEXT_ARGUMENT_4], exception);
+ let caught: u64 = call_helper(wasm_runtime_throw, context_pointer);
+ guard caught != 0 else @cold {
+ trap(TRAP_RUNTIME);
+ };
+ resume_at_handler();
+}
+
+handler Throw() @opcode(0x08) {
+ let [tag_index, _] = read_leb(immediates());
+ let instance_pointer = instance();
+ let mut tags_pointer: u64;
+ load64(tags_pointer, [instance_pointer, INSTANCE_TAGS]);
+ let tags: Sequence<u64> = alias(tags_pointer);
+ let tag = tags[tag_index];
+ throw_exception(tag, 0);
+}
+
+handler ThrowRef() @opcode(0x0a) {
+ let exception = pop();
+ guard exception != 0 else @cold {
+ trap(TRAP_NULL_REFERENCE);
+ };
+ throw_exception(0, exception);
+}
+
+# A try_table runs like a block; its handlers are found by the runtime when something throws.
+handler TryTable() @opcode(0x1f) {
+ let block_length = block_type_length(immediates());
+ let current: u64 = ip;
+ let count_bytes: Sequence<u8> = alias(current + 1 + block_length);
+ let [count, count_length] = read_leb(count_bytes);
+ let mut position = current + 1 + block_length + count_length;
+ let mut remaining = count;
+ while remaining != 0 {
+ let clause: Sequence<u8> = alias(position);
+ let kind: u64 = alias(clause[0]);
+ position = position + 1;
+ if kind < 2 {
+ let tag_bytes: Sequence<u8> = alias(position);
+ let tag_length = leb_length(tag_bytes);
+ position = position + tag_length;
+ }
+ let label_bytes: Sequence<u8> = alias(position);
+ let label_length = leb_length(label_bytes);
+ position = position + label_length;
+ remaining = remaining - 1;
+ }
+ ip = position;
+ dispatch;
+}
+
+# Enter a function with v128 parameters or locals, whose frame has storage for them (see call_function).
+inline fn call_vector_function(function: u64, return_ip: u64, context_pointer: u64) {
+ let mut locals_size: u64;
+ load32(locals_size, [function, FUNCTION_LOCALS_SIZE]);
+ let mut frame_size: u64;
+ load32(frame_size, [function, FUNCTION_FRAME_SIZE]);
+ let caller_vsp: u64 = vsp;
+ let new_fp = align_down_16(caller_vsp - locals_size);
+ # The stack pointer only ever moves down while WebAssembly runs: returns leave it where the callee had it, and a
+ # frame that would end above it ends at it instead. Spilled values rely on that when they move into the new
+ # frame (see spill.rs in Flap).
+ let current_sp: u64 = sp;
+ let mut bottom = new_fp - frame_size;
+ if current_sp < bottom {
+ bottom = current_sp;
+ }
+ let mut limit: u64;
+ load64(limit, [context_pointer, CONTEXT_STACK_LIMIT]);
+ guard bottom >= limit else @cold {
+ trap_with(TRAP_STACK_EXHAUSTED, context_pointer);
+ };
+ sp = bottom;
+ store64([new_fp, FRAME_SAVED_FP], fp);
+ store64([new_fp, FRAME_RETURN_IP], return_ip);
+ store64([new_fp, FRAME_SAVED_STP], stp);
+ store64([new_fp, FRAME_FUNCTION], function);
+ store64([new_fp, FRAME_SAVED_MEMORY_BASE], memory_base);
+ store64([new_fp, FRAME_CONTEXT], context_pointer);
+ fp = new_fp;
+
+ # Copy the arguments into the first locals and clear the others. A v128 local's slot gets the address of its
+ # storage, at the offset from fp the function's vector storage table gives; scalar locals have offset zero.
+ let mut param_slots: u64;
+ load32(param_slots, [function, FUNCTION_PARAM_SLOTS]);
+ let mut storage_table: u64;
+ load64(storage_table, [function, FUNCTION_VECTOR_STORAGE]);
+ let offsets: Sequence<u32> = alias(storage_table);
+ let arguments = stack();
+ let locals: Sequence<u64> = alias(new_fp);
+ let mut index: u64 = 0;
+ let mut source: u64 = param_slots;
+ while source != 0 {
+ let offset: u64 = alias(offsets[index]);
+ if offset == 0 {
+ source = source - 1;
+ locals[index] = arguments[source];
+ } else {
+ source = source - 2;
+ let storage = new_fp + offset;
+ let high_source = source + 1;
+ let low = arguments[source];
+ let high = arguments[high_source];
+ store64([storage, 0], low);
+ store64([storage, 8], high);
+ locals[index] = storage;
+ }
+ index = index + 1;
+ }
+ let return_vsp = caller_vsp + (param_slots << 3);
+ store64([new_fp, FRAME_RETURN_VSP], return_vsp);
+ let mut local_count: u64;
+ load32(local_count, [function, FUNCTION_LOCAL_COUNT]);
+ while index < local_count {
+ let offset: u64 = alias(offsets[index]);
+ if offset == 0 {
+ locals[index] = 0;
+ } else {
+ let storage = new_fp + offset;
+ store64([storage, 0], 0);
+ store64([storage, 8], 0);
+ locals[index] = storage;
+ }
+ index = index + 1;
+ }
+
+ let mut callee_instance: u64;
+ load64(callee_instance, [function, FUNCTION_INSTANCE]);
+ store64([new_fp, FRAME_INSTANCE], callee_instance);
+ let mut code: u64;
+ load64(code, [function, FUNCTION_CODE]);
+ let mut side_table: u64;
+ load64(side_table, [function, FUNCTION_SIDE_TABLE]);
+ let mut callee_memory_base: u64;
+ load64(callee_memory_base, [callee_instance, INSTANCE_MEMORY0_BASE]);
+ let empty_stack = new_fp - FRAME_HEADER_SIZE;
+ ip = code;
+ stp = side_table;
+ memory_base = callee_memory_base;
+ vsp = empty_stack;
+ dispatch;
+}
+
+# Enter `function` with its arguments on top of the operand stack, continuing at `return_ip` when it returns.
+#
+# OPTIMIZATION: The caller's state goes into the new frame's header as soon as the frame's address is known, so that
+# its registers can be reused while the arguments are copied.
+inline fn call_function(function: u64, return_ip: u64, context_pointer: u64) {
+ let mut kind: u64;
+ load32(kind, [function, FUNCTION_KIND]);
+ if kind != FUNCTION_KIND_WASM @cold {
+ if kind == FUNCTION_KIND_HOST {
+ call_host_function(function, return_ip, context_pointer);
+ }
+ call_vector_function(function, return_ip, context_pointer);
+ }
+ let mut locals_size: u64;
+ load32(locals_size, [function, FUNCTION_LOCALS_SIZE]);
+ let mut frame_size: u64;
+ load32(frame_size, [function, FUNCTION_FRAME_SIZE]);
+ let caller_vsp: u64 = vsp;
+ let new_fp = align_down_16(caller_vsp - locals_size);
+ # The stack pointer only ever moves down while WebAssembly runs: returns leave it where the callee had it, and a
+ # frame that would end above it ends at it instead. Spilled values rely on that when they move into the new
+ # frame (see spill.rs in Flap).
+ let current_sp: u64 = sp;
+ let mut bottom = new_fp - frame_size;
+ if current_sp < bottom {
+ bottom = current_sp;
+ }
+ let mut limit: u64;
+ load64(limit, [context_pointer, CONTEXT_STACK_LIMIT]);
+ guard bottom >= limit else @cold {
+ trap_with(TRAP_STACK_EXHAUSTED, context_pointer);
+ };
+ sp = bottom;
+ store64([new_fp, FRAME_SAVED_FP], fp);
+ store64([new_fp, FRAME_RETURN_IP], return_ip);
+ store64([new_fp, FRAME_SAVED_STP], stp);
+ store64([new_fp, FRAME_FUNCTION], function);
+ store64([new_fp, FRAME_SAVED_MEMORY_BASE], memory_base);
+ store64([new_fp, FRAME_CONTEXT], context_pointer);
+ fp = new_fp;
+
+ # Copy the arguments into the first locals and clear the others.
+ let mut param_slots: u64;
+ load32(param_slots, [function, FUNCTION_PARAM_SLOTS]);
+ let arguments = stack();
+ let locals: Sequence<u64> = alias(new_fp);
+ let mut index: u64 = 0;
+ let mut source: u64 = param_slots;
+ while index < param_slots {
+ source = source - 1;
+ locals[index] = arguments[source];
+ index = index + 1;
+ }
+ let return_vsp = caller_vsp + (param_slots << 3);
+ store64([new_fp, FRAME_RETURN_VSP], return_vsp);
+ let mut local_count: u64;
+ load32(local_count, [function, FUNCTION_LOCAL_COUNT]);
+ while index < local_count {
+ locals[index] = 0;
+ index = index + 1;
+ }
+
+ let mut callee_instance: u64;
+ load64(callee_instance, [function, FUNCTION_INSTANCE]);
+ store64([new_fp, FRAME_INSTANCE], callee_instance);
+ let mut code: u64;
+ load64(code, [function, FUNCTION_CODE]);
+ let mut side_table: u64;
+ load64(side_table, [function, FUNCTION_SIDE_TABLE]);
+ let mut callee_memory_base: u64;
+ load64(callee_memory_base, [callee_instance, INSTANCE_MEMORY0_BASE]);
+ let empty_stack = new_fp - FRAME_HEADER_SIZE;
+ ip = code;
+ stp = side_table;
+ memory_base = callee_memory_base;
+ vsp = empty_stack;
+ dispatch;
+}
+
+# Move `count` slots from the top of the operand stack to just below `destination`, as the new top of the stack. The
+# slots move up, so the highest one is copied first.
+inline fn move_top_slots(count: u64, destination: u64) -> u64 {
+ let new_top = destination - (count << 3);
+ let source = stack();
+ let target: Sequence<u64> = alias(new_top);
+ let mut index: u64 = count;
+ while index != 0 {
+ index = index - 1;
+ target[index] = source[index];
+ }
+ new_top
+}
+
+# Return from the current function with its results on top of the operand stack. The results land where the
+# arguments were, which may overlap the frame header, so the header is read first.
+inline fn return_from_function() {
+ let frame: u64 = fp;
+ let mut function: u64;
+ load64(function, [frame, FRAME_FUNCTION]);
+ let mut return_vsp: u64;
+ load64(return_vsp, [frame, FRAME_RETURN_VSP]);
+ let mut return_ip: u64;
+ load64(return_ip, [frame, FRAME_RETURN_IP]);
+ ip = return_ip;
+ let mut saved_stp: u64;
+ load64(saved_stp, [frame, FRAME_SAVED_STP]);
+ stp = saved_stp;
+ let mut saved_memory_base: u64;
+ load64(saved_memory_base, [frame, FRAME_SAVED_MEMORY_BASE]);
+ memory_base = saved_memory_base;
+ let mut saved_fp: u64;
+ load64(saved_fp, [frame, FRAME_SAVED_FP]);
+ fp = saved_fp;
+ let mut result_slots: u64;
+ load32(result_slots, [function, FUNCTION_RESULT_SLOTS]);
+ let new_top = move_top_slots(result_slots, return_vsp);
+ vsp = new_top;
+ dispatch;
+}
+
+# Replace the current frame with a call to `function`, whose arguments are on top of the operand stack: move them to
+# where the current function's caller put its arguments, and call from the caller's state.
+inline fn tail_call(function: u64) {
+ let context_pointer = context();
+ let frame: u64 = fp;
+ let mut return_vsp: u64;
+ load64(return_vsp, [frame, FRAME_RETURN_VSP]);
+ let mut return_ip: u64;
+ load64(return_ip, [frame, FRAME_RETURN_IP]);
+ let mut saved_stp: u64;
+ load64(saved_stp, [frame, FRAME_SAVED_STP]);
+ stp = saved_stp;
+ let mut saved_memory_base: u64;
+ load64(saved_memory_base, [frame, FRAME_SAVED_MEMORY_BASE]);
+ memory_base = saved_memory_base;
+ let mut saved_fp: u64;
+ load64(saved_fp, [frame, FRAME_SAVED_FP]);
+ fp = saved_fp;
+ let mut param_slots: u64;
+ load32(param_slots, [function, FUNCTION_PARAM_SLOTS]);
+ let new_top = move_top_slots(param_slots, return_vsp);
+ vsp = new_top;
+ call_function(function, return_ip, context_pointer);
+}
+
+# Branches.
+
+# Take the branch whose side-table entry is at `entry`, from the instruction at `branch_ip`.
+inline fn take_branch(entry: u64, branch_ip: u64) {
+ let mut drop: u64;
+ load32(drop, [entry, 12]);
+ if drop != 0 {
+ let mut keep: u64;
+ load32(keep, [entry, 8]);
+ let top: u64 = vsp;
+ let new_top = top + (drop << 3);
+ let destination = new_top + (keep << 3);
+ let moved_top = move_top_slots(keep, destination);
+ vsp = moved_top;
+ }
+ let mut pc_delta: u64;
+ load32(pc_delta, [entry, 0]);
+ let mut stp_delta: u64;
+ load32(stp_delta, [entry, 4]);
+ let narrow_pc_delta = i32(pc_delta);
+ let signed_pc_delta = i64(narrow_pc_delta);
+ let narrow_stp_delta = i32(stp_delta);
+ let signed_stp_delta = i64(narrow_stp_delta);
+ let pc_offset: u64 = alias(signed_pc_delta);
+ let stp_offset: u64 = alias(signed_stp_delta);
+ let target_ip = branch_ip + pc_offset;
+ let target_stp = entry + (stp_offset << 4);
+ ip = target_ip;
+ stp = target_stp;
+ dispatch;
+}
+
+inline fn branch() {
+ let entry: u64 = stp;
+ let current: u64 = ip;
+ take_branch(entry, current);
+}
+
+inline fn skip_entry_and_advance(length: u64) {
+ let current_stp: u64 = stp;
+ let next_stp = current_stp + 16;
+ stp = next_stp;
+ advance(length);
+}
+
+# The pseudo-instructions the runtime enters and leaves the interpreter with.
+
+# Enter: `vsp` holds the entry record. Build a frame for the runtime below the entry frame and push the arguments.
+# The runtime's code continues with a CallEntry pseudo-instruction, which calls the function, and an Exit one, which
+# the function returns to.
+handler Enter() @opcode(0xf0) {
+ let record: u64 = vsp;
+ let mut context_pointer: u64;
+ load64(context_pointer, [record, ENTRY_CONTEXT]);
+ let mut previous_fp: u64;
+ load64(previous_fp, [context_pointer, CONTEXT_ENTRY_FP]);
+ store64([record, ENTRY_SAVED_ENTRY_FP], previous_fp);
+ let mut previous_record: u64;
+ load64(previous_record, [context_pointer, CONTEXT_ENTRY_RECORD]);
+ store64([record, ENTRY_SAVED_ENTRY_RECORD], previous_record);
+ store64([context_pointer, CONTEXT_ENTRY_FP], fp);
+ store64([context_pointer, CONTEXT_ENTRY_RECORD], record);
+ store32([record, ENTRY_TRAP], 0);
+
+ let mut function: u64;
+ load64(function, [record, ENTRY_FUNCTION]);
+ let mut param_slots: u64;
+ load32(param_slots, [function, FUNCTION_PARAM_SLOTS]);
+ let entry_sp: u64 = sp;
+ 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);
+ sp = new_sp;
+ fp = runtime_fp;
+ store64([runtime_fp, FRAME_INSTANCE], 0);
+ store64([runtime_fp, FRAME_CONTEXT], context_pointer);
+ store64([runtime_fp, FRAME_FUNCTION], function);
+ vsp = arguments_top;
+ let mut arguments_pointer: u64;
+ load64(arguments_pointer, [record, ENTRY_ARGUMENTS]);
+ let arguments: Sequence<u64> = alias(arguments_pointer);
+ let slots: Sequence<u64> = alias(arguments_top);
+ let mut index: u64 = 0;
+ while index < param_slots {
+ slots[index] = arguments[index];
+ index = index + 1;
+ }
+ advance(1);
+}
+
+# Call the function of the entry record, which Enter left in the runtime's frame.
+handler CallEntry() @opcode(0xf3) {
+ let context_pointer = context();
+ let function = frame_word(FRAME_FUNCTION);
+ let current: u64 = ip;
+ let exit_ip = current + 1;
+ call_function(function, exit_ip, context_pointer);
+}
+
+# The function returned to the runtime's frame with its results on top of the operand stack.
+handler Exit() @opcode(0xf1) {
+ let context_pointer = context();
+ let mut record: u64;
+ load64(record, [context_pointer, CONTEXT_ENTRY_RECORD]);
+ let mut function: u64;
+ load64(function, [record, ENTRY_FUNCTION]);
+ let mut result_slots: u64;
+ load32(result_slots, [function, FUNCTION_RESULT_SLOTS]);
+ let mut results_pointer: u64;
+ load64(results_pointer, [record, ENTRY_RESULTS]);
+ let results: Sequence<u64> = alias(results_pointer);
+ let values = stack();
+ let mut index: u64 = 0;
+ while index < result_slots {
+ results[index] = values[index];
+ index = index + 1;
+ }
+ leave(context_pointer, record);
+}
+
+# The runtime's fault handler continues here when a memory access faults.
+handler MemoryFault() @opcode(0xf2) {
+ trap(TRAP_MEMORY_OUT_OF_BOUNDS);
+}
+
+# Bytes that are no instruction. Validation rejects every one of them, so this is never reached.
+handler Fallback() @fallback {
+ trap(TRAP_UNREACHABLE);
+}
+
+# Control instructions.
+
+handler Unreachable() @opcode(0x00) {
+ trap(TRAP_UNREACHABLE);
+}
+
+handler Nop() @opcode(0x01) {
+ dispatch_next;
+}
+
+handler Block() @opcode(0x02) {
+ let length = block_type_length(immediates());
+ advance(length + 1);
+}
+
+handler Loop() @opcode(0x03) {
+ let length = block_type_length(immediates());
+ advance(length + 1);
+}
+
+handler If() @opcode(0x04) {
+ let condition = pop32();
+ if condition == 0 {
+ branch();
+ }
+ let length = block_type_length(immediates());
+ skip_entry_and_advance(length + 1);
+}
+
+# Reached at the end of an if's first arm: skip the second one.
+handler Else() @opcode(0x05) {
+ branch();
+}
+
+handler End() @opcode(0x0b) {
+ let frame: u64 = fp;
+ let mut function: u64;
+ load64(function, [frame, FRAME_FUNCTION]);
+ let mut code_end: u64;
+ load64(code_end, [function, FUNCTION_CODE_END]);
+ let current: u64 = ip;
+ if current == code_end {
+ return_from_function();
+ }
+ dispatch_next;
+}
+
+handler Br() @opcode(0x0c) {
+ branch();
+}
+
+handler BrIf() @opcode(0x0d) {
+ let condition = pop32();
+ if condition != 0 {
+ branch();
+ }
+ let length = leb_length(immediates());
+ skip_entry_and_advance(length + 1);
+}
+
+handler BrTable() @opcode(0x0e) {
+ let [count, _] = read_leb(immediates());
+ let popped = pop32();
+ let index: u64 = alias(popped);
+ let mut chosen = index;
+ if index > count {
+ chosen = count;
+ }
+ let first: u64 = stp;
+ let entry = first + (chosen << 4);
+ let current: u64 = ip;
+ take_branch(entry, current);
+}
+
+handler Return() @opcode(0x0f) {
+ return_from_function();
+}
+
+inline fn function_at(index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut functions_pointer: u64;
+ load64(functions_pointer, [instance_pointer, INSTANCE_FUNCTIONS]);
+ let functions: Sequence<u64> = alias(functions_pointer);
+ functions[index]
+}
+
+handler Call() @opcode(0x10) {
+ let [function_index, length] = read_leb(immediates());
+ let function = function_at(function_index);
+ let current: u64 = ip;
+ let return_ip = current + length + 1;
+ call_function(function, return_ip, context());
+}
+
+# The function a call_indirect calls, after checking that it exists and has the expected type.
+inline fn indirect_callee(bytes: Sequence<u8>) -> (u64, u64) {
+ let [type_index, type_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let table_bytes: Sequence<u8> = alias(start + type_length);
+ let [table_index, table_length] = read_leb(table_bytes);
+ let element = pop();
+ let instance_pointer = instance();
+ let mut tables_pointer: u64;
+ load64(tables_pointer, [instance_pointer, INSTANCE_TABLES]);
+ let tables: Sequence<u64> = alias(tables_pointer);
+ let table = tables[table_index];
+ let mut size: u64;
+ load64(size, [table, TABLE_SIZE]);
+ guard element < size else @cold {
+ trap(TRAP_UNDEFINED_ELEMENT);
+ };
+ let mut elements_pointer: u64;
+ load64(elements_pointer, [table, TABLE_ELEMENTS]);
+ let elements: Sequence<u64> = alias(elements_pointer);
+ let function = elements[element];
+ guard function != 0 else @cold {
+ trap(TRAP_UNINITIALIZED_ELEMENT);
+ };
+ let mut identities_pointer: u64;
+ load64(identities_pointer, [instance_pointer, INSTANCE_TYPE_IDENTITIES]);
+ let identities: Sequence<u32> = alias(identities_pointer);
+ let expected = identities[type_index];
+ let mut actual: u32;
+ load32(actual, [function, FUNCTION_TYPE_IDENTITY]);
+ if actual != expected @cold {
+ # A function whose type is a subtype of the expected one may be called too.
+ let wide_actual: u64 = alias(actual);
+ let wide_expected: u64 = alias(expected);
+ let actual_rtt = rtt_of_identity(wide_actual);
+ let matches = rtt_is_subtype(actual_rtt, wide_expected);
+ guard matches != 0 else @cold {
+ trap(TRAP_INDIRECT_CALL_TYPE_MISMATCH);
+ };
+ }
+ (function, type_length + table_length)
+}
+
+handler CallIndirect() @opcode(0x11) {
+ let [function, length] = indirect_callee(immediates());
+ let current: u64 = ip;
+ let return_ip = current + length + 1;
+ call_function(function, return_ip, context());
+}
+
+handler ReturnCall() @opcode(0x12) {
+ let [function_index, _] = read_leb(immediates());
+ let function = function_at(function_index);
+ tail_call(function);
+}
+
+handler ReturnCallIndirect() @opcode(0x13) {
+ let [function, _] = indirect_callee(immediates());
+ tail_call(function);
+}
+
+handler CallRef() @opcode(0x14) {
+ let length = leb_length(immediates());
+ let function = pop();
+ guard function != 0 else @cold {
+ trap(TRAP_NULL_REFERENCE);
+ };
+ let current: u64 = ip;
+ let return_ip = current + length + 1;
+ call_function(function, return_ip, context());
+}
+
+handler ReturnCallRef() @opcode(0x15) {
+ let function = pop();
+ guard function != 0 else @cold {
+ trap(TRAP_NULL_REFERENCE);
+ };
+ tail_call(function);
+}
+
+handler Drop() @opcode(0x1a) {
+ drop_slots(1);
+ dispatch_next;
+}
+
+handler Select() @opcode(0x1b) {
+ let condition = pop32();
+ let [first, second] = binary_operands();
+ if condition == 0 {
+ set_top(second);
+ }
+ dispatch_next;
+}
+
+handler SelectTyped() @opcode(0x1c) {
+ let bytes = immediates();
+ let type_byte: u64 = alias(bytes[1]);
+ let length = leb_length(bytes);
+ let current: u64 = ip;
+ let mut type_length: u64 = 1;
+ if type_byte >= 0x63 @cold {
+ if type_byte <= 0x64 {
+ let heap_bytes: Sequence<u8> = alias(current + 3);
+ let heap_length = leb_length(heap_bytes);
+ type_length = heap_length + 1;
+ }
+ }
+ let condition = pop32();
+ if type_byte == 0x7b @cold {
+ # A v128 takes two slots.
+ if condition == 0 {
+ let slots = stack();
+ slots[2] = slots[0];
+ slots[3] = slots[1];
+ }
+ drop_slots(2);
+ advance(1 + length + type_length);
+ }
+ let [first, second] = binary_operands();
+ if condition == 0 {
+ set_top(second);
+ }
+ advance(1 + length + type_length);
+}
+
+# Locals and globals.
+
+handler LocalGet() @opcode(0x20) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let value = locals[index];
+ push(value);
+ advance(length + 1);
+}
+
+handler LocalSet() @opcode(0x21) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let value = pop();
+ locals[index] = value;
+ advance(length + 1);
+}
+
+handler LocalTee() @opcode(0x22) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let value = unary_operand();
+ locals[index] = value;
+ advance(length + 1);
+}
+
+inline fn global_address(index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut globals_pointer: u64;
+ load64(globals_pointer, [instance_pointer, INSTANCE_GLOBALS]);
+ let globals: Sequence<u64> = alias(globals_pointer);
+ globals[index]
+}
+
+handler GlobalGet() @opcode(0x23) {
+ let [index, length] = read_leb(immediates());
+ let address = global_address(index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ push(value);
+ advance(length + 1);
+}
+
+handler GlobalSet() @opcode(0x24) {
+ let [index, length] = read_leb(immediates());
+ let address = global_address(index);
+ let value = pop();
+ store64([address, 0], value);
+ advance(length + 1);
+}
+
+# Tables.
+
+inline fn table_at(index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut tables_pointer: u64;
+ load64(tables_pointer, [instance_pointer, INSTANCE_TABLES]);
+ let tables: Sequence<u64> = alias(tables_pointer);
+ tables[index]
+}
+
+inline fn table_element_address(table: u64, index: u64) -> u64 {
+ let mut size: u64;
+ load64(size, [table, TABLE_SIZE]);
+ guard index < size else @cold {
+ trap(TRAP_TABLE_OUT_OF_BOUNDS);
+ };
+ let mut elements: u64;
+ load64(elements, [table, TABLE_ELEMENTS]);
+ elements + (index << 3)
+}
+
+handler TableGet() @opcode(0x25) {
+ let [table_index, length] = read_leb(immediates());
+ let table = table_at(table_index);
+ let index = unary_operand();
+ let address = table_element_address(table, index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length + 1);
+}
+
+handler TableSet() @opcode(0x26) {
+ let [table_index, length] = read_leb(immediates());
+ let table = table_at(table_index);
+ let [index, value] = binary_operands();
+ drop_slots(1);
+ let address = table_element_address(table, index);
+ store64([address, 0], value);
+ advance(length + 1);
+}
+
+# Memory 0. The memory is reserved with guard pages for every address and offset a memory32 access can form, so an
+# out-of-bounds access faults, and the runtime's fault handler turns that into a trap. Other memories check bounds.
+
+inline fn memory_at(index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut memories_pointer: u64;
+ load64(memories_pointer, [instance_pointer, INSTANCE_MEMORIES]);
+ let memories: Sequence<u64> = alias(memories_pointer);
+ memories[index]
+}
+
+# Check that `size` bytes from `address` are in the memory, and return their address.
+inline fn checked_memory_address(memory: u64, address: u64, size: u64) -> u64 {
+ let mut memory_size: u64;
+ load64(memory_size, [memory, MEMORY_SIZE]);
+ let end = address + size;
+ guard end >= address else @cold {
+ trap(TRAP_MEMORY_OUT_OF_BOUNDS);
+ };
+ guard end <= memory_size else @cold {
+ trap(TRAP_MEMORY_OUT_OF_BOUNDS);
+ };
+ let mut base: u64;
+ load64(base, [memory, MEMORY_BASE]);
+ base + address
+}
+
+# The address of a `size`-byte memory access, and the length of the instruction.
+# The address of an access to memory 0, and the length of the instruction. Accesses that cannot rely on memory 0's
+# guard pages were quickened into checked forms (see quickening.rs), so the alignment is followed by the offset.
+inline fn memory_address(address_operand: u64, size: u64) -> (u64, u64) {
+ let current: u64 = ip;
+ let offset_bytes: Sequence<u8> = alias(current + 2);
+ let [offset, offset_length] = read_leb(offset_bytes);
+ let index: u64 = alias(u32(address_operand));
+ let base: u64 = memory_base;
+ let address = base + index + offset;
+ (address, offset_length + 2)
+}
+
+# The address of a quickened, bounds-checked access of `size` bytes (`0xFF sub [memory] offset`), and the length of
+# its immediates after the sub-opcode.
+inline fn checked_access_address(address_operand: u64, size: u64, has_memory_index: u64) -> (u64, u64) {
+ let current: u64 = ip;
+ let mut memory_index: u64 = 0;
+ let mut index_length: u64 = 0;
+ if has_memory_index != 0 {
+ let index_bytes: Sequence<u8> = alias(current + 2);
+ let [decoded_index, decoded_length] = read_leb(index_bytes);
+ memory_index = decoded_index;
+ index_length = decoded_length;
+ }
+ let offset_bytes: Sequence<u8> = alias(current + 2 + index_length);
+ let [offset, offset_length] = read_leb(offset_bytes);
+ let memory = memory_at(memory_index);
+ let effective = address_operand + offset;
+ guard effective >= address_operand else @cold {
+ trap(TRAP_MEMORY_OUT_OF_BOUNDS);
+ };
+ let address = checked_memory_address(memory, effective, size);
+ (address, index_length + offset_length + 2)
+}
+
+handler Quickened() @opcode(0xff) {
+ let bytes = immediates();
+ let sub_opcode: u64 = alias(bytes[0]);
+ dispatch_secondary(0xff, sub_opcode);
+}
+
+inline fn store_operands() -> (u64, u64) {
+ let [address_operand, value] = binary_operands();
+ drop_slots(1);
+ (address_operand, value)
+}
+
+
+handler I32Load() @opcode(0x28) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 4);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I64Load() @opcode(0x29) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 8);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler F32Load() @opcode(0x2a) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 4);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler F64Load() @opcode(0x2b) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 8);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I32Load8S() @opcode(0x2c) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 1);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler I32Load8U() @opcode(0x2d) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 1);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I32Load16S() @opcode(0x2e) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 2);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler I32Load16U() @opcode(0x2f) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 2);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I64Load8S() @opcode(0x30) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 1);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler I64Load8U() @opcode(0x31) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 1);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I64Load16S() @opcode(0x32) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 2);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler I64Load16U() @opcode(0x33) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 2);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I64Load32S() @opcode(0x34) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 4);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler I64Load32U() @opcode(0x35) {
+ let address_operand = unary_operand();
+ let [address, length] = memory_address(address_operand, 4);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler I32Store() @opcode(0x36) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 4);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler I64Store() @opcode(0x37) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 8);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler F32Store() @opcode(0x38) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 4);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler F64Store() @opcode(0x39) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 8);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler I32Store8() @opcode(0x3a) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 1);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler I32Store16() @opcode(0x3b) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 2);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler I64Store8() @opcode(0x3c) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 1);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler I64Store16() @opcode(0x3d) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 2);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler I64Store32() @opcode(0x3e) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = memory_address(address_operand, 4);
+ store32([address, 0], value);
+ advance(length);
+}
+
+# Bounds-checked accesses, for other memories and for memory64 (quickening rule 1). The sub-opcode is the original
+# opcode, plus 0x40 if a memory index follows.
+
+handler CheckedI32Load() @opcode(0xff, 0x28) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32LoadIndexed() @opcode(0xff, 0x68) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load() @opcode(0xff, 0x29) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64LoadIndexed() @opcode(0xff, 0x69) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedF32Load() @opcode(0xff, 0x2a) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedF32LoadIndexed() @opcode(0xff, 0x6a) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedF64Load() @opcode(0xff, 0x2b) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedF64LoadIndexed() @opcode(0xff, 0x6b) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32Load8S() @opcode(0xff, 0x2c) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI32Load8SIndexed() @opcode(0xff, 0x6c) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI32Load8U() @opcode(0xff, 0x2d) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32Load8UIndexed() @opcode(0xff, 0x6d) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32Load16S() @opcode(0xff, 0x2e) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI32Load16SIndexed() @opcode(0xff, 0x6e) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = u32(value);
+ let extended: u64 = alias(narrow);
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI32Load16U() @opcode(0xff, 0x2f) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32Load16UIndexed() @opcode(0xff, 0x6f) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load8S() @opcode(0xff, 0x30) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load8SIndexed() @opcode(0xff, 0x70) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let mut value: u64;
+ load8s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load8U() @opcode(0xff, 0x31) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load8UIndexed() @opcode(0xff, 0x71) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load16S() @opcode(0xff, 0x32) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load16SIndexed() @opcode(0xff, 0x72) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let mut value: u64;
+ load16s(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load16U() @opcode(0xff, 0x33) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load16UIndexed() @opcode(0xff, 0x73) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load32S() @opcode(0xff, 0x34) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load32SIndexed() @opcode(0xff, 0x74) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let narrow = i32(value);
+ let extended: u64 = alias(i64(narrow));
+ set_top(extended);
+ advance(length);
+}
+
+handler CheckedI64Load32U() @opcode(0xff, 0x35) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI64Load32UIndexed() @opcode(0xff, 0x75) {
+ let address_operand = unary_operand();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler CheckedI32Store() @opcode(0xff, 0x36) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI32StoreIndexed() @opcode(0xff, 0x76) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store() @opcode(0xff, 0x37) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64StoreIndexed() @opcode(0xff, 0x77) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler CheckedF32Store() @opcode(0xff, 0x38) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler CheckedF32StoreIndexed() @opcode(0xff, 0x78) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler CheckedF64Store() @opcode(0xff, 0x39) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler CheckedF64StoreIndexed() @opcode(0xff, 0x79) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ store64([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI32Store8() @opcode(0xff, 0x3a) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI32Store8Indexed() @opcode(0xff, 0x7a) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI32Store16() @opcode(0xff, 0x3b) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI32Store16Indexed() @opcode(0xff, 0x7b) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store8() @opcode(0xff, 0x3c) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store8Indexed() @opcode(0xff, 0x7c) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ store8([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store16() @opcode(0xff, 0x3d) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store16Indexed() @opcode(0xff, 0x7d) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ store16([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store32() @opcode(0xff, 0x3e) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler CheckedI64Store32Indexed() @opcode(0xff, 0x7e) {
+ let [address_operand, value] = store_operands();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ store32([address, 0], value);
+ advance(length);
+}
+
+handler MemorySize() @opcode(0x3f) {
+ let [memory_index, length] = read_leb(immediates());
+ let memory = memory_at(memory_index);
+ let mut size: u64;
+ load64(size, [memory, MEMORY_SIZE]);
+ push(size >> 16);
+ advance(length + 1);
+}
+
+handler MemoryGrow() @opcode(0x40) {
+ let [memory_index, length] = read_leb(immediates());
+ let memory = memory_at(memory_index);
+ let delta = unary_operand();
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], memory);
+ store64([context_pointer, CONTEXT_ARGUMENT_1], delta);
+ let previous: u64 = call_helper(wasm_runtime_memory_grow, context_pointer);
+ # The result is an i64 for a memory64, whose -1 must not be truncated.
+ let grown_memory = memory_at(memory_index);
+ let mut address64: u64;
+ load64(address64, [grown_memory, MEMORY_ADDRESS64]);
+ let mut result: u64 = previous;
+ if address64 == 0 {
+ let narrow = u32(previous);
+ result = alias(narrow);
+ }
+ set_top(result);
+ advance(length + 1);
+}
+
+handler I32Const() @opcode(0x41) {
+ let [value, length] = read_signed_leb(immediates());
+ let narrow = u32(value);
+ let wide: u64 = alias(narrow);
+ push(wide);
+ advance(length + 1);
+}
+
+handler I64Const() @opcode(0x42) {
+ let [value, length] = read_signed_leb(immediates());
+ push(value);
+ advance(length + 1);
+}
+
+handler F32Const() @opcode(0x43) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push(value);
+ advance(5);
+}
+
+handler F64Const() @opcode(0x44) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load64(value, [current, 1]);
+ push(value);
+ advance(9);
+}
+
+
+handler I32Eqz() @opcode(0x45) {
+ let operand = u32(unary_operand());
+ let mut value: u64 = 0;
+ if operand == 0 {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32Eq() @opcode(0x46) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a == b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32Ne() @opcode(0x47) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a != b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32LtS() @opcode(0x48) {
+ let [lhs, rhs] = binary_operands();
+ let a = i32(lhs);
+ let b = i32(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32LtU() @opcode(0x49) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32GtS() @opcode(0x4a) {
+ let [lhs, rhs] = binary_operands();
+ let a = i32(lhs);
+ let b = i32(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32GtU() @opcode(0x4b) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32LeS() @opcode(0x4c) {
+ let [lhs, rhs] = binary_operands();
+ let a = i32(lhs);
+ let b = i32(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32LeU() @opcode(0x4d) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32GeS() @opcode(0x4e) {
+ let [lhs, rhs] = binary_operands();
+ let a = i32(lhs);
+ let b = i32(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I32GeU() @opcode(0x4f) {
+ let [lhs, rhs] = binary_operands();
+ let a = u32(lhs);
+ let b = u32(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64Eqz() @opcode(0x50) {
+ let operand = unsigned64(unary_operand());
+ let mut value: u64 = 0;
+ if operand == 0 {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64Eq() @opcode(0x51) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a == b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64Ne() @opcode(0x52) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a != b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64LtS() @opcode(0x53) {
+ let [lhs, rhs] = binary_operands();
+ let a = signed64(lhs);
+ let b = signed64(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64LtU() @opcode(0x54) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64GtS() @opcode(0x55) {
+ let [lhs, rhs] = binary_operands();
+ let a = signed64(lhs);
+ let b = signed64(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64GtU() @opcode(0x56) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64LeS() @opcode(0x57) {
+ let [lhs, rhs] = binary_operands();
+ let a = signed64(lhs);
+ let b = signed64(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64LeU() @opcode(0x58) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64GeS() @opcode(0x59) {
+ let [lhs, rhs] = binary_operands();
+ let a = signed64(lhs);
+ let b = signed64(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler I64GeU() @opcode(0x5a) {
+ let [lhs, rhs] = binary_operands();
+ let a = unsigned64(lhs);
+ let b = unsigned64(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Eq() @opcode(0x5b) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a == b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Ne() @opcode(0x5c) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a != b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Lt() @opcode(0x5d) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Gt() @opcode(0x5e) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Le() @opcode(0x5f) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F32Ge() @opcode(0x60) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Eq() @opcode(0x61) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a == b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Ne() @opcode(0x62) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a != b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Lt() @opcode(0x63) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a < b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Gt() @opcode(0x64) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a > b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Le() @opcode(0x65) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a <= b {
+ value = 1;
+ }
+ result(value);
+}
+
+handler F64Ge() @opcode(0x66) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = 0;
+ if a >= b {
+ value = 1;
+ }
+ result(value);
+}
+# Floats are kept as their bits. f32 comparisons and roundings go through f64, which holds every f32 exactly.
+
+inline fn f32_value(bits: u64) -> f64 {
+ let narrow = u32(bits);
+ let single = f32_from_bits(narrow);
+ promote_f32(single)
+}
+
+inline fn f32_operand(bits: u64) -> f32 {
+ let narrow = u32(bits);
+ f32_from_bits(narrow)
+}
+
+inline fn f64_value(bits: u64) -> f64 {
+ f64_from_bits(bits)
+}
+
+inline fn f32_result(value: f32) {
+ let bits = f32_to_bits(value);
+ result32(bits);
+}
+
+inline fn f64_result(value: f64) {
+ let bits = f64_to_bits(value);
+ result(bits);
+}
+
+
+handler I32Clz() @opcode(0x67) {
+ let operand = unary32();
+ let value = clz32(operand);
+ result32(value);
+}
+
+handler I32Ctz() @opcode(0x68) {
+ let operand = unary32();
+ let value = ctz32(operand);
+ result32(value);
+}
+
+handler I32Popcnt() @opcode(0x69) {
+ let operand = unary32();
+ let value = popcnt32(operand);
+ result32(value);
+}
+
+handler I32Add() @opcode(0x6a) {
+ let [lhs, rhs] = binary32();
+ let value = lhs + rhs;
+ result32(value);
+}
+
+handler I32Sub() @opcode(0x6b) {
+ let [lhs, rhs] = binary32();
+ let value = lhs - rhs;
+ result32(value);
+}
+
+handler I32Mul() @opcode(0x6c) {
+ let [lhs, rhs] = binary32();
+ let value = lhs * rhs;
+ result32(value);
+}
+
+handler I32And() @opcode(0x71) {
+ let [lhs, rhs] = binary32();
+ let value = lhs & rhs;
+ result32(value);
+}
+
+handler I32Or() @opcode(0x72) {
+ let [lhs, rhs] = binary32();
+ let value = lhs | rhs;
+ result32(value);
+}
+
+handler I32Xor() @opcode(0x73) {
+ let [lhs, rhs] = binary32();
+ let value = lhs ^ rhs;
+ result32(value);
+}
+
+handler I32DivS() @opcode(0x6d) {
+ let [lhs, rhs] = binary32();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ if rhs == 0xffffffff @cold {
+ guard lhs != 0x80000000 else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ }
+ let value = div_s32(lhs, rhs);
+ result32(value);
+}
+
+handler I32DivU() @opcode(0x6e) {
+ let [lhs, rhs] = binary32();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ let value = div_u32(lhs, rhs);
+ result32(value);
+}
+
+handler I32RemS() @opcode(0x6f) {
+ let [lhs, rhs] = binary32();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ # The remainder of dividing by -1 is 0, but the division of the smallest value by it would fault.
+ if rhs == 0xffffffff @cold {
+ result(0);
+ }
+ let value = rem_s32(lhs, rhs);
+ result32(value);
+}
+
+handler I32RemU() @opcode(0x70) {
+ let [lhs, rhs] = binary32();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ let value = rem_u32(lhs, rhs);
+ result32(value);
+}
+
+handler I32Shl() @opcode(0x74) {
+ let [lhs, rhs] = binary32();
+ let value = lhs << (rhs & 31);
+ result32(value);
+}
+
+handler I32ShrS() @opcode(0x75) {
+ let [lhs, rhs] = binary32();
+ let narrow = i32(lhs);
+ let wide = i64(narrow);
+ let count = rhs & 31;
+ let signed_count = i64(i32(count));
+ let shifted = wide >> signed_count;
+ let value = u32(shifted);
+ result32(value);
+}
+
+handler I32ShrU() @opcode(0x76) {
+ let [lhs, rhs] = binary32();
+ let value = lhs >> (rhs & 31);
+ result32(value);
+}
+
+handler I32Rotl() @opcode(0x77) {
+ let [lhs, rhs] = binary32();
+ let value = rotl32(lhs, rhs);
+ result32(value);
+}
+
+handler I32Rotr() @opcode(0x78) {
+ let [lhs, rhs] = binary32();
+ let value = rotr32(lhs, rhs);
+ result32(value);
+}
+
+handler I64Clz() @opcode(0x79) {
+ let operand = unary_operand();
+ let value = clz64(operand);
+ result(value);
+}
+
+handler I64Ctz() @opcode(0x7a) {
+ let operand = unary_operand();
+ let value = ctz64(operand);
+ result(value);
+}
+
+handler I64Popcnt() @opcode(0x7b) {
+ let operand = unary_operand();
+ let value = popcnt64(operand);
+ result(value);
+}
+
+handler I64Add() @opcode(0x7c) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs + rhs;
+ result(value);
+}
+
+handler I64Sub() @opcode(0x7d) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs - rhs;
+ result(value);
+}
+
+handler I64Mul() @opcode(0x7e) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs * rhs;
+ result(value);
+}
+
+handler I64And() @opcode(0x83) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs & rhs;
+ result(value);
+}
+
+handler I64Or() @opcode(0x84) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs | rhs;
+ result(value);
+}
+
+handler I64Xor() @opcode(0x85) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs ^ rhs;
+ result(value);
+}
+
+handler I64DivS() @opcode(0x7f) {
+ let [lhs, rhs] = binary_operands();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ if rhs == 0xffffffffffffffff @cold {
+ guard lhs != 0x8000000000000000 else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ }
+ let value = div_s64(lhs, rhs);
+ result(value);
+}
+
+handler I64DivU() @opcode(0x80) {
+ let [lhs, rhs] = binary_operands();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ let value = div_u64(lhs, rhs);
+ result(value);
+}
+
+handler I64RemS() @opcode(0x81) {
+ let [lhs, rhs] = binary_operands();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ if rhs == 0xffffffffffffffff @cold {
+ result(0);
+ }
+ let value = rem_s64(lhs, rhs);
+ result(value);
+}
+
+handler I64RemU() @opcode(0x82) {
+ let [lhs, rhs] = binary_operands();
+ guard rhs != 0 else @cold {
+ trap(TRAP_INTEGER_DIVIDE_BY_ZERO);
+ };
+ let value = rem_u64(lhs, rhs);
+ result(value);
+}
+
+handler I64Shl() @opcode(0x86) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs << (rhs & 63);
+ result(value);
+}
+
+handler I64ShrS() @opcode(0x87) {
+ let [lhs, rhs] = binary_operands();
+ let signed = signed64(lhs);
+ let count = signed64(rhs & 63);
+ let shifted = signed >> count;
+ let value: u64 = alias(shifted);
+ result(value);
+}
+
+handler I64ShrU() @opcode(0x88) {
+ let [lhs, rhs] = binary_operands();
+ let value = lhs >> (rhs & 63);
+ result(value);
+}
+
+handler I64Rotl() @opcode(0x89) {
+ let [lhs, rhs] = binary_operands();
+ let value = rotl64(lhs, rhs);
+ result(value);
+}
+
+handler I64Rotr() @opcode(0x8a) {
+ let [lhs, rhs] = binary_operands();
+ let value = rotr64(lhs, rhs);
+ result(value);
+}
+
+handler F32Abs() @opcode(0x8b) {
+ let operand = unary32();
+ let value = operand & 0x7fffffff;
+ result32(value);
+}
+
+handler F32Neg() @opcode(0x8c) {
+ let operand = unary32();
+ let value = operand ^ 0x80000000;
+ result32(value);
+}
+
+handler F32Ceil() @opcode(0x8d) {
+ let operand = f32_value(unary_operand());
+ let rounded = ceil_f64(operand);
+ let value = demote_f64(rounded);
+ f32_result(value);
+}
+
+handler F32Floor() @opcode(0x8e) {
+ let operand = f32_value(unary_operand());
+ let rounded = floor_f64(operand);
+ let value = demote_f64(rounded);
+ f32_result(value);
+}
+
+handler F32Trunc() @opcode(0x8f) {
+ let operand = f32_value(unary_operand());
+ let rounded = trunc_f64(operand);
+ let value = demote_f64(rounded);
+ f32_result(value);
+}
+
+handler F32Nearest() @opcode(0x90) {
+ let operand = f32_value(unary_operand());
+ let rounded = nearest_f64(operand);
+ let value = demote_f64(rounded);
+ f32_result(value);
+}
+
+handler F32Sqrt() @opcode(0x91) {
+ let operand = f32_operand(unary_operand());
+ let value = sqrt_f32(operand);
+ f32_result(value);
+}
+
+handler F32Add() @opcode(0x92) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_operand(lhs);
+ let b = f32_operand(rhs);
+ let value = add_f32(a, b);
+ f32_result(value);
+}
+
+handler F32Sub() @opcode(0x93) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_operand(lhs);
+ let b = f32_operand(rhs);
+ let value = sub_f32(a, b);
+ f32_result(value);
+}
+
+handler F32Mul() @opcode(0x94) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_operand(lhs);
+ let b = f32_operand(rhs);
+ let value = mul_f32(a, b);
+ f32_result(value);
+}
+
+handler F32Div() @opcode(0x95) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_operand(lhs);
+ let b = f32_operand(rhs);
+ let value = div_f32(a, b);
+ f32_result(value);
+}
+
+handler F32Min() @opcode(0x96) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = lhs;
+ if b < a {
+ value = rhs;
+ }
+ if a == b {
+ # Equal values only differ in the sign of zero, which the minimum takes from either operand that has it.
+ value = lhs | rhs;
+ }
+ if a != a @cold {
+ let x = f32_operand(lhs);
+ let y = f32_operand(rhs);
+ let sum = add_f32(x, y);
+ let nan_bits = f32_to_bits(sum);
+ let wide_nan: u64 = alias(nan_bits);
+ value = wide_nan;
+ }
+ if b != b @cold {
+ let x = f32_operand(lhs);
+ let y = f32_operand(rhs);
+ let sum = add_f32(x, y);
+ let nan_bits = f32_to_bits(sum);
+ let wide_nan: u64 = alias(nan_bits);
+ value = wide_nan;
+ }
+ result(value);
+}
+
+handler F32Max() @opcode(0x97) {
+ let [lhs, rhs] = binary_operands();
+ let a = f32_value(lhs);
+ let b = f32_value(rhs);
+ let mut value: u64 = lhs;
+ if b > a {
+ value = rhs;
+ }
+ if a == b {
+ # Equal values only differ in the sign of zero, which the minimum takes from either operand that has it.
+ value = lhs & rhs;
+ }
+ if a != a @cold {
+ let x = f32_operand(lhs);
+ let y = f32_operand(rhs);
+ let sum = add_f32(x, y);
+ let nan_bits = f32_to_bits(sum);
+ let wide_nan: u64 = alias(nan_bits);
+ value = wide_nan;
+ }
+ if b != b @cold {
+ let x = f32_operand(lhs);
+ let y = f32_operand(rhs);
+ let sum = add_f32(x, y);
+ let nan_bits = f32_to_bits(sum);
+ let wide_nan: u64 = alias(nan_bits);
+ value = wide_nan;
+ }
+ result(value);
+}
+
+handler F32Copysign() @opcode(0x98) {
+ let [lhs, rhs] = binary32();
+ let value = (lhs & 0x7fffffff) | (rhs & 0x80000000);
+ result32(value);
+}
+
+handler F64Abs() @opcode(0x99) {
+ let operand = unary_operand();
+ let value = operand & 0x7fffffffffffffff;
+ result(value);
+}
+
+handler F64Neg() @opcode(0x9a) {
+ let operand = unary_operand();
+ let value = operand ^ 0x8000000000000000;
+ result(value);
+}
+
+handler F64Ceil() @opcode(0x9b) {
+ let operand = f64_value(unary_operand());
+ let value = ceil_f64(operand);
+ f64_result(value);
+}
+
+handler F64Floor() @opcode(0x9c) {
+ let operand = f64_value(unary_operand());
+ let value = floor_f64(operand);
+ f64_result(value);
+}
+
+handler F64Trunc() @opcode(0x9d) {
+ let operand = f64_value(unary_operand());
+ let value = trunc_f64(operand);
+ f64_result(value);
+}
+
+handler F64Nearest() @opcode(0x9e) {
+ let operand = f64_value(unary_operand());
+ let value = nearest_f64(operand);
+ f64_result(value);
+}
+
+handler F64Sqrt() @opcode(0x9f) {
+ let operand = f64_value(unary_operand());
+ let value = sqrt_f64(operand);
+ f64_result(value);
+}
+
+handler F64Add() @opcode(0xa0) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let value = a + b;
+ f64_result(value);
+}
+
+handler F64Sub() @opcode(0xa1) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let value = a - b;
+ f64_result(value);
+}
+
+handler F64Mul() @opcode(0xa2) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let value = a * b;
+ f64_result(value);
+}
+
+handler F64Div() @opcode(0xa3) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let value = a / b;
+ f64_result(value);
+}
+
+handler F64Min() @opcode(0xa4) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = lhs;
+ if b < a {
+ value = rhs;
+ }
+ if a == b {
+ # Equal values only differ in the sign of zero, which the minimum takes from either operand that has it.
+ value = lhs | rhs;
+ }
+ if a != a @cold {
+ let x = f64_value(lhs);
+ let y = f64_value(rhs);
+ let sum = x + y;
+ value = f64_to_bits(sum);
+ }
+ if b != b @cold {
+ let x = f64_value(lhs);
+ let y = f64_value(rhs);
+ let sum = x + y;
+ value = f64_to_bits(sum);
+ }
+ result(value);
+}
+
+handler F64Max() @opcode(0xa5) {
+ let [lhs, rhs] = binary_operands();
+ let a = f64_value(lhs);
+ let b = f64_value(rhs);
+ let mut value: u64 = lhs;
+ if b > a {
+ value = rhs;
+ }
+ if a == b {
+ # Equal values only differ in the sign of zero, which the minimum takes from either operand that has it.
+ value = lhs & rhs;
+ }
+ if a != a @cold {
+ let x = f64_value(lhs);
+ let y = f64_value(rhs);
+ let sum = x + y;
+ value = f64_to_bits(sum);
+ }
+ if b != b @cold {
+ let x = f64_value(lhs);
+ let y = f64_value(rhs);
+ let sum = x + y;
+ value = f64_to_bits(sum);
+ }
+ result(value);
+}
+
+handler F64Copysign() @opcode(0xa6) {
+ let [lhs, rhs] = binary_operands();
+ let value = (lhs & 0x7fffffffffffffff) | (rhs & 0x8000000000000000);
+ result(value);
+}
+# Conversions.
+
+# Truncate a float to an integer, trapping unless the result is in the open interval (lower, upper).
+inline fn checked_truncation(value: f64, lower: u64, upper: u64) -> f64 {
+ guard value == value else @cold {
+ trap(TRAP_INVALID_CONVERSION);
+ };
+ let lower_bound = f64_from_bits(lower);
+ let upper_bound = f64_from_bits(upper);
+ guard value > lower_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ guard value < upper_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ value
+}
+
+# Truncate a non-negative float below 2^64 to an unsigned 64-bit integer.
+inline fn truncate_unsigned64(value: f64) -> u64 {
+ let two_to_63 = f64_from_bits(0x43e0000000000000);
+ let mut truncated = truncate_f64_to_s64(value);
+ if value >= two_to_63 @cold {
+ let reduced = value - two_to_63;
+ let low = truncate_f64_to_s64(reduced);
+ truncated = low ^ 0x8000000000000000;
+ }
+ truncated
+}
+
+# Truncate a float with saturation: NaN becomes zero, and values out of range the nearest bound. The result is in
+# range if the value is in the open interval (lower, upper).
+inline fn saturating_truncation(value: f64, lower: u64, upper: u64, minimum: u64, maximum: u64, unsigned: u64) -> u64 {
+ let mut truncated: u64 = minimum;
+ let lower_bound = f64_from_bits(lower);
+ if value > lower_bound {
+ truncated = maximum;
+ let upper_bound = f64_from_bits(upper);
+ if value < upper_bound {
+ if unsigned != 0 {
+ truncated = truncate_unsigned64(value);
+ } else {
+ truncated = truncate_f64_to_s64(value);
+ }
+ }
+ }
+ if value != value {
+ truncated = 0;
+ }
+ truncated
+}
+
+handler I32WrapI64() @opcode(0xa7) {
+ let value = unary32();
+ result32(value);
+}
+
+handler I32TruncF32S() @opcode(0xa8) {
+ let operand = f32_value(unary_operand());
+ let checked = checked_truncation(operand, 0xc1e0000000200000, 0x41e0000000000000);
+ let truncated = truncate_f64_to_s64(checked);
+ let value = u32(truncated);
+ result32(value);
+}
+
+handler I32TruncF32U() @opcode(0xa9) {
+ let operand = f32_value(unary_operand());
+ let checked = checked_truncation(operand, 0xbff0000000000000, 0x41f0000000000000);
+ let truncated = truncate_f64_to_s64(checked);
+ let value = u32(truncated);
+ result32(value);
+}
+
+handler I32TruncF64S() @opcode(0xaa) {
+ let operand = f64_value(unary_operand());
+ let checked = checked_truncation(operand, 0xc1e0000000200000, 0x41e0000000000000);
+ let truncated = truncate_f64_to_s64(checked);
+ let value = u32(truncated);
+ result32(value);
+}
+
+handler I32TruncF64U() @opcode(0xab) {
+ let operand = f64_value(unary_operand());
+ let checked = checked_truncation(operand, 0xbff0000000000000, 0x41f0000000000000);
+ let truncated = truncate_f64_to_s64(checked);
+ let value = u32(truncated);
+ result32(value);
+}
+
+handler I64TruncF32S() @opcode(0xae) {
+ let operand = f32_value(unary_operand());
+ guard operand == operand else @cold {
+ trap(TRAP_INVALID_CONVERSION);
+ };
+ let lower_bound = f64_from_bits(0xc3e0000000000000);
+ let upper_bound = f64_from_bits(0x43e0000000000000);
+ guard operand >= lower_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ guard operand < upper_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ let value = truncate_f64_to_s64(operand);
+ result(value);
+}
+
+handler I64TruncF32U() @opcode(0xaf) {
+ let operand = f32_value(unary_operand());
+ let checked = checked_truncation(operand, 0xbff0000000000000, 0x43f0000000000000);
+ let value = truncate_unsigned64(checked);
+ result(value);
+}
+
+handler I64TruncF64S() @opcode(0xb0) {
+ let operand = f64_value(unary_operand());
+ guard operand == operand else @cold {
+ trap(TRAP_INVALID_CONVERSION);
+ };
+ let lower_bound = f64_from_bits(0xc3e0000000000000);
+ let upper_bound = f64_from_bits(0x43e0000000000000);
+ guard operand >= lower_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ guard operand < upper_bound else @cold {
+ trap(TRAP_INTEGER_OVERFLOW);
+ };
+ let value = truncate_f64_to_s64(operand);
+ result(value);
+}
+
+handler I64TruncF64U() @opcode(0xb1) {
+ let operand = f64_value(unary_operand());
+ let checked = checked_truncation(operand, 0xbff0000000000000, 0x43f0000000000000);
+ let value = truncate_unsigned64(checked);
+ result(value);
+}
+
+handler I64ExtendI32S() @opcode(0xac) {
+ let operand = unary32();
+ let narrow = i32(operand);
+ let value: u64 = alias(i64(narrow));
+ result(value);
+}
+
+handler I64ExtendI32U() @opcode(0xad) {
+ let operand = unary32();
+ let value: u64 = alias(operand);
+ result(value);
+}
+
+handler F32ConvertI32S() @opcode(0xb2) {
+ let operand = unary32();
+ let narrow = i32(operand);
+ let wide: u64 = alias(i64(narrow));
+ let value = s64_to_f32(wide);
+ f32_result(value);
+}
+
+handler F32ConvertI32U() @opcode(0xb3) {
+ let operand = unary32();
+ let wide: u64 = alias(operand);
+ let value = s64_to_f32(wide);
+ f32_result(value);
+}
+
+handler F32ConvertI64S() @opcode(0xb4) {
+ let operand = unary_operand();
+ let value = s64_to_f32(operand);
+ f32_result(value);
+}
+
+handler F32ConvertI64U() @opcode(0xb5) {
+ let operand = unary_operand();
+ let mut value = s64_to_f32(operand);
+ if signed64(operand) < 0 @cold {
+ # Halve the value, keeping the lowest bit so that rounding stays correct, and double the result.
+ let half = (operand >> 1) | (operand & 1);
+ let half_value = s64_to_f32(half);
+ value = add_f32(half_value, half_value);
+ }
+ f32_result(value);
+}
+
+handler F64ConvertI32S() @opcode(0xb7) {
+ let operand = unary32();
+ let narrow = i32(operand);
+ let wide: u64 = alias(i64(narrow));
+ let value = s64_to_f64(wide);
+ f64_result(value);
+}
+
+handler F64ConvertI32U() @opcode(0xb8) {
+ let operand = unary32();
+ let wide: u64 = alias(operand);
+ let value = s64_to_f64(wide);
+ f64_result(value);
+}
+
+handler F64ConvertI64S() @opcode(0xb9) {
+ let operand = unary_operand();
+ let value = s64_to_f64(operand);
+ f64_result(value);
+}
+
+handler F64ConvertI64U() @opcode(0xba) {
+ let operand = unary_operand();
+ let mut value = s64_to_f64(operand);
+ if signed64(operand) < 0 @cold {
+ # Halve the value, keeping the lowest bit so that rounding stays correct, and double the result.
+ let half = (operand >> 1) | (operand & 1);
+ let half_value = s64_to_f64(half);
+ value = half_value + half_value;
+ }
+ f64_result(value);
+}
+
+handler F32DemoteF64() @opcode(0xb6) {
+ let operand = f64_value(unary_operand());
+ let value = demote_f64(operand);
+ f32_result(value);
+}
+
+handler F64PromoteF32() @opcode(0xbb) {
+ let operand = f32_operand(unary_operand());
+ let value = promote_f32(operand);
+ f64_result(value);
+}
+
+handler I32ReinterpretF32() @opcode(0xbc) {
+ dispatch_next;
+}
+
+handler I64ReinterpretF64() @opcode(0xbd) {
+ dispatch_next;
+}
+
+handler F32ReinterpretI32() @opcode(0xbe) {
+ dispatch_next;
+}
+
+handler F64ReinterpretI64() @opcode(0xbf) {
+ dispatch_next;
+}
+
+handler I32Extend8S() @opcode(0xc0) {
+ let operand = unary_operand();
+ let moved = operand << 56;
+ let signed = signed64(moved);
+ let extended = signed >> 56;
+ let value = u32(extended);
+ result32(value);
+}
+
+handler I32Extend16S() @opcode(0xc1) {
+ let operand = unary_operand();
+ let moved = operand << 48;
+ let signed = signed64(moved);
+ let extended = signed >> 48;
+ let value = u32(extended);
+ result32(value);
+}
+
+handler I64Extend8S() @opcode(0xc2) {
+ let operand = unary_operand();
+ let moved = operand << 56;
+ let signed = signed64(moved);
+ let extended = signed >> 56;
+ let value: u64 = alias(extended);
+ result(value);
+}
+
+handler I64Extend16S() @opcode(0xc3) {
+ let operand = unary_operand();
+ let moved = operand << 48;
+ let signed = signed64(moved);
+ let extended = signed >> 48;
+ let value: u64 = alias(extended);
+ result(value);
+}
+
+handler I64Extend32S() @opcode(0xc4) {
+ let operand = unary_operand();
+ let moved = operand << 32;
+ let signed = signed64(moved);
+ let extended = signed >> 32;
+ let value: u64 = alias(extended);
+ result(value);
+}
+
+# References. A reference is the address of what it refers to, or zero for null.
+
+handler RefNull() @opcode(0xd0) {
+ let length = leb_length(immediates());
+ push(0);
+ advance(length + 1);
+}
+
+handler RefIsNull() @opcode(0xd1) {
+ let operand = unary_operand();
+ let mut value: u64 = 0;
+ if operand == 0 {
+ value = 1;
+ }
+ result(value);
+}
+
+handler RefFunc() @opcode(0xd2) {
+ let [function_index, length] = read_leb(immediates());
+ let function = function_at(function_index);
+ push(function);
+ advance(length + 1);
+}
+
+handler RefEq() @opcode(0xd3) {
+ let [lhs, rhs] = binary_operands();
+ let mut value: u64 = 0;
+ if lhs == rhs {
+ value = 1;
+ }
+ result(value);
+}
+
+handler RefAsNonNull() @opcode(0xd4) {
+ let operand = unary_operand();
+ guard operand != 0 else @cold {
+ trap(TRAP_NULL_REFERENCE);
+ };
+ dispatch_next;
+}
+
+handler BrOnNull() @opcode(0xd5) {
+ let operand = unary_operand();
+ if operand == 0 {
+ drop_slots(1);
+ branch();
+ }
+ let length = leb_length(immediates());
+ skip_entry_and_advance(length + 1);
+}
+
+handler BrOnNonNull() @opcode(0xd6) {
+ let operand = unary_operand();
+ if operand != 0 {
+ branch();
+ }
+ drop_slots(1);
+ let length = leb_length(immediates());
+ skip_entry_and_advance(length + 1);
+}
+
+# The 0xFC prefix: saturating truncations, bulk memory, and table instructions.
+
+handler PrefixFC() @opcode(0xfc) {
+ let [sub_opcode, _] = read_leb(immediates());
+ dispatch_secondary(0xfc, sub_opcode);
+}
+
+inline fn prefixed_advance(offset: u64) {
+ advance(offset);
+}
+
+handler I32TruncSatF32S() @opcode(0xfc, 0) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f32_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let narrow = u32(truncated);
+ let value: u64 = alias(narrow);
+ set_top(value);
+ advance(offset);
+}
+
+handler I32TruncSatF32U() @opcode(0xfc, 1) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f32_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let narrow = u32(truncated);
+ let value: u64 = alias(narrow);
+ set_top(value);
+ advance(offset);
+}
+
+handler I32TruncSatF64S() @opcode(0xfc, 2) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f64_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let narrow = u32(truncated);
+ let value: u64 = alias(narrow);
+ set_top(value);
+ advance(offset);
+}
+
+handler I32TruncSatF64U() @opcode(0xfc, 3) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f64_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let narrow = u32(truncated);
+ let value: u64 = alias(narrow);
+ set_top(value);
+ advance(offset);
+}
+
+handler I64TruncSatF32S() @opcode(0xfc, 4) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f32_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xc3e0000000000001, 0x43e0000000000000, 0x8000000000000000, 0x7fffffffffffffff, 0);
+ let value = truncated;
+ set_top(value);
+ advance(offset);
+}
+
+handler I64TruncSatF32U() @opcode(0xfc, 5) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f32_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xbff0000000000000, 0x43f0000000000000, 0, 0xffffffffffffffff, 1);
+ let value = truncated;
+ set_top(value);
+ advance(offset);
+}
+
+handler I64TruncSatF64S() @opcode(0xfc, 6) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f64_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xc3e0000000000001, 0x43e0000000000000, 0x8000000000000000, 0x7fffffffffffffff, 0);
+ let value = truncated;
+ set_top(value);
+ advance(offset);
+}
+
+handler I64TruncSatF64U() @opcode(0xfc, 7) {
+ let [_, offset] = prefixed_immediates();
+ let operand = f64_value(unary_operand());
+ let truncated = saturating_truncation(operand, 0xbff0000000000000, 0x43f0000000000000, 0, 0xffffffffffffffff, 1);
+ let value = truncated;
+ set_top(value);
+ advance(offset);
+}
+# Bulk memory and tables. The operands are checked against the bounds before anything is written, so these do not
+# rely on guard pages.
+
+inline fn three_operands() -> (u64, u64, u64) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let third = slots[0];
+ let second = slots[1];
+ let first = slots[2];
+ let next = top + 24;
+ vsp = next;
+ (first, second, third)
+}
+
+# Trap unless `count` items from `start` are within `size`.
+inline fn check_range(start: u64, count: u64, size: u64, code: u64) {
+ let end = start + count;
+ guard end <= size else @cold {
+ trap(code);
+ };
+}
+
+inline fn segment_at(segments_offset: u64, index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut segments: u64;
+ load64(segments, [instance_pointer, segments_offset]);
+ segments + (index << 4)
+}
+
+# Copy `count` bytes from `source` to `destination`, which may overlap.
+inline fn copy_bytes(destination: u64, source: u64, count: u64) {
+ let to: Sequence<u8> = alias(destination);
+ let from: Sequence<u8> = alias(source);
+ let mut index: u64 = 0;
+ if destination <= source {
+ while index < count {
+ let byte = from[index];
+ to[index] = byte;
+ index = index + 1;
+ }
+ } else {
+ index = count;
+ while index != 0 {
+ index = index - 1;
+ let byte = from[index];
+ to[index] = byte;
+ }
+ }
+}
+
+# Copy `count` table elements from `source` to `destination`, which may overlap.
+inline fn copy_elements(destination: u64, source: u64, count: u64) {
+ let to: Sequence<u64> = alias(destination);
+ let from: Sequence<u64> = alias(source);
+ let mut index: u64 = 0;
+ if destination <= source {
+ while index < count {
+ to[index] = from[index];
+ index = index + 1;
+ }
+ } else {
+ index = count;
+ while index != 0 {
+ index = index - 1;
+ to[index] = from[index];
+ }
+ }
+}
+
+handler MemoryInit() @opcode(0xfc, 8) {
+ let [bytes, offset] = prefixed_immediates();
+ let [data_index, data_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let memory_bytes: Sequence<u8> = alias(start + data_length);
+ let [memory_index, memory_length] = read_leb(memory_bytes);
+ let [destination, source, count] = three_operands();
+ let segment = segment_at(INSTANCE_DATA_SEGMENTS, data_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ check_range(source, count, segment_length, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let memory = memory_at(memory_index);
+ let mut memory_size: u64;
+ load64(memory_size, [memory, MEMORY_SIZE]);
+ check_range(destination, count, memory_size, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ let mut base: u64;
+ load64(base, [memory, MEMORY_BASE]);
+ copy_bytes(base + destination, contents + source, count);
+ advance(offset + data_length + memory_length);
+}
+
+handler DataDrop() @opcode(0xfc, 9) {
+ let [bytes, offset] = prefixed_immediates();
+ let [data_index, data_length] = read_leb(bytes);
+ let segment = segment_at(INSTANCE_DATA_SEGMENTS, data_index);
+ store64([segment, SEGMENT_LENGTH], 0);
+ advance(offset + data_length);
+}
+
+handler MemoryCopy() @opcode(0xfc, 10) {
+ let [bytes, offset] = prefixed_immediates();
+ let [destination_index, destination_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let source_bytes: Sequence<u8> = alias(start + destination_length);
+ let [source_index, source_length] = read_leb(source_bytes);
+ let [destination, source, count] = three_operands();
+ let destination_memory = memory_at(destination_index);
+ let source_memory = memory_at(source_index);
+ let mut destination_size: u64;
+ load64(destination_size, [destination_memory, MEMORY_SIZE]);
+ check_range(destination, count, destination_size, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let mut source_size: u64;
+ load64(source_size, [source_memory, MEMORY_SIZE]);
+ check_range(source, count, source_size, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let mut destination_base: u64;
+ load64(destination_base, [destination_memory, MEMORY_BASE]);
+ let mut source_base: u64;
+ load64(source_base, [source_memory, MEMORY_BASE]);
+ copy_bytes(destination_base + destination, source_base + source, count);
+ advance(offset + destination_length + source_length);
+}
+
+handler MemoryFill() @opcode(0xfc, 11) {
+ let [bytes, offset] = prefixed_immediates();
+ let [memory_index, memory_length] = read_leb(bytes);
+ let [destination, value, count] = three_operands();
+ let memory = memory_at(memory_index);
+ let mut memory_size: u64;
+ load64(memory_size, [memory, MEMORY_SIZE]);
+ check_range(destination, count, memory_size, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let mut base: u64;
+ load64(base, [memory, MEMORY_BASE]);
+ let start = base + destination;
+ let end = start + count;
+ let mut address: u64 = start;
+ while address < end {
+ store8([address, 0], value);
+ address = address + 1;
+ }
+ advance(offset + memory_length);
+}
+
+handler TableInit() @opcode(0xfc, 12) {
+ let [bytes, offset] = prefixed_immediates();
+ let [element_index, element_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let table_bytes: Sequence<u8> = alias(start + element_length);
+ let [table_index, table_length] = read_leb(table_bytes);
+ let [destination, source, count] = three_operands();
+ let segment = segment_at(INSTANCE_ELEMENT_SEGMENTS, element_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ check_range(source, count, segment_length, TRAP_TABLE_OUT_OF_BOUNDS);
+ let table = table_at(table_index);
+ let mut table_size: u64;
+ load64(table_size, [table, TABLE_SIZE]);
+ check_range(destination, count, table_size, TRAP_TABLE_OUT_OF_BOUNDS);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ let mut elements: u64;
+ load64(elements, [table, TABLE_ELEMENTS]);
+ copy_elements(elements + (destination << 3), contents + (source << 3), count);
+ advance(offset + element_length + table_length);
+}
+
+handler ElemDrop() @opcode(0xfc, 13) {
+ let [bytes, offset] = prefixed_immediates();
+ let [element_index, element_length] = read_leb(bytes);
+ let segment = segment_at(INSTANCE_ELEMENT_SEGMENTS, element_index);
+ store64([segment, SEGMENT_LENGTH], 0);
+ advance(offset + element_length);
+}
+
+handler TableCopy() @opcode(0xfc, 14) {
+ let [bytes, offset] = prefixed_immediates();
+ let [destination_index, destination_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let source_bytes: Sequence<u8> = alias(start + destination_length);
+ let [source_index, source_length] = read_leb(source_bytes);
+ let [destination, source, count] = three_operands();
+ let destination_table = table_at(destination_index);
+ let source_table = table_at(source_index);
+ let mut destination_size: u64;
+ load64(destination_size, [destination_table, TABLE_SIZE]);
+ check_range(destination, count, destination_size, TRAP_TABLE_OUT_OF_BOUNDS);
+ let mut source_size: u64;
+ load64(source_size, [source_table, TABLE_SIZE]);
+ check_range(source, count, source_size, TRAP_TABLE_OUT_OF_BOUNDS);
+ let mut destination_elements: u64;
+ load64(destination_elements, [destination_table, TABLE_ELEMENTS]);
+ let mut source_elements: u64;
+ load64(source_elements, [source_table, TABLE_ELEMENTS]);
+ copy_elements(destination_elements + (destination << 3), source_elements + (source << 3), count);
+ advance(offset + destination_length + source_length);
+}
+
+handler TableGrow() @opcode(0xfc, 15) {
+ let [bytes, offset] = prefixed_immediates();
+ let [table_index, table_length] = read_leb(bytes);
+ let [initial, delta] = binary_operands();
+ let table = table_at(table_index);
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], table);
+ store64([context_pointer, CONTEXT_ARGUMENT_1], delta);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], initial);
+ let previous: u64 = call_helper(wasm_runtime_table_grow, context_pointer);
+ # The result is an i64 for a table64, whose -1 must not be truncated.
+ let grown_table = table_at(table_index);
+ let mut address64: u64;
+ load64(address64, [grown_table, TABLE_ADDRESS64]);
+ let mut result: u64 = previous;
+ if address64 == 0 {
+ let narrow = u32(previous);
+ result = alias(narrow);
+ }
+ set_top(result);
+ advance(offset + table_length);
+}
+
+handler TableSize() @opcode(0xfc, 16) {
+ let [bytes, offset] = prefixed_immediates();
+ let [table_index, table_length] = read_leb(bytes);
+ let table = table_at(table_index);
+ let mut size: u64;
+ load64(size, [table, TABLE_SIZE]);
+ push(size);
+ advance(offset + table_length);
+}
+
+handler TableFill() @opcode(0xfc, 17) {
+ let [bytes, offset] = prefixed_immediates();
+ let [table_index, table_length] = read_leb(bytes);
+ let [destination, value, count] = three_operands();
+ let table = table_at(table_index);
+ let mut table_size: u64;
+ load64(table_size, [table, TABLE_SIZE]);
+ check_range(destination, count, table_size, TRAP_TABLE_OUT_OF_BOUNDS);
+ let mut elements_pointer: u64;
+ load64(elements_pointer, [table, TABLE_ELEMENTS]);
+ let elements: Sequence<u64> = alias(elements_pointer + (destination << 3));
+ let mut index: u64 = 0;
+ while index < count {
+ elements[index] = value;
+ index = index + 1;
+ }
+ advance(offset + table_length);
+}
+# SIMD (the 0xFD prefix). A v128 takes two slots on the operand stack, its low half in the lower one, so a vector on
+# top of the stack is a 16-byte value at vsp. Lane operations that have no vector instruction work on that memory
+# directly.
+
+handler PrefixFD() @opcode(0xfd) {
+ let [sub_opcode, _] = read_leb(immediates());
+ dispatch_secondary(0xfd, sub_opcode);
+}
+
+inline fn top_vector() -> v128 {
+ let top: u64 = vsp;
+ let mut value: v128;
+ load128(value, [top, 0]);
+ value
+}
+
+inline fn set_top_vector(value: v128) {
+ let top: u64 = vsp;
+ store128([top, 0], value);
+}
+
+# The two vector operands of a binary instruction, whose result replaces the first.
+inline fn binary_vectors() -> (v128, v128) {
+ let top: u64 = vsp;
+ let mut rhs: v128;
+ load128(rhs, [top, 0]);
+ let mut lhs: v128;
+ load128(lhs, [top, 16]);
+ let next = top + 16;
+ vsp = next;
+ (lhs, rhs)
+}
+
+inline fn vector_result(value: v128, offset: u64) {
+ set_top_vector(value);
+ advance(offset);
+}
+
+inline fn splat_u64(value: u64) -> v128 {
+ v128_from_u64x2(value, value)
+}
+
+inline fn splat_i8(value: u64) -> v128 {
+ let byte = value & 0xff;
+ let wide = byte * 0x0101010101010101;
+ splat_u64(wide)
+}
+
+inline fn splat_i16(value: u64) -> v128 {
+ let half = value & 0xffff;
+ let wide = half * 0x0001000100010001;
+ splat_u64(wide)
+}
+
+inline fn splat_i32(value: u64) -> v128 {
+ let word = value & 0xffffffff;
+ let wide = word * 0x0000000100000001;
+ splat_u64(wide)
+}
+
+inline fn zero_vector() -> v128 {
+ v128_from_u64x2(0, 0)
+}
+
+inline fn ones_vector() -> v128 {
+ v128_from_u64x2(0xffffffffffffffff, 0xffffffffffffffff)
+}
+
+inline fn not_vector(value: v128) -> v128 {
+ v128_xor(value, ones_vector())
+}
+
+# The shift count of a vector shift, modulo the lane width, as a vector whose low 64 bits hold it.
+inline fn shift_count(mask: u64) -> v128 {
+ let count = pop();
+ let masked = count & mask;
+ v128_from_u64x2(masked, 0)
+}
+
+# Replace the vector on top of the stack with two 64-bit halves.
+inline fn set_top_halves(low: u64, high: u64) {
+ let top: u64 = vsp;
+ store64([top, 0], low);
+ store64([top, 8], high);
+}
+
+# Push a vector given as two 64-bit halves, replacing `popped` slots.
+inline fn replace_with_halves(popped: u64, low: u64, high: u64) {
+ let top: u64 = vsp;
+ let next = top + (popped << 3) - 16;
+ vsp = next;
+ store64([next, 0], low);
+ store64([next, 8], high);
+}
+
+# The address of a SIMD memory access to memory 0, whose memory argument starts `offset` bytes after the instruction,
+# and the length of the instruction.
+inline fn simd_memory_address(address_operand: u64, offset: u64) -> (u64, u64) {
+ let current: u64 = ip;
+ let alignment_bytes: Sequence<u8> = alias(current + offset);
+ let alignment_length = leb_length(alignment_bytes);
+ let offset_bytes: Sequence<u8> = alias(current + offset + alignment_length);
+ let [displacement, displacement_length] = read_leb(offset_bytes);
+ let index: u64 = alias(u32(address_operand));
+ let base: u64 = memory_base;
+ let address = base + index + displacement;
+ (address, offset + alignment_length + displacement_length)
+}
+
+handler V128Load() @opcode(0xfd, 0x0) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut value: v128;
+ load128(value, [address, 0]);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load8x8S() @opcode(0xfd, 0x1) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load8x8U() @opcode(0xfd, 0x2) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load16x4S() @opcode(0xfd, 0x3) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load16x4U() @opcode(0xfd, 0x4) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load32x2S() @opcode(0xfd, 0x5) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load32x2U() @opcode(0xfd, 0x6) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler V128Load8Splat() @opcode(0xfd, 0x7) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load8(lane, [address, 0]);
+ let wide = lane * 0x0101010101010101;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler V128Load16Splat() @opcode(0xfd, 0x8) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load16(lane, [address, 0]);
+ let wide = lane * 0x0001000100010001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler V128Load32Splat() @opcode(0xfd, 0x9) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ let wide = lane * 0x0000000100000001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler V128Load64Splat() @opcode(0xfd, 0xa) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ let wide = lane;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler V128Load32Zero() @opcode(0xfd, 0x5c) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler V128Load64Zero() @opcode(0xfd, 0x5d) {
+ let [_, offset] = prefixed_immediates();
+ let address_operand = pop();
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler V128Store() @opcode(0xfd, 0xb) {
+ let [_, offset] = prefixed_immediates();
+ let value = top_vector();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let next = top + 24;
+ vsp = next;
+ let [address, length] = simd_memory_address(address_operand, offset);
+ store128([address, 0], value);
+ advance(length);
+}
+
+handler V128Load8Lane() @opcode(0xfd, 0x54) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ let lane_address = top + (lane * 1);
+ store8([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Load16Lane() @opcode(0xfd, 0x55) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ let lane_address = top + (lane * 2);
+ store16([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Load32Lane() @opcode(0xfd, 0x56) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let lane_address = top + (lane * 4);
+ store32([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Load64Lane() @opcode(0xfd, 0x57) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ let lane_address = top + (lane * 8);
+ store64([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Store8Lane() @opcode(0xfd, 0x58) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 1);
+ let mut value: u64;
+ load8(value, [lane_address, 0]);
+ store8([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Store16Lane() @opcode(0xfd, 0x59) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 2);
+ let mut value: u64;
+ load16(value, [lane_address, 0]);
+ store16([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Store32Lane() @opcode(0xfd, 0x5a) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 4);
+ let mut value: u64;
+ load32(value, [lane_address, 0]);
+ store32([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Store64Lane() @opcode(0xfd, 0x5b) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = simd_memory_address(address_operand, offset);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 8);
+ let mut value: u64;
+ load64(value, [lane_address, 0]);
+ store64([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler V128Const() @opcode(0xfd, 0xc) {
+ let [bytes, offset] = prefixed_immediates();
+ let start: u64 = alias(bytes);
+ let mut low: u64;
+ load64(low, [start, 0]);
+ let mut high: u64;
+ load64(high, [start, 8]);
+ replace_with_halves(0, low, high);
+ advance(offset + 16);
+}
+
+handler I8x16Shuffle() @opcode(0xfd, 0xd) {
+ let [bytes, offset] = prefixed_immediates();
+ let start: u64 = alias(bytes);
+ let mut mask: v128;
+ load128(mask, [start, 0]);
+ let [a, b] = binary_vectors();
+ # Lanes 0 to 15 pick from a and 16 to 31 from b; a selector with its top bit set picks zero.
+ let from_b = v128_gt_s_i8(mask, splat_i8(15));
+ let mask_a = v128_or(mask, from_b);
+ let mask_b = v128_sub_i8(mask, splat_i8(16));
+ let picked_a = v128_shuffle_i8(a, mask_a);
+ let picked_b = v128_shuffle_i8(b, mask_b);
+ let value = v128_or(picked_a, picked_b);
+ vector_result(value, offset + 16);
+}
+
+handler I8x16Swizzle() @opcode(0xfd, 0xe) {
+ let [_, offset] = prefixed_immediates();
+ let [a, selectors] = binary_vectors();
+ # Selectors of 16 and more pick zero, which they do once their top bit is set.
+ let mask = v128_add_sat_u_i8(selectors, splat_i8(0x70));
+ let value = v128_shuffle_i8(a, mask);
+ vector_result(value, offset);
+}
+
+handler I8x16RelaxedSwizzle() @opcode(0xfd, 0x100) {
+ let [_, offset] = prefixed_immediates();
+ let [a, selectors] = binary_vectors();
+ # Selectors of 16 and more pick zero, which they do once their top bit is set.
+ let mask = v128_add_sat_u_i8(selectors, splat_i8(0x70));
+ let value = v128_shuffle_i8(a, mask);
+ vector_result(value, offset);
+}
+
+handler I8x16Splat() @opcode(0xfd, 0xf) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let masked = lane & 0xff;
+ let wide = masked * 0x0101010101010101;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler I16x8Splat() @opcode(0xfd, 0x10) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let masked = lane & 0xffff;
+ let wide = masked * 0x0001000100010001;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler I32x4Splat() @opcode(0xfd, 0x11) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let masked = lane & 0xffffffff;
+ let wide = masked * 0x0000000100000001;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler I64x2Splat() @opcode(0xfd, 0x12) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let wide = lane;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler F32x4Splat() @opcode(0xfd, 0x13) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let masked = lane & 0xffffffff;
+ let wide = masked * 0x0000000100000001;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler F64x2Splat() @opcode(0xfd, 0x14) {
+ let [_, offset] = prefixed_immediates();
+ let lane = unary_operand();
+ let wide = lane;
+ replace_with_halves(1, wide, wide);
+ advance(offset);
+}
+
+handler I8x16ExtractLaneS() @opcode(0xfd, 0x15) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 1);
+ let mut value: u64;
+ load8s(value, [lane_address, 0]);
+ let narrow = u32(value);
+ let result: u64 = alias(narrow);
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I8x16ExtractLaneU() @opcode(0xfd, 0x16) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 1);
+ let mut value: u64;
+ load8(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I16x8ExtractLaneS() @opcode(0xfd, 0x18) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 2);
+ let mut value: u64;
+ load16s(value, [lane_address, 0]);
+ let narrow = u32(value);
+ let result: u64 = alias(narrow);
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I16x8ExtractLaneU() @opcode(0xfd, 0x19) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 2);
+ let mut value: u64;
+ load16(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I32x4ExtractLane() @opcode(0xfd, 0x1b) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 4);
+ let mut value: u64;
+ load32(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I64x2ExtractLane() @opcode(0xfd, 0x1d) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 8);
+ let mut value: u64;
+ load64(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler F32x4ExtractLane() @opcode(0xfd, 0x1f) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 4);
+ let mut value: u64;
+ load32(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler F64x2ExtractLane() @opcode(0xfd, 0x21) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 8);
+ let mut value: u64;
+ load64(value, [lane_address, 0]);
+ let result = value;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset + 1);
+}
+
+handler I8x16ReplaceLane() @opcode(0xfd, 0x17) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 1);
+ store8([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler I16x8ReplaceLane() @opcode(0xfd, 0x1a) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 2);
+ store16([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler I32x4ReplaceLane() @opcode(0xfd, 0x1c) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 4);
+ store32([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler I64x2ReplaceLane() @opcode(0xfd, 0x1e) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 8);
+ store64([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler F32x4ReplaceLane() @opcode(0xfd, 0x20) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 4);
+ store32([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler F64x2ReplaceLane() @opcode(0xfd, 0x22) {
+ let [bytes, offset] = prefixed_immediates();
+ let lane: u64 = alias(bytes[0]);
+ let value = pop();
+ let top: u64 = vsp;
+ let lane_address = top + (lane * 8);
+ store64([lane_address, 0], value);
+ advance(offset + 1);
+}
+
+handler I8x16Eq() @opcode(0xfd, 0x23) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16Ne() @opcode(0xfd, 0x24) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i8(a, b));
+ vector_result(value, offset);
+}
+
+handler I8x16LtS() @opcode(0xfd, 0x25) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i8(b, a);
+ vector_result(value, offset);
+}
+
+handler I8x16LtU() @opcode(0xfd, 0x26) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i8(v128_max_u_i8(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I8x16GtS() @opcode(0xfd, 0x27) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16GtU() @opcode(0xfd, 0x28) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i8(v128_min_u_i8(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I8x16LeS() @opcode(0xfd, 0x29) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i8(v128_min_s_i8(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I8x16LeU() @opcode(0xfd, 0x2a) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i8(v128_min_u_i8(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I8x16GeS() @opcode(0xfd, 0x2b) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i8(v128_max_s_i8(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I8x16GeU() @opcode(0xfd, 0x2c) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i8(v128_max_u_i8(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I16x8Eq() @opcode(0xfd, 0x2d) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8Ne() @opcode(0xfd, 0x2e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i16(a, b));
+ vector_result(value, offset);
+}
+
+handler I16x8LtS() @opcode(0xfd, 0x2f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i16(b, a);
+ vector_result(value, offset);
+}
+
+handler I16x8LtU() @opcode(0xfd, 0x30) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i16(v128_max_u_i16(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I16x8GtS() @opcode(0xfd, 0x31) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8GtU() @opcode(0xfd, 0x32) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i16(v128_min_u_i16(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I16x8LeS() @opcode(0xfd, 0x33) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i16(v128_min_s_i16(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I16x8LeU() @opcode(0xfd, 0x34) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i16(v128_min_u_i16(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I16x8GeS() @opcode(0xfd, 0x35) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i16(v128_max_s_i16(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I16x8GeU() @opcode(0xfd, 0x36) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i16(v128_max_u_i16(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I32x4Eq() @opcode(0xfd, 0x37) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4Ne() @opcode(0xfd, 0x38) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i32(a, b));
+ vector_result(value, offset);
+}
+
+handler I32x4LtS() @opcode(0xfd, 0x39) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i32(b, a);
+ vector_result(value, offset);
+}
+
+handler I32x4LtU() @opcode(0xfd, 0x3a) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i32(v128_max_u_i32(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I32x4GtS() @opcode(0xfd, 0x3b) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4GtU() @opcode(0xfd, 0x3c) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i32(v128_min_u_i32(a, b), a));
+ vector_result(value, offset);
+}
+
+handler I32x4LeS() @opcode(0xfd, 0x3d) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i32(v128_min_s_i32(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I32x4LeU() @opcode(0xfd, 0x3e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i32(v128_min_u_i32(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I32x4GeS() @opcode(0xfd, 0x3f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i32(v128_max_s_i32(a, b), a);
+ vector_result(value, offset);
+}
+
+handler I32x4GeU() @opcode(0xfd, 0x40) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i32(v128_max_u_i32(a, b), a);
+ vector_result(value, offset);
+}
+
+handler F32x4Eq() @opcode(0xfd, 0x41) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Ne() @opcode(0xfd, 0x42) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_ne_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Lt() @opcode(0xfd, 0x43) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_lt_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Gt() @opcode(0xfd, 0x44) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_lt_f32(b, a);
+ vector_result(value, offset);
+}
+
+handler F32x4Le() @opcode(0xfd, 0x45) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_le_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Ge() @opcode(0xfd, 0x46) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_le_f32(b, a);
+ vector_result(value, offset);
+}
+
+handler F64x2Eq() @opcode(0xfd, 0x47) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Ne() @opcode(0xfd, 0x48) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_ne_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Lt() @opcode(0xfd, 0x49) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_lt_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Gt() @opcode(0xfd, 0x4a) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_lt_f64(b, a);
+ vector_result(value, offset);
+}
+
+handler F64x2Le() @opcode(0xfd, 0x4b) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_le_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Ge() @opcode(0xfd, 0x4c) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_le_f64(b, a);
+ vector_result(value, offset);
+}
+
+handler V128Not() @opcode(0xfd, 0x4d) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = not_vector(a);
+ vector_result(value, offset);
+}
+
+handler V128And() @opcode(0xfd, 0x4e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_and(a, b);
+ vector_result(value, offset);
+}
+
+handler V128AndNot() @opcode(0xfd, 0x4f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_andnot(b, a);
+ vector_result(value, offset);
+}
+
+handler V128Or() @opcode(0xfd, 0x50) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_or(a, b);
+ vector_result(value, offset);
+}
+
+handler V128Xor() @opcode(0xfd, 0x51) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_xor(a, b);
+ vector_result(value, offset);
+}
+
+handler V128Bitselect() @opcode(0xfd, 0x52) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut mask: v128;
+ load128(mask, [top, 0]);
+ let mut second: v128;
+ load128(second, [top, 16]);
+ let mut first: v128;
+ load128(first, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let chosen_first = v128_and(first, mask);
+ let chosen_second = v128_andnot(mask, second);
+ let value = v128_or(chosen_first, chosen_second);
+ vector_result(value, offset);
+}
+
+handler I8x16RelaxedLaneselect() @opcode(0xfd, 0x109) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut mask: v128;
+ load128(mask, [top, 0]);
+ let mut second: v128;
+ load128(second, [top, 16]);
+ let mut first: v128;
+ load128(first, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let chosen_first = v128_and(first, mask);
+ let chosen_second = v128_andnot(mask, second);
+ let value = v128_or(chosen_first, chosen_second);
+ vector_result(value, offset);
+}
+
+handler I16x8RelaxedLaneselect() @opcode(0xfd, 0x10a) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut mask: v128;
+ load128(mask, [top, 0]);
+ let mut second: v128;
+ load128(second, [top, 16]);
+ let mut first: v128;
+ load128(first, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let chosen_first = v128_and(first, mask);
+ let chosen_second = v128_andnot(mask, second);
+ let value = v128_or(chosen_first, chosen_second);
+ vector_result(value, offset);
+}
+
+handler I32x4RelaxedLaneselect() @opcode(0xfd, 0x10b) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut mask: v128;
+ load128(mask, [top, 0]);
+ let mut second: v128;
+ load128(second, [top, 16]);
+ let mut first: v128;
+ load128(first, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let chosen_first = v128_and(first, mask);
+ let chosen_second = v128_andnot(mask, second);
+ let value = v128_or(chosen_first, chosen_second);
+ vector_result(value, offset);
+}
+
+handler I64x2RelaxedLaneselect() @opcode(0xfd, 0x10c) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut mask: v128;
+ load128(mask, [top, 0]);
+ let mut second: v128;
+ load128(second, [top, 16]);
+ let mut first: v128;
+ load128(first, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let chosen_first = v128_and(first, mask);
+ let chosen_second = v128_andnot(mask, second);
+ let value = v128_or(chosen_first, chosen_second);
+ vector_result(value, offset);
+}
+
+handler V128AnyTrue() @opcode(0xfd, 0x53) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let low = v128_low_u64(a);
+ let high = v128_high_u64(a);
+ let combined = low | high;
+ let mut result: u64 = 0;
+ if combined != 0 {
+ result = 1;
+ }
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I8x16AllTrue() @opcode(0xfd, 0x63) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let zero_lanes = v128_eq_i8(a, zero_vector());
+ let zero_mask = v128_bitmask_i8(zero_lanes);
+ let mut result: u64 = 0;
+ if zero_mask == 0 {
+ result = 1;
+ }
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I16x8AllTrue() @opcode(0xfd, 0x83) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let zero_lanes = v128_eq_i16(a, zero_vector());
+ let zero_mask = v128_bitmask_i8(zero_lanes);
+ let mut result: u64 = 0;
+ if zero_mask == 0 {
+ result = 1;
+ }
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I32x4AllTrue() @opcode(0xfd, 0xa3) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let zero_lanes = v128_eq_i32(a, zero_vector());
+ let zero_mask = v128_bitmask_i8(zero_lanes);
+ let mut result: u64 = 0;
+ if zero_mask == 0 {
+ result = 1;
+ }
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I64x2AllTrue() @opcode(0xfd, 0xc3) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let zero_lanes = v128_eq_i64(a, zero_vector());
+ let zero_mask = v128_bitmask_i8(zero_lanes);
+ let mut result: u64 = 0;
+ if zero_mask == 0 {
+ result = 1;
+ }
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I8x16Bitmask() @opcode(0xfd, 0x64) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let result = v128_bitmask_i8(a);
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I16x8Bitmask() @opcode(0xfd, 0x84) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let narrowed = v128_narrow_s_i16(a, a);
+ let mask = v128_bitmask_i8(narrowed);
+ let result = mask & 0xff;
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I32x4Bitmask() @opcode(0xfd, 0xa4) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let result = v128_bitmask_f32(a);
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler I64x2Bitmask() @opcode(0xfd, 0xc4) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let result = v128_bitmask_f64(a);
+ replace_with_halves(2, 0, 0);
+ let top: u64 = vsp;
+ let next = top + 8;
+ vsp = next;
+ let slots: Sequence<u64> = alias(next);
+ slots[0] = result;
+ advance(offset);
+}
+
+handler F32x4DemoteF64x2Zero() @opcode(0xfd, 0x5e) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_demote_f64(a);
+ vector_result(value, offset);
+}
+
+handler F64x2PromoteLowF32x4() @opcode(0xfd, 0x5f) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_promote_low_f32(a);
+ vector_result(value, offset);
+}
+
+handler I8x16Abs() @opcode(0xfd, 0x60) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_abs_i8(a);
+ vector_result(value, offset);
+}
+
+handler I8x16Neg() @opcode(0xfd, 0x61) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sub_i8(zero_vector(), a);
+ vector_result(value, offset);
+}
+
+handler I16x8Abs() @opcode(0xfd, 0x80) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_abs_i16(a);
+ vector_result(value, offset);
+}
+
+handler I16x8Neg() @opcode(0xfd, 0x81) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sub_i16(zero_vector(), a);
+ vector_result(value, offset);
+}
+
+handler I32x4Abs() @opcode(0xfd, 0xa0) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_abs_i32(a);
+ vector_result(value, offset);
+}
+
+handler I32x4Neg() @opcode(0xfd, 0xa1) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sub_i32(zero_vector(), a);
+ vector_result(value, offset);
+}
+
+handler I64x2Abs() @opcode(0xfd, 0xc0) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let sign = v128_gt_s_i64(zero_vector(), a);
+ let value = v128_sub_i64(v128_xor(a, sign), sign);
+ vector_result(value, offset);
+}
+
+handler I64x2Neg() @opcode(0xfd, 0xc1) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sub_i64(zero_vector(), a);
+ vector_result(value, offset);
+}
+
+handler I8x16Popcnt() @opcode(0xfd, 0x62) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let low = slots[0];
+ let high = slots[1];
+ let low_1 = low - ((low >> 1) & 0x5555555555555555);
+ let low_2 = (low_1 & 0x3333333333333333) + ((low_1 >> 2) & 0x3333333333333333);
+ let low_3 = (low_2 + (low_2 >> 4)) & 0x0f0f0f0f0f0f0f0f;
+ let high_1 = high - ((high >> 1) & 0x5555555555555555);
+ let high_2 = (high_1 & 0x3333333333333333) + ((high_1 >> 2) & 0x3333333333333333);
+ let high_3 = (high_2 + (high_2 >> 4)) & 0x0f0f0f0f0f0f0f0f;
+ slots[0] = low_3;
+ slots[1] = high_3;
+ advance(offset);
+}
+
+handler I8x16NarrowI16x8S() @opcode(0xfd, 0x65) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_narrow_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16NarrowI16x8U() @opcode(0xfd, 0x66) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_narrow_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8NarrowI32x4S() @opcode(0xfd, 0x85) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_narrow_s_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8NarrowI32x4U() @opcode(0xfd, 0x86) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_narrow_u_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Ceil() @opcode(0xfd, 0x67) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_ceil_f32(a);
+ vector_result(value, offset);
+}
+
+handler F32x4Floor() @opcode(0xfd, 0x68) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_floor_f32(a);
+ vector_result(value, offset);
+}
+
+handler F32x4Trunc() @opcode(0xfd, 0x69) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_trunc_f32(a);
+ vector_result(value, offset);
+}
+
+handler F32x4Nearest() @opcode(0xfd, 0x6a) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_nearest_f32(a);
+ vector_result(value, offset);
+}
+
+handler F64x2Ceil() @opcode(0xfd, 0x74) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_ceil_f64(a);
+ vector_result(value, offset);
+}
+
+handler F64x2Floor() @opcode(0xfd, 0x75) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_floor_f64(a);
+ vector_result(value, offset);
+}
+
+handler F64x2Trunc() @opcode(0xfd, 0x7a) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_trunc_f64(a);
+ vector_result(value, offset);
+}
+
+handler F64x2Nearest() @opcode(0xfd, 0x94) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_nearest_f64(a);
+ vector_result(value, offset);
+}
+
+handler I16x8Shl() @opcode(0xfd, 0x8b) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(15);
+ let a = top_vector();
+ let value = v128_shl_i16(a, count);
+ vector_result(value, offset);
+}
+
+handler I16x8ShrS() @opcode(0xfd, 0x8c) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(15);
+ let a = top_vector();
+ let value = v128_shr_s_i16(a, count);
+ vector_result(value, offset);
+}
+
+handler I16x8ShrU() @opcode(0xfd, 0x8d) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(15);
+ let a = top_vector();
+ let value = v128_shr_u_i16(a, count);
+ vector_result(value, offset);
+}
+
+handler I32x4Shl() @opcode(0xfd, 0xab) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(31);
+ let a = top_vector();
+ let value = v128_shl_i32(a, count);
+ vector_result(value, offset);
+}
+
+handler I32x4ShrS() @opcode(0xfd, 0xac) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(31);
+ let a = top_vector();
+ let value = v128_shr_s_i32(a, count);
+ vector_result(value, offset);
+}
+
+handler I32x4ShrU() @opcode(0xfd, 0xad) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(31);
+ let a = top_vector();
+ let value = v128_shr_u_i32(a, count);
+ vector_result(value, offset);
+}
+
+handler I64x2Shl() @opcode(0xfd, 0xcb) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(63);
+ let a = top_vector();
+ let value = v128_shl_i64(a, count);
+ vector_result(value, offset);
+}
+
+handler I64x2ShrU() @opcode(0xfd, 0xcd) {
+ let [_, offset] = prefixed_immediates();
+ let count = shift_count(63);
+ let a = top_vector();
+ let value = v128_shr_u_i64(a, count);
+ vector_result(value, offset);
+}
+
+handler I64x2ShrS() @opcode(0xfd, 0xcc) {
+ let [_, offset] = prefixed_immediates();
+ let raw_count = pop();
+ let masked = raw_count & 63;
+ let count = v128_from_u64x2(masked, 0);
+ let lane_bits: u64 = 64;
+ let complement = lane_bits - masked;
+ let fill_count = v128_from_u64x2(complement, 0);
+ let a = top_vector();
+ # Shift logically, and fill the vacated bits from the sign.
+ let sign = v128_gt_s_i64(zero_vector(), a);
+ let shifted = v128_shr_u_i64(a, count);
+ let fill = v128_shl_i64(sign, fill_count);
+ let value = v128_or(shifted, fill);
+ vector_result(value, offset);
+}
+
+handler I8x16Shl() @opcode(0xfd, 0x6b) {
+ let [_, offset] = prefixed_immediates();
+ let raw_count = pop();
+ let masked = raw_count & 7;
+ let count = v128_from_u64x2(masked, 0);
+ let a = top_vector();
+ # Shift 16-bit lanes and clear the bits that crossed into the next byte.
+ let shifted = v128_shl_i16(a, count);
+ let all_bits: u64 = 0xff;
+ let byte_mask = (all_bits << masked) & 0xff;
+ let value = v128_and(shifted, splat_i8(byte_mask));
+ vector_result(value, offset);
+}
+
+handler I8x16ShrU() @opcode(0xfd, 0x6d) {
+ let [_, offset] = prefixed_immediates();
+ let raw_count = pop();
+ let masked = raw_count & 7;
+ let count = v128_from_u64x2(masked, 0);
+ let a = top_vector();
+ let shifted = v128_shr_u_i16(a, count);
+ let all_bits: u64 = 0xff;
+ let byte_mask = all_bits >> masked;
+ let value = v128_and(shifted, splat_i8(byte_mask));
+ vector_result(value, offset);
+}
+
+handler I8x16ShrS() @opcode(0xfd, 0x6c) {
+ let [_, offset] = prefixed_immediates();
+ let raw_count = pop();
+ let masked = raw_count & 7;
+ let count = v128_from_u64x2(masked + 8, 0);
+ let a = top_vector();
+ # Each byte goes into the high byte of a 16-bit lane, which shifts arithmetically, and narrows back.
+ let low = v128_interleave_low_i8(a, a);
+ let high = v128_interleave_high_i8(a, a);
+ let shifted_low = v128_shr_s_i16(low, count);
+ let shifted_high = v128_shr_s_i16(high, count);
+ let value = v128_narrow_s_i16(shifted_low, shifted_high);
+ vector_result(value, offset);
+}
+
+handler I8x16Add() @opcode(0xfd, 0x6e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16AddSatS() @opcode(0xfd, 0x6f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_sat_s_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16AddSatU() @opcode(0xfd, 0x70) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_sat_u_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16Sub() @opcode(0xfd, 0x71) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16SubSatS() @opcode(0xfd, 0x72) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_sat_s_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16SubSatU() @opcode(0xfd, 0x73) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_sat_u_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8Add() @opcode(0xfd, 0x8e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8AddSatS() @opcode(0xfd, 0x8f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_sat_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8AddSatU() @opcode(0xfd, 0x90) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_sat_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8Sub() @opcode(0xfd, 0x91) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8SubSatS() @opcode(0xfd, 0x92) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_sat_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8SubSatU() @opcode(0xfd, 0x93) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_sat_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16MinS() @opcode(0xfd, 0x76) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_s_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16MinU() @opcode(0xfd, 0x77) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_u_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16MaxS() @opcode(0xfd, 0x78) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_s_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16MaxU() @opcode(0xfd, 0x79) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_u_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8MinS() @opcode(0xfd, 0x96) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8MinU() @opcode(0xfd, 0x97) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8MaxS() @opcode(0xfd, 0x98) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_s_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8MaxU() @opcode(0xfd, 0x99) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4MinS() @opcode(0xfd, 0xb6) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_s_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4MinU() @opcode(0xfd, 0xb7) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_u_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4MaxS() @opcode(0xfd, 0xb8) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_s_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4MaxU() @opcode(0xfd, 0xb9) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_u_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I8x16AvgrU() @opcode(0xfd, 0x7b) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_avgr_u_i8(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8AvgrU() @opcode(0xfd, 0x9b) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_avgr_u_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtaddPairwiseI8x16S() @opcode(0xfd, 0x7c) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_madd_u8_s8(splat_i8(1), a);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtaddPairwiseI8x16U() @opcode(0xfd, 0x7d) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_madd_u8_s8(a, splat_i8(1));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtaddPairwiseI16x8S() @opcode(0xfd, 0x7e) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_madd_i16(a, splat_i16(1));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtaddPairwiseI16x8U() @opcode(0xfd, 0x7f) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_add_i32(v128_madd_i16(v128_xor(a, splat_i16(0x8000)), splat_i16(1)), splat_i32(0x10000));
+ vector_result(value, offset);
+}
+
+handler I16x8Q15mulrSatS() @opcode(0xfd, 0x82) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # The only product that overflows is -1 * -1, which gives 0x8000 and must saturate to 0x7fff.
+ let product = v128_mulhrs_i16(a, b);
+ let overflowed = v128_eq_i16(product, splat_i16(0x8000));
+ let value = v128_xor(product, overflowed);
+ vector_result(value, offset);
+}
+
+handler I16x8RelaxedQ15mulrS() @opcode(0xfd, 0x111) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # The only product that overflows is -1 * -1, which gives 0x8000 and must saturate to 0x7fff.
+ let product = v128_mulhrs_i16(a, b);
+ let overflowed = v128_eq_i16(product, splat_i16(0x8000));
+ let value = v128_xor(product, overflowed);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtendLowI8x16S() @opcode(0xfd, 0x87) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i8(a);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtendHighI8x16S() @opcode(0xfd, 0x88) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i8(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I16x8ExtendLowI8x16U() @opcode(0xfd, 0x89) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i8(a);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtendHighI8x16U() @opcode(0xfd, 0x8a) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i8(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtendLowI16x8S() @opcode(0xfd, 0xa7) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i16(a);
+ vector_result(value, offset);
+}
+
+handler I32x4ExtendHighI16x8S() @opcode(0xfd, 0xa8) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i16(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtendLowI16x8U() @opcode(0xfd, 0xa9) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i16(a);
+ vector_result(value, offset);
+}
+
+handler I32x4ExtendHighI16x8U() @opcode(0xfd, 0xaa) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i16(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I64x2ExtendLowI32x4S() @opcode(0xfd, 0xc7) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i32(a);
+ vector_result(value, offset);
+}
+
+handler I64x2ExtendHighI32x4S() @opcode(0xfd, 0xc8) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_s_i32(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I64x2ExtendLowI32x4U() @opcode(0xfd, 0xc9) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i32(a);
+ vector_result(value, offset);
+}
+
+handler I64x2ExtendHighI32x4U() @opcode(0xfd, 0xca) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_extend_low_u_i32(v128_high_half(a));
+ vector_result(value, offset);
+}
+
+handler I16x8Mul() @opcode(0xfd, 0x95) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I16x8ExtmulLowI8x16S() @opcode(0xfd, 0x9c) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i16(v128_extend_low_s_i8(a), v128_extend_low_s_i8(b));
+ vector_result(value, offset);
+}
+
+handler I16x8ExtmulHighI8x16S() @opcode(0xfd, 0x9d) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i16(v128_extend_low_s_i8(v128_high_half(a)), v128_extend_low_s_i8(v128_high_half(b)));
+ vector_result(value, offset);
+}
+
+handler I16x8ExtmulLowI8x16U() @opcode(0xfd, 0x9e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i16(v128_extend_low_u_i8(a), v128_extend_low_u_i8(b));
+ vector_result(value, offset);
+}
+
+handler I16x8ExtmulHighI8x16U() @opcode(0xfd, 0x9f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i16(v128_extend_low_u_i8(v128_high_half(a)), v128_extend_low_u_i8(v128_high_half(b)));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtmulLowI16x8S() @opcode(0xfd, 0xbc) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i32(v128_extend_low_s_i16(a), v128_extend_low_s_i16(b));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtmulHighI16x8S() @opcode(0xfd, 0xbd) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i32(v128_extend_low_s_i16(v128_high_half(a)), v128_extend_low_s_i16(v128_high_half(b)));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtmulLowI16x8U() @opcode(0xfd, 0xbe) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i32(v128_extend_low_u_i16(a), v128_extend_low_u_i16(b));
+ vector_result(value, offset);
+}
+
+handler I32x4ExtmulHighI16x8U() @opcode(0xfd, 0xbf) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i32(v128_extend_low_u_i16(v128_high_half(a)), v128_extend_low_u_i16(v128_high_half(b)));
+ vector_result(value, offset);
+}
+
+handler I64x2ExtmulLowI32x4U() @opcode(0xfd, 0xde) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_u32_to_u64(v128_extend_low_u_i32(a), v128_extend_low_u_i32(b));
+ vector_result(value, offset);
+}
+
+handler I64x2ExtmulHighI32x4U() @opcode(0xfd, 0xdf) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_u32_to_u64(v128_extend_low_u_i32(v128_high_half(a)), v128_extend_low_u_i32(v128_high_half(b)));
+ vector_result(value, offset);
+}
+
+handler I64x2ExtmulLowI32x4S() @opcode(0xfd, 0xdc) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut b0: u64;
+ load32(b0, [top, 0]);
+ let mut b1: u64;
+ load32(b1, [top, 4]);
+ let mut a0: u64;
+ load32(a0, [top, 16]);
+ let mut a1: u64;
+ load32(a1, [top, 20]);
+ let extended_a0 = sign_extend_32(a0);
+ let product0 = extended_a0 * sign_extend_32(b0);
+ let extended_a1 = sign_extend_32(a1);
+ let product1 = extended_a1 * sign_extend_32(b1);
+ let next = top + 16;
+ vsp = next;
+ set_top_halves(product0, product1);
+ advance(offset);
+}
+
+handler I64x2ExtmulHighI32x4S() @opcode(0xfd, 0xdd) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut b0: u64;
+ load32(b0, [top, 8]);
+ let mut b1: u64;
+ load32(b1, [top, 12]);
+ let mut a0: u64;
+ load32(a0, [top, 24]);
+ let mut a1: u64;
+ load32(a1, [top, 28]);
+ let extended_a0 = sign_extend_32(a0);
+ let product0 = extended_a0 * sign_extend_32(b0);
+ let extended_a1 = sign_extend_32(a1);
+ let product1 = extended_a1 * sign_extend_32(b1);
+ let next = top + 16;
+ vsp = next;
+ set_top_halves(product0, product1);
+ advance(offset);
+}
+
+handler I32x4Add() @opcode(0xfd, 0xae) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4Sub() @opcode(0xfd, 0xb1) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4Mul() @opcode(0xfd, 0xb5) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_i32(a, b);
+ vector_result(value, offset);
+}
+
+handler I32x4DotI16x8S() @opcode(0xfd, 0xba) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_madd_i16(a, b);
+ vector_result(value, offset);
+}
+
+handler I64x2Add() @opcode(0xfd, 0xce) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_i64(a, b);
+ vector_result(value, offset);
+}
+
+handler I64x2Sub() @opcode(0xfd, 0xd1) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_i64(a, b);
+ vector_result(value, offset);
+}
+
+handler I64x2Mul() @opcode(0xfd, 0xd5) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let a_low = slots[2];
+ let a_high = slots[3];
+ let low = a_low * slots[0];
+ let high = a_high * slots[1];
+ let next = top + 16;
+ vsp = next;
+ set_top_halves(low, high);
+ advance(offset);
+}
+
+handler I64x2Eq() @opcode(0xfd, 0xd6) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_eq_i64(a, b);
+ vector_result(value, offset);
+}
+
+handler I64x2Ne() @opcode(0xfd, 0xd7) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_eq_i64(a, b));
+ vector_result(value, offset);
+}
+
+handler I64x2LtS() @opcode(0xfd, 0xd8) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i64(b, a);
+ vector_result(value, offset);
+}
+
+handler I64x2GtS() @opcode(0xfd, 0xd9) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_gt_s_i64(a, b);
+ vector_result(value, offset);
+}
+
+handler I64x2LeS() @opcode(0xfd, 0xda) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_gt_s_i64(a, b));
+ vector_result(value, offset);
+}
+
+handler I64x2GeS() @opcode(0xfd, 0xdb) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = not_vector(v128_gt_s_i64(b, a));
+ vector_result(value, offset);
+}
+
+handler F32x4Abs() @opcode(0xfd, 0xe0) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_and(a, splat_u64(0x7fffffff7fffffff));
+ vector_result(value, offset);
+}
+
+handler F32x4Neg() @opcode(0xfd, 0xe1) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_xor(a, splat_u64(0x8000000080000000));
+ vector_result(value, offset);
+}
+
+handler F32x4Sqrt() @opcode(0xfd, 0xe3) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sqrt_f32(a);
+ vector_result(value, offset);
+}
+
+handler F32x4Add() @opcode(0xfd, 0xe4) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Sub() @opcode(0xfd, 0xe5) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Mul() @opcode(0xfd, 0xe6) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Div() @opcode(0xfd, 0xe7) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_div_f32(a, b);
+ vector_result(value, offset);
+}
+
+handler F32x4Min() @opcode(0xfd, 0xe8) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes canonical.
+ let first = v128_min_f32(a, b);
+ let second = v128_min_f32(b, a);
+ let merged = v128_or(first, second);
+ let nan_lanes = v128_unord_f32(merged, merged);
+ let with_nans = v128_or(merged, nan_lanes);
+ let payload = v128_shr_u_i32(nan_lanes, v128_from_u64x2(10, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F32x4Max() @opcode(0xfd, 0xe9) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN lanes are canonical.
+ let first = v128_max_f32(a, b);
+ let second = v128_max_f32(b, a);
+ let differences = v128_xor(first, second);
+ let propagated = v128_or(second, differences);
+ let with_nans = v128_sub_f32(propagated, differences);
+ let nan_lanes = v128_unord_f32(differences, with_nans);
+ let payload = v128_shr_u_i32(nan_lanes, v128_from_u64x2(10, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F32x4Pmin() @opcode(0xfd, 0xea) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_f32(b, a);
+ vector_result(value, offset);
+}
+
+handler F32x4Pmax() @opcode(0xfd, 0xeb) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_f32(b, a);
+ vector_result(value, offset);
+}
+
+handler F32x4RelaxedMin() @opcode(0xfd, 0x10d) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes canonical.
+ let first = v128_min_f32(a, b);
+ let second = v128_min_f32(b, a);
+ let merged = v128_or(first, second);
+ let nan_lanes = v128_unord_f32(merged, merged);
+ let with_nans = v128_or(merged, nan_lanes);
+ let payload = v128_shr_u_i32(nan_lanes, v128_from_u64x2(10, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F32x4RelaxedMax() @opcode(0xfd, 0x10e) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN lanes are canonical.
+ let first = v128_max_f32(a, b);
+ let second = v128_max_f32(b, a);
+ let differences = v128_xor(first, second);
+ let propagated = v128_or(second, differences);
+ let with_nans = v128_sub_f32(propagated, differences);
+ let nan_lanes = v128_unord_f32(differences, with_nans);
+ let payload = v128_shr_u_i32(nan_lanes, v128_from_u64x2(10, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F32x4RelaxedMadd() @opcode(0xfd, 0x105) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut addend: v128;
+ load128(addend, [top, 0]);
+ let mut b: v128;
+ load128(b, [top, 16]);
+ let mut a: v128;
+ load128(a, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let product = v128_mul_f32(a, b);
+ let value = v128_add_f32(product, addend);
+ vector_result(value, offset);
+}
+
+handler F32x4RelaxedNmadd() @opcode(0xfd, 0x106) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut addend: v128;
+ load128(addend, [top, 0]);
+ let mut b: v128;
+ load128(b, [top, 16]);
+ let mut a: v128;
+ load128(a, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let product = v128_mul_f32(a, b);
+ let value = v128_sub_f32(addend, product);
+ vector_result(value, offset);
+}
+
+handler F64x2Abs() @opcode(0xfd, 0xec) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_and(a, splat_u64(0x7fffffffffffffff));
+ vector_result(value, offset);
+}
+
+handler F64x2Neg() @opcode(0xfd, 0xed) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_xor(a, splat_u64(0x8000000000000000));
+ vector_result(value, offset);
+}
+
+handler F64x2Sqrt() @opcode(0xfd, 0xef) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_sqrt_f64(a);
+ vector_result(value, offset);
+}
+
+handler F64x2Add() @opcode(0xfd, 0xf0) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_add_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Sub() @opcode(0xfd, 0xf1) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_sub_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Mul() @opcode(0xfd, 0xf2) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_mul_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Div() @opcode(0xfd, 0xf3) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_div_f64(a, b);
+ vector_result(value, offset);
+}
+
+handler F64x2Min() @opcode(0xfd, 0xf4) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes canonical.
+ let first = v128_min_f64(a, b);
+ let second = v128_min_f64(b, a);
+ let merged = v128_or(first, second);
+ let nan_lanes = v128_unord_f64(merged, merged);
+ let with_nans = v128_or(merged, nan_lanes);
+ let payload = v128_shr_u_i64(nan_lanes, v128_from_u64x2(13, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F64x2Max() @opcode(0xfd, 0xf5) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN lanes are canonical.
+ let first = v128_max_f64(a, b);
+ let second = v128_max_f64(b, a);
+ let differences = v128_xor(first, second);
+ let propagated = v128_or(second, differences);
+ let with_nans = v128_sub_f64(propagated, differences);
+ let nan_lanes = v128_unord_f64(differences, with_nans);
+ let payload = v128_shr_u_i64(nan_lanes, v128_from_u64x2(13, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F64x2Pmin() @opcode(0xfd, 0xf6) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_min_f64(b, a);
+ vector_result(value, offset);
+}
+
+handler F64x2Pmax() @opcode(0xfd, 0xf7) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_max_f64(b, a);
+ vector_result(value, offset);
+}
+
+handler F64x2RelaxedMin() @opcode(0xfd, 0x10f) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN or -0 in either operand makes it into the result, and NaN lanes canonical.
+ let first = v128_min_f64(a, b);
+ let second = v128_min_f64(b, a);
+ let merged = v128_or(first, second);
+ let nan_lanes = v128_unord_f64(merged, merged);
+ let with_nans = v128_or(merged, nan_lanes);
+ let payload = v128_shr_u_i64(nan_lanes, v128_from_u64x2(13, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F64x2RelaxedMax() @opcode(0xfd, 0x110) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ # Both orders, so that a NaN in either operand makes it into the result, +0 beats -0, and NaN lanes are canonical.
+ let first = v128_max_f64(a, b);
+ let second = v128_max_f64(b, a);
+ let differences = v128_xor(first, second);
+ let propagated = v128_or(second, differences);
+ let with_nans = v128_sub_f64(propagated, differences);
+ let nan_lanes = v128_unord_f64(differences, with_nans);
+ let payload = v128_shr_u_i64(nan_lanes, v128_from_u64x2(13, 0));
+ let value = v128_andnot(payload, with_nans);
+ vector_result(value, offset);
+}
+
+handler F64x2RelaxedMadd() @opcode(0xfd, 0x107) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut addend: v128;
+ load128(addend, [top, 0]);
+ let mut b: v128;
+ load128(b, [top, 16]);
+ let mut a: v128;
+ load128(a, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let product = v128_mul_f64(a, b);
+ let value = v128_add_f64(product, addend);
+ vector_result(value, offset);
+}
+
+handler F64x2RelaxedNmadd() @opcode(0xfd, 0x108) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut addend: v128;
+ load128(addend, [top, 0]);
+ let mut b: v128;
+ load128(b, [top, 16]);
+ let mut a: v128;
+ load128(a, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let product = v128_mul_f64(a, b);
+ let value = v128_sub_f64(addend, product);
+ vector_result(value, offset);
+}
+
+handler F32x4ConvertI32x4S() @opcode(0xfd, 0xfa) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_convert_s_i32_f32(a);
+ vector_result(value, offset);
+}
+
+handler F64x2ConvertLowI32x4S() @opcode(0xfd, 0xfe) {
+ let [_, offset] = prefixed_immediates();
+ let a = top_vector();
+ let value = v128_convert_low_s_i32_f64(a);
+ vector_result(value, offset);
+}
+
+handler I32x4TruncSatF32x4S() @opcode(0xfd, 0xf8) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load32(bits0, [top, 0]);
+ let value0 = f32_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits1: u64;
+ load32(bits1, [top, 4]);
+ let value1 = f32_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits2: u64;
+ load32(bits2, [top, 8]);
+ let value2 = f32_value(bits2);
+ let truncated2 = saturating_truncation(value2, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits3: u64;
+ load32(bits3, [top, 12]);
+ let value3 = f32_value(bits3);
+ let truncated3 = saturating_truncation(value3, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store32([top, 8], truncated2);
+ store32([top, 12], truncated3);
+ advance(offset);
+}
+
+handler I32x4TruncSatF32x4U() @opcode(0xfd, 0xf9) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load32(bits0, [top, 0]);
+ let value0 = f32_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits1: u64;
+ load32(bits1, [top, 4]);
+ let value1 = f32_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits2: u64;
+ load32(bits2, [top, 8]);
+ let value2 = f32_value(bits2);
+ let truncated2 = saturating_truncation(value2, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits3: u64;
+ load32(bits3, [top, 12]);
+ let value3 = f32_value(bits3);
+ let truncated3 = saturating_truncation(value3, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store32([top, 8], truncated2);
+ store32([top, 12], truncated3);
+ advance(offset);
+}
+
+handler I32x4TruncSatF64x2SZero() @opcode(0xfd, 0xfc) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load64(bits0, [top, 0]);
+ let value0 = f64_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits1: u64;
+ load64(bits1, [top, 8]);
+ let value1 = f64_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store64([top, 8], 0);
+ advance(offset);
+}
+
+handler I32x4TruncSatF64x2UZero() @opcode(0xfd, 0xfd) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load64(bits0, [top, 0]);
+ let value0 = f64_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits1: u64;
+ load64(bits1, [top, 8]);
+ let value1 = f64_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store64([top, 8], 0);
+ advance(offset);
+}
+
+handler I32x4RelaxedTruncF32x4S() @opcode(0xfd, 0x101) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load32(bits0, [top, 0]);
+ let value0 = f32_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits1: u64;
+ load32(bits1, [top, 4]);
+ let value1 = f32_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits2: u64;
+ load32(bits2, [top, 8]);
+ let value2 = f32_value(bits2);
+ let truncated2 = saturating_truncation(value2, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits3: u64;
+ load32(bits3, [top, 12]);
+ let value3 = f32_value(bits3);
+ let truncated3 = saturating_truncation(value3, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store32([top, 8], truncated2);
+ store32([top, 12], truncated3);
+ advance(offset);
+}
+
+handler I32x4RelaxedTruncF32x4U() @opcode(0xfd, 0x102) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load32(bits0, [top, 0]);
+ let value0 = f32_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits1: u64;
+ load32(bits1, [top, 4]);
+ let value1 = f32_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits2: u64;
+ load32(bits2, [top, 8]);
+ let value2 = f32_value(bits2);
+ let truncated2 = saturating_truncation(value2, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits3: u64;
+ load32(bits3, [top, 12]);
+ let value3 = f32_value(bits3);
+ let truncated3 = saturating_truncation(value3, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store32([top, 8], truncated2);
+ store32([top, 12], truncated3);
+ advance(offset);
+}
+
+handler I32x4RelaxedTruncF64x2SZero() @opcode(0xfd, 0x103) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load64(bits0, [top, 0]);
+ let value0 = f64_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ let mut bits1: u64;
+ load64(bits1, [top, 8]);
+ let value1 = f64_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xc1e0000000200000, 0x41e0000000000000, 0x80000000, 0x7fffffff, 0);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store64([top, 8], 0);
+ advance(offset);
+}
+
+handler I32x4RelaxedTruncF64x2UZero() @opcode(0xfd, 0x104) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut bits0: u64;
+ load64(bits0, [top, 0]);
+ let value0 = f64_value(bits0);
+ let truncated0 = saturating_truncation(value0, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ let mut bits1: u64;
+ load64(bits1, [top, 8]);
+ let value1 = f64_value(bits1);
+ let truncated1 = saturating_truncation(value1, 0xbff0000000000000, 0x41f0000000000000, 0, 0xffffffff, 1);
+ store32([top, 0], truncated0);
+ store32([top, 4], truncated1);
+ store64([top, 8], 0);
+ advance(offset);
+}
+
+handler F32x4ConvertI32x4U() @opcode(0xfd, 0xfb) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut lane0: u64;
+ load32(lane0, [top, 0]);
+ let converted0 = s64_to_f32(lane0);
+ let bits0 = f32_to_bits(converted0);
+ let mut lane1: u64;
+ load32(lane1, [top, 4]);
+ let converted1 = s64_to_f32(lane1);
+ let bits1 = f32_to_bits(converted1);
+ let mut lane2: u64;
+ load32(lane2, [top, 8]);
+ let converted2 = s64_to_f32(lane2);
+ let bits2 = f32_to_bits(converted2);
+ let mut lane3: u64;
+ load32(lane3, [top, 12]);
+ let converted3 = s64_to_f32(lane3);
+ let bits3 = f32_to_bits(converted3);
+ store32([top, 0], bits0);
+ store32([top, 4], bits1);
+ store32([top, 8], bits2);
+ store32([top, 12], bits3);
+ advance(offset);
+}
+
+handler F64x2ConvertLowI32x4U() @opcode(0xfd, 0xff) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut lane0: u64;
+ load32(lane0, [top, 0]);
+ let mut lane1: u64;
+ load32(lane1, [top, 4]);
+ let converted0 = s64_to_f64(lane0);
+ let converted1 = s64_to_f64(lane1);
+ let bits0 = f64_to_bits(converted0);
+ let bits1 = f64_to_bits(converted1);
+ set_top_halves(bits0, bits1);
+ advance(offset);
+}
+
+handler I16x8RelaxedDotI8x16I7x16S() @opcode(0xfd, 0x112) {
+ let [_, offset] = prefixed_immediates();
+ let [a, b] = binary_vectors();
+ let value = v128_madd_u8_s8(b, a);
+ vector_result(value, offset);
+}
+
+handler I32x4RelaxedDotI8x16I7x16AddS() @opcode(0xfd, 0x113) {
+ let [_, offset] = prefixed_immediates();
+ let top: u64 = vsp;
+ let mut addend: v128;
+ load128(addend, [top, 0]);
+ let mut b: v128;
+ load128(b, [top, 16]);
+ let mut a: v128;
+ load128(a, [top, 32]);
+ let next = top + 32;
+ vsp = next;
+ let pairs = v128_madd_u8_s8(b, a);
+ let quads = v128_madd_i16(pairs, splat_i16(1));
+ let value = v128_add_i32(quads, addend);
+ vector_result(value, offset);
+}
+
+# Bounds-checked SIMD accesses, for other memories and for memory64 (quickening rule 1).
+
+handler CheckedV128Load() @opcode(0xff, 0x80) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 16, 0);
+ let mut value: v128;
+ load128(value, [address, 0]);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128LoadIndexed() @opcode(0xff, 0xa0) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 16, 1);
+ let mut value: v128;
+ load128(value, [address, 0]);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8x8S() @opcode(0xff, 0x81) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8x8SIndexed() @opcode(0xff, 0xa1) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8x8U() @opcode(0xff, 0x82) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8x8UIndexed() @opcode(0xff, 0xa2) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i8(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load16x4S() @opcode(0xff, 0x83) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load16x4SIndexed() @opcode(0xff, 0xa3) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load16x4U() @opcode(0xff, 0x84) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load16x4UIndexed() @opcode(0xff, 0xa4) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i16(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load32x2S() @opcode(0xff, 0x85) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load32x2SIndexed() @opcode(0xff, 0xa5) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_s_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load32x2U() @opcode(0xff, 0x86) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load32x2UIndexed() @opcode(0xff, 0xa6) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut half: u64;
+ load64(half, [address, 0]);
+ let narrow = v128_from_u64x2(half, 0);
+ let value = v128_extend_low_u_i32(narrow);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8Splat() @opcode(0xff, 0x87) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let mut lane: u64;
+ load8(lane, [address, 0]);
+ let wide = lane * 0x0101010101010101;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load8SplatIndexed() @opcode(0xff, 0xa7) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let mut lane: u64;
+ load8(lane, [address, 0]);
+ let wide = lane * 0x0101010101010101;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load16Splat() @opcode(0xff, 0x88) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let mut lane: u64;
+ load16(lane, [address, 0]);
+ let wide = lane * 0x0001000100010001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load16SplatIndexed() @opcode(0xff, 0xa8) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let mut lane: u64;
+ load16(lane, [address, 0]);
+ let wide = lane * 0x0001000100010001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load32Splat() @opcode(0xff, 0x89) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ let wide = lane * 0x0000000100000001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load32SplatIndexed() @opcode(0xff, 0xa9) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ let wide = lane * 0x0000000100000001;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load64Splat() @opcode(0xff, 0x8a) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ let wide = lane;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load64SplatIndexed() @opcode(0xff, 0xaa) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ let wide = lane;
+ replace_with_halves(0, wide, wide);
+ advance(length);
+}
+
+handler CheckedV128Load32Zero() @opcode(0xff, 0x94) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler CheckedV128Load32ZeroIndexed() @opcode(0xff, 0xb4) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let mut lane: u64;
+ load32(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler CheckedV128Load64Zero() @opcode(0xff, 0x95) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler CheckedV128Load64ZeroIndexed() @opcode(0xff, 0xb5) {
+ let address_operand = pop();
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let mut lane: u64;
+ load64(lane, [address, 0]);
+ replace_with_halves(0, lane, 0);
+ advance(length);
+}
+
+handler CheckedV128Store() @opcode(0xff, 0x8b) {
+ let value = top_vector();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let next = top + 24;
+ vsp = next;
+ let [address, length] = checked_access_address(address_operand, 16, 0);
+ store128([address, 0], value);
+ advance(length);
+}
+
+handler CheckedV128StoreIndexed() @opcode(0xff, 0xab) {
+ let value = top_vector();
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let next = top + 24;
+ vsp = next;
+ let [address, length] = checked_access_address(address_operand, 16, 1);
+ store128([address, 0], value);
+ advance(length);
+}
+
+handler CheckedV128Load8Lane() @opcode(0xff, 0x8c) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ let lane_address = top + (lane * 1);
+ store8([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load8LaneIndexed() @opcode(0xff, 0xac) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load8(value, [address, 0]);
+ let lane_address = top + (lane * 1);
+ store8([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load16Lane() @opcode(0xff, 0x8d) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ let lane_address = top + (lane * 2);
+ store16([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load16LaneIndexed() @opcode(0xff, 0xad) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load16(value, [address, 0]);
+ let lane_address = top + (lane * 2);
+ store16([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load32Lane() @opcode(0xff, 0x8e) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let lane_address = top + (lane * 4);
+ store32([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load32LaneIndexed() @opcode(0xff, 0xae) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load32(value, [address, 0]);
+ let lane_address = top + (lane * 4);
+ store32([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load64Lane() @opcode(0xff, 0x8f) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ let lane_address = top + (lane * 8);
+ store64([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Load64LaneIndexed() @opcode(0xff, 0xaf) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ let lane_address = top + (lane * 8);
+ store64([lane_address, 0], value);
+ # The vector moves up into the address's slot.
+ let low = slots[0];
+ let high = slots[1];
+ slots[2] = high;
+ slots[1] = low;
+ let next = top + 8;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store8Lane() @opcode(0xff, 0x90) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 1, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 1);
+ let mut value: u64;
+ load8(value, [lane_address, 0]);
+ store8([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store8LaneIndexed() @opcode(0xff, 0xb0) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 1, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 1);
+ let mut value: u64;
+ load8(value, [lane_address, 0]);
+ store8([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store16Lane() @opcode(0xff, 0x91) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 2, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 2);
+ let mut value: u64;
+ load16(value, [lane_address, 0]);
+ store16([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store16LaneIndexed() @opcode(0xff, 0xb1) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 2, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 2);
+ let mut value: u64;
+ load16(value, [lane_address, 0]);
+ store16([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store32Lane() @opcode(0xff, 0x92) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 4, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 4);
+ let mut value: u64;
+ load32(value, [lane_address, 0]);
+ store32([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store32LaneIndexed() @opcode(0xff, 0xb2) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 4, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 4);
+ let mut value: u64;
+ load32(value, [lane_address, 0]);
+ store32([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store64Lane() @opcode(0xff, 0x93) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 8, 0);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 8);
+ let mut value: u64;
+ load64(value, [lane_address, 0]);
+ store64([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+handler CheckedV128Store64LaneIndexed() @opcode(0xff, 0xb3) {
+ let top: u64 = vsp;
+ let slots: Sequence<u64> = alias(top);
+ let address_operand = slots[2];
+ let [address, length] = checked_access_address(address_operand, 8, 1);
+ let current: u64 = ip;
+ let lane_bytes: Sequence<u8> = alias(current + length);
+ let lane: u64 = alias(lane_bytes[0]);
+ let lane_address = top + (lane * 8);
+ let mut value: u64;
+ load64(value, [lane_address, 0]);
+ store64([address, 0], value);
+ let next = top + 24;
+ vsp = next;
+ advance(length + 1);
+}
+
+inline fn sign_extend_32(value: u64) -> u64 {
+ let narrow = i32(value);
+ let wide: u64 = alias(i64(narrow));
+ wide
+}
+
+# The v128 forms of instructions that move values (quickening rule 2). The scalar slot of a v128 local holds the
+# address of its 16-byte storage.
+
+handler LocalGetV128() @opcode(0xf4) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let storage = locals[index];
+ let mut value: v128;
+ load128(value, [storage, 0]);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length + 1);
+}
+
+handler LocalSetV128() @opcode(0xf5) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let storage = locals[index];
+ let value = top_vector();
+ store128([storage, 0], value);
+ drop_slots(2);
+ advance(length + 1);
+}
+
+handler LocalTeeV128() @opcode(0xf6) {
+ let [index, length] = read_leb(immediates());
+ let locals: Sequence<u64> = alias(fp);
+ let storage = locals[index];
+ let value = top_vector();
+ store128([storage, 0], value);
+ advance(length + 1);
+}
+
+handler GlobalGetV128() @opcode(0xf7) {
+ let [index, length] = read_leb(immediates());
+ let address = global_address(index);
+ let mut value: v128;
+ load128(value, [address, 0]);
+ let top: u64 = vsp;
+ let next = top - 16;
+ vsp = next;
+ store128([next, 0], value);
+ advance(length + 1);
+}
+
+handler GlobalSetV128() @opcode(0xf8) {
+ let [index, length] = read_leb(immediates());
+ let address = global_address(index);
+ let value = top_vector();
+ store128([address, 0], value);
+ drop_slots(2);
+ advance(length + 1);
+}
+
+handler DropV128() @opcode(0xf9) {
+ drop_slots(2);
+ dispatch_next;
+}
+
+handler SelectV128() @opcode(0xfa) {
+ let condition = pop32();
+ let [first, second] = binary_vectors();
+ if condition == 0 {
+ set_top_vector(second);
+ }
+ dispatch_next;
+}
+
+# The GC proposal (the 0xFB prefix). See gc.rs for how references and objects are encoded.
+
+handler PrefixFB() @opcode(0xfb) {
+ let [sub_opcode, _] = read_leb(immediates());
+ dispatch_secondary(0xfb, sub_opcode);
+}
+
+# The runtime type of the module's type `type_index`.
+inline fn rtt_of_type(type_index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut identities_pointer: u64;
+ load64(identities_pointer, [instance_pointer, INSTANCE_TYPE_IDENTITIES]);
+ let identities: Sequence<u32> = alias(identities_pointer);
+ let identity: u64 = alias(identities[type_index]);
+ rtt_of_identity(identity)
+}
+
+inline fn rtt_of_identity(identity: u64) -> u64 {
+ let context_pointer = context();
+ let mut rtts_pointer: u64;
+ load64(rtts_pointer, [context_pointer, CONTEXT_RTTS]);
+ let rtts: Sequence<u64> = alias(rtts_pointer);
+ rtts[identity]
+}
+
+inline fn identity_of_type(type_index: u64) -> u64 {
+ let instance_pointer = instance();
+ let mut identities_pointer: u64;
+ load64(identities_pointer, [instance_pointer, INSTANCE_TYPE_IDENTITIES]);
+ let identities: Sequence<u32> = alias(identities_pointer);
+ let identity: u64 = alias(identities[type_index]);
+ identity
+}
+
+# Allocate a zeroed object of `size` bytes whose type is `rtt`.
+inline fn allocate_object(rtt: u64, size: u64) -> u64 {
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], rtt);
+ store64([context_pointer, CONTEXT_ARGUMENT_1], size);
+ let object: u64 = call_helper(wasm_runtime_allocate, context_pointer);
+ guard object != 0 else @cold {
+ trap(TRAP_RUNTIME);
+ };
+ object
+}
+
+# Whether `subtype` is the runtime type `identity` or one of its subtypes.
+inline fn rtt_is_subtype(subtype: u64, identity: u64) -> u64 {
+ let target = rtt_of_identity(identity);
+ let mut target_depth: u64;
+ load32(target_depth, [target, RTT_DEPTH]);
+ let mut depth: u64;
+ load32(depth, [subtype, RTT_DEPTH]);
+ let mut result: u64 = 0;
+ if depth >= target_depth {
+ let mut display_pointer: u64;
+ load64(display_pointer, [subtype, RTT_DISPLAY]);
+ let display: Sequence<u32> = alias(display_pointer);
+ let ancestor: u64 = alias(display[target_depth]);
+ if ancestor == identity {
+ result = 1;
+ }
+ }
+ result
+}
+
+# A field value as it is stored: packed fields keep only their bits.
+inline fn packed_value(value: u64, kind: u64) -> u64 {
+ let mut stored = value;
+ if kind == STORAGE_I8 {
+ stored = value & 0xff;
+ }
+ if kind == STORAGE_I16 {
+ stored = value & 0xffff;
+ }
+ stored
+}
+
+# A packed value sign-extended to an i32.
+inline fn sign_extend_packed(value: u64, kind: u64) -> u64 {
+ let mut shift: u64 = 48;
+ if kind == STORAGE_I8 {
+ shift = 56;
+ }
+ let moved = value << shift;
+ let signed = signed64(moved);
+ let extended = signed >> signed64(shift);
+ let narrow = u32(extended);
+ let result: u64 = alias(narrow);
+ result
+}
+
+# Push the value of the field or element at `address`, whose storage is `kind`, replacing `popped` slots.
+inline fn push_stored(address: u64, kind: u64, popped: u64) {
+ let mut low: u64;
+ load64(low, [address, 0]);
+ if kind == STORAGE_V128 {
+ let mut high: u64;
+ load64(high, [address, 8]);
+ replace_with_halves(popped, low, high);
+ } else {
+ let top: u64 = vsp;
+ let next = top + (popped << 3) - 8;
+ vsp = next;
+ store64([next, 0], low);
+ }
+}
+
+# Store the value on top of the operand stack into the field or element at `address`, whose storage is `kind`.
+inline fn pop_into_storage(address: u64, kind: u64) {
+ let low = pop();
+ if kind == STORAGE_V128 {
+ let high = pop();
+ store64([address, 0], low);
+ store64([address, 8], high);
+ } else {
+ let stored = packed_value(low, kind);
+ store64([address, 0], stored);
+ }
+}
+
+# The value of a v128 or other element, as two halves.
+inline fn pop_storage_value(kind: u64) -> (u64, u64) {
+ let low = pop();
+ let mut high: u64 = 0;
+ if kind == STORAGE_V128 {
+ high = pop();
+ }
+ let stored = packed_value(low, kind);
+ (stored, high)
+}
+
+inline fn store_storage_value(address: u64, kind: u64, low: u64, high: u64) {
+ store64([address, 0], low);
+ if kind == STORAGE_V128 {
+ store64([address, 8], high);
+ }
+}
+
+inline fn storage_size(kind: u64) -> u64 {
+ let mut size: u64 = 8;
+ if kind == STORAGE_V128 {
+ size = 16;
+ }
+ size
+}
+
+# The bytes an element of `kind` takes in a data segment.
+inline fn data_size(kind: u64) -> u64 {
+ let mut size: u64 = 8;
+ if kind == STORAGE_I8 {
+ size = 1;
+ }
+ if kind == STORAGE_I16 {
+ size = 2;
+ }
+ if kind == STORAGE_32 {
+ size = 4;
+ }
+ if kind == STORAGE_V128 {
+ size = 16;
+ }
+ size
+}
+
+# Copy `count` elements of `kind` from a data segment's bytes at `source` into elements at `destination`.
+inline fn copy_data_elements(destination: u64, source: u64, count: u64, kind: u64) {
+ let size = data_size(kind);
+ let element_size = storage_size(kind);
+ let mut index: u64 = 0;
+ while index < count {
+ let from = source + (index * size);
+ let to = destination + (index * element_size);
+ let mut low: u64 = 0;
+ let mut high: u64 = 0;
+ if kind == STORAGE_I8 {
+ load8(low, [from, 0]);
+ }
+ if kind == STORAGE_I16 {
+ load16(low, [from, 0]);
+ }
+ if kind == STORAGE_32 {
+ load32(low, [from, 0]);
+ }
+ if kind == STORAGE_64 {
+ load64(low, [from, 0]);
+ }
+ if kind == STORAGE_V128 {
+ load64(low, [from, 0]);
+ load64(high, [from, 8]);
+ }
+ store_storage_value(to, kind, low, high);
+ index = index + 1;
+ }
+}
+
+inline fn non_null(reference: u64) -> u64 {
+ guard reference != 0 else @cold {
+ trap(TRAP_NULL_REFERENCE);
+ };
+ reference
+}
+
+inline fn array_length(array: u64) -> u64 {
+ let mut length: u64;
+ load64(length, [array, 8]);
+ length
+}
+
+inline fn array_element_kind(array: u64) -> u64 {
+ let mut rtt: u64;
+ load64(rtt, [array, 0]);
+ let mut kinds: u64;
+ load64(kinds, [rtt, RTT_FIELD_KINDS]);
+ let mut kind: u64;
+ load8(kind, [kinds, 0]);
+ kind
+}
+
+inline fn check_array_range(start: u64, count: u64, length: u64) {
+ let end = start + count;
+ guard end <= length else @cold {
+ trap(TRAP_ARRAY_OUT_OF_BOUNDS);
+ };
+}
+
+inline fn element_address(array: u64, index: u64, kind: u64) -> u64 {
+ let size = storage_size(kind);
+ array + ARRAY_ELEMENTS_OFFSET + (index * size)
+}
+
+# The two LEB128 immediates of a GC instruction, and the length of the instruction.
+inline fn two_immediates() -> (u64, u64, u64) {
+ let [bytes, offset] = prefixed_immediates();
+ let [first, first_length] = read_leb(bytes);
+ let start: u64 = alias(bytes);
+ let second_bytes: Sequence<u8> = alias(start + first_length);
+ let [second, second_length] = read_leb(second_bytes);
+ (first, second, offset + first_length + second_length)
+}
+
+inline fn one_immediate() -> (u64, u64) {
+ let [bytes, offset] = prefixed_immediates();
+ let [value, length] = read_leb(bytes);
+ (value, offset + length)
+}
+
+handler StructNew() @opcode(0xfb, 0x0) {
+ let [type_index, length] = one_immediate();
+ let rtt = rtt_of_type(type_index);
+ let mut size: u64;
+ load32(size, [rtt, RTT_SIZE]);
+ let object = allocate_object(rtt, size);
+ let mut field_count: u64;
+ load32(field_count, [rtt, RTT_FIELD_COUNT]);
+ let mut offsets_pointer: u64;
+ load64(offsets_pointer, [rtt, RTT_FIELD_OFFSETS]);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let offsets: Sequence<u32> = alias(offsets_pointer);
+ let kinds: Sequence<u8> = alias(kinds_pointer);
+ # The last field is on top.
+ let mut index = field_count;
+ while index != 0 {
+ index = index - 1;
+ let offset: u64 = alias(offsets[index]);
+ let kind: u64 = alias(kinds[index]);
+ pop_into_storage(object + offset, kind);
+ }
+ push(object);
+ advance(length);
+}
+
+handler StructNewDefault() @opcode(0xfb, 0x1) {
+ let [type_index, length] = one_immediate();
+ let rtt = rtt_of_type(type_index);
+ let mut size: u64;
+ load32(size, [rtt, RTT_SIZE]);
+ let object = allocate_object(rtt, size);
+ push(object);
+ advance(length);
+}
+
+# The address and storage kind of field `field_index` of a struct of the module's type `type_index`.
+inline fn field_of(object: u64, type_index: u64, field_index: u64) -> (u64, u64) {
+ let rtt = rtt_of_type(type_index);
+ let mut offsets_pointer: u64;
+ load64(offsets_pointer, [rtt, RTT_FIELD_OFFSETS]);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let offsets: Sequence<u32> = alias(offsets_pointer);
+ let kinds: Sequence<u8> = alias(kinds_pointer);
+ let offset: u64 = alias(offsets[field_index]);
+ let kind: u64 = alias(kinds[field_index]);
+ (object + offset, kind)
+}
+
+handler StructGet() @opcode(0xfb, 0x2) {
+ let [type_index, field_index, length] = two_immediates();
+ let object = non_null(unary_operand());
+ let [address, kind] = field_of(object, type_index, field_index);
+ push_stored(address, kind, 1);
+ advance(length);
+}
+
+handler StructGetS() @opcode(0xfb, 0x3) {
+ let [type_index, field_index, length] = two_immediates();
+ let object = non_null(unary_operand());
+ let [address, kind] = field_of(object, type_index, field_index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ let extended = sign_extend_packed(value, kind);
+ set_top(extended);
+ advance(length);
+}
+
+handler StructGetU() @opcode(0xfb, 0x4) {
+ let [type_index, field_index, length] = two_immediates();
+ let object = non_null(unary_operand());
+ let [address, _] = field_of(object, type_index, field_index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler StructSet() @opcode(0xfb, 0x5) {
+ let [type_index, field_index, length] = two_immediates();
+ let rtt = rtt_of_type(type_index);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let kinds: Sequence<u8> = alias(kinds_pointer);
+ let kind: u64 = alias(kinds[field_index]);
+ let [low, high] = pop_storage_value(kind);
+ let object = non_null(pop());
+ let [address, _] = field_of(object, type_index, field_index);
+ store_storage_value(address, kind, low, high);
+ advance(length);
+}
+
+# Allocate an array of `count` elements of the module's type `type_index`.
+inline fn allocate_array(type_index: u64, count: u64) -> u64 {
+ let rtt = rtt_of_type(type_index);
+ let mut element_size: u64;
+ load32(element_size, [rtt, RTT_SIZE]);
+ let size = (count * element_size) + ARRAY_ELEMENTS_OFFSET;
+ let array = allocate_object(rtt, size);
+ store64([array, 8], count);
+ array
+}
+
+handler ArrayNew() @opcode(0xfb, 0x6) {
+ let [type_index, length] = one_immediate();
+ let count = pop32();
+ let wide_count: u64 = alias(count);
+ let array = allocate_array(type_index, wide_count);
+ let kind = array_element_kind(array);
+ let [low, high] = pop_storage_value(kind);
+ let mut index: u64 = 0;
+ while index < wide_count {
+ let address = element_address(array, index, kind);
+ store_storage_value(address, kind, low, high);
+ index = index + 1;
+ }
+ push(array);
+ advance(length);
+}
+
+handler ArrayNewDefault() @opcode(0xfb, 0x7) {
+ let [type_index, length] = one_immediate();
+ let count = pop32();
+ let wide_count: u64 = alias(count);
+ let array = allocate_array(type_index, wide_count);
+ push(array);
+ advance(length);
+}
+
+handler ArrayNewFixed() @opcode(0xfb, 0x8) {
+ let [type_index, count, length] = two_immediates();
+ let array = allocate_array(type_index, count);
+ let kind = array_element_kind(array);
+ # The last element is on top.
+ let mut index = count;
+ while index != 0 {
+ index = index - 1;
+ let address = element_address(array, index, kind);
+ pop_into_storage(address, kind);
+ }
+ push(array);
+ advance(length);
+}
+
+handler ArrayNewData() @opcode(0xfb, 0x9) {
+ let [type_index, data_index, length] = two_immediates();
+ let count = pop32();
+ let source = pop32();
+ let wide_count: u64 = alias(count);
+ let wide_source: u64 = alias(source);
+ let rtt = rtt_of_type(type_index);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let mut kind: u64;
+ load8(kind, [kinds_pointer, 0]);
+ let segment = segment_at(INSTANCE_DATA_SEGMENTS, data_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ let byte_count = wide_count * data_size(kind);
+ check_range(wide_source, byte_count, segment_length, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let array = allocate_array(type_index, wide_count);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ copy_data_elements(array + ARRAY_ELEMENTS_OFFSET, contents + wide_source, wide_count, kind);
+ push(array);
+ advance(length);
+}
+
+handler ArrayNewElem() @opcode(0xfb, 0xa) {
+ let [type_index, element_index, length] = two_immediates();
+ let count = pop32();
+ let source = pop32();
+ let wide_count: u64 = alias(count);
+ let wide_source: u64 = alias(source);
+ let segment = segment_at(INSTANCE_ELEMENT_SEGMENTS, element_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ check_range(wide_source, wide_count, segment_length, TRAP_TABLE_OUT_OF_BOUNDS);
+ let array = allocate_array(type_index, wide_count);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ copy_elements(array + ARRAY_ELEMENTS_OFFSET, contents + (wide_source << 3), wide_count);
+ push(array);
+ advance(length);
+}
+
+# The address and kind of an element, after checking the array for null and the index against its length.
+inline fn checked_element(array: u64, index: u64) -> (u64, u64) {
+ let checked = non_null(array);
+ let element_count = array_length(checked);
+ guard index < element_count else @cold {
+ trap(TRAP_ARRAY_OUT_OF_BOUNDS);
+ };
+ let kind = array_element_kind(checked);
+ let address = element_address(checked, index, kind);
+ (address, kind)
+}
+
+handler ArrayGet() @opcode(0xfb, 0xb) {
+ let [_, length] = one_immediate();
+ let [array, index] = binary_operands();
+ let [address, kind] = checked_element(array, index);
+ push_stored(address, kind, 1);
+ advance(length);
+}
+
+handler ArrayGetS() @opcode(0xfb, 0xc) {
+ let [_, length] = one_immediate();
+ let [array, index] = binary_operands();
+ let [address, kind] = checked_element(array, index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ let extended = sign_extend_packed(value, kind);
+ set_top(extended);
+ advance(length);
+}
+
+handler ArrayGetU() @opcode(0xfb, 0xd) {
+ let [_, length] = one_immediate();
+ let [array, index] = binary_operands();
+ let [address, _] = checked_element(array, index);
+ let mut value: u64;
+ load64(value, [address, 0]);
+ set_top(value);
+ advance(length);
+}
+
+handler ArraySet() @opcode(0xfb, 0xe) {
+ let [type_index, length] = one_immediate();
+ let rtt = rtt_of_type(type_index);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let mut kind: u64;
+ load8(kind, [kinds_pointer, 0]);
+ let [low, high] = pop_storage_value(kind);
+ let index = pop();
+ let array = pop();
+ let [address, _] = checked_element(array, index);
+ store_storage_value(address, kind, low, high);
+ advance(length);
+}
+
+handler ArrayLen() @opcode(0xfb, 0xf) {
+ let [_, offset] = prefixed_immediates();
+ let array = non_null(unary_operand());
+ let element_count = array_length(array);
+ set_top(element_count);
+ advance(offset);
+}
+
+handler ArrayFill() @opcode(0xfb, 0x10) {
+ let [type_index, length] = one_immediate();
+ let rtt = rtt_of_type(type_index);
+ let mut kinds_pointer: u64;
+ load64(kinds_pointer, [rtt, RTT_FIELD_KINDS]);
+ let mut kind: u64;
+ load8(kind, [kinds_pointer, 0]);
+ let count = pop();
+ let [low, high] = pop_storage_value(kind);
+ let start = pop();
+ let array = non_null(pop());
+ check_array_range(start, count, array_length(array));
+ let mut index: u64 = 0;
+ while index < count {
+ let address = element_address(array, start + index, kind);
+ store_storage_value(address, kind, low, high);
+ index = index + 1;
+ }
+ advance(length);
+}
+
+handler ArrayCopy() @opcode(0xfb, 0x11) {
+ let [_, _, length] = two_immediates();
+ let count = pop();
+ let source_start = pop();
+ let source = non_null(pop());
+ let destination_start = pop();
+ let destination = non_null(pop());
+ check_array_range(source_start, count, array_length(source));
+ check_array_range(destination_start, count, array_length(destination));
+ let kind = array_element_kind(destination);
+ let size = storage_size(kind);
+ let from = element_address(source, source_start, kind);
+ let to = element_address(destination, destination_start, kind);
+ copy_bytes(to, from, count * size);
+ advance(length);
+}
+
+handler ArrayInitData() @opcode(0xfb, 0x12) {
+ let [_, data_index, length] = two_immediates();
+ let count = pop();
+ let source = pop();
+ let destination_start = pop();
+ let array = non_null(pop());
+ let kind = array_element_kind(array);
+ check_array_range(destination_start, count, array_length(array));
+ let segment = segment_at(INSTANCE_DATA_SEGMENTS, data_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ let byte_count = count * data_size(kind);
+ check_range(source, byte_count, segment_length, TRAP_MEMORY_OUT_OF_BOUNDS);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ let to = element_address(array, destination_start, kind);
+ copy_data_elements(to, contents + source, count, kind);
+ advance(length);
+}
+
+handler ArrayInitElem() @opcode(0xfb, 0x13) {
+ let [_, element_index, length] = two_immediates();
+ let count = pop();
+ let source = pop();
+ let destination_start = pop();
+ let array = non_null(pop());
+ check_array_range(destination_start, count, array_length(array));
+ let segment = segment_at(INSTANCE_ELEMENT_SEGMENTS, element_index);
+ let mut segment_length: u64;
+ load64(segment_length, [segment, SEGMENT_LENGTH]);
+ check_range(source, count, segment_length, TRAP_TABLE_OUT_OF_BOUNDS);
+ let mut contents: u64;
+ load64(contents, [segment, SEGMENT_CONTENTS]);
+ let to = element_address(array, destination_start, STORAGE_64);
+ copy_elements(to, contents + (source << 3), count);
+ advance(length);
+}
+
+# Whether `reference` matches the heap type encoded at `bytes`, with null matching if `nullable` is set, and the
+# length of the encoding.
+inline fn reference_matches(reference: u64, bytes: Sequence<u8>, nullable: u64) -> (u64, u64) {
+ let first: u64 = alias(bytes[0]);
+ let mut matches: u64 = 0;
+ let mut length: u64 = 1;
+ # Abstract heap types are single bytes from 0x40 to 0x7F, negative as s33 values.
+ let biased = first - 0x40;
+ if biased < 0x40 {
+ if reference != 0 {
+ let tag = reference & 3;
+ let low_bit = reference & 1;
+ # any, func, extern, and exn take any non-null reference of their hierarchy.
+ if first == 0x6e {
+ matches = 1;
+ }
+ if first == 0x70 {
+ matches = 1;
+ }
+ if first == 0x6f {
+ matches = 1;
+ }
+ if first == 0x69 {
+ matches = 1;
+ }
+ if first == 0x6d {
+ if low_bit != 0 {
+ matches = 1;
+ }
+ if tag == 0 {
+ matches = 1;
+ }
+ }
+ if first == 0x6c {
+ matches = low_bit;
+ }
+ if first == 0x6b {
+ if tag == 0 {
+ let mut rtt: u64;
+ load64(rtt, [reference, 0]);
+ let mut kind: u64;
+ load32(kind, [rtt, RTT_KIND]);
+ if kind == RTT_KIND_STRUCT {
+ matches = 1;
+ }
+ }
+ }
+ if first == 0x6a {
+ if tag == 0 {
+ let mut rtt: u64;
+ load64(rtt, [reference, 0]);
+ let mut kind: u64;
+ load32(kind, [rtt, RTT_KIND]);
+ if kind == RTT_KIND_ARRAY {
+ matches = 1;
+ }
+ }
+ }
+ }
+ } else {
+ let [type_index, index_length] = read_leb(bytes);
+ length = index_length;
+ if reference != 0 {
+ let identity = identity_of_type(type_index);
+ let target = rtt_of_identity(identity);
+ let mut target_kind: u64;
+ load32(target_kind, [target, RTT_KIND]);
+ if target_kind == RTT_KIND_FUNCTION {
+ let mut function_identity: u64;
+ load32(function_identity, [reference, FUNCTION_TYPE_IDENTITY]);
+ let actual = rtt_of_identity(function_identity);
+ matches = rtt_is_subtype(actual, identity);
+ } else {
+ let tag = reference & 3;
+ if tag == 0 {
+ let mut actual: u64;
+ load64(actual, [reference, 0]);
+ matches = rtt_is_subtype(actual, identity);
+ }
+ }
+ }
+ }
+ if reference == 0 {
+ matches = nullable;
+ }
+ (matches, length)
+}
+
+inline fn test_reference(nullable: u64) {
+ let [bytes, offset] = prefixed_immediates();
+ let reference = unary_operand();
+ let [matches, length] = reference_matches(reference, bytes, nullable);
+ set_top(matches);
+ advance(offset + length);
+}
+
+inline fn cast_reference(nullable: u64) {
+ let [bytes, offset] = prefixed_immediates();
+ let reference = unary_operand();
+ let [matches, length] = reference_matches(reference, bytes, nullable);
+ guard matches != 0 else @cold {
+ trap(TRAP_CAST_FAILURE);
+ };
+ advance(offset + length);
+}
+
+handler RefTest() @opcode(0xfb, 0x14) {
+ test_reference(0);
+}
+
+handler RefTestNull() @opcode(0xfb, 0x15) {
+ test_reference(1);
+}
+
+handler RefCast() @opcode(0xfb, 0x16) {
+ cast_reference(0);
+}
+
+handler RefCastNull() @opcode(0xfb, 0x17) {
+ cast_reference(1);
+}
+
+# br_on_cast and br_on_cast_fail: `0xFB sub flags label source target`. The branch is taken when the cast's outcome
+# is `taken_on`.
+inline fn branch_on_cast(taken_on: u64) {
+ let [bytes, offset] = prefixed_immediates();
+ let flags: u64 = alias(bytes[0]);
+ let start: u64 = alias(bytes);
+ let label_bytes: Sequence<u8> = alias(start + 1);
+ let label_length = leb_length(label_bytes);
+ let source_bytes: Sequence<u8> = alias(start + 1 + label_length);
+ let source_length = heap_type_length(source_bytes);
+ let target_bytes: Sequence<u8> = alias(start + 1 + label_length + source_length);
+ let reference = unary_operand();
+ let nullable = (flags >> 1) & 1;
+ let [matches, target_length] = reference_matches(reference, target_bytes, nullable);
+ if matches == taken_on {
+ branch();
+ }
+ skip_entry_and_advance(offset + 1 + label_length + source_length + target_length);
+}
+
+inline fn heap_type_length(bytes: Sequence<u8>) -> u64 {
+ let first: u64 = alias(bytes[0]);
+ let mut length: u64 = 1;
+ let biased = first - 0x40;
+ if biased >= 0x40 {
+ length = leb_length(bytes);
+ }
+ length
+}
+
+handler BrOnCast() @opcode(0xfb, 0x18) {
+ branch_on_cast(1);
+}
+
+handler BrOnCastFail() @opcode(0xfb, 0x19) {
+ branch_on_cast(0);
+}
+
+# References keep their bits between the any and extern hierarchies.
+handler AnyConvertExtern() @opcode(0xfb, 0x1a) {
+ let [_, offset] = prefixed_immediates();
+ advance(offset);
+}
+
+handler ExternConvertAny() @opcode(0xfb, 0x1b) {
+ let [_, offset] = prefixed_immediates();
+ advance(offset);
+}
+
+handler RefI31() @opcode(0xfb, 0x1c) {
+ let [_, offset] = prefixed_immediates();
+ let value = unary_operand();
+ let bits = (value & 0x7fffffff) << 1;
+ let reference = bits | 1;
+ set_top(reference);
+ advance(offset);
+}
+
+handler I31GetS() @opcode(0xfb, 0x1d) {
+ let [_, offset] = prefixed_immediates();
+ let reference = non_null(unary_operand());
+ let moved = reference << 32;
+ let signed = signed64(moved);
+ let extended = signed >> 33;
+ let narrow = u32(extended);
+ let value: u64 = alias(narrow);
+ set_top(value);
+ advance(offset);
+}
+
+handler I31GetU() @opcode(0xfb, 0x1e) {
+ let [_, offset] = prefixed_immediates();
+ let reference = non_null(unary_operand());
+ let value = (reference >> 1) & 0x7fffffff;
+ set_top(value);
+ advance(offset);
+}
+
+# Atomics (the 0xFE prefix). Their accesses are always bounds checked and then checked for alignment, in that order,
+# whatever memory they access.
+
+handler PrefixFE() @opcode(0xfe) {
+ let [sub_opcode, _] = read_leb(immediates());
+ dispatch_secondary(0xfe, sub_opcode);
+}
+
+# The memory, address of a `size`-byte atomic access, and length of the instruction.
+inline fn atomic_access(address_operand: u64, size: u64) -> (u64, u64, u64) {
+ let [bytes, prefix_length] = prefixed_immediates();
+ let flags: u64 = alias(bytes[0]);
+ let alignment_length = leb_length(bytes);
+ let start: u64 = alias(bytes);
+ let mut memory_index: u64 = 0;
+ let mut index_length: u64 = 0;
+ if flags >= 0x40 {
+ let index_bytes: Sequence<u8> = alias(start + alignment_length);
+ let [decoded_index, decoded_length] = read_leb(index_bytes);
+ memory_index = decoded_index;
+ index_length = decoded_length;
+ }
+ let offset_bytes: Sequence<u8> = alias(start + alignment_length + index_length);
+ let [offset, offset_length] = read_leb(offset_bytes);
+ let memory = memory_at(memory_index);
+ let effective = address_operand + offset;
+ guard effective >= address_operand else @cold {
+ trap(TRAP_MEMORY_OUT_OF_BOUNDS);
+ };
+ let address = checked_memory_address(memory, effective, size);
+ let misalignment = effective & (size - 1);
+ guard misalignment == 0 else @cold {
+ trap(TRAP_UNALIGNED_ATOMIC);
+ };
+ (memory, address, prefix_length + alignment_length + index_length + offset_length)
+}
+
+inline fn width_mask(size: u64) -> u64 {
+ let mut mask: u64 = 0xffffffffffffffff;
+ if size == 1 {
+ mask = 0xff;
+ }
+ if size == 2 {
+ mask = 0xffff;
+ }
+ if size == 4 {
+ mask = 0xffffffff;
+ }
+ mask
+}
+
+handler AtomicNotify() @opcode(0xfe, 0x0) {
+ let count = pop();
+ let address_operand = unary_operand();
+ let [memory, address, length] = atomic_access(address_operand, 4);
+ let mut shared: u64;
+ load64(shared, [memory, MEMORY_SHARED]);
+ let mut woken: u64 = 0;
+ # Only a shared memory can have threads waiting on it.
+ if shared != 0 {
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], address);
+ store64([context_pointer, CONTEXT_ARGUMENT_1], count);
+ woken = call_helper(wasm_runtime_notify, context_pointer);
+ }
+ set_top(woken);
+ advance(length);
+}
+
+inline fn atomic_wait(size: u64) {
+ let timeout = pop();
+ let expected = pop();
+ let address_operand = unary_operand();
+ let [memory, address, length] = atomic_access(address_operand, size);
+ let mut shared: u64;
+ load64(shared, [memory, MEMORY_SHARED]);
+ guard shared != 0 else @cold {
+ trap(TRAP_EXPECTED_SHARED_MEMORY);
+ };
+ let context_pointer = context();
+ store64([context_pointer, CONTEXT_ARGUMENTS], address);
+ store64([context_pointer, CONTEXT_ARGUMENT_1], expected);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], timeout);
+ store64([context_pointer, CONTEXT_ARGUMENT_3], size);
+ let result: u64 = call_helper(wasm_runtime_wait, context_pointer);
+ set_top(result);
+ advance(length);
+}
+
+handler AtomicWait32() @opcode(0xfe, 0x1) {
+ atomic_wait(4);
+}
+
+handler AtomicWait64() @opcode(0xfe, 0x2) {
+ atomic_wait(8);
+}
+
+# Locked instructions order everything around them, so a fence needs nothing more.
+handler AtomicFence() @opcode(0xfe, 0x3) {
+ let [_, offset] = prefixed_immediates();
+ 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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+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]);
+ set_top(value);
+ advance(length);
+}
+
+handler I32AtomicStore() @opcode(0xfe, 0x17) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg32([address, 0], value);
+ advance(length);
+}
+
+handler I64AtomicStore() @opcode(0xfe, 0x18) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg64([address, 0], value);
+ advance(length);
+}
+
+handler I32AtomicStore8() @opcode(0xfe, 0x19) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg8([address, 0], value);
+ advance(length);
+}
+
+handler I32AtomicStore16() @opcode(0xfe, 0x1a) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg16([address, 0], value);
+ advance(length);
+}
+
+handler I64AtomicStore8() @opcode(0xfe, 0x1b) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg8([address, 0], value);
+ advance(length);
+}
+
+handler I64AtomicStore16() @opcode(0xfe, 0x1c) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg16([address, 0], value);
+ advance(length);
+}
+
+handler I64AtomicStore32() @opcode(0xfe, 0x1d) {
+ let [address_operand, value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ # An exchange is a sequentially consistent store.
+ let _ = atomic_xchg32([address, 0], value);
+ advance(length);
+}
+
+handler I32AtomicRmwAdd() @opcode(0xfe, 0x1e) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let old = atomic_add32([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwAdd() @opcode(0xfe, 0x1f) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ let old = atomic_add64([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8AddU() @opcode(0xfe, 0x20) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let old = atomic_add8([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16AddU() @opcode(0xfe, 0x21) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let old = atomic_add16([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8AddU() @opcode(0xfe, 0x22) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let old = atomic_add8([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16AddU() @opcode(0xfe, 0x23) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let old = atomic_add16([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32AddU() @opcode(0xfe, 0x24) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let old = atomic_add32([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwSub() @opcode(0xfe, 0x25) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add32([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwSub() @opcode(0xfe, 0x26) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add64([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8SubU() @opcode(0xfe, 0x27) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add8([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16SubU() @opcode(0xfe, 0x28) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add16([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8SubU() @opcode(0xfe, 0x29) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add8([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16SubU() @opcode(0xfe, 0x2a) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add16([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32SubU() @opcode(0xfe, 0x2b) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let zero: u64 = 0;
+ let negated = zero - value;
+ let old = atomic_add32([address, 0], negated);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwAnd() @opcode(0xfe, 0x2c) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwAnd() @opcode(0xfe, 0x2d) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load64(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg64([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8AndU() @opcode(0xfe, 0x2e) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16AndU() @opcode(0xfe, 0x2f) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8AndU() @opcode(0xfe, 0x30) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16AndU() @opcode(0xfe, 0x31) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32AndU() @opcode(0xfe, 0x32) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old & value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwOr() @opcode(0xfe, 0x33) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwOr() @opcode(0xfe, 0x34) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load64(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg64([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8OrU() @opcode(0xfe, 0x35) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16OrU() @opcode(0xfe, 0x36) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8OrU() @opcode(0xfe, 0x37) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16OrU() @opcode(0xfe, 0x38) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32OrU() @opcode(0xfe, 0x39) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old | value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwXor() @opcode(0xfe, 0x3a) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwXor() @opcode(0xfe, 0x3b) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load64(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg64([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8XorU() @opcode(0xfe, 0x3c) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16XorU() @opcode(0xfe, 0x3d) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8XorU() @opcode(0xfe, 0x3e) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load8(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg8([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16XorU() @opcode(0xfe, 0x3f) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load16(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg16([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32XorU() @opcode(0xfe, 0x40) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ # Retry until no other thread changed the location between the read and the exchange.
+ let mut old: u64;
+ load32(old, [address, 0]);
+ let mut done: u64 = 0;
+ while done == 0 {
+ let updated = (old ^ value) & mask;
+ let replaced = atomic_cmpxchg32([address, 0], old, updated);
+ if replaced == old {
+ done = 1;
+ } else {
+ old = replaced;
+ }
+ }
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwXchg() @opcode(0xfe, 0x41) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let old = atomic_xchg32([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwXchg() @opcode(0xfe, 0x42) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ let mask = width_mask(8);
+ let value = raw_value & mask;
+ let old = atomic_xchg64([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8XchgU() @opcode(0xfe, 0x43) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let old = atomic_xchg8([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16XchgU() @opcode(0xfe, 0x44) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let old = atomic_xchg16([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8XchgU() @opcode(0xfe, 0x45) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ let mask = width_mask(1);
+ let value = raw_value & mask;
+ let old = atomic_xchg8([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16XchgU() @opcode(0xfe, 0x46) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ let mask = width_mask(2);
+ let value = raw_value & mask;
+ let old = atomic_xchg16([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32XchgU() @opcode(0xfe, 0x47) {
+ let [address_operand, raw_value] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ let mask = width_mask(4);
+ let value = raw_value & mask;
+ let old = atomic_xchg32([address, 0], value);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmwCmpxchg() @opcode(0xfe, 0x48) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ # Both values wrap at the access width.
+ let mask = width_mask(4);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg32([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmwCmpxchg() @opcode(0xfe, 0x49) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 8);
+ # Both values wrap at the access width.
+ let mask = width_mask(8);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg64([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw8CmpxchgU() @opcode(0xfe, 0x4a) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ # Both values wrap at the access width.
+ let mask = width_mask(1);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg8([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I32AtomicRmw16CmpxchgU() @opcode(0xfe, 0x4b) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ # Both values wrap at the access width.
+ let mask = width_mask(2);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg16([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw8CmpxchgU() @opcode(0xfe, 0x4c) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 1);
+ # Both values wrap at the access width.
+ let mask = width_mask(1);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg8([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw16CmpxchgU() @opcode(0xfe, 0x4d) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 2);
+ # Both values wrap at the access width.
+ let mask = width_mask(2);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg16([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
+
+handler I64AtomicRmw32CmpxchgU() @opcode(0xfe, 0x4e) {
+ let replacement = pop();
+ let [address_operand, raw_expected] = store_operands();
+ let [_, address, length] = atomic_access(address_operand, 4);
+ # Both values wrap at the access width.
+ let mask = width_mask(4);
+ let expected = raw_expected & mask;
+ let wrapped = replacement & mask;
+ let old = atomic_cmpxchg32([address, 0], expected, wrapped);
+ push(old);
+ advance(length);
+}
diff --git a/Libraries/LibWasm/Runtime/CMakeLists.txt b/Libraries/LibWasm/Runtime/CMakeLists.txt
new file mode 100644
index 00000000000..2e377061ca8
--- /dev/null
+++ b/Libraries/LibWasm/Runtime/CMakeLists.txt
@@ -0,0 +1,11 @@
+set(SOURCES
+ Runtime.cpp
+)
+
+ladybird_lib(LibWasmRuntime wasmruntime EXPLICIT_SYMBOL_EXPORT)
+
+import_rust_crate(MANIFEST_PATH ../Engine/Cargo.toml CRATE_NAME libwasm_engine FEATURES allocator FFI_HEADER RustFFI.h)
+target_link_libraries(LibWasmRuntime PRIVATE libwasm_engine)
+if ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)
+ target_link_options(LibWasmRuntime INTERFACE LINKER:--allow-multiple-definition)
+endif()
diff --git a/Libraries/LibWasm/Runtime/Runtime.cpp b/Libraries/LibWasm/Runtime/Runtime.cpp
new file mode 100644
index 00000000000..39d7fd7d49b
--- /dev/null
+++ b/Libraries/LibWasm/Runtime/Runtime.cpp
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWasm/Runtime/Runtime.h>
+#include <RustFFI.h>
+
+namespace Wasm::Runtime {
+
+static_assert(sizeof(ValueType) == sizeof(FFI::WasmValueType));
+static_assert(sizeof(Value) == sizeof(FFI::WasmValue));
+static_assert(sizeof(Extern) == sizeof(FFI::WasmExtern));
+static_assert(sizeof(Limits) == sizeof(FFI::WasmLimits));
+static_assert(sizeof(ExternType) == sizeof(FFI::WasmExternType));
+
+static FFI::WasmValueType to_ffi(ValueType type) { return bit_cast<FFI::WasmValueType>(type); }
+static FFI::WasmValue to_ffi(Value value) { return bit_cast<FFI::WasmValue>(value); }
+static FFI::WasmLimits to_ffi(Limits limits) { return bit_cast<FFI::WasmLimits>(limits); }
+static ValueType from_ffi(FFI::WasmValueType type) { return bit_cast<ValueType>(type); }
+static Value from_ffi(FFI::WasmValue value) { return bit_cast<Value>(value); }
+static Limits from_ffi(FFI::WasmLimits limits) { return bit_cast<Limits>(limits); }
+static ExternType from_ffi(FFI::WasmExternType type) { return bit_cast<ExternType>(type); }
+static StringView from_ffi(FFI::WasmStringView view) { return { reinterpret_cast<char const*>(view.data), view.length }; }
+
+static ByteString take_string(FFI::WasmString string)
+{
+ if (!string.data)
+ return {};
+ ByteString result { reinterpret_cast<char const*>(string.data), string.length };
+ FFI::wasm_string_release(string);
+ return result;
+}
+
+static FFI::WasmString make_string(StringView text)
+{
+ // The engine releases the strings it gets back, so they are allocated the way it allocates its own: as a boxed
+ // byte slice, which only the engine can create.
+ FFI::WasmString string {};
+ FFI::wasm_string_create(reinterpret_cast<u8 const*>(text.characters_without_null_termination()), text.length(), &string);
+ return string;
+}
+
+ErrorOr<NonnullRefPtr<Module>, ByteString> Module::compile(ReadonlyBytes bytes)
+{
+ FFI::WasmString error {};
+ auto const* module = FFI::wasm_module_compile(bytes.data(), bytes.size(), &error);
+ if (!module)
+ return take_string(error);
+ return adopt_ref(*new Module(module));
+}
+
+Module::~Module()
+{
+ FFI::wasm_module_release(m_module);
+}
+
+size_t Module::import_count() const
+{
+ return FFI::wasm_module_import_count(m_module);
+}
+
+Import Module::import(size_t index) const
+{
+ FFI::WasmStringView module_name {};
+ FFI::WasmStringView name {};
+ FFI::WasmExternType type {};
+ FFI::wasm_module_import(m_module, index, &module_name, &name, &type);
+ return { from_ffi(module_name), from_ffi(name), from_ffi(type) };
+}
+
+size_t Module::export_count() const
+{
+ return FFI::wasm_module_export_count(m_module);
+}
+
+ModuleExport Module::module_export(size_t index) const
+{
+ FFI::WasmStringView name {};
+ FFI::WasmExternType type {};
+ FFI::wasm_module_export(m_module, index, &name, &type);
+ return { from_ffi(name), from_ffi(type) };
+}
+
+static FunctionType make_function_type(size_t parameter_count, size_t result_count, auto copy)
+{
+ Vector<FFI::WasmValueType> parameters;
+ Vector<FFI::WasmValueType> results;
+ parameters.resize(parameter_count);
+ results.resize(result_count);
+ copy(parameters.data(), results.data());
+ FunctionType type;
+ type.parameters.ensure_capacity(parameter_count);
+ type.results.ensure_capacity(result_count);
+ for (auto parameter : parameters)
+ type.parameters.unchecked_append(from_ffi(parameter));
+ for (auto result : results)
+ type.results.unchecked_append(from_ffi(result));
+ return type;
+}
+
+Optional<FunctionType> Module::function_type(u32 type_index) const
+{
+ size_t parameter_count = 0;
+ size_t result_count = 0;
+ if (!FFI::wasm_module_function_type(m_module, type_index, &parameter_count, &result_count))
+ return {};
+ return make_function_type(parameter_count, result_count, [&](auto* parameters, auto* results) {
+ FFI::wasm_module_function_type_values(m_module, type_index, parameters, results);
+ });
+}
+
+Store::Store()
+ : m_store(FFI::wasm_store_create())
+{
+}
+
+Store::~Store()
+{
+ FFI::wasm_store_destroy(m_store);
+}
+
+namespace {
+
+struct HostFunctionData {
+ Store& store;
+ Store::HostFunction function;
+ size_t result_count { 0 };
+};
+
+}
+
+static bool call_host_function(void* user_data, FFI::WasmStore*, FFI::WasmValue const* arguments, size_t argument_count, FFI::WasmValue* results, size_t result_count, FFI::WasmString* error)
+{
+ auto& data = *static_cast<HostFunctionData*>(user_data);
+ ReadonlySpan<Value> argument_span { reinterpret_cast<Value const*>(arguments), argument_count };
+ Span<Value> result_span { reinterpret_cast<Value*>(results), result_count };
+ auto result = data.function(data.store, argument_span, result_span);
+ if (result.is_error()) {
+ *error = make_string(result.error());
+ return false;
+ }
+ return true;
+}
+
+static void release_host_function(void* user_data)
+{
+ delete static_cast<HostFunctionData*>(user_data);
+}
+
+u32 Store::allocate_host_function(FunctionType const& type, HostFunction function)
+{
+ Vector<FFI::WasmValueType> parameters;
+ Vector<FFI::WasmValueType> results;
+ for (auto parameter : type.parameters)
+ parameters.append(to_ffi(parameter));
+ for (auto result : type.results)
+ results.append(to_ffi(result));
+ auto* data = new HostFunctionData { *this, move(function), type.results.size() };
+ return FFI::wasm_store_allocate_host_function(m_store, parameters.data(), parameters.size(), results.data(), results.size(), call_host_function, data, release_host_function);
+}
+
+Optional<u32> Store::allocate_memory(Limits limits)
+{
+ u32 address = 0;
+ if (!FFI::wasm_store_allocate_memory(m_store, to_ffi(limits), &address))
+ return {};
+ return address;
+}
+
+u32 Store::allocate_table(ValueType element, Limits limits, u64 initial)
+{
+ return FFI::wasm_store_allocate_table(m_store, to_ffi(element), to_ffi(limits), initial);
+}
+
+u32 Store::allocate_global(ValueType type, bool is_mutable, Value value)
+{
+ return FFI::wasm_store_allocate_global(m_store, to_ffi(type), is_mutable, to_ffi(value));
+}
+
+ErrorOr<u32, Failure> Store::instantiate(Module const& module, ReadonlySpan<Extern> imports)
+{
+ u32 instance = 0;
+ FFI::WasmString error {};
+ auto status = FFI::wasm_store_instantiate(m_store, module.handle(), reinterpret_cast<FFI::WasmExtern const*>(imports.data()), imports.size(), &instance, &error);
+ switch (status) {
+ case FFI::WasmStatus::Ok:
+ return instance;
+ case FFI::WasmStatus::LinkError:
+ return Failure { FailureKind::LinkError, take_string(error) };
+ case FFI::WasmStatus::Trap:
+ return Failure { FailureKind::Trap, take_string(error) };
+ }
+ VERIFY_NOT_REACHED();
+}
+
+Vector<InstanceExport> Store::instance_exports(u32 instance)
+{
+ auto count = FFI::wasm_store_instance_export_count(m_store, instance);
+ Vector<InstanceExport> exports;
+ exports.ensure_capacity(count);
+ for (size_t index = 0; index < count; ++index) {
+ FFI::WasmStringView name {};
+ FFI::WasmExtern value {};
+ if (!FFI::wasm_store_instance_export(m_store, instance, index, &name, &value))
+ continue;
+ exports.unchecked_append({ from_ffi(name), bit_cast<Extern>(value) });
+ }
+ return exports;
+}
+
+Optional<Extern> Store::find_export(u32 instance, StringView name)
+{
+ FFI::WasmExtern value {};
+ if (!FFI::wasm_store_instance_find_export(m_store, instance, reinterpret_cast<u8 const*>(name.characters_without_null_termination()), name.length(), &value))
+ return {};
+ return bit_cast<Extern>(value);
+}
+
+FunctionType Store::function_type(u32 function)
+{
+ size_t parameter_count = 0;
+ size_t result_count = 0;
+ FFI::wasm_store_function_type(m_store, function, &parameter_count, &result_count);
+ return make_function_type(parameter_count, result_count, [&](auto* parameters, auto* results) {
+ FFI::wasm_store_function_type_values(m_store, function, parameters, results);
+ });
+}
+
+ErrorOr<Vector<Value>, ByteString> Store::invoke(u32 function, ReadonlySpan<Value> arguments)
+{
+ size_t parameter_count = 0;
+ size_t result_count = 0;
+ FFI::wasm_store_function_type(m_store, function, &parameter_count, &result_count);
+ Vector<Value> results;
+ results.resize(result_count);
+ FFI::WasmString error {};
+ auto status = FFI::wasm_store_invoke(m_store, function, reinterpret_cast<FFI::WasmValue const*>(arguments.data()), arguments.size(), reinterpret_cast<FFI::WasmValue*>(results.data()), results.size(), &error);
+ if (status != FFI::WasmStatus::Ok)
+ return take_string(error);
+ return results;
+}
+
+u64 Store::function_reference(u32 function)
+{
+ return FFI::wasm_store_function_reference(m_store, function);
+}
+
+Optional<u32> Store::function_from_reference(u64 reference)
+{
+ u32 function = 0;
+ if (!FFI::wasm_store_function_from_reference(m_store, reference, &function))
+ return {};
+ return function;
+}
+
+Bytes Store::memory(u32 memory)
+{
+ size_t size = 0;
+ auto* data = FFI::wasm_store_memory_data(m_store, memory, &size);
+ return { data, size };
+}
+
+i64 Store::grow_memory(u32 memory, u64 delta)
+{
+ return FFI::wasm_store_memory_grow(m_store, memory, delta);
+}
+
+Limits Store::memory_limits(u32 memory)
+{
+ return from_ffi(FFI::wasm_store_memory_limits(m_store, memory));
+}
+
+u64 Store::table_size(u32 table)
+{
+ return FFI::wasm_store_table_size(m_store, table);
+}
+
+ValueType Store::table_element_type(u32 table)
+{
+ FFI::WasmValueType element {};
+ FFI::WasmLimits limits {};
+ FFI::wasm_store_table_type(m_store, table, &element, &limits);
+ return from_ffi(element);
+}
+
+Limits Store::table_limits(u32 table)
+{
+ FFI::WasmValueType element {};
+ FFI::WasmLimits limits {};
+ FFI::wasm_store_table_type(m_store, table, &element, &limits);
+ return from_ffi(limits);
+}
+
+Optional<u64> Store::table_get(u32 table, u64 index)
+{
+ u64 value = 0;
+ if (!FFI::wasm_store_table_get(m_store, table, index, &value))
+ return {};
+ return value;
+}
+
+bool Store::table_set(u32 table, u64 index, u64 value)
+{
+ return FFI::wasm_store_table_set(m_store, table, index, value);
+}
+
+i64 Store::grow_table(u32 table, u64 delta, u64 initial)
+{
+ return FFI::wasm_store_table_grow(m_store, table, delta, initial);
+}
+
+ValueType Store::global_type(u32 global, bool& is_mutable)
+{
+ return from_ffi(FFI::wasm_store_global_type(m_store, global, &is_mutable));
+}
+
+Value Store::global_get(u32 global)
+{
+ return from_ffi(FFI::wasm_store_global_get(m_store, global));
+}
+
+void Store::global_set(u32 global, Value value)
+{
+ FFI::wasm_store_global_set(m_store, global, to_ffi(value));
+}
+
+}
diff --git a/Libraries/LibWasm/Runtime/Runtime.h b/Libraries/LibWasm/Runtime/Runtime.h
new file mode 100644
index 00000000000..cff33a68929
--- /dev/null
+++ b/Libraries/LibWasm/Runtime/Runtime.h
@@ -0,0 +1,237 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/AtomicRefCounted.h>
+#include <AK/BitCast.h>
+#include <AK/ByteString.h>
+#include <AK/Error.h>
+#include <AK/Function.h>
+#include <AK/NonnullRefPtr.h>
+#include <AK/Optional.h>
+#include <AK/Span.h>
+#include <AK/StringView.h>
+#include <AK/Vector.h>
+#include <LibWasm/Runtime/Export.h>
+
+namespace Wasm::FFI {
+
+struct WasmModule;
+struct WasmStore;
+
+}
+
+// The C++ interface of the WebAssembly engine, which is written in Rust (Libraries/LibWasm/Engine). These types mirror
+// the ones of its C ABI (Libraries/LibWasm/Engine/src/capi.rs) exactly.
+namespace Wasm::Runtime {
+
+enum class ValueKind : u8 {
+ I32,
+ I64,
+ F32,
+ F64,
+ V128,
+ Reference,
+};
+
+enum class HeapKind : u8 {
+ Function,
+ NoFunction,
+ Extern,
+ NoExtern,
+ Any,
+ Eq,
+ I31,
+ Struct,
+ Array,
+ None,
+ Exception,
+ NoException,
+ Concrete,
+};
+
+// A value type. `heap`, `nullable`, and `type_index` only matter for references; `type_index` indexes the types of
+// the module the type comes from.
+struct ValueType {
+ ValueKind kind { ValueKind::I32 };
+ HeapKind heap { HeapKind::Function };
+ bool nullable { false };
+ u32 type_index { 0 };
+
+ static constexpr ValueType scalar(ValueKind kind) { return { kind, HeapKind::Function, false, 0 }; }
+ static constexpr ValueType reference(HeapKind heap, bool nullable = true) { return { ValueKind::Reference, heap, nullable, 0 }; }
+
+ bool is_reference() const { return kind == ValueKind::Reference; }
+};
+
+// A value. i32 and f32 bits are zero-extended in `low`, a v128 is `low` and `high`, and a reference is its bits, which
+// are zero for null.
+struct Value {
+ ValueKind kind { ValueKind::I32 };
+ u64 low { 0 };
+ u64 high { 0 };
+
+ static Value from_i32(i32 value) { return { ValueKind::I32, static_cast<u32>(value), 0 }; }
+ static Value from_i64(i64 value) { return { ValueKind::I64, static_cast<u64>(value), 0 }; }
+ static Value from_f32_bits(u32 bits) { return { ValueKind::F32, bits, 0 }; }
+ static Value from_f64_bits(u64 bits) { return { ValueKind::F64, bits, 0 }; }
+ static Value from_f32(float value) { return from_f32_bits(bit_cast<u32>(value)); }
+ static Value from_f64(double value) { return from_f64_bits(bit_cast<u64>(value)); }
+ static Value from_v128(u64 low, u64 high) { return { ValueKind::V128, low, high }; }
+ static Value from_reference(u64 bits) { return { ValueKind::Reference, bits, 0 }; }
+ static Value default_for(ValueType type) { return { type.kind, 0, 0 }; }
+
+ i32 to_i32() const { return static_cast<i32>(static_cast<u32>(low)); }
+ i64 to_i64() const { return static_cast<i64>(low); }
+ u32 f32_bits() const { return static_cast<u32>(low); }
+ u64 f64_bits() const { return low; }
+ float to_f32() const { return bit_cast<float>(f32_bits()); }
+ double to_f64() const { return bit_cast<double>(f64_bits()); }
+ u64 reference_bits() const { return low; }
+ bool is_null_reference() const { return low == 0; }
+};
+
+enum class ExternKind : u8 {
+ Function,
+ Table,
+ Memory,
+ Global,
+ Tag,
+};
+
+// A function, table, memory, or global of a store, by its address.
+struct Extern {
+ ExternKind kind { ExternKind::Function };
+ u32 address { 0 };
+};
+
+struct Limits {
+ u64 minimum { 0 };
+ u64 maximum { 0 };
+ bool has_maximum { false };
+ bool address64 { false };
+ bool shared { false };
+
+ Optional<u64> maximum_if_any() const { return has_maximum ? Optional<u64> { maximum } : Optional<u64> {}; }
+};
+
+// What an import or export is: the type index of a function or tag, the limits of a memory or table, the element type
+// of a table, and the value type and mutability of a global.
+struct ExternType {
+ ExternKind kind { ExternKind::Function };
+ u32 type_index { 0 };
+ Limits limits;
+ ValueType value_type;
+ bool is_mutable { false };
+};
+
+struct FunctionType {
+ Vector<ValueType> parameters;
+ Vector<ValueType> results;
+};
+
+struct Import {
+ StringView module;
+ StringView name;
+ ExternType type;
+};
+
+struct ModuleExport {
+ StringView name;
+ ExternType type;
+};
+
+struct InstanceExport {
+ StringView name;
+ Extern value;
+};
+
+// A compiled module, which can be shared across threads and instantiated in any store.
+class WASMRUNTIME_API Module : public AtomicRefCounted<Module> {
+public:
+ static ErrorOr<NonnullRefPtr<Module>, ByteString> compile(ReadonlyBytes);
+ ~Module();
+
+ size_t import_count() const;
+ Import import(size_t index) const;
+ size_t export_count() const;
+ ModuleExport module_export(size_t index) const;
+ Optional<FunctionType> function_type(u32 type_index) const;
+
+ FFI::WasmModule const* handle() const { return m_module; }
+
+private:
+ explicit Module(FFI::WasmModule const* module)
+ : m_module(module)
+ {
+ }
+
+ FFI::WasmModule const* m_module { nullptr };
+};
+
+enum class FailureKind : u8 {
+ LinkError,
+ Trap,
+};
+
+struct Failure {
+ FailureKind kind { FailureKind::Trap };
+ ByteString message;
+};
+
+// Functions, tables, memories, globals, and instances, all of one thread.
+class WASMRUNTIME_API Store {
+ AK_MAKE_NONCOPYABLE(Store);
+ AK_MAKE_NONMOVABLE(Store);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ Store();
+ ~Store();
+
+ // A host function writes one result for each result of its type, or returns an error to trap.
+ using HostFunction = Function<ErrorOr<void, ByteString>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
+
+ u32 allocate_host_function(FunctionType const&, HostFunction);
+ Optional<u32> allocate_memory(Limits);
+ u32 allocate_table(ValueType element, Limits, u64 initial);
+ u32 allocate_global(ValueType, bool is_mutable, Value);
+
+ ErrorOr<u32, Failure> instantiate(Module const&, ReadonlySpan<Extern> imports);
+ Vector<InstanceExport> instance_exports(u32 instance);
+ Optional<Extern> find_export(u32 instance, StringView name);
+
+ FunctionType function_type(u32 function);
+ ErrorOr<Vector<Value>, ByteString> invoke(u32 function, ReadonlySpan<Value> arguments);
+ u64 function_reference(u32 function);
+ Optional<u32> function_from_reference(u64 reference);
+
+ // The bytes of a memory move when it grows.
+ Bytes memory(u32 memory);
+ // The previous size in pages, or -1 if the memory cannot grow.
+ i64 grow_memory(u32 memory, u64 delta);
+ Limits memory_limits(u32 memory);
+
+ u64 table_size(u32 table);
+ ValueType table_element_type(u32 table);
+ Limits table_limits(u32 table);
+ Optional<u64> table_get(u32 table, u64 index);
+ bool table_set(u32 table, u64 index, u64 value);
+ // The previous size, or -1 if the table cannot grow.
+ i64 grow_table(u32 table, u64 delta, u64 initial);
+
+ ValueType global_type(u32 global, bool& is_mutable);
+ Value global_get(u32 global);
+ void global_set(u32 global, Value);
+
+ FFI::WasmStore* handle() { return m_store; }
+
+private:
+ FFI::WasmStore* m_store { nullptr };
+};
+
+}
diff --git a/Tests/LibWasm/CMakeLists.txt b/Tests/LibWasm/CMakeLists.txt
index ecf2da4c5f2..62795aed71e 100644
--- a/Tests/LibWasm/CMakeLists.txt
+++ b/Tests/LibWasm/CMakeLists.txt
@@ -2,7 +2,7 @@ ladybird_test(TestWasmMemory.cpp LibWasm LIBS LibGC LibWasm)
ladybird_test(TestWasmExecution.cpp LibWasm LIBS LibGC LibWasm)
add_executable(test-wasm test-wasm.cpp)
-target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasm LibJSStandalone LibCrypto LibGC)
+target_link_libraries(test-wasm AK LibCore LibFileSystem JavaScriptTestRunnerMain LibTest LibWasmRuntime LibJSStandalone LibCrypto LibGC)
set(wasm_test_root "${LADYBIRD_SOURCE_DIR}")
if (INCLUDE_WASM_SPEC_TESTS)
set(wasm_test_root "${CMAKE_BINARY_DIR}")
diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp
index e8f8ffee5a0..5bd894bad05 100644
--- a/Tests/LibWasm/test-wasm.cpp
+++ b/Tests/LibWasm/test-wasm.cpp
@@ -5,7 +5,7 @@
*/
#include <AK/ByteBuffer.h>
-#include <AK/MemoryStream.h>
+#include <AK/HashMap.h>
#include <LibCore/File.h>
#include <LibGC/CellAllocator.h>
#include <LibJS/Heap/Cell.h>
@@ -22,9 +22,7 @@
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibTest/JavaScriptTestHost.h>
-#include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/Types.h>
+#include <LibWasm/Runtime/Runtime.h>
#include <string.h>
TEST_ROOT("Libraries/LibWasm/Tests");
@@ -58,8 +56,40 @@ TESTJS_GLOBAL_FUNCTION(read_binary_wasm_file, readBinaryWasmFile)
return JS::Value(array);
}
+namespace {
+
static constexpr JSHostClass web_assembly_module_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "WebAssemblyModule"sv, nullptr, nullptr, nullptr, 0);
+// Host references (`ref.extern n` in the spec tests) are encoded so that they are never null, and never look like a
+// pointer or an i31 reference.
+static u64 host_reference_bits(u64 value)
+{
+ return (value << 2) | 2;
+}
+
+static Optional<u64> host_reference_value(u64 bits)
+{
+ if ((bits & 3) != 2)
+ return {};
+ return bits >> 2;
+}
+
+struct ImportName {
+ ByteString module;
+ ByteString name;
+
+ bool operator==(ImportName const&) const = default;
+};
+
+}
+
+template<>
+struct AK::Traits<ImportName> : public DefaultTraits<ImportName> {
+ static unsigned hash(ImportName const& name) { return pair_int_hash(name.module.hash(), name.name.hash()); }
+};
+
+namespace {
+
// The module that parseWebAssemblyModule() instantiates. Script sees it as a host object that carries this cell as its
// host data and has the module's getExport() and invoke() as own properties.
class WebAssemblyModule final : public JS::Cell {
@@ -69,48 +99,51 @@ class WebAssemblyModule final : public JS::Cell {
public:
using JSValueConversionIsForbidden = void;
- WebAssemblyModule()
- {
- machine().enable_instruction_count_limit();
- }
-
static WebAssemblyModule* from_object(JS::Object const& object)
{
return JS::host_data_if<WebAssemblyModule>(object);
}
- static Wasm::AbstractMachine& machine()
+ static Wasm::Runtime::Store& store()
{
- if (!s_machine)
- s_machine = make<Wasm::AbstractMachine>();
- return *s_machine;
+ if (!s_store)
+ s_store = make<Wasm::Runtime::Store>();
+ return *s_store;
}
- static void reset_machine()
+ static void reset_store()
{
- s_machine = nullptr;
s_spec_test_namespace.clear();
+ s_store = nullptr;
}
- Wasm::Module& module() { return *m_module; }
- Wasm::ModuleInstance& module_instance() { return *m_module_instance; }
+ u32 instance() const { return m_instance; }
- static JS::ThrowCompletionOr<GC::Ref<JS::HostObject>> create(JS::Realm& realm, NonnullRefPtr<Wasm::Module> module, HashMap<Wasm::Linker::Name, Wasm::ExternValue> const& imports)
+ static JS::ThrowCompletionOr<GC::Ref<JS::HostObject>> create(JS::Realm& realm, NonnullRefPtr<Wasm::Runtime::Module> module, HashMap<ImportName, Wasm::Runtime::Extern> const& registered)
{
auto& vm = realm.vm();
- auto instance = realm.create<WebAssemblyModule>();
- instance->m_module = move(module);
- Wasm::Linker linker(*instance->m_module);
- linker.link(imports);
- linker.link(spec_test_namespace());
- auto link_result = linker.finish();
- if (link_result.is_error())
+ auto const& spectest = spec_test_namespace();
+ Vector<Wasm::Runtime::Extern> imports;
+ for (size_t index = 0; index < module->import_count(); ++index) {
+ auto import = module->import(index);
+ ImportName name { import.module, import.name };
+ if (auto value = registered.get(name); value.has_value()) {
+ imports.append(*value);
+ continue;
+ }
+ if (auto value = spectest.get(name); value.has_value()) {
+ imports.append(*value);
+ continue;
+ }
return vm.throw_completion<JS::TypeError>("Link failed"_utf16);
- auto result = machine().instantiate(*instance->m_module, link_result.release_value());
+ }
+ auto result = store().instantiate(*module, imports);
if (result.is_error())
- return vm.throw_completion<JS::TypeError>(Utf16String::from_utf8(result.release_error().error));
- instance->m_module_instance = result.release_value();
+ return vm.throw_completion<JS::TypeError>(Utf16String::from_utf8(result.error().message));
+ auto instance = realm.create<WebAssemblyModule>();
+ instance->m_module = move(module);
+ instance->m_instance = result.value();
auto object = JS::HostObject::create(realm, web_assembly_module_host_class, realm.intrinsics().object_prototype(), {}, instance);
object->define_native_function(realm, "getExport"_utf16_fly_string, get_export, 1, JS::default_attributes);
object->define_native_function(realm, "invoke"_utf16_fly_string, wasm_invoke, 1, JS::default_attributes);
@@ -123,113 +156,86 @@ private:
JS_DECLARE_NATIVE_FUNCTION(get_export);
JS_DECLARE_NATIVE_FUNCTION(wasm_invoke);
- static HashMap<Wasm::Linker::Name, Wasm::ExternValue> const& spec_test_namespace()
+ static HashMap<ImportName, Wasm::Runtime::Extern> const& spec_test_namespace()
{
+ using namespace Wasm::Runtime;
if (!s_spec_test_namespace.is_empty())
return s_spec_test_namespace;
- Wasm::FunctionType print_type { {}, {} };
- auto address_print = alloc_noop_function(print_type);
- s_spec_test_namespace.set({ "spectest", "print", print_type }, Wasm::ExternValue { *address_print });
-
- Wasm::FunctionType print_i32_type { { Wasm::ValueType(Wasm::ValueType::I32) }, {} };
- auto address_i32 = alloc_noop_function(print_i32_type);
- s_spec_test_namespace.set({ "spectest", "print_i32", print_i32_type }, Wasm::ExternValue { *address_i32 });
-
- Wasm::FunctionType print_i64_type { { Wasm::ValueType(Wasm::ValueType::I64) }, {} };
- auto address_i64 = alloc_noop_function(print_i64_type);
- s_spec_test_namespace.set({ "spectest", "print_i64", print_i64_type }, Wasm::ExternValue { *address_i64 });
-
- Wasm::FunctionType print_f32_type { { Wasm::ValueType(Wasm::ValueType::F32) }, {} };
- auto address_f32 = alloc_noop_function(print_f32_type);
- s_spec_test_namespace.set({ "spectest", "print_f32", print_f32_type }, Wasm::ExternValue { *address_f32 });
-
- Wasm::FunctionType print_f64_type { { Wasm::ValueType(Wasm::ValueType::F64) }, {} };
- auto address_f64 = alloc_noop_function(print_f64_type);
- s_spec_test_namespace.set({ "spectest", "print_f64", print_f64_type }, Wasm::ExternValue { *address_f64 });
-
- Wasm::FunctionType print_i32_f32_type { { Wasm::ValueType(Wasm::ValueType::I32), Wasm::ValueType(Wasm::ValueType::F32) }, {} };
- auto address_i32_f32 = alloc_noop_function(print_i32_f32_type);
- s_spec_test_namespace.set({ "spectest", "print_i32_f32", print_i32_f32_type }, Wasm::ExternValue { *address_i32_f32 });
-
- Wasm::FunctionType print_f64_f64_type { { Wasm::ValueType(Wasm::ValueType::F64), Wasm::ValueType(Wasm::ValueType::F64) }, {} };
- auto address_f64_f64 = alloc_noop_function(print_f64_f64_type);
- s_spec_test_namespace.set({ "spectest", "print_f64_f64", print_f64_f64_type }, Wasm::ExternValue { *address_f64_f64 });
-
- Wasm::TableType table_type { Wasm::ValueType(Wasm::ValueType::FunctionReference), Wasm::Limits(Wasm::AddressType::I32, 10, 20) };
- auto table_address = machine().store().allocate(table_type);
- s_spec_test_namespace.set({ "spectest", "table", table_type }, Wasm::ExternValue { *table_address });
-
- Wasm::TableType table64_type { Wasm::ValueType(Wasm::ValueType::FunctionReference), Wasm::Limits(Wasm::AddressType::I64, 10, 20) };
- auto table64_address = machine().store().allocate(table64_type);
- s_spec_test_namespace.set({ "spectest", "table64", table64_type }, Wasm::ExternValue { *table64_address });
-
- Wasm::MemoryType memory_type { Wasm::Limits(Wasm::AddressType::I32, 1, 2) };
- auto memory_address = machine().store().allocate(memory_type);
- s_spec_test_namespace.set({ "spectest", "memory", memory_type }, Wasm::ExternValue { *memory_address });
-
- Wasm::GlobalType global_i32 { Wasm::ValueType(Wasm::ValueType::I32), false };
- auto global_i32_address = machine().store().allocate(global_i32, Wasm::Value(666));
- s_spec_test_namespace.set({ "spectest", "global_i32", global_i32 }, Wasm::ExternValue { *global_i32_address });
-
- Wasm::GlobalType global_i64 { Wasm::ValueType(Wasm::ValueType::I64), false };
- auto global_i64_address = machine().store().allocate(global_i64, Wasm::Value((i64)666));
- s_spec_test_namespace.set({ "spectest", "global_i64", global_i64 }, Wasm::ExternValue { *global_i64_address });
-
- Wasm::GlobalType global_f32 { Wasm::ValueType(Wasm::ValueType::F32), false };
- auto global_f32_address = machine().store().allocate(global_f32, Wasm::Value(666.6f));
- s_spec_test_namespace.set({ "spectest", "global_f32", global_f32 }, Wasm::ExternValue { *global_f32_address });
-
- Wasm::GlobalType global_f64 { Wasm::ValueType(Wasm::ValueType::F64), false };
- auto global_f64_address = machine().store().allocate(global_f64, Wasm::Value(666.6));
- s_spec_test_namespace.set({ "spectest", "global_f64", global_f64 }, Wasm::ExternValue { *global_f64_address });
+ auto add_print = [](StringView name, Vector<ValueType> parameters) {
+ auto address = store().allocate_host_function({ move(parameters), {} }, [](auto&, auto, auto) -> ErrorOr<void, ByteString> {
+ // Noop, this just needs to exist.
+ return {};
+ });
+ s_spec_test_namespace.set({ "spectest", name }, { ExternKind::Function, address });
+ };
+ auto i32 = ValueType::scalar(ValueKind::I32);
+ auto i64 = ValueType::scalar(ValueKind::I64);
+ auto f32 = ValueType::scalar(ValueKind::F32);
+ auto f64 = ValueType::scalar(ValueKind::F64);
+ add_print("print"sv, {});
+ add_print("print_i32"sv, { i32 });
+ add_print("print_i64"sv, { i64 });
+ add_print("print_f32"sv, { f32 });
+ add_print("print_f64"sv, { f64 });
+ add_print("print_i32_f32"sv, { i32, f32 });
+ add_print("print_f64_f64"sv, { f64, f64 });
+
+ auto funcref = ValueType::reference(HeapKind::Function);
+ auto table = store().allocate_table(funcref, { 10, 20, true, false, false }, 0);
+ s_spec_test_namespace.set({ "spectest", "table" }, { ExternKind::Table, table });
+ auto table64 = store().allocate_table(funcref, { 10, 20, true, true, false }, 0);
+ s_spec_test_namespace.set({ "spectest", "table64" }, { ExternKind::Table, table64 });
+
+ auto memory = store().allocate_memory({ 1, 2, true, false, false });
+ s_spec_test_namespace.set({ "spectest", "memory" }, { ExternKind::Memory, memory.value() });
+
+ s_spec_test_namespace.set({ "spectest", "global_i32" }, { ExternKind::Global, store().allocate_global(i32, false, Value::from_i32(666)) });
+ s_spec_test_namespace.set({ "spectest", "global_i64" }, { ExternKind::Global, store().allocate_global(i64, false, Value::from_i64(666)) });
+ s_spec_test_namespace.set({ "spectest", "global_f32" }, { ExternKind::Global, store().allocate_global(f32, false, Value::from_f32(666.6f)) });
+ s_spec_test_namespace.set({ "spectest", "global_f64" }, { ExternKind::Global, store().allocate_global(f64, false, Value::from_f64(666.6)) });
return s_spec_test_namespace;
}
- static Optional<Wasm::FunctionAddress> alloc_noop_function(Wasm::FunctionType type)
- {
- return machine().store().allocate(Wasm::HostFunction {
- [](auto&, auto) -> Wasm::Result {
- // Noop, this just needs to exist.
- return Wasm::Result { Vector<Wasm::Value> {} };
- },
- type,
- "__TEST" });
- }
-
- static HashMap<Wasm::Linker::Name, Wasm::ExternValue> s_spec_test_namespace;
- static OwnPtr<Wasm::AbstractMachine> s_machine;
- RefPtr<Wasm::Module> m_module;
- RefPtr<Wasm::ModuleInstance> m_module_instance;
+ static HashMap<ImportName, Wasm::Runtime::Extern> s_spec_test_namespace;
+ static OwnPtr<Wasm::Runtime::Store> s_store;
+ RefPtr<Wasm::Runtime::Module> m_module;
+ u32 m_instance { 0 };
};
GC_DEFINE_ALLOCATOR(WebAssemblyModule);
-OwnPtr<Wasm::AbstractMachine> WebAssemblyModule::s_machine;
-HashMap<Wasm::Linker::Name, Wasm::ExternValue> WebAssemblyModule::s_spec_test_namespace;
+OwnPtr<Wasm::Runtime::Store> WebAssemblyModule::s_store;
+HashMap<ImportName, Wasm::Runtime::Extern> WebAssemblyModule::s_spec_test_namespace;
+
+}
TESTJS_RUN_FILE_FUNCTION(ByteString const&, JS::Realm&, JS::ExecutionContext&)
{
- WebAssemblyModule::reset_machine();
+ WebAssemblyModule::reset_store();
return Test::JS::RunFileHookResult::RunAsNormal;
}
-TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
+static JS::ThrowCompletionOr<ByteBuffer> bytes_of_typed_array(JS::VM& vm, JS::Value value, StringView function_name)
{
- auto& realm = *vm.current_realm();
- auto object = TRY(vm.argument(0).to_object(vm));
+ auto object = TRY(value.to_object(vm));
if (!is<JS::Uint8Array>(*object))
- return vm.throw_completion<JS::TypeError>("Expected a Uint8Array argument to parse_webassembly_module"_utf16);
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Expected a Uint8Array argument to {}", function_name));
auto& array = static_cast<JS::Uint8Array&>(*object);
auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::SeqCst);
- auto bytes = MUST(array.viewed_array_buffer()->copy_to_byte_buffer(array.byte_offset(), JS::typed_array_byte_length(record)));
- FixedMemoryStream stream { ReadonlyBytes { bytes.data(), bytes.size() } };
- auto result = Wasm::Module::parse(stream);
- if (result.is_error())
- return vm.throw_completion<JS::SyntaxError>(Utf16String::from_utf8(Wasm::parse_error_to_byte_string(result.error())));
+ return MUST(array.viewed_array_buffer()->copy_to_byte_buffer(array.byte_offset(), JS::typed_array_byte_length(record)));
+}
- HashMap<Wasm::Linker::Name, Wasm::ExternValue> imports;
+TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
+{
+ auto& realm = *vm.current_realm();
+ auto bytes = TRY(bytes_of_typed_array(vm, vm.argument(0), "parse_webassembly_module"sv));
+ auto module = Wasm::Runtime::Module::compile(bytes);
+ if (module.is_error())
+ return vm.throw_completion<JS::SyntaxError>(Utf16String::from_utf8(module.error()));
+
+ HashMap<ImportName, Wasm::Runtime::Extern> imports;
auto import_value = vm.argument(1);
if (auto import_object = import_value.template as_if<JS::Object>()) {
for (auto property_key_value : TRY(import_object->ordinary_own_property_keys())) {
@@ -240,61 +246,34 @@ TESTJS_GLOBAL_FUNCTION(parse_webassembly_module, parseWebAssemblyModule)
auto* module_object = module_value.is_object() ? WebAssemblyModule::from_object(module_value.as_object()) : nullptr;
if (!module_object)
continue;
- for (auto& entry : module_object->module_instance().exports()) {
- // FIXME: Don't pretend that everything is a function
- imports.set({ property_key.as_string().to_utf16_string().to_byte_string(), entry.name(), Wasm::TypeIndex(0) }, entry.value());
- }
+ auto module_name = property_key.as_string().to_utf16_string().to_byte_string();
+ for (auto& entry : WebAssemblyModule::store().instance_exports(module_object->instance()))
+ imports.set({ module_name, entry.name }, entry.value);
}
}
- return JS::Value(TRY(WebAssemblyModule::create(realm, result.release_value(), imports)));
+ return JS::Value(TRY(WebAssemblyModule::create(realm, module.release_value(), imports)));
}
TESTJS_GLOBAL_FUNCTION(validate_webassembly_module, validateWebAssemblyModule)
{
- auto object = TRY(vm.argument(0).to_object(vm));
- if (!is<JS::Uint8Array>(*object))
- return vm.throw_completion<JS::TypeError>("Expected a Uint8Array argument to validate_webassembly_module"_utf16);
- auto& array = static_cast<JS::Uint8Array&>(*object);
- auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::SeqCst);
- auto bytes = MUST(array.viewed_array_buffer()->copy_to_byte_buffer(array.byte_offset(), JS::typed_array_byte_length(record)));
- FixedMemoryStream stream { ReadonlyBytes { bytes.data(), bytes.size() } };
- auto result = Wasm::Module::parse(stream);
- if (result.is_error())
- return vm.throw_completion<JS::SyntaxError>(Utf16String::from_utf8(Wasm::parse_error_to_byte_string(result.error())));
- if (auto validation = WebAssemblyModule::machine().validate(*result.value(), {}, Wasm::CompileToNative::No); validation.is_error())
- return vm.throw_completion<JS::SyntaxError>(Utf16String::from_utf8(validation.release_error().error_string));
+ auto bytes = TRY(bytes_of_typed_array(vm, vm.argument(0), "validate_webassembly_module"sv));
+ auto module = Wasm::Runtime::Module::compile(bytes);
+ if (module.is_error())
+ return vm.throw_completion<JS::SyntaxError>(Utf16String::from_utf8(module.error()));
return JS::js_undefined();
}
+// FIXME: These ask about the Cranelift JIT, which is gone; the tests that use them return early when nothing is
+// eligible.
TESTJS_GLOBAL_FUNCTION(is_cranelift_compiled, isCraneliftCompiled)
{
- auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(vm)));
- auto function_instance = WebAssemblyModule::machine().store().get(Wasm::FunctionAddress { address });
- if (!function_instance)
- return vm.throw_completion<JS::TypeError>("Invalid function address"_utf16);
-
- auto* wasm_function = function_instance->get_pointer<Wasm::WasmFunction>();
- if (!wasm_function)
- return JS::Value(false);
-
- auto const& compiled_instructions = wasm_function->code().func().body().compiled_instructions;
- return JS::Value(Wasm::cranelift_entry_acquire(compiled_instructions) != 0);
+ return JS::Value(false);
}
TESTJS_GLOBAL_FUNCTION(is_cranelift_eligible, isCraneliftEligible)
{
- auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(vm)));
- auto function_instance = WebAssemblyModule::machine().store().get(Wasm::FunctionAddress { address });
- if (!function_instance)
- return vm.throw_completion<JS::TypeError>("Invalid function address"_utf16);
-
- auto* wasm_function = function_instance->get_pointer<Wasm::WasmFunction>();
- if (!wasm_function)
- return JS::Value(false);
-
- auto const& compiled_instructions = wasm_function->code().func().body().compiled_instructions;
- return JS::Value(compiled_instructions.cranelift_eligible);
+ return JS::Value(false);
}
TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays)
@@ -354,16 +333,6 @@ TESTJS_GLOBAL_FUNCTION(is_arithmetic_nan64, isArithmeticNaN64)
return (bits & 0x7FF0000000000000ull) == 0x7FF0000000000000ull && payload >= 0x0008000000000000ull;
}
-TESTJS_GLOBAL_FUNCTION(is_valid_funcref_in, isValidFuncrefIn)
-{
- auto value = TRY(vm.argument(0).to_length(vm));
- auto module_object = TRY(vm.argument(1).to_object(vm));
- auto* module = WebAssemblyModule::from_object(*module_object);
- if (!module)
- return vm.throw_completion<JS::TypeError>("Expected a WebAssemblyModule"_utf16);
- return JS::Value(module->machine().store().get(Wasm::FunctionAddress { value }) != nullptr);
-}
-
TESTJS_GLOBAL_FUNCTION(test_simd_vector, testSIMDVector)
{
auto expected = TRY(vm.argument(0).to_object(vm));
@@ -407,237 +376,172 @@ TESTJS_GLOBAL_FUNCTION(test_simd_vector, testSIMDVector)
return true;
}
+TESTJS_GLOBAL_FUNCTION(is_valid_funcref_in, isValidFuncrefIn)
+{
+ auto value = TRY(vm.argument(0).to_length(vm));
+ auto module_object = TRY(vm.argument(1).to_object(vm));
+ if (!WebAssemblyModule::from_object(*module_object))
+ return vm.throw_completion<JS::TypeError>("Expected a WebAssemblyModule"_utf16);
+ return JS::Value(value < NumericLimits<u32>::max());
+}
+
+static JS::Value reference_to_js_value(Wasm::Runtime::Value value, Wasm::Runtime::ValueType type)
+{
+ using namespace Wasm::Runtime;
+ if (value.is_null_reference())
+ return JS::js_null();
+ auto bits = value.reference_bits();
+ if (auto host = host_reference_value(bits); host.has_value())
+ return JS::Value(static_cast<double>(*host));
+ if ((bits & 1) != 0)
+ return JS::Value(static_cast<double>(static_cast<i32>(bits) >> 1));
+ if (type.heap == HeapKind::Function || type.heap == HeapKind::NoFunction || type.heap == HeapKind::Concrete) {
+ if (auto function = WebAssemblyModule::store().function_from_reference(bits); function.has_value())
+ return JS::Value(static_cast<double>(*function));
+ }
+ return JS::js_undefined();
+}
+
+static JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM& vm, Wasm::Runtime::Value value, Wasm::Runtime::ValueType type)
+{
+ using namespace Wasm::Runtime;
+ switch (type.kind) {
+ case ValueKind::I32:
+ return JS::Value(static_cast<double>(value.to_i32()));
+ case ValueKind::I64:
+ return JS::Value(JS::BigInt::create(vm, Crypto::SignedBigInteger { value.to_i64() }));
+ case ValueKind::F32:
+ return JS::Value(static_cast<double>(value.f32_bits()));
+ case ValueKind::F64:
+ return JS::Value(JS::BigInt::create(vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger { value.f64_bits() } }));
+ case ValueKind::V128: {
+ auto buffer = TRY(JS::ArrayBuffer::create(*vm.current_realm(), 16));
+ u64 halves[2] = { value.low, value.high };
+ buffer->overwrite(0, reinterpret_cast<u8 const*>(halves), sizeof(halves));
+ return JS::Value(buffer);
+ }
+ case ValueKind::Reference:
+ return reference_to_js_value(value, type);
+ }
+ VERIFY_NOT_REACHED();
+}
+
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
{
+ using namespace Wasm::Runtime;
auto name = TRY(vm.argument(0).to_utf16_string(vm)).to_utf8_but_should_be_ported_to_utf16();
- auto this_value = vm.this_value();
- auto object = TRY(this_value.to_object(vm));
+ auto object = TRY(vm.this_value().to_object(vm));
auto* instance = WebAssemblyModule::from_object(*object);
if (!instance)
return vm.throw_completion<JS::TypeError>("Not a WebAssemblyModule"_utf16);
- for (auto& entry : instance->module_instance().exports()) {
- if (entry.name() == name.to_byte_string()) {
- auto& value = entry.value();
- if (auto ptr = value.get_pointer<Wasm::FunctionAddress>())
- return JS::Value(static_cast<unsigned long>(ptr->value()));
- if (auto v = value.get_pointer<Wasm::GlobalAddress>()) {
- auto global = machine().store().get(*v);
- switch (global->type().type().kind()) {
- case Wasm::ValueType::I32:
- return JS::Value(static_cast<double>(global->value().to<i32>()));
- case Wasm::ValueType::I64:
- return JS::BigInt::create(vm, Crypto::SignedBigInteger { global->value().to<i64>() });
- case Wasm::ValueType::F32:
- return JS::Value(static_cast<double>(global->value().to<float>()));
- case Wasm::ValueType::F64:
- return JS::Value(global->value().to<double>());
- case Wasm::ValueType::V128: {
- auto value = global->value().to<u128>();
- return JS::BigInt::create(vm, Crypto::SignedBigInteger::import_data(value.bytes()));
- }
- case Wasm::ValueType::FunctionReference:
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::ExternReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::ExceptionReference:
- case Wasm::ValueType::NoExceptionReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::TypeUseReference: {
- auto ref = global->value().to<Wasm::Reference>();
- return ref.ref().visit(
- [&](Wasm::Reference::Null const&) -> JS::Value { return JS::js_null(); },
- [](Wasm::Reference::Exception const&) -> JS::Value { return JS::js_undefined(); },
- [](Wasm::Reference::I31 const& ref) -> JS::Value { return JS::Value(static_cast<double>(ref.value)); },
- [](Wasm::Reference::GcObject const&) -> JS::Value { return JS::js_undefined(); },
- [&](auto const& ref) -> JS::Value { return JS::Value(static_cast<double>(ref.address.value())); });
- }
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);
- }
- }
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' does not refer to a function or a global", name));
+ auto value = store().find_export(instance->instance(), name);
+ if (!value.has_value())
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' could not be found", name));
+ if (value->kind == ExternKind::Function)
+ return JS::Value(static_cast<double>(value->address));
+ if (value->kind == ExternKind::Global) {
+ bool is_mutable = false;
+ auto type = store().global_type(value->address, is_mutable);
+ auto global = store().global_get(value->address);
+ switch (type.kind) {
+ case ValueKind::I32:
+ return JS::Value(static_cast<double>(global.to_i32()));
+ case ValueKind::I64:
+ return JS::BigInt::create(vm, Crypto::SignedBigInteger { global.to_i64() });
+ case ValueKind::F32:
+ return JS::Value(static_cast<double>(global.to_f32()));
+ case ValueKind::F64:
+ return JS::Value(global.to_f64());
+ case ValueKind::V128: {
+ u64 halves[2] = { global.low, global.high };
+ return JS::BigInt::create(vm, Crypto::SignedBigInteger::import_data({ reinterpret_cast<u8 const*>(halves), sizeof(halves) }));
+ }
+ case ValueKind::Reference:
+ return reference_to_js_value(global, type);
}
}
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' could not be found", name));
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' does not refer to a function or a global", name));
}
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
{
- auto address = static_cast<unsigned long>(TRY(vm.argument(0).to_double(vm)));
- Wasm::FunctionAddress function_address { address };
- auto function_instance = WebAssemblyModule::machine().store().get(function_address);
- if (!function_instance)
- return vm.throw_completion<JS::TypeError>("Invalid function address"_utf16);
-
- Wasm::FunctionType const* type { nullptr };
- function_instance->visit([&](auto& value) { type = &value.type(); });
- if (!type)
- return vm.throw_completion<JS::TypeError>("Invalid function found at given address"_utf16);
-
- Vector<Wasm::Value> arguments;
- if (type->parameters().size() + 1 > vm.argument_count())
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Expected {} arguments for call, but found {}", type->parameters().size() + 1, vm.argument_count()));
+ using namespace Wasm::Runtime;
+ auto address = static_cast<u32>(TRY(vm.argument(0).to_double(vm)));
+ auto type = store().function_type(address);
+
+ Vector<Value> arguments;
+ if (type.parameters.size() + 1 > vm.argument_count())
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Expected {} arguments for call, but found {}", type.parameters.size() + 1, vm.argument_count()));
size_t index = 1;
- for (auto& param : type->parameters()) {
+ for (auto parameter : type.parameters) {
auto argument = vm.argument(index++);
double double_value = 0;
if (!argument.is_bigint() && !argument.is_object())
double_value = TRY(argument.to_double(vm));
- switch (param.kind()) {
- case Wasm::ValueType::Kind::I32:
- arguments.append(Wasm::Value(static_cast<i64>(double_value)));
+ switch (parameter.kind) {
+ case ValueKind::I32:
+ arguments.append(Value::from_i32(static_cast<i32>(static_cast<i64>(double_value))));
break;
- case Wasm::ValueType::Kind::I64:
- if (argument.is_bigint()) {
- auto value = bit_cast<i64>(TRY(argument.to_bigint_uint64(vm)));
- arguments.append(Wasm::Value(value));
- } else {
- arguments.append(Wasm::Value(static_cast<i64>(double_value)));
- }
+ case ValueKind::I64:
+ if (argument.is_bigint())
+ arguments.append(Value::from_i64(bit_cast<i64>(TRY(argument.to_bigint_uint64(vm)))));
+ else
+ arguments.append(Value::from_i64(static_cast<i64>(double_value)));
break;
- case Wasm::ValueType::Kind::F32:
- arguments.append(Wasm::Value(bit_cast<float>(static_cast<u32>(double_value))));
+ case ValueKind::F32:
+ arguments.append(Value::from_f32_bits(static_cast<u32>(double_value)));
break;
- case Wasm::ValueType::Kind::F64:
- if (argument.is_bigint()) {
- auto value = TRY(argument.to_bigint_uint64(vm));
- arguments.append(Wasm::Value(bit_cast<double>(value)));
- } else {
- arguments.append(Wasm::Value(double_value));
- }
+ case ValueKind::F64:
+ if (argument.is_bigint())
+ arguments.append(Value::from_f64_bits(TRY(argument.to_bigint_uint64(vm))));
+ else
+ arguments.append(Value::from_f64(double_value));
break;
- case Wasm::ValueType::Kind::V128: {
+ case ValueKind::V128: {
auto object = MUST(argument.to_object(vm));
if (!is<JS::TypedArrayBase>(*object))
return vm.throw_completion<JS::TypeError>("Expected typed array"_utf16);
auto& array = static_cast<JS::TypedArrayBase&>(*object);
auto record = JS::make_typed_array_with_buffer_witness_record(array, JS::ArrayBuffer::Order::SeqCst);
- if (JS::typed_array_byte_length(record) < sizeof(u128))
+ if (JS::typed_array_byte_length(record) < 16)
return vm.throw_completion<JS::TypeError>("Expected at least 16 bytes"_utf16);
- u128 bits = 0;
- auto* ptr = bit_cast<u8*>(&bits);
- array.viewed_array_buffer()->copy_to(array.byte_offset(), { ptr, sizeof(u128) });
- arguments.append(Wasm::Value(bits));
+ u64 halves[2] = { 0, 0 };
+ array.viewed_array_buffer()->copy_to(array.byte_offset(), { reinterpret_cast<u8*>(halves), sizeof(halves) });
+ arguments.append(Value::from_v128(halves[0], halves[1]));
break;
}
- case Wasm::ValueType::Kind::FunctionReference: {
+ case ValueKind::Reference:
if (argument.is_null()) {
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::FunctionReference) } }));
+ arguments.append(Value::from_reference(0));
break;
}
- Wasm::FunctionAddress addr = static_cast<u64>(double_value);
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Func { addr, machine().store().get_module_for(addr) } }));
- break;
- }
- case Wasm::ValueType::Kind::ExternReference:
- if (argument.is_null()) {
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::ExternReference) } }));
+ switch (parameter.heap) {
+ case HeapKind::Function:
+ arguments.append(Value::from_reference(store().function_reference(static_cast<u32>(double_value))));
break;
- }
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Extern { static_cast<u64>(double_value) } }));
- break;
- case Wasm::ValueType::Kind::ExceptionReference:
- if (argument.is_null())
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::ExceptionReference) } }));
- else
- return vm.throw_completion<JS::TypeError>("Exception references are not supported"_utf16);
- break;
- case Wasm::ValueType::Kind::TypeUseReference:
- if (argument.is_null())
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(Wasm::ValueType::Kind::TypeUseReference, param.unsafe_typeindex()) } }));
- else
- return vm.throw_completion<JS::TypeError>("GC Heap references are not supported"_utf16);
- break;
- case Wasm::ValueType::Kind::AnyReference:
- if (argument.is_null()) {
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(param.kind()) } }));
+ case HeapKind::Extern:
+ case HeapKind::Any:
+ arguments.append(Value::from_reference(host_reference_bits(static_cast<u64>(double_value))));
break;
- }
- // A host reference passed by address (e.g. a `(ref.host n)` spec-test argument); it enters the any hierarchy as an internalized extern reference.
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Extern { static_cast<u64>(double_value) } }));
- break;
- case Wasm::ValueType::Kind::NoFunctionReference:
- case Wasm::ValueType::Kind::NoExternReference:
- case Wasm::ValueType::Kind::EqReference:
- case Wasm::ValueType::Kind::I31Reference:
- case Wasm::ValueType::Kind::StructReference:
- case Wasm::ValueType::Kind::ArrayReference:
- case Wasm::ValueType::Kind::NoneReference:
- case Wasm::ValueType::Kind::NoExceptionReference:
- if (argument.is_null())
- arguments.append(Wasm::Value(Wasm::Reference { Wasm::Reference::Null { Wasm::ValueType(param.kind()) } }));
- else
+ default:
return vm.throw_completion<JS::TypeError>("GC Heap references are not supported"_utf16);
+ }
break;
- case Wasm::ValueType::Kind::I8:
- case Wasm::ValueType::Kind::I16:
- return vm.throw_completion<JS::TypeError>("Packed types are not valid parameter types"_utf16);
}
}
- auto functype = WebAssemblyModule::machine().store().get(function_address)->visit([&](auto& func) { return func.type(); });
- auto result = WebAssemblyModule::machine().invoke(function_address, arguments);
- if (result.is_trap()) {
- if (auto ptr = result.trap().data.get_pointer<Wasm::ExternallyManagedTrap>())
- return ptr->unsafe_external_object_as<JS::Completion>();
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Execution trapped: {}", result.trap().format()));
- }
+ auto result = store().invoke(address, arguments);
+ if (result.is_error())
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Execution trapped: {}", result.error()));
- if (result.values().is_empty())
+ auto& values = result.value();
+ if (values.is_empty())
return JS::js_null();
+ if (values.size() == 1)
+ return to_js_value(vm, values.first(), type.results.first());
- auto to_js_value = [&](Wasm::Value const& value, Wasm::ValueType type) -> JS::ThrowCompletionOr<JS::Value> {
- switch (type.kind()) {
- case Wasm::ValueType::I32:
- return JS::Value(static_cast<double>(value.to<i32>()));
- case Wasm::ValueType::I64:
- return JS::Value(JS::BigInt::create(vm, Crypto::SignedBigInteger { value.to<i64>() }));
- case Wasm::ValueType::F32:
- return JS::Value(static_cast<double>(bit_cast<u32>(value.to<float>())));
- case Wasm::ValueType::F64:
- return JS::Value(JS::BigInt::create(vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger { bit_cast<u64>(value.to<double>()) } }));
- case Wasm::ValueType::V128: {
- u128 val = value.to<u128>();
- // FIXME: remove the MUST here
- auto buf = MUST(JS::ArrayBuffer::create(*vm.current_realm(), 16));
- auto bytes = val.bytes();
- buf->overwrite(0, bytes.data(), bytes.size());
- return JS::Value(buf);
- }
- case Wasm::ValueType::FunctionReference:
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::ExternReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::TypeUseReference:
- return (value.to<Wasm::Reference>()).ref().visit([&](Wasm::Reference::Null) { return JS::js_null(); }, [&](Wasm::Reference::Exception) { return JS::js_undefined(); }, [&](Wasm::Reference::I31 const& ref) { return JS::Value(static_cast<double>(ref.value)); }, [&](Wasm::Reference::GcObject const&) { return JS::js_undefined(); }, [&](auto const& ref) { return JS::Value(static_cast<double>(ref.address.value())); });
- case Wasm::ValueType::ExceptionReference:
- case Wasm::ValueType::NoExceptionReference:
- return JS::js_null();
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- return vm.throw_completion<JS::TypeError>("Unsupported packed type"_utf16);
- }
- VERIFY_NOT_REACHED();
- };
-
- if (result.values().size() == 1)
- return to_js_value(result.values().first(), functype.results().first());
-
- size_t i = 0;
- return JS::Array::create_from<Wasm::Value>(*vm.current_realm(), result.values(), [&](Wasm::Value value) {
- auto value_type = type->results()[i++];
- return MUST(to_js_value(value, value_type));
- });
+ Vector<JS::Value> js_values;
+ for (size_t result_index = 0; result_index < values.size(); ++result_index)
+ js_values.append(TRY(to_js_value(vm, values[result_index], type.results[result_index])));
+ return JS::Array::create_from(*vm.current_realm(), js_values);
}