Skip to content

Truly independent web browser

LibWeb: Implement the WebAssembly JS API in Rust

Shannon Booth496702613f26
diff --git a/Cargo.lock b/Cargo.lock
index 7f32b7b0804..35edbe0fa34 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -922,6 +922,7 @@ dependencies = [
"libjs_rust",
"libtextcodec_rust",
"liburl_rust",
+ "libwasm_engine",
"libweb_rust",
"libwebcommon_rust",
"rustc-demangle",
diff --git a/Libraries/LibWeb/Bindings/HostDefined.cpp b/Libraries/LibWeb/Bindings/HostDefined.cpp
index 618c1f3797f..f2d53ccd3d9 100644
--- a/Libraries/LibWeb/Bindings/HostDefined.cpp
+++ b/Libraries/LibWeb/Bindings/HostDefined.cpp
@@ -7,7 +7,6 @@
#include <LibWeb/Bindings/HostDefined.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/WebAssembly/Tag.h>
namespace Web::Bindings {
@@ -32,7 +31,6 @@ void HostDefined::visit_edges(Cell::Visitor& visitor)
visitor.visit(intrinsics);
visitor.visit(wrapper_world);
visitor.visit(principal_realm);
- visitor.visit(wasm_js_tag);
}
}
diff --git a/Libraries/LibWeb/Bindings/HostDefined.h b/Libraries/LibWeb/Bindings/HostDefined.h
index b1b9b64a5e4..ef81f2091d5 100644
--- a/Libraries/LibWeb/Bindings/HostDefined.h
+++ b/Libraries/LibWeb/Bindings/HostDefined.h
@@ -37,9 +37,6 @@ public:
// Principal realms point this at themselves via PrincipalHostDefined's construction path. Non-principal realms must
// point at an already-created principal realm with a PrincipalHostDefined.
GC::Ref<JS::Realm> principal_realm;
- // The Tag object of the JavaScript exception tag in this realm. The tag lives as long as the agent, but a Tag object
- // belongs to the realm it is first wrapped in, so each realm has one of its own.
- GC::Ptr<WebAssembly::Tag> wasm_js_tag;
protected:
HostDefined(GC::Ref<Intrinsics> intrinsics, GC::Ref<WrapperWorld> wrapper_world, GC::Ref<JS::Realm> principal_realm, PrincipalRealmUnderConstruction principal_realm_under_construction = PrincipalRealmUnderConstruction::No);
diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
index 5bd8616379a..feda28f31c8 100644
--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp
+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp
@@ -708,7 +708,7 @@ void initialize_main_thread_vm(HTML::AgentType type)
};
main_thread_vm_ptr()->host_resize_array_buffer = [default_host_resize_array_buffer = move(main_thread_vm_ptr()->host_resize_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {
- auto wasm_handled = TRY(WebAssembly::Detail::host_resize_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));
+ auto wasm_handled = TRY(WebAssembly::host_resize_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));
if (wasm_handled == JS::HandledByHost::Handled)
return JS::HandledByHost::Handled;
@@ -716,7 +716,7 @@ void initialize_main_thread_vm(HTML::AgentType type)
};
main_thread_vm_ptr()->host_grow_shared_array_buffer = [default_host_grow_shared_array_buffer = move(main_thread_vm_ptr()->host_grow_shared_array_buffer)](JS::ArrayBuffer& buffer, size_t new_byte_length) -> JS::ThrowCompletionOr<JS::HandledByHost> {
- auto wasm_handled = TRY(WebAssembly::Detail::host_grow_shared_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));
+ auto wasm_handled = TRY(WebAssembly::host_grow_shared_array_buffer(*main_thread_vm_ptr(), buffer, new_byte_length));
if (wasm_handled == JS::HandledByHost::Handled)
return JS::HandledByHost::Handled;
diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
index 6c5e2a38ae5..775827a7e85 100644
--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
@@ -10,7 +10,7 @@ crate-type = ["staticlib", "rlib"]
# The features of the LibJS runtime, which this crate builds for LibWeb's library. The JIT is a default feature, as it
# is of the runtime's crate, so that cargo builds and lints the crate the way LibWeb's library does unless told otherwise.
default = ["jit"]
-allocator = ["dep:ladybird_allocator", "libjs_rust/allocator", "libweb_rust/allocator"]
+allocator = ["dep:ladybird_allocator", "libjs_rust/allocator", "libwasm_engine/allocator", "libweb_rust/allocator"]
jit = ["libjs_rust/jit"]
address-sanitizer = ["libjs_rust/address-sanitizer"]
thread-sanitizer = ["libjs_rust/thread-sanitizer", "libweb_rust/thread-sanitizer"]
@@ -27,6 +27,7 @@ libgfx_rust = { path = "../../../LibGfx/Rust", default-features = false }
libjs_rust = { path = "../../../LibJS/Rust", default-features = false }
libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }
liburl_rust = { path = "../../../LibURL/Rust", default-features = false }
+libwasm_engine = { path = "../../../LibWasm/Engine" }
libweb_rust = { path = "../../Rust" }
libwebcommon_rust = { path = "../../../LibWebCommon/Rust" }
rustc-demangle = "0.1"
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
index e4623146363..0dbef0af3c8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs
@@ -12,9 +12,12 @@ use core::cell::Cell;
use core::ffi::c_void;
use core::ptr::NonNull;
-use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, FunctionObject, Gc, Realm, Trace, Vm};
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, FunctionObject, Gc, Object, Realm, Trace, Vm};
+
+use crate::bindings::interface::Ref;
use crate::bindings::services::web_bindings_wrapper_world;
+use crate::web_assembly::tag::Tag;
/// The wrapper world of a realm, Web::Bindings::WrapperWorld, which the realm keeps alive.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -38,6 +41,12 @@ pub(crate) struct RealmData {
pub(crate) count_queuing_strategy_size_function: Cell<Option<Gc<FunctionObject>>>,
/// https://streams.spec.whatwg.org/#byte-length-queuing-strategy-size-function
pub(crate) byte_length_queuing_strategy_size_function: Cell<Option<Gc<FunctionObject>>>,
+ /// The NativeError prototypes and constructors of WebAssembly.CompileError, LinkError and RuntimeError,
+ /// https://webassembly.github.io/spec/js-api/#error-objects
+ pub(crate) webassembly_error_prototypes: [Cell<Option<Gc<Object>>>; 3],
+ pub(crate) webassembly_error_constructors: [Cell<Option<Gc<Object>>>; 3],
+ /// The Tag object of the JavaScript exception tag, https://webassembly.github.io/spec/js-api/#javascript-exception-tag
+ pub(crate) webassembly_js_tag: Cell<Option<Ref<Tag>>>,
}
static REALM_DATA_CLASS: EmbedderClass<RealmData> = EmbedderClass::new("RealmData");
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
index ab8a6dc1ff5..395c7223872 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/structured_data.rs
@@ -32,6 +32,7 @@ unsafe extern "C" {
fn web_bindings_serialize_f64(serialized: *mut c_void, value: f64);
fn web_bindings_serialize_bool(serialized: *mut c_void, value: bool);
fn web_bindings_serialize_i64(serialized: *mut c_void, value: i64);
+ fn web_bindings_serialize_optional_u64(serialized: *mut c_void, has_value: bool, value: u64);
fn web_bindings_serialize_utf16_string(serialized: *mut c_void, string: usize);
fn web_bindings_serialize_bytes(serialized: *mut c_void, bytes: ak::Span<'_, u8>);
fn web_bindings_deserialize_value(serialized: *mut c_void) -> RawNativeFunctionResult;
@@ -39,6 +40,11 @@ unsafe extern "C" {
fn web_bindings_deserialize_f64(serialized: *mut c_void, out_value: &mut f64) -> RawNativeFunctionResult;
fn web_bindings_deserialize_bool(serialized: *mut c_void, out_value: &mut bool) -> RawNativeFunctionResult;
fn web_bindings_deserialize_i64(serialized: *mut c_void, out_value: &mut i64) -> RawNativeFunctionResult;
+ fn web_bindings_deserialize_optional_u64(
+ serialized: *mut c_void,
+ out_has_value: &mut bool,
+ out_value: &mut u64,
+ ) -> RawNativeFunctionResult;
fn web_bindings_deserialize_bytes(
serialized: *mut c_void,
bytes: *mut c_void,
@@ -96,6 +102,11 @@ impl SerializationWriter<'_> {
unsafe { web_bindings_serialize_i64(self.raw.as_ptr(), value) };
}
+ pub(crate) fn write_optional_u64(&mut self, value: Option<u64>) {
+ // SAFETY: The writer is lent for the steps.
+ unsafe { web_bindings_serialize_optional_u64(self.raw.as_ptr(), value.is_some(), value.unwrap_or(0)) };
+ }
+
pub(crate) fn write_utf16_string(&mut self, string: &Utf16String) {
// SAFETY: The writer is lent for the steps, and the call borrows the string.
unsafe { web_bindings_serialize_utf16_string(self.raw.as_ptr(), string.raw_identity()) };
@@ -178,6 +189,15 @@ impl SerializationReader<'_> {
Ok(value)
}
+ pub(crate) fn read_optional_u64(&mut self) -> WebIdlResult<Option<u64>> {
+ let mut has_value = false;
+ let mut value = 0;
+ // SAFETY: The reader is lent for the steps.
+ unsafe { web_bindings_deserialize_optional_u64(self.raw.as_ptr(), &mut has_value, &mut value) }
+ .into_completion()?;
+ Ok(has_value.then_some(value))
+ }
+
pub(crate) fn read_bytes(&mut self) -> WebIdlResult<Vec<u8>> {
unsafe extern "C" fn append(bytes: *mut c_void, data: *const u8, length: usize) {
// SAFETY: The bytes are the Vec that read_bytes() lends, and LibWeb passes that many bytes.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 4f28ab32ea4..ce44de48cd4 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -109,6 +109,16 @@ pub(crate) mod streams;
allow(dead_code, reason = "only the generated bindings use the interfaces")
)]
pub(crate) mod url_pattern;
+#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod web_assembly;
#[cfg_attr(
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the interfaces")
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/builtins.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/builtins.rs
new file mode 100644
index 00000000000..4c164487cf3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/builtins.rs
@@ -0,0 +1,820 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The builtins of the JS API, https://webassembly.github.io/spec/js-api/#builtins, and the imported strings,
+//! https://webassembly.github.io/spec/js-api/#instantiate-imported-strings
+
+use core::ffi::c_void;
+use std::collections::HashSet;
+use std::rc::Rc;
+
+use ak::{Utf16String, Utf16StringUnits};
+use libjs_rust::api::{Gc, Must, Object, PrimitiveString, PropertyKey, Value, Vm};
+use libwasm_engine::module::{Import, ImportDescription};
+use libwasm_engine::runtime::{FunctionAddress, HostFunction, Store, Trap, Value as WasmValue};
+use libwasm_engine::types::{GlobalType, HeapType, RefType, ValType};
+
+use crate::bindings::conversions::UsvString;
+use crate::web_assembly::exported_function::create_exported_function;
+use crate::web_assembly::instance::function_type_in_store;
+use crate::web_assembly::values::{EXTERNREF, to_js_value, to_webassembly_value};
+use crate::web_assembly::{Agent, CompiledModule};
+
+const JS_STRING_BUILTIN_SET_NAME: &str = "js-string";
+const JS_STRING_BUILTIN_SET_QUALIFIED_NAME: &str = "wasm:js-string";
+
+/// The funcTypes of the builtins, each in a recursion group of its own, as the types of a module that has nothing
+/// else. The store gives types the same identity wherever they are equivalent, so an import matches the funcType of a
+/// builtin exactly when the identity of its type is the identity of that funcType.
+#[derive(Clone, Copy)]
+enum BuiltinTypeIndex {
+ // (rec (type (array (mut i16)))).0
+ #[allow(
+ dead_code,
+ reason = "the array type is the type of the other types' array parameters"
+ )]
+ ArrayType,
+ // (rec (type (func (param externref) (result (ref extern))))).0
+ ExternrefToRefExtern,
+ // (rec (type (func (param externref) (result i32)))).0
+ ExternrefToI32,
+ // (rec (type (func (param (ref null arrayType) i32 i32) (result (ref extern))))).0
+ ArrayI32I32ToRefExtern,
+ // (rec (type (func (param externref (ref null arrayType) i32) (result i32)))).0
+ ExternrefArrayI32ToI32,
+ // (rec (type (func (param i32) (result (ref extern))))).0
+ I32ToRefExtern,
+ // (rec (type (func (param externref i32) (result i32)))).0
+ ExternrefI32ToI32,
+ // (rec (type (func (param externref externref) (result (ref extern))))).0
+ ExternrefExternrefToRefExtern,
+ // (rec (type (func (param externref i32 i32) (result (ref extern))))).0
+ ExternrefI32I32ToRefExtern,
+ // (rec (type (func (param externref externref) (result i32)))).0
+ ExternrefExternrefToI32,
+}
+
+pub(crate) const BUILTIN_TYPES_MODULE_BYTES: [u8; 75] = [
+ // Magic and version.
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, //
+ // The type section: 65 bytes, 10 types.
+ 0x01, 0x41, 0x0a, //
+ // array (mut i16)
+ 0x5e, 0x77, 0x01, //
+ // func (param externref) (result (ref extern))
+ 0x60, 0x01, 0x6f, 0x01, 0x64, 0x6f, //
+ // func (param externref) (result i32)
+ 0x60, 0x01, 0x6f, 0x01, 0x7f, //
+ // func (param (ref null 0) i32 i32) (result (ref extern))
+ 0x60, 0x03, 0x63, 0x00, 0x7f, 0x7f, 0x01, 0x64, 0x6f, //
+ // func (param externref (ref null 0) i32) (result i32)
+ 0x60, 0x03, 0x6f, 0x63, 0x00, 0x7f, 0x01, 0x7f, //
+ // func (param i32) (result (ref extern))
+ 0x60, 0x01, 0x7f, 0x01, 0x64, 0x6f, //
+ // func (param externref i32) (result i32)
+ 0x60, 0x02, 0x6f, 0x7f, 0x01, 0x7f, //
+ // func (param externref externref) (result (ref extern))
+ 0x60, 0x02, 0x6f, 0x6f, 0x01, 0x64, 0x6f, //
+ // func (param externref i32 i32) (result (ref extern))
+ 0x60, 0x03, 0x6f, 0x7f, 0x7f, 0x01, 0x64, 0x6f, //
+ // func (param externref externref) (result i32)
+ 0x60, 0x02, 0x6f, 0x6f, 0x01, 0x7f,
+];
+
+/// The store-wide identity of the type at `type_index` of a module.
+fn type_identity(vm: &Vm, module: &CompiledModule, type_index: u32) -> u32 {
+ Agent::the(vm).store().module_type_identities_of(module)[type_index as usize]
+}
+
+type BuiltinSteps = fn(&Vm, &[WasmValue]) -> Result<WasmValue, Trap>;
+
+struct Builtin {
+ name: &'static str,
+ function_type: BuiltinTypeIndex,
+ steps: BuiltinSteps,
+}
+
+fn trap(message: &str) -> Trap {
+ Trap::Host(message.to_string())
+}
+
+fn js_value_of(vm: &Vm, value: WasmValue) -> Value {
+ to_js_value(vm, value, EXTERNREF).must()
+}
+
+fn string_reference(vm: &Vm, string: Gc<PrimitiveString>) -> WasmValue {
+ to_webassembly_value(vm, Value::from_string(string), EXTERNREF).must()
+}
+
+fn string_reference_of_code_units(vm: &Vm, code_units: &[u16]) -> WasmValue {
+ string_reference(vm, PrimitiveString::create(vm, Utf16String::from_utf16(code_units)))
+}
+
+fn i32_of(value: WasmValue) -> i32 {
+ let WasmValue::I32(value) = value else {
+ unreachable!("the funcType of the builtin has an i32 there");
+ };
+ value
+}
+
+fn unsigned_i32(value: WasmValue) -> u32 {
+ i32_of(value) as u32
+}
+
+/// The code units of a string.
+fn code_units_of(string: Gc<PrimitiveString>) -> Vec<u16> {
+ let string = string.utf16_string();
+ match string.as_units() {
+ Utf16StringUnits::Ascii(characters) => characters.iter().map(|&character| u16::from(character)).collect(),
+ Utf16StringUnits::Utf16(code_units) => code_units.to_vec(),
+ }
+}
+
+/// The number of elements of an array, which is not null.
+fn array_length(array: u64) -> u32 {
+ // SAFETY: The array is the argument of a builtin whose funcType makes it a live array of i16s.
+ unsafe { libwasm_engine::runtime::gc::array_length(array) }
+}
+
+// https://webassembly.github.io/spec/js-api/#abstract-opdef-unwrapstring
+fn unwrap_string(vm: &Vm, v: WasmValue) -> Result<Gc<PrimitiveString>, Trap> {
+ let value = js_value_of(vm, v);
+
+ // 1. If v is not a String,
+ if !value.is_string() {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("Expected a string"));
+ }
+
+ // 2. Return v
+ Ok(value.as_string())
+}
+
+// https://webassembly.github.io/spec/js-api/#abstract-opdef-fromcharcode
+fn from_char_code(v: i32) -> u16 {
+ // 1. Assert: v is of type i32.
+ // 2. Return ! Call(String.fromCharCode, undefined, « ToJSValue(v) »).
+ v as u16
+}
+
+// https://webassembly.github.io/spec/js-api/#abstract-opdef-charcodeat
+fn char_code_at(string: Gc<PrimitiveString>, index: u32) -> i32 {
+ // 1. Assert: index is of type i32.
+ // 2. Return ! Call(String.prototype.charCodeAt, string, « ToJSValue(index) »).
+ i32::from(string.code_unit_at(index as usize))
+}
+
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the steps of every builtin have the one type, and some can trap"
+)]
+mod js_string_builtins {
+ use libjs_rust::api::{PrimitiveString, Vm};
+ use libwasm_engine::runtime::{Trap, Value as WasmValue};
+
+ use super::{
+ array_length, code_units_of, i32_of, js_value_of, string_reference, string_reference_of_code_units, trap,
+ unsigned_i32, unwrap_string,
+ };
+
+ // https://webassembly.github.io/spec/js-api/#js-string-cast
+ pub(super) fn cast(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. Return ? UnwrapString(v)
+ unwrap_string(vm, arguments[0])?;
+ Ok(arguments[0])
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-test
+ pub(super) fn test(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. If v is not a String,
+ if !js_value_of(vm, arguments[0]).is_string() {
+ // 1. Return 0.
+ return Ok(WasmValue::I32(0));
+ }
+
+ // 2. Return 1.
+ Ok(WasmValue::I32(1))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-fromcharcodearray
+ pub(super) fn from_char_code_array(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let WasmValue::Ref(array) = arguments[0] else {
+ unreachable!("the funcType of the builtin has an array reference there");
+ };
+ // NB: The indices are unsigned, as everywhere else in WebAssembly.
+ let start = unsigned_i32(arguments[1]);
+ let end = unsigned_i32(arguments[2]);
+
+ // 1. If array is null,
+ if array == 0 {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The array is null"));
+ }
+
+ // 2. Let length be the number of elements in array.
+ let length = array_length(array);
+
+ // 3. If start > end or end > length,
+ if start > end || end > length {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The range is out of the array's bounds"));
+ }
+
+ // 4. Let result be the empty string.
+ let mut result = Vec::with_capacity((end - start) as usize);
+
+ // 5. Let i be start.
+ // 6. While i < end:
+ for i in start..end {
+ // 1. Let charCode be the value of the element stored at index i in array.
+ // SAFETY: The array is a live array of i16s, and i is in its bounds.
+ let char_code = unsafe { libwasm_engine::runtime::gc::array_element(array, i) } as i32;
+
+ // 2. Let charCodeString be FromCharCode(charCode).
+ // 3. Let result be the concatenation of result and charCodeString.
+ // NB: FromCharCode() makes a string of one code unit, which is the code unit itself here.
+ result.push(super::from_char_code(char_code));
+
+ // 4. Set i to i + 1.
+ }
+
+ // 7. Return result.
+ Ok(string_reference_of_code_units(vm, &result))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-intocharcodearray
+ pub(super) fn into_char_code_array(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let WasmValue::Ref(array) = arguments[1] else {
+ unreachable!("the funcType of the builtin has an array reference there");
+ };
+ let start = unsigned_i32(arguments[2]);
+
+ // 1. If array is null,
+ if array == 0 {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The array is null"));
+ }
+
+ // 2. Let string be ? UnwrapString(string).
+ let string = unwrap_string(vm, arguments[0])?;
+
+ // 3. Let stringLength be the length of string.
+ let string_length = string.length_in_utf16_code_units();
+
+ // 4. Let arrayLength be the number of elements in array.
+ let array_length = array_length(array);
+
+ // 5. If start + stringLength > arrayLength,
+ if u64::from(start) + string_length as u64 > u64::from(array_length) {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The string does not fit in the array"));
+ }
+
+ // 6. Let i be 0.
+ // 7. While i < stringLength:
+ for i in 0..string_length as u32 {
+ // 1. Let charCode be CharCodeAt(string, i).
+ let char_code = super::char_code_at(string, i);
+
+ // 2. Set the element at index start + i in array to ToWebAssemblyValue(charCode, i32).
+ // SAFETY: The array is a live array of i16s, and start + i is in its bounds.
+ unsafe { libwasm_engine::runtime::gc::set_array_element(array, start + i, u64::from(char_code as u32)) };
+
+ // 3. Set i to i + 1.
+ }
+
+ // 8. Return stringLength.
+ Ok(WasmValue::I32(string_length as i32))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-fromcharcode
+ pub(super) fn from_char_code(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. Return FromCharCode(v).
+ Ok(string_reference_of_code_units(
+ vm,
+ &[super::from_char_code(i32_of(arguments[0]))],
+ ))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-fromcodepoint
+ pub(super) fn from_code_point(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let v = unsigned_i32(arguments[0]);
+
+ // 1. If v > 0x10ffff,
+ if v > 0x10ffff {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The code point is out of range"));
+ }
+
+ // 2. Return ! Call(String.fromCodePoint, undefined, « ToJSValue(v) »).
+ // NB: A code point beyond the BMP is a surrogate pair, and a surrogate code point is a lone surrogate.
+ if v < 0x10000 {
+ return Ok(string_reference_of_code_units(vm, &[v as u16]));
+ }
+ let offset = v - 0x10000;
+ Ok(string_reference_of_code_units(
+ vm,
+ &[0xd800 | (offset >> 10) as u16, 0xdc00 | (offset & 0x3ff) as u16],
+ ))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-charcodeat
+ pub(super) fn char_code_at(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let index = unsigned_i32(arguments[1]);
+
+ // 1. Let string be ? UnwrapString(string).
+ let string = unwrap_string(vm, arguments[0])?;
+
+ // 2. Let length be the length of string.
+ let length = string.length_in_utf16_code_units();
+
+ // 3. If index >= length,
+ if index as usize >= length {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The index is out of the string's bounds"));
+ }
+
+ // 4. Return CharCodeAt(string, index).
+ Ok(WasmValue::I32(super::char_code_at(string, index)))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-codepointat
+ pub(super) fn code_point_at(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let index = unsigned_i32(arguments[1]) as usize;
+
+ // 1. Let string be ? UnwrapString(string).
+ let string = unwrap_string(vm, arguments[0])?;
+
+ // 2. Let length be the length of string.
+ let length = string.length_in_utf16_code_units();
+
+ // 3. If index >= length,
+ if index >= length {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("The index is out of the string's bounds"));
+ }
+
+ // 4. Return ! Call(String.prototype.codePointAt, string, « ToJSValue(index) »).
+ // NB: A leading surrogate that a trailing one follows is the code point of the pair, and any other code unit
+ // is the code point of its value.
+ let first = string.code_unit_at(index);
+ if (0xd800..=0xdbff).contains(&first) && index + 1 < length {
+ let second = string.code_unit_at(index + 1);
+ if (0xdc00..=0xdfff).contains(&second) {
+ let code_point = 0x10000 + ((u32::from(first) - 0xd800) << 10) + (u32::from(second) - 0xdc00);
+ return Ok(WasmValue::I32(code_point as i32));
+ }
+ }
+ Ok(WasmValue::I32(i32::from(first)))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-length
+ pub(super) fn length(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. Let string be ? UnwrapString(v).
+ let string = unwrap_string(vm, arguments[0])?;
+
+ // 2. Return the length of string.
+ Ok(WasmValue::I32(string.length_in_utf16_code_units() as i32))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-concat
+ pub(super) fn concat(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. Let first be ? UnwrapString(first).
+ let first = unwrap_string(vm, arguments[0])?;
+
+ // 2. Let second be ? UnwrapString(second).
+ let second = unwrap_string(vm, arguments[1])?;
+
+ // 3. Return ! Call(String.prototype.concat, first, « second »).
+ let mut result = code_units_of(first);
+ result.extend(code_units_of(second));
+ Ok(string_reference_of_code_units(vm, &result))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-substring
+ pub(super) fn substring(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // NB: The indices are unsigned, as everywhere else in WebAssembly.
+ let start = unsigned_i32(arguments[1]) as usize;
+ let end = unsigned_i32(arguments[2]) as usize;
+
+ // 1. Let string be ? UnwrapString(string).
+ let string = unwrap_string(vm, arguments[0])?;
+
+ // 2. Let length be the length of string.
+ let length = string.length_in_utf16_code_units();
+
+ // 3. If start > end or start > length,
+ if start > end || start > length {
+ // 1. Return the empty string.
+ return Ok(string_reference(vm, vm.empty_string()));
+ }
+
+ // 4. Return ! Call(String.prototype.substring, string, « ToJSValue(start), ToJSValue(end) »).
+ // NB: start <= end here, and String.prototype.substring clamps end to the length.
+ let clamped_end = end.min(length);
+ Ok(string_reference(
+ vm,
+ PrimitiveString::create_from_substring(vm, string, start, clamped_end - start),
+ ))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-equals
+ pub(super) fn equals(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ let first = js_value_of(vm, arguments[0]);
+ let second = js_value_of(vm, arguments[1]);
+
+ // 1. If first is not null and first is not a String,
+ if !first.is_null() && !first.is_string() {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("Expected a string or null"));
+ }
+
+ // 2. If second is not null and second is not a String,
+ if !second.is_null() && !second.is_string() {
+ // 1. Throw a RuntimeError exception as if a trap was executed.
+ return Err(trap("Expected a string or null"));
+ }
+
+ // 3. If IsStrictlyEqual(first, second) is true,
+ let strictly_equal = if first.is_null() || second.is_null() {
+ first.is_null() && second.is_null()
+ } else {
+ first.as_string().utf16_string() == second.as_string().utf16_string()
+ };
+ if strictly_equal {
+ // 1. Return 1.
+ return Ok(WasmValue::I32(1));
+ }
+
+ // 4. Return 0.
+ Ok(WasmValue::I32(0))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#js-string-compare
+ pub(super) fn compare(vm: &Vm, arguments: &[WasmValue]) -> Result<WasmValue, Trap> {
+ // 1. Let first be ? UnwrapString(first).
+ let first = code_units_of(unwrap_string(vm, arguments[0])?);
+
+ // 2. Let second be ? UnwrapString(second).
+ let second = code_units_of(unwrap_string(vm, arguments[1])?);
+
+ // 3. If IsStrictlyEqual(first, second) is true,
+ if first == second {
+ // 1. Return 0.
+ return Ok(WasmValue::I32(0));
+ }
+
+ // 4. If ! IsLessThan(first, second, true) is true,
+ // NB: IsLessThan() compares two strings by their code units.
+ if first < second {
+ // 1. Return -1.
+ return Ok(WasmValue::I32(-1));
+ }
+
+ // 5. Return 1.
+ Ok(WasmValue::I32(1))
+ }
+}
+
+// https://webassembly.github.io/spec/js-api/#string-builtins
+const JS_STRING_BUILTINS: [Builtin; 13] = [
+ Builtin {
+ name: "cast",
+ function_type: BuiltinTypeIndex::ExternrefToRefExtern,
+ steps: js_string_builtins::cast,
+ },
+ Builtin {
+ name: "test",
+ function_type: BuiltinTypeIndex::ExternrefToI32,
+ steps: js_string_builtins::test,
+ },
+ Builtin {
+ name: "fromCharCodeArray",
+ function_type: BuiltinTypeIndex::ArrayI32I32ToRefExtern,
+ steps: js_string_builtins::from_char_code_array,
+ },
+ Builtin {
+ name: "intoCharCodeArray",
+ function_type: BuiltinTypeIndex::ExternrefArrayI32ToI32,
+ steps: js_string_builtins::into_char_code_array,
+ },
+ Builtin {
+ name: "fromCharCode",
+ function_type: BuiltinTypeIndex::I32ToRefExtern,
+ steps: js_string_builtins::from_char_code,
+ },
+ // INTEROP: The funcType of fromCodePoint has a (ref extern) result in other implementations, where the spec has an
+ // externref result.
+ Builtin {
+ name: "fromCodePoint",
+ function_type: BuiltinTypeIndex::I32ToRefExtern,
+ steps: js_string_builtins::from_code_point,
+ },
+ Builtin {
+ name: "charCodeAt",
+ function_type: BuiltinTypeIndex::ExternrefI32ToI32,
+ steps: js_string_builtins::char_code_at,
+ },
+ Builtin {
+ name: "codePointAt",
+ function_type: BuiltinTypeIndex::ExternrefI32ToI32,
+ steps: js_string_builtins::code_point_at,
+ },
+ Builtin {
+ name: "length",
+ function_type: BuiltinTypeIndex::ExternrefToI32,
+ steps: js_string_builtins::length,
+ },
+ Builtin {
+ name: "concat",
+ function_type: BuiltinTypeIndex::ExternrefExternrefToRefExtern,
+ steps: js_string_builtins::concat,
+ },
+ Builtin {
+ name: "substring",
+ function_type: BuiltinTypeIndex::ExternrefI32I32ToRefExtern,
+ steps: js_string_builtins::substring,
+ },
+ Builtin {
+ name: "equals",
+ function_type: BuiltinTypeIndex::ExternrefExternrefToI32,
+ steps: js_string_builtins::equals,
+ },
+ Builtin {
+ name: "compare",
+ function_type: BuiltinTypeIndex::ExternrefExternrefToI32,
+ steps: js_string_builtins::compare,
+ },
+];
+
+pub(crate) fn refers_to_a_builtin_set(builtin_set_name: &UsvString) -> bool {
+ builtin_set_name.to_utf8() == JS_STRING_BUILTIN_SET_NAME
+}
+
+// https://webassembly.github.io/spec/js-api/#get-the-builtins-for-a-builtin-set
+fn get_the_builtins_for_a_builtin_set(builtin_set_name: &UsvString) -> &'static [Builtin] {
+ // 1. Return a list of (name, funcType, steps) for the set with name builtinSetName defined within this section.
+ assert!(refers_to_a_builtin_set(builtin_set_name));
+ &JS_STRING_BUILTINS
+}
+
+// https://webassembly.github.io/spec/js-api/#validate-builtin-set-names
+fn validate_builtin_set_names(builtin_set_names: &[UsvString]) -> bool {
+ // 1. If builtinSetNames contains any duplicates, return false.
+ let mut seen_names = HashSet::new();
+ if !builtin_set_names
+ .iter()
+ .all(|builtin_set_name| seen_names.insert(builtin_set_name.to_utf8()))
+ {
+ return false;
+ }
+
+ // 2. Return true.
+ true
+}
+
+// https://webassembly.github.io/spec/js-api/#find-a-builtin
+fn find_a_builtin(import: &Import, builtin_set_names: &[UsvString]) -> Option<&'static Builtin> {
+ // 1. Assert: validate builtin set names builtinSetNames is true.
+ assert!(validate_builtin_set_names(builtin_set_names));
+
+ // 2. Let importModuleName be import[0].
+ let import_module_name = &import.module;
+
+ // 3. Let importName be import[1].
+ let import_name = &import.name;
+
+ // 4. For each builtinSetName of builtinSetNames,
+ for builtin_set_name in builtin_set_names {
+ // 1. If builtinSetName does not refer to a builtin set, then continue.
+ if !refers_to_a_builtin_set(builtin_set_name) {
+ continue;
+ }
+
+ // 2. Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:".
+ let builtin_set_qualified_name = JS_STRING_BUILTIN_SET_QUALIFIED_NAME;
+
+ // 3. If importModuleName equals builtinSetQualifiedName,
+ if import_module_name == builtin_set_qualified_name {
+ // 1. Let builtins be the result of get the builtins for a builtin set builtinSetName.
+ let builtins = get_the_builtins_for_a_builtin_set(builtin_set_name);
+
+ // 2. For each builtin of builtins,
+ for builtin in builtins {
+ // 1. Let builtinName be builtin[0].
+ // 2. If importName equals builtinName, return (builtinSetName, builtin).
+ if import_name == builtin.name {
+ return Some(builtin);
+ }
+ }
+ }
+ }
+
+ // 5. Return null.
+ None
+}
+
+/// Whether finding a builtin for the import and builtinSetNames does not return null.
+pub(crate) fn import_refers_to_a_builtin(import: &Import, builtin_set_names: &[UsvString]) -> bool {
+ find_a_builtin(import, builtin_set_names).is_some()
+}
+
+// https://webassembly.github.io/spec/js-api/#validate-an-import-for-builtins
+fn validate_an_import_for_builtins(
+ vm: &Vm,
+ module: &CompiledModule,
+ import: &Import,
+ builtin_set_names: &[UsvString],
+) -> bool {
+ // 1. Assert: validate builtin set names builtinSetNames is true.
+ assert!(validate_builtin_set_names(builtin_set_names));
+
+ // 2. Let maybeBuiltin be the result of finding a builtin for import and builtinSetNames.
+ let maybe_builtin = find_a_builtin(import, builtin_set_names);
+
+ // 3. If maybeBuiltin is null, return true.
+ let Some(maybe_builtin) = maybe_builtin else {
+ return true;
+ };
+
+ // 4. Let importExternType be import[2].
+ let import_extern_type = &import.description;
+
+ // 5. Let builtinFuncType be maybeBuiltin[1][1].
+ let builtin_func_type = maybe_builtin.function_type;
+
+ // 6. Let builtinExternType be func |builtinFuncType|.
+ // 7. Return match_externtype(builtinExternType, importExternType).
+ // NB: The funcType of a builtin is final and has no supertypes, so it only matches the import's type if both are
+ // the same type.
+ let ImportDescription::Function(type_index) = *import_extern_type else {
+ return false;
+ };
+ let builtin_types_module = Agent::the(vm).builtin_types_module();
+ type_identity(vm, module, type_index) == type_identity(vm, builtin_types_module, builtin_func_type as u32)
+}
+
+// https://webassembly.github.io/spec/js-api/#validate-builtins-and-imported-string-for-a-webassembly-module
+pub(crate) fn validate_builtins_and_imported_strings(
+ vm: &Vm,
+ module: &CompiledModule,
+ builtin_set_names: &[UsvString],
+ imported_string_module: Option<&UsvString>,
+) -> bool {
+ // 1. If validating builtin set names for builtinSetNames is false, return false.
+ if !validate_builtin_set_names(builtin_set_names) {
+ return false;
+ }
+
+ let imported_string_module = imported_string_module.map(UsvString::to_utf8);
+
+ // 2. For each import of module_imports(module),
+ for import in &module.imports {
+ // 1. If importedStringModule is not null and import[0] equals importedStringModule,
+ if imported_string_module.as_ref() == Some(&import.module) {
+ // 1. Let importExternType be import[2].
+ let import_extern_type = &import.description;
+
+ // 2. Let stringExternType be global ref extern.
+ // 3. If match_externtype(stringExternType, importExternType) is false, return false
+ // NB: An immutable global matches if (ref extern) is a subtype of the import's value type, which then is
+ // (ref extern) or externref.
+ if !matches!(
+ import_extern_type,
+ ImportDescription::Global(GlobalType {
+ value: ValType::Ref(RefType {
+ heap: HeapType::Extern,
+ ..
+ }),
+ mutable: false,
+ })
+ ) {
+ return false;
+ }
+ }
+ // 2. Else,
+ else {
+ // 1. If validating an import for builtins with import and builtinSetNames is false, return false.
+ if !validate_an_import_for_builtins(vm, module, import, builtin_set_names) {
+ return false;
+ }
+ }
+ }
+
+ // 3. Return true.
+ true
+}
+
+/// The steps of a builtin's host function, and the index of the builtin in its set.
+struct BuiltinFunction {
+ steps: BuiltinSteps,
+ index: u32,
+}
+
+impl HostFunction for BuiltinFunction {
+ fn call(&self, _: &mut Store, arguments: &[WasmValue]) -> Result<Vec<WasmValue>, Trap> {
+ let vm = Agent::current().vm();
+ (self.steps)(vm, arguments).map(|result| vec![result])
+ }
+
+ fn user_data(&self) -> *mut c_void {
+ core::ptr::from_ref(&self.index).cast_mut().cast()
+ }
+}
+
+// https://webassembly.github.io/spec/js-api/#create-a-builtin-function
+fn create_a_builtin_function(
+ vm: &Vm,
+ function_type: BuiltinTypeIndex,
+ steps: BuiltinSteps,
+ index: u32,
+) -> FunctionAddress {
+ // 1. Let hostfunc be a host function which executes steps when called.
+ let host_function = Rc::new(BuiltinFunction { steps, index });
+
+ // 2. Let store be the surrounding agent's associated store.
+ // 3. Let (store, funcaddr) be func_alloc(store, funcType, hostfunc).
+ // 4. Set the surrounding agent's associated store to store.
+ // 5. Return funcaddr.
+ // NB: The index is the builtin's position in its set, which names the Exported Function made for it.
+ let agent = Agent::the(vm);
+ let ty = function_type_in_store(vm, agent.builtin_types_module(), function_type as u32);
+ agent.store().allocate_host_function(ty, host_function)
+}
+
+// https://webassembly.github.io/spec/js-api/#instantiate-a-builtin-set
+pub(crate) fn instantiate_a_builtin_set(vm: &Vm, builtin_set_name: &UsvString) -> Gc<Object> {
+ let realm = vm.current_realm().expect("instantiating a builtin set runs in a realm");
+
+ // 1. Let builtins be the result of get the builtins for a builtin set builtinSetName.
+ let builtins = get_the_builtins_for_a_builtin_set(builtin_set_name);
+
+ // 2. Let exportsObject be OrdinaryObjectCreate(null).
+ let exports_object = Object::create(vm, realm, None);
+
+ // 3. For each (name, funcType, steps) of builtins,
+ for (index, builtin) in builtins.iter().enumerate() {
+ // 1. Let funcaddr be the result of create a builtin function with funcType and steps.
+ let funcaddr = create_a_builtin_function(vm, builtin.function_type, builtin.steps, index as u32);
+
+ // 2. Let func be the result of creating a new Exported Function from funcaddr.
+ let func = create_exported_function(vm, realm, funcaddr);
+
+ // 3. Let value be func.
+ let value = Value::from_object(func.upcast::<Object>());
+
+ // 4. Let status be ! CreateDataProperty(exportsObject, name, value).
+ let status = exports_object
+ .create_data_property(vm, &PropertyKey::from_utf8(builtin.name), value, None, None)
+ .must();
+
+ // 5. Assert: status is true.
+ assert!(status);
+ }
+
+ // 4. Return exportsObject.
+ exports_object
+}
+
+// https://webassembly.github.io/spec/js-api/#instantiate-imported-strings
+pub(crate) fn instantiate_imported_strings(
+ vm: &Vm,
+ module: &CompiledModule,
+ imported_string_module: &UsvString,
+) -> Gc<Object> {
+ let realm = vm
+ .current_realm()
+ .expect("instantiating imported strings runs in a realm");
+
+ // 1. Assert: importedStringModule is not null.
+ let imported_string_module = imported_string_module.to_utf8();
+
+ // 2. Let exportsObject be OrdinaryObjectCreate(null).
+ let exports_object = Object::create(vm, realm, None);
+
+ // 3. For each (moduleName, componentName, externtype) of module_imports(module),
+ for import in &module.imports {
+ // 1. If moduleName does not equal importedStringModule, then continue.
+ if import.module != imported_string_module {
+ continue;
+ }
+
+ // 2. Let stringConstant be componentName.
+ let string_constant = Utf16String::from_utf8(&import.name);
+
+ // 3. Let status be ! CreateDataProperty(exportsObject, stringConstant, stringConstant).
+ let value = Value::from_string(PrimitiveString::create(vm, string_constant.clone()));
+ let status = exports_object
+ .create_data_property(vm, &PropertyKey::from(&string_constant), value, None, None)
+ .must();
+
+ // 4. Assert: status is true.
+ assert!(status);
+ }
+
+ // 4. Return exportsObject.
+ exports_object
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/errors.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/errors.rs
new file mode 100644
index 00000000000..d645017b42b
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/errors.rs
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The error types of the namespace, https://webassembly.github.io/spec/js-api/#error-objects: objects implementing
+//! the NativeError Object Structure, https://tc39.es/ecma262/#sec-nativeerror-object-structure, whose prototypes and
+//! constructors every realm has its own of.
+
+use core::ffi::c_void;
+
+use ak::{Utf16FlyString, Utf16String};
+use libjs_rust::api::{
+ Attribute, Error, Gc, HostFunction, JS_HOST_CLASS_FUNCTION, JS_HOST_CLASS_HAS_CONSTRUCTOR, JSCompletion,
+ JSHostClass, JSHostFunctionHooks, JSObject, JSVM, Object, PrimitiveString, PropertyAttributes, Realm, Throw,
+ ThrowCompletionOr, Value, Vm, completion_into_abi, get_function_realm, object_from_abi, vm_from_abi,
+};
+
+use crate::bindings::realm_data::realm_data;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum WebAssemblyError {
+ Compile,
+ Link,
+ Runtime,
+}
+
+impl WebAssemblyError {
+ pub(crate) const ALL: [Self; 3] = [Self::Compile, Self::Link, Self::Runtime];
+
+ pub(crate) fn name(self) -> &'static str {
+ match self {
+ Self::Compile => "CompileError",
+ Self::Link => "LinkError",
+ Self::Runtime => "RuntimeError",
+ }
+ }
+
+ fn index(self) -> usize {
+ self as usize
+ }
+
+ const fn of_index(index: usize) -> Self {
+ match index {
+ 0 => Self::Compile,
+ 1 => Self::Link,
+ _ => Self::Runtime,
+ }
+ }
+}
+
+const fn constructor_hooks<const ERROR: usize>() -> JSHostFunctionHooks {
+ JSHostFunctionHooks {
+ call: Some(call_native_error_constructor::<ERROR>),
+ construct: Some(construct_native_error::<ERROR>),
+ finalize: None,
+ }
+}
+
+static CONSTRUCTOR_HOOKS: [JSHostFunctionHooks; 3] = [
+ constructor_hooks::<{ WebAssemblyError::Compile as usize }>(),
+ constructor_hooks::<{ WebAssemblyError::Link as usize }>(),
+ constructor_hooks::<{ WebAssemblyError::Runtime as usize }>(),
+];
+
+static CONSTRUCTOR_CLASSES: [JSHostClass; 3] = [
+ JSHostClass::new(
+ JS_HOST_CLASS_FUNCTION,
+ "CompileErrorConstructor",
+ None,
+ (&raw const CONSTRUCTOR_HOOKS[0]).cast(),
+ JS_HOST_CLASS_HAS_CONSTRUCTOR,
+ ),
+ JSHostClass::new(
+ JS_HOST_CLASS_FUNCTION,
+ "LinkErrorConstructor",
+ None,
+ (&raw const CONSTRUCTOR_HOOKS[1]).cast(),
+ JS_HOST_CLASS_HAS_CONSTRUCTOR,
+ ),
+ JSHostClass::new(
+ JS_HOST_CLASS_FUNCTION,
+ "RuntimeErrorConstructor",
+ None,
+ (&raw const CONSTRUCTOR_HOOKS[2]).cast(),
+ JS_HOST_CLASS_HAS_CONSTRUCTOR,
+ ),
+];
+
+/// The NativeError prototype and constructor of the error type in the realm, which the first use in the realm
+/// creates.
+fn prototype_and_constructor(vm: &Vm, realm: Gc<Realm>, error: WebAssemblyError) -> (Gc<Object>, Gc<Object>) {
+ let data = realm_data(vm, realm);
+ let index = error.index();
+ if let (Some(prototype), Some(constructor)) = (
+ data.webassembly_error_prototypes[index].get(),
+ data.webassembly_error_constructors[index].get(),
+ ) {
+ return (prototype, constructor);
+ }
+
+ let name = Value::from_string(PrimitiveString::create_from_utf8(vm, error.name()));
+ let attributes = PropertyAttributes::new(Attribute::WRITABLE | Attribute::CONFIGURABLE);
+
+ // 20.5.6.3 Properties of the NativeError Prototype Objects, https://tc39.es/ecma262/#sec-properties-of-the-nativeerror-prototype-objects
+ let prototype = Object::create(vm, realm, Some(realm.intrinsics().error_prototype(vm)));
+ prototype.define_direct_property(vm, &vm.names.name, name, attributes);
+ let empty = Value::from_string(PrimitiveString::create(vm, Utf16String::default()));
+ prototype.define_direct_property(vm, &vm.names.message, empty, attributes);
+
+ // 20.5.6.2 Properties of the NativeError Constructors, https://tc39.es/ecma262/#sec-properties-of-the-nativeerror-constructors
+ // SAFETY: The class is of kind JS_HOST_CLASS_FUNCTION, and the constructor has no host data.
+ let constructor = unsafe {
+ HostFunction::create_without_own_properties(
+ vm,
+ realm,
+ &CONSTRUCTOR_CLASSES[index],
+ Utf16FlyString::from_utf8(error.name()),
+ Some(realm.intrinsics().error_constructor(vm).upcast()),
+ None,
+ )
+ }
+ .upcast::<Object>();
+ constructor.define_direct_property(
+ vm,
+ &vm.names.prototype,
+ Value::from_object(prototype),
+ PropertyAttributes::new(0),
+ );
+ let configurable = PropertyAttributes::new(Attribute::CONFIGURABLE);
+ constructor.define_direct_property(vm, &vm.names.name, name, configurable);
+ constructor.define_direct_property(vm, &vm.names.length, Value::from_i32(1), configurable);
+
+ prototype.define_direct_property(vm, &vm.names.constructor, Value::from_object(constructor), attributes);
+
+ data.webassembly_error_prototypes[index].set(Some(prototype));
+ data.webassembly_error_constructors[index].set(Some(constructor));
+ (prototype, constructor)
+}
+
+/// The constructor of the error type in the realm.
+pub(crate) fn error_constructor(vm: &Vm, realm: Gc<Realm>, error: WebAssemblyError) -> Gc<Object> {
+ prototype_and_constructor(vm, realm, error).1
+}
+
+/// A new error of the type in the realm, with the message.
+pub(crate) fn create_webassembly_error(vm: &Vm, realm: Gc<Realm>, error: WebAssemblyError, message: &str) -> Gc<Error> {
+ let (prototype, _) = prototype_and_constructor(vm, realm, error);
+ let object = Error::create_with_prototype(vm, realm, prototype);
+ object.set_message(vm, Utf16String::from_utf8(message));
+ object
+}
+
+/// What throwing a new error of the type in the realm, with the message, throws.
+pub(crate) fn throw_webassembly_error(vm: &Vm, realm: Gc<Realm>, error: WebAssemblyError, message: &str) -> Throw {
+ Throw::new(Value::from_object(
+ create_webassembly_error(vm, realm, error, message).upcast::<Object>(),
+ ))
+}
+
+// 20.5.6.1.1 NativeError ( message [ , options ] ), https://tc39.es/ecma262/#sec-nativeerror
+unsafe extern "C" fn call_native_error_constructor<const ERROR: usize>(
+ function: *mut JSObject,
+ vm: *mut JSVM,
+) -> JSCompletion {
+ // 1. If NewTarget is undefined, let newTarget be the active function object; else let newTarget be NewTarget.
+ // SAFETY: The runtime passes the live function and the VM.
+ unsafe { construct_native_error::<ERROR>(function, vm, function) }
+}
+
+// 20.5.6.1.1 NativeError ( message [ , options ] ), https://tc39.es/ecma262/#sec-nativeerror
+unsafe extern "C" fn construct_native_error<const ERROR: usize>(
+ _function: *mut JSObject,
+ vm: *mut JSVM,
+ new_target: *mut JSObject,
+) -> JSCompletion {
+ // SAFETY: The runtime passes the VM and the live new target.
+ let (vm, new_target) = unsafe { (vm_from_abi(vm), object_from_abi(new_target)) };
+ completion_into_abi(native_error(vm, new_target, WebAssemblyError::of_index(ERROR)).map(Value::from_object))
+}
+
+fn native_error(vm: &Vm, new_target: Gc<Object>, error: WebAssemblyError) -> ThrowCompletionOr<Gc<Object>> {
+ let message = vm.argument(0);
+ let options = vm.argument(1);
+
+ // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] »).
+ // NB: The intrinsic default prototype is that of the error type in the realm of newTarget, which the realm's data
+ // keeps, not its intrinsics.
+ // https://tc39.es/ecma262/#sec-getprototypefromconstructor
+ // 2. Let proto be ? Get(constructor, "prototype").
+ let mut prototype = new_target.get(vm, &vm.names.prototype)?;
+
+ // 3. If Type(proto) is not Object, then
+ if !prototype.is_object() {
+ // a. Let realm be ? GetFunctionRealm(constructor).
+ let realm = get_function_realm(
+ vm,
+ new_target
+ .downcast::<libjs_rust::api::FunctionObject>()
+ .expect("the new target of a construction is a function"),
+ )?;
+
+ // b. Set proto to realm's intrinsic object named intrinsicDefaultProto.
+ prototype = Value::from_object(prototype_and_constructor(vm, realm, error).0);
+ }
+ let realm = vm.current_realm().expect("a constructor runs in a realm");
+ let object = Error::create_with_prototype(vm, realm, prototype.as_object());
+
+ // 3. If message is not undefined, then
+ if !message.is_undefined() {
+ // a. Let msg be ? ToString(message).
+ let message = message.to_utf16_string(vm)?;
+
+ // b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg).
+ object.create_non_enumerable_data_property_or_throw(
+ vm,
+ &vm.names.message,
+ Value::from_string(PrimitiveString::create(vm, message)),
+ );
+ }
+
+ // 4. Perform ? InstallErrorCause(O, options).
+ object.install_error_cause(vm, options)?;
+
+ // 5. Return O.
+ Ok(object.upcast())
+}
+
+/// A CompileError with the message in the realm, for C++ code that throws one: the CSP check of
+/// HostEnsureCanCompileWasmBytes.
+///
+/// # Safety
+///
+/// The pointers must be the VM, a live realm, and the message, a borrowed AK::Utf16String.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_web_assembly_create_compile_error(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ message: usize,
+) -> *mut c_void {
+ // SAFETY: The caller passes the VM and a live realm.
+ let (vm, realm) = unsafe { crate::bindings::interface::realm_arguments(vm, realm) };
+ // SAFETY: The caller lends the message for the call, which this takes a reference of its own to.
+ let message = unsafe {
+ ak::reference_utf16_string(message);
+ Utf16String::from_raw_owned(message)
+ };
+ let (prototype, _) = prototype_and_constructor(vm, realm, WebAssemblyError::Compile);
+ let error = Error::create_with_prototype(vm, realm, prototype);
+ error.set_message(vm, message);
+ error.as_ptr().cast()
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs
new file mode 100644
index 00000000000..1900c981c54
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Exception, https://webassembly.github.io/spec/js-api/#exceptions
+
+use ak::Utf16String;
+use libjs_rust::api::{CompactTraceback, Error, Gc, MarkedVec, Realm, Trace, Value, Vm};
+use libwasm_engine::runtime::TagInstance;
+
+use crate::bindings::interface::{Ref, Wrappable, allocate, wrap};
+use crate::bindings::{CallContext, Exception as WebIdlException, WebIdlResult};
+use crate::web_assembly::tag::Tag;
+use crate::web_assembly::values::{to_js_value, to_webassembly_value};
+use crate::web_assembly::{
+ Agent, CellReference, EntityRef, WasmValues, host_object, implementation_of_value, set_host_object,
+};
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-exceptionoptions
+pub(crate) struct ExceptionOptions {
+ pub(crate) trace_stack: bool,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Exception {
+ // [[Address]]
+ address: CellReference,
+ // [[Type]]
+ // NB: The payload of an exception never changes, so getArg() reads [[Payload]] from the store.
+ tag: EntityRef<TagInstance>,
+ // [[Stack]]
+ #[gc(untraced)]
+ stack: Option<Utf16String>,
+}
+
+impl Wrappable for Exception {}
+
+impl Exception {
+ // https://webassembly.github.io/spec/js-api/#dom-exception-exception
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ exception_tag: Ref<Tag>,
+ payload: MarkedVec<'_, Value>,
+ options: ExceptionOptions,
+ ) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+ let agent = Agent::the(vm);
+
+ // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.
+ // 2. If exceptionTag.[[Address]] is equal to JSTagAddr,
+ // 1. Throw a TypeError.
+ if exception_tag.address() == agent.js_tag() {
+ return Err(WebIdlException::type_error(
+ "Cannot construct an exception with the JavaScript tag",
+ ));
+ }
+
+ // 3. Let store be the surrounding agent's associated store.
+ // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).
+ let types = agent.store().tag(exception_tag.address()).ty.params.clone();
+
+ // 5. If types's size is not payload's size,
+ // 1. Throw a TypeError.
+ if types.len() != payload.len() {
+ return Err(WebIdlException::TypeError(Utf16String::from_utf8(&format!(
+ "The tag takes {} values, not {}",
+ types.len(),
+ payload.len()
+ ))));
+ }
+
+ // 6. Let wasmPayload be « ».
+ // NB: The converted values may refer to new cells, which the cell of the values keeps alive until they are in
+ // the exception.
+ let wasm_payload = WasmValues::allocate(vm);
+
+ // 7. For each value and resultType of payload and types, paired linearly,
+ for (index, &result_type) in types.iter().enumerate() {
+ // 1. If resultType is v128 or exnref,
+ // 1. Throw a TypeError.
+ // 2. Append ? ToWebAssemblyValue(value, resultType) to wasmPayload.
+ // NB: ToWebAssemblyValue throws the TypeError for v128 and exnref.
+ let value = to_webassembly_value(
+ vm,
+ payload.get(index).expect("the payload has a value per type"),
+ result_type,
+ )?;
+ wasm_payload.0.borrow_mut().push(value);
+ }
+
+ // 8. Let (store, exceptionAddr) be exn_alloc(store, exceptionTag.[[Address]], wasmPayload).
+ // 9. Set the surrounding agent's associated store to store.
+ let exception = agent
+ .store()
+ .allocate_exception_with_values(exception_tag.address(), &wasm_payload.0.borrow());
+ // NB: Using the Gc after the allocation keeps the payload where the conservative scan finds it until it is in
+ // the exception.
+ core::hint::black_box(wasm_payload);
+
+ // 10. Initialize this from exceptionAddr.
+ // 11. If options["traceStack"] is true,
+ // 1. Set this.[[Stack]] to either a DOMString representation of the current call stack or undefined.
+ // 12. Otherwise,
+ // 1. Set this.[[Stack]] to undefined.
+ let stack = options.trace_stack.then(|| {
+ let realm = vm.current_realm().expect("a constructor runs in a realm");
+ Error::create(vm, realm).stack_string(CompactTraceback::No)
+ });
+ Ok(Self::initialize(vm, exception, stack))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-an-exception-object
+ fn initialize(vm: &Vm, exception: u64, stack: Option<Utf16String>) -> Ref<Self> {
+ // 1. Let map be the surrounding agent's associated exception object cache.
+ // 2. Assert: map[exnAddr] doesn't exist.
+ let cell = exception as *mut u8;
+ assert!(host_object::<()>(cell).is_none());
+
+ // 3. Set exn.[[Address]] to exnAddr.
+ // 4. Set map[exnAddr] to exn.
+ // 5. Let store be the surrounding agent's associated store.
+ // 6. Let tagaddr be exn_tag(store, exnAddr).
+ // 7. Let payload be exn_read(store, exnAddr).
+ // 8. Set exn.[[Type]] to tagaddr.
+ // 9. Set exn.[[Payload]] to payload.
+ let tag = Agent::the(vm).store().exception(exception).tag;
+ let object = allocate(vm, |_| Self {
+ address: CellReference(exception),
+ tag: EntityRef(tag),
+ stack,
+ });
+ set_host_object(cell, object);
+ object
+ }
+
+ /// The wrapper of the Exception object of the exception in the realm,
+ /// https://webassembly.github.io/spec/js-api/#create-an-exception-object
+ pub(crate) fn wrapper_of_address(vm: &Vm, realm: Gc<Realm>, exception: u64) -> Value {
+ // 1. Let map be the surrounding agent's associated exception object cache.
+ // 2. If map[exnAddr] exists,
+ // 1. Return map[exnAddr].
+ // 3. Let exn be a new Exception.
+ // 4. Initialize exn from exnAddr.
+ let object = host_object(exception as *mut u8).unwrap_or_else(|| Self::initialize(vm, exception, None));
+ Value::from_object(wrap(&CallContext::new(vm, realm), object))
+ }
+
+ /// The [[Address]] of the Exception object that the value is, if it is the wrapper of one.
+ pub(crate) fn address_of_value(value: Value) -> Option<u64> {
+ implementation_of_value::<Self>(value).map(|exception| exception.address.0)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-exception-getarg
+ pub(crate) fn get_arg(&self, cx: &mut CallContext, exception_tag: Ref<Tag>, index: u32) -> WebIdlResult<Value> {
+ let vm = cx.vm();
+ let store = Agent::the(vm).store();
+
+ // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]],
+ // 1. Throw a TypeError.
+ if self.tag.0 != exception_tag.address() {
+ return Err(WebIdlException::type_error("The exception does not have this tag"));
+ }
+
+ // 2. Let payload be this.[[Payload]].
+ let payload = store.exception_values(self.address.0);
+
+ // 3. If index ≥ payload's size,
+ // 1. Throw a RangeError.
+ let Some(&value) = payload.get(index as usize) else {
+ return Err(WebIdlException::RangeError(Utf16String::from_utf8(&format!(
+ "The exception has {} values",
+ payload.len()
+ ))));
+ };
+
+ // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).
+ // 5. If types[index] matches v128 or exnref,
+ // 1. Throw a TypeError.
+ // 6. Return ToJSValue(payload[index]).
+ // NB: ToJSValue throws the TypeError for v128 and exnref.
+ let ty = store.tag(exception_tag.address()).ty.params[index as usize];
+ Ok(to_js_value(vm, value, ty)?)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-exception-is
+ pub(crate) fn is(&self, _: &mut CallContext, exception_tag: Ref<Tag>) -> WebIdlResult<bool> {
+ // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]],
+ // 1. Return false.
+ // 2. Return true.
+ Ok(self.tag.0 == exception_tag.address())
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-exception-stack
+ pub(crate) fn stack(&self, _: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {
+ // 1. Return this.[[Stack]].
+ Ok(self.stack.clone())
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
new file mode 100644
index 00000000000..957c5143cc4
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
@@ -0,0 +1,289 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Exported Functions, https://webassembly.github.io/spec/js-api/#exported-function, and the host functions that
+//! JavaScript functions become when a module imports them, https://webassembly.github.io/spec/js-api/#create-a-host-function
+
+use core::ffi::c_void;
+use std::rc::Rc;
+
+use ak::{Utf16FlyString, Utf16String};
+use libjs_rust::api::{
+ Attribute, DeferGc, ErrorKind, ErrorType, FunctionObject, Gc, MarkedVec, Must, NativeFunction, Object,
+ PrimitiveString, PropertyAttributes, PropertyKey, Realm, ThrowCompletionOr, Trace, Value, Visitor, Vm, call,
+ get_iterator_from_method_impl, iterator_to_list,
+};
+use libwasm_engine::runtime::heap::Visitor as StoreVisitor;
+use libwasm_engine::runtime::{
+ FunctionAddress, FunctionInstance, FunctionKind, HostCallback, HostFunction, Store, Trap, Value as WasmValue,
+};
+use libwasm_engine::types::FuncType;
+
+use crate::web_assembly::exception::Exception;
+use crate::web_assembly::values::{EXTERNREF, results_to_js_value, to_js_value, to_webassembly_value};
+use crate::web_assembly::{
+ Agent, EntityRef, WasmValues, gc_visitor_visit_cell, host_object, set_host_object, throw_of_trap,
+};
+
+/// The internal slots of an Exported Function: its [[FunctionAddress]], and the type of its function.
+struct ExportedFunction {
+ function: EntityRef<FunctionInstance>,
+ ty: FuncType,
+}
+
+// SAFETY: The type holds no cells, so the function is the one cell the slots reach.
+unsafe impl Trace for ExportedFunction {
+ fn trace(&self, visitor: &mut Visitor) {
+ self.function.trace(visitor);
+ }
+}
+
+/// The value of the function's [[FunctionAddress]] internal slot, if it has one and is therefore an Exported Function.
+pub(crate) fn exported_function_address(function: Gc<Object>) -> Option<FunctionAddress> {
+ NativeFunction::captures_if::<ExportedFunction>(&function).map(|function| function.function.0)
+}
+
+/// The name of the WebAssembly function, https://webassembly.github.io/spec/js-api/#name-of-the-webassembly-function
+fn name_of_webassembly_function(store: &Store, function: FunctionAddress) -> Utf16FlyString {
+ // 1. Let store be the surrounding agent's associated store.
+ // 2. Let funcinst be store.funcs[funcaddr].
+ let index = match &store.function(function).kind {
+ // 3. If funcinst is of the form {type functype, hostcode hostfunc},
+ // 1. Assert: hostfunc is a JavaScript object and IsCallable(hostfunc) is true.
+ // 2. Let index be the index of the host function funcaddr.
+ // SAFETY: The data of the browser's host functions, the steps of a JavaScript function or of a builtin, is the
+ // index of the host function.
+ FunctionKind::Host(steps) => unsafe { *steps.user_data().cast::<u32>() },
+ // 4. Otherwise,
+ // 1. Let moduleinst be funcinst.module.
+ // 2. Assert: funcaddr is contained in moduleinst.funcaddrs.
+ // 3. Let index be the index of moduleinst.funcaddrs where funcaddr is found.
+ FunctionKind::Wasm { index, .. } => *index,
+ };
+
+ // 5. Return ! ToString(index).
+ Utf16FlyString::from_utf8(&index.to_string())
+}
+
+/// https://webassembly.github.io/spec/js-api/#a-new-exported-function
+pub(crate) fn create_exported_function(vm: &Vm, realm: Gc<Realm>, function: FunctionAddress) -> Gc<NativeFunction> {
+ if let Some(object) = host_object::<NativeFunction>(function.cell()) {
+ return object;
+ }
+
+ // 5. Let store be the surrounding agent's associated store.
+ let store = Agent::the(vm).store();
+ let ty = store.function(function).ty.clone();
+ let arity = ty.params.len() as i32;
+ let name = name_of_webassembly_function(store, function);
+
+ // NB: The function has its name on call stacks too, as a HostFunction of the C++ API would.
+ let object = NativeFunction::create_with_name(
+ vm,
+ realm,
+ &name,
+ ExportedFunction {
+ function: EntityRef(function),
+ ty,
+ },
+ |vm: &Vm, function: &ExportedFunction| call_an_exported_function(vm, function),
+ );
+ let configurable = PropertyAttributes::new(Attribute::CONFIGURABLE);
+ object.define_direct_property(vm, &vm.names.length, Value::from_i32(arity), configurable);
+ let name_value = Value::from_string(PrimitiveString::create(vm, Utf16String::from(&name)));
+ object.define_direct_property(vm, &vm.names.name, name_value, configurable);
+ object.set_initial_name(name);
+
+ set_host_object(function.cell(), object);
+
+ object
+}
+
+/// https://webassembly.github.io/spec/js-api/#call-an-exported-function
+fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompletionOr<Value> {
+ // 1. Let store be the surrounding agent's associated store.
+ // NB: The conversions below throw that TypeError.
+
+ // NB: The converted arguments may refer to new cells, which the cell of the arguments keeps alive during the call.
+ let arguments = WasmValues::allocate(vm);
+
+ for (index, &parameter) in function.ty.params.iter().enumerate() {
+ let argument = to_webassembly_value(vm, vm.argument(index), parameter)?;
+ arguments.0.borrow_mut().push(argument);
+ }
+
+ // NB: The results may refer to new cells, which the cell of the results keeps alive from when the call returns them.
+ let results = WasmValues::allocate(vm);
+
+ // 9. Set the surrounding agent's associated store to store.
+ let result = Agent::the(vm)
+ .store()
+ .invoke(function.function.0, &arguments.0.borrow());
+ // NB: Using the Gc after the call keeps the arguments where the conservative scan finds them until it has returned.
+ core::hint::black_box(arguments);
+
+ match result {
+ Ok(values) => *results.0.borrow_mut() = values,
+ Err(trap) => return Err(throw_of_trap(vm, trap)),
+ }
+
+ let result = results_to_js_value(vm, &results.0.borrow(), &function.ty.results);
+ // NB: Using the Gc after the conversion keeps the results where the conservative scan finds them until it is done.
+ core::hint::black_box(results);
+ result
+}
+
+/// The steps of a host function that a JavaScript function becomes, and the index of the host function.
+struct HostFunctionSteps {
+ function: Gc<FunctionObject>,
+ ty: FuncType,
+ index: u32,
+}
+
+impl HostFunction for HostFunctionSteps {
+ // https://webassembly.github.io/spec/js-api/#create-a-host-function
+ // NB: The store the engine passes is the agent's. The JavaScript function reaches it through the agent as well,
+ // and may call back into WebAssembly, so the steps reach it the same way and never through both at once.
+ fn call(&self, _: &mut Store, arguments: &[WasmValue]) -> Result<Vec<WasmValue>, Trap> {
+ let agent = Agent::current();
+ let vm = agent.vm();
+ // FIXME: The settings steps around the call.
+ let result = run_a_host_function(vm, self.function, &self.ty, arguments);
+
+ let throw = match result {
+ Ok(results) => return Ok(results),
+ Err(throw) => throw,
+ };
+ let value = throw.value();
+
+ if let Some(exception) = Exception::address_of_value(value) {
+ return Err(Trap::UncaughtException(exception));
+ }
+
+ // 3. Otherwise,
+ // 1. Let type be the JavaScript exception tag.
+ // 2. Let payload be ! ToWebAssemblyValue(v, externref).
+ // 3. Let (store, address) be exn_alloc(store, type, « payload »).
+ // NB: The exception is v again once it leaves WebAssembly.
+ let payload = to_webassembly_value(vm, value, EXTERNREF).must();
+ Err(Trap::UncaughtException(
+ agent.store().allocate_exception_with_values(agent.js_tag(), &[payload]),
+ ))
+ }
+
+ fn visit_edges(&self, visitor: &StoreVisitor) {
+ // SAFETY: The visitor is live while it visits, and the function is a cell of its heap.
+ unsafe { gc_visitor_visit_cell(visitor.raw(), self.function.as_ptr().cast()) };
+ }
+
+ fn user_data(&self) -> *mut c_void {
+ core::ptr::from_ref(&self.index).cast_mut().cast()
+ }
+}
+
+/// https://webassembly.github.io/spec/js-api/#run-a-host-function
+fn run_a_host_function(
+ vm: &Vm,
+ function: Gc<FunctionObject>,
+ ty: &FuncType,
+ arguments: &[WasmValue],
+) -> ThrowCompletionOr<Vec<WasmValue>> {
+ // NB: The conversions below throw that TypeError.
+
+ let js_arguments = MarkedVec::with_capacity(vm, arguments.len());
+
+ for (argument, &parameter) in arguments.iter().zip(&ty.params) {
+ js_arguments.push(to_js_value(vm, *argument, parameter)?);
+ }
+
+ let ret = call(
+ vm,
+ Value::from_object(function.upcast::<Object>()),
+ Value::UNDEFINED,
+ &js_arguments.values(),
+ )?;
+
+ if ty.results.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // NB: The converted values may refer to new cells, which the cell of the values keeps alive until the engine has
+ // them.
+ let converted = WasmValues::allocate(vm);
+
+ if ty.results.len() == 1 {
+ let value = to_webassembly_value(vm, ret, ty.results[0])?;
+ converted.0.borrow_mut().push(value);
+ } else {
+ // 1. Let method be ? GetMethod(ret, %Symbol.iterator%).
+ let method = ret.get_method(vm, &PropertyKey::from(vm.well_known_symbols().iterator))?;
+
+ // 2. If method is undefined, throw a TypeError.
+ let Some(method) = method else {
+ return vm.throw_completion(
+ ErrorKind::TypeError,
+ ErrorType::NotIterable,
+ &[&ret.to_utf16_string_without_side_effects()],
+ );
+ };
+
+ // 3. Let values be ? IteratorToList(? GetIteratorFromMethod(ret, method)).
+ let iterator = get_iterator_from_method_impl(vm, ret, method)?;
+ let values = iterator_to_list(vm, &iterator)?;
+
+ // 4. Let wasmValues be a new, empty list.
+ // 5. If values's size is not resultsSize, throw a TypeError exception.
+ if values.len() != ty.results.len() {
+ return vm.throw_completion_with_message(
+ ErrorKind::TypeError,
+ format!(
+ "Invalid number of return values for multi-value wasm return of {} objects",
+ ty.results.len()
+ ),
+ );
+ }
+
+ for (index, &result_type) in ty.results.iter().enumerate() {
+ let value = to_webassembly_value(
+ vm,
+ values.get(index).expect("the list has a value per result"),
+ result_type,
+ )?;
+ converted.0.borrow_mut().push(value);
+ }
+
+ // 7. Return wasmValues.
+ }
+ Ok(converted.0.take())
+}
+
+/// https://webassembly.github.io/spec/js-api/#create-a-host-function
+pub(crate) fn create_host_function(vm: &Vm, function: Gc<FunctionObject>, ty: FuncType, index: u32) -> FunctionAddress {
+ // 1. Assert: IsCallable(func).
+ // 2. Let stored settings be the incumbent settings object.
+ // 3. Let hostfunc be a host function which performs the following steps when called with arguments arguments:
+ // NB: The function's entity visits what the steps hold, which keeps the JavaScript function alive with it. Until
+ // the entity holds them, nothing collects garbage.
+ // 4. Let store be the surrounding agent's associated store.
+ // 6. Set the surrounding agent's associated store to store.
+ DeferGc::scope(vm, |_| {
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(
+ gc_container_on_stack,
+ reason = "the function's entity visits the steps through HostFunction::visit_edges()"
+ )
+ )]
+ let steps: HostCallback = Rc::new(HostFunctionSteps {
+ function,
+ ty: ty.clone(),
+ index,
+ });
+ Agent::the(vm).store().allocate_host_function(ty, steps)
+ })
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/gc_object.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/gc_object.rs
new file mode 100644
index 00000000000..2d5dcb39b00
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/gc_object.rs
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Exported GC Objects, https://webassembly.github.io/spec/js-api/#exported-gc-object: objects that stand for a struct
+//! or an array, whose reference is the address of its cell. An object keeps that cell as its host data, and has no
+//! properties, no prototype, and no way to get either.
+
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ ErrorKind, Gc, HostObject, JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE, JS_HOST_CLASS_OBJECT, JSCompletion,
+ JSGetCacheMetadata, JSHostClass, JSHostObjectHooks, JSObject, JSPropertyDescriptor, JSPropertyKey,
+ JSSetCacheMetadata, JSValue, JSValueSink, Object, Value, Vm, completion_into_abi, host_data_of,
+ is_host_instance_of,
+};
+
+use crate::web_assembly::{Agent, host_object, set_host_object};
+
+static EXPORTED_GC_OBJECT_HOOKS: JSHostObjectHooks = JSHostObjectHooks {
+ get_prototype_of: Some(get_prototype_of),
+ set_prototype_of: Some(set_prototype_of),
+ is_extensible: Some(is_extensible),
+ prevent_extensions: Some(prevent_extensions),
+ get_own_property: Some(get_own_property),
+ define_own_property: Some(define_own_property),
+ has_property: Some(has_property),
+ get: Some(get),
+ set: Some(set),
+ delete_property: Some(delete_property),
+ own_property_keys: Some(own_property_keys),
+ is_cacheable_for_inherited_property: None,
+ error_data: None,
+ finalize: None,
+ get_indexed_value: None,
+};
+
+static EXPORTED_GC_OBJECT_CLASS: JSHostClass = JSHostClass::new(
+ JS_HOST_CLASS_OBJECT,
+ "WebAssemblyGCObject",
+ None,
+ (&raw const EXPORTED_GC_OBJECT_HOOKS).cast(),
+ JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE,
+);
+
+fn throw_type_error(message: &str) -> JSCompletion {
+ let vm = Agent::current().vm();
+ completion_into_abi(vm.throw_completion_with_message::<()>(ErrorKind::TypeError, message.to_string()))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-getprototypeof
+unsafe extern "C" fn get_prototype_of(_: *mut JSObject) -> JSCompletion {
+ // 1. Return null.
+ completion_into_abi(Ok(()))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-setprototypeof
+unsafe extern "C" fn set_prototype_of(_: *mut JSObject, _: *mut JSObject) -> JSCompletion {
+ // 1. Throw a TypeError.
+ throw_type_error("Cannot set the prototype of a WebAssembly GC object")
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-isextensible
+unsafe extern "C" fn is_extensible(_: *mut JSObject) -> JSCompletion {
+ // 1. Return false.
+ completion_into_abi(Ok(false))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-preventextensions
+unsafe extern "C" fn prevent_extensions(_: *mut JSObject) -> JSCompletion {
+ // 1. Throw a TypeError.
+ throw_type_error("Cannot prevent extensions of a WebAssembly GC object")
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-getownproperty
+unsafe extern "C" fn get_own_property(
+ _: *mut JSObject,
+ _: JSPropertyKey,
+ _: *mut JSPropertyDescriptor,
+) -> JSCompletion {
+ // 1. Return undefined.
+ completion_into_abi(Ok(()))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-defineownproperty
+unsafe extern "C" fn define_own_property(
+ _: *mut JSObject,
+ _: JSPropertyKey,
+ _: *mut JSPropertyDescriptor,
+ _: *const JSPropertyDescriptor,
+) -> JSCompletion {
+ // 1. Throw a TypeError.
+ throw_type_error("Cannot define properties of a WebAssembly GC object")
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-hasproperty
+unsafe extern "C" fn has_property(_: *mut JSObject, _: JSPropertyKey) -> JSCompletion {
+ // 1. Return false.
+ completion_into_abi(Ok(false))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-get
+unsafe extern "C" fn get(
+ _: *mut JSObject,
+ _: JSPropertyKey,
+ _: JSValue,
+ _: *mut JSGetCacheMetadata,
+ _: u8,
+) -> JSCompletion {
+ // 1. Return undefined.
+ completion_into_abi(Ok(Value::UNDEFINED))
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-set
+unsafe extern "C" fn set(
+ _: *mut JSObject,
+ _: JSPropertyKey,
+ _: JSValue,
+ _: JSValue,
+ _: *mut JSSetCacheMetadata,
+ _: u8,
+) -> JSCompletion {
+ // 1. Throw a TypeError.
+ throw_type_error("Cannot set properties of a WebAssembly GC object")
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-delete
+unsafe extern "C" fn delete_property(_: *mut JSObject, _: JSPropertyKey) -> JSCompletion {
+ // 1. Throw a TypeError.
+ throw_type_error("Cannot delete properties of a WebAssembly GC object")
+}
+
+// https://webassembly.github.io/spec/js-api/#exported-gc-object-ownpropertykeys
+unsafe extern "C" fn own_property_keys(_: *mut JSObject, _: *mut JSValueSink) -> JSCompletion {
+ // 1. Let keys be a new empty list.
+ // 2. Return keys.
+ completion_into_abi(Ok(()))
+}
+
+/// https://webassembly.github.io/spec/js-api/#create-a-new-exported-gc-object
+pub(crate) fn create_exported_gc_object(vm: &Vm, reference: u64) -> Gc<Object> {
+ // 1. Assert: objectaddr is a struct or array address.
+ // 2. Let map be the current agent's associated exported GC object cache.
+ // 3. If map[objectaddr] exists, return map[objectaddr].
+ let cell = reference as *mut u8;
+ if let Some(object) = host_object::<Object>(cell) {
+ return object;
+ }
+
+ // 4. Let object be a new Exported GC Object, with [[ObjectAddress]] set to objectaddr and [[ObjectKind]] set to
+ // objectKind.
+ let realm = vm.current_realm().expect("a conversion runs in a realm");
+ // SAFETY: The class is of kind JS_HOST_CLASS_OBJECT, and the host data is the live cell of the struct or array.
+ let object = unsafe {
+ HostObject::create(
+ vm,
+ realm,
+ &EXPORTED_GC_OBJECT_CLASS,
+ None,
+ None,
+ Some(NonNull::new_unchecked(cell.cast())),
+ )
+ }
+ .upcast::<Object>();
+
+ // 5. Set map[objectaddr] to object.
+ set_host_object(cell, object);
+
+ // 6. Return object.
+ object
+}
+
+/// The value of the object's [[ObjectAddress]] internal slot, if it has one and is therefore an Exported GC Object.
+pub(crate) fn exported_gc_object_address(object: Gc<Object>) -> Option<u64> {
+ if !is_host_instance_of(&object, &EXPORTED_GC_OBJECT_CLASS) {
+ return None;
+ }
+ host_data_of(&object).map(|cell| cell.as_ptr() as u64)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/global.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/global.rs
new file mode 100644
index 00000000000..759dfaef146
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/global.rs
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2024, Andrew Kaster <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Global, https://webassembly.github.io/spec/js-api/#globals
+
+use libjs_rust::api::{Trace, Value, Vm};
+use libwasm_engine::runtime::{GlobalAddress, GlobalInstance};
+use libwasm_engine::types::{GlobalType, HeapType, RefType, ValType};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::web_assembly::values::{default_webassembly_value, to_js_value, to_webassembly_value};
+use crate::web_assembly::{Agent, EntityRef, host_object, implementation_of_value, set_host_object};
+
+/// https://webassembly.github.io/spec/js-api/#enumdef-valuetype
+#[derive(Clone, Copy)]
+pub(crate) enum ValueType {
+ I32,
+ I64,
+ F32,
+ F64,
+ V128,
+ Externref,
+ Anyfunc,
+}
+
+impl ValueType {
+ // https://webassembly.github.io/spec/js-api/#tovaluetype
+ pub(crate) fn to_value_type(self) -> ValType {
+ let reference = |heap| ValType::Ref(RefType { nullable: true, heap });
+ match self {
+ Self::I32 => ValType::I32,
+ Self::I64 => ValType::I64,
+ Self::F32 => ValType::F32,
+ Self::F64 => ValType::F64,
+ Self::V128 => ValType::V128,
+ Self::Anyfunc => reference(HeapType::Func),
+ Self::Externref => reference(HeapType::Extern),
+ }
+ }
+}
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-globaldescriptor
+pub(crate) struct GlobalDescriptor {
+ pub(crate) value: ValueType,
+ pub(crate) mutable: bool,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Global {
+ // [[Global]]
+ address: EntityRef<GlobalInstance>,
+}
+
+impl Wrappable for Global {}
+
+impl Global {
+ // https://webassembly.github.io/spec/js-api/#dom-global-global
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ descriptor: GlobalDescriptor,
+ v: Option<Value>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+
+ // 1. Let mutable be descriptor["mutable"].
+ let mutable = descriptor.mutable;
+
+ // 2. Let valuetype be ToValueType(descriptor["value"]).
+ let value_type = descriptor.value.to_value_type();
+
+ // 1. Throw a TypeError.
+ if value_type == ValType::V128 {
+ return Err(Exception::type_error("V128 is not supported as a global value type"));
+ }
+
+ // FIXME: https://github.com/WebAssembly/spec/issues/1861
+ // Is there a difference between *missing* and undefined for optional any values?
+ let value = match v {
+ None => default_webassembly_value(vm, value_type),
+ Some(v) => to_webassembly_value(vm, v, value_type)?,
+ };
+
+ // 6. If mutable is true, let globaltype be var valuetype; otherwise, let globaltype be const valuetype.
+ // 7. Let store be the current agent’s associated store.
+ // 8. Let (store, globaladdr) be global_alloc(store, globaltype, value).
+ // 9. Set the current agent’s associated store to store.
+ let global = Agent::the(vm).store().allocate_global(
+ GlobalType {
+ value: value_type,
+ mutable,
+ },
+ value,
+ );
+
+ // 10. Initialize this from globaladdr.
+ Ok(Self::initialize(vm, global))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-a-global-object
+ fn initialize(vm: &Vm, global: GlobalAddress) -> Ref<Self> {
+ assert!(host_object::<()>(global.cell()).is_none());
+
+ let object = allocate(vm, |_| Self {
+ address: EntityRef(global),
+ });
+
+ set_host_object(global.cell(), object);
+ object
+ }
+
+ /// The Global object of the global, https://webassembly.github.io/spec/js-api/#create-a-global-object
+ pub(crate) fn from_address(vm: &Vm, global: GlobalAddress) -> Ref<Self> {
+ if let Some(object) = host_object(global.cell()) {
+ return object;
+ }
+
+ Self::initialize(vm, global)
+ }
+
+ pub(crate) fn from_value(value: Value) -> Option<Ref<Self>> {
+ implementation_of_value(value)
+ }
+
+ pub(crate) fn address(&self) -> GlobalAddress {
+ self.address.0
+ }
+
+ // https://webassembly.github.io/spec/js-api/#getglobalvalue
+ fn get_global_value(&self, cx: &CallContext) -> WebIdlResult<Value> {
+ // 1. Let store be the current agent’s associated store.
+ // 2. Let globaladdr be global.[[Global]].
+ // 3. Let globaltype be global_type(store, globaladdr).
+ let global = Agent::the(cx.vm()).store().global(self.address());
+
+ if global.ty.value == ValType::V128 {
+ return Err(Exception::type_error("V128 is not supported as a global value type"));
+ }
+
+ // 5. Let value be global_read(store, globaladdr).
+ Ok(to_js_value(cx.vm(), global.get(), global.ty.value)?)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-global-value
+ pub(crate) fn value(&self, cx: &mut CallContext) -> WebIdlResult<Value> {
+ self.get_global_value(cx)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-global-value
+ pub(crate) fn set_value(&self, cx: &mut CallContext, value: Value) -> WebIdlResult<()> {
+ // 1. Let store be the current agent’s associated store.
+ // 2. Let globaladdr be this.[[Global]].
+ // 3. Let mut valuetype be global_type(store, globaladdr).
+ let ty = Agent::the(cx.vm()).store().global(self.address()).ty;
+
+ if ty.value == ValType::V128 {
+ return Err(Exception::type_error("Cannot set the value of a V128 global"));
+ }
+
+ // 5. If mut is const, throw a TypeError.
+ if !ty.mutable {
+ return Err(Exception::type_error("Cannot set the value of a const global"));
+ }
+
+ // 6. Let value be ? ToWebAssemblyValue(the given value, valuetype).
+ let value = to_webassembly_value(cx.vm(), value, ty.value)?;
+
+ // 7. Let store be global_write(store, globaladdr, value).
+ // 8. If store is error, throw a RangeError exception.
+ // 9. Set the current agent’s associated store to store.
+ // NB: Writing cannot fail, as the value has the global's type.
+ Agent::the(cx.vm()).store().global_mut(self.address()).set(value);
+ Ok(())
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-global-valueof
+ pub(crate) fn value_of(&self, cx: &mut CallContext) -> WebIdlResult<Value> {
+ self.get_global_value(cx)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/instance.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/instance.rs
new file mode 100644
index 00000000000..72efd4e7a4f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/instance.rs
@@ -0,0 +1,484 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Instance, https://webassembly.github.io/spec/js-api/#instances
+
+use core::cell::RefCell;
+
+use ak::Utf16FlyString;
+use libjs_rust::api::{
+ Attribute, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, IntegrityLevel, MarkedVec, Must,
+ Object, PropertyAttributes, PropertyKey, Realm, ThrowCompletionOr, Trace, Value, Visitor, Vm,
+};
+use libwasm_engine::module::ImportDescription;
+use libwasm_engine::runtime::{ExternValue, Instance as CoreInstance, InstanceAddress};
+use libwasm_engine::types::{FuncType, GlobalType, HeapType, RefType, ValType};
+
+use crate::bindings::conversions::UsvString;
+use crate::bindings::interface::{Ref, Wrappable, wrap};
+use crate::bindings::realm_data::wrapper_world_of;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::web_assembly::builtins::{instantiate_a_builtin_set, instantiate_imported_strings, refers_to_a_builtin_set};
+use crate::web_assembly::errors::{WebAssemblyError, throw_webassembly_error};
+use crate::web_assembly::exported_function::{
+ create_exported_function, create_host_function, exported_function_address,
+};
+use crate::web_assembly::global::Global;
+use crate::web_assembly::memory::Memory;
+use crate::web_assembly::module::Module;
+use crate::web_assembly::table::Table;
+use crate::web_assembly::tag::Tag;
+use crate::web_assembly::values::to_webassembly_value;
+use crate::web_assembly::{Agent, CompiledModule, EntityRef, throw_of_instantiation_error};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Instance {
+ // [[Instance]]
+ instance: EntityRef<CoreInstance>,
+ // [[Exports]]
+ exports: Gc<Object>,
+}
+
+impl Wrappable for Instance {}
+
+/// The imports of a module, which keep the entities they are alive while they wait for an instance to hold them: the
+/// host functions and globals made for the imports are referenced from nowhere else, reading the imports runs user
+/// code (getters, valueOf) that may collect garbage, and an asynchronous instantiation holds them until its task runs.
+#[derive(Default)]
+pub(crate) struct Imports(pub(crate) RefCell<Vec<ExternValue>>);
+
+static IMPORTS_CLASS: EmbedderClass<Imports> = EmbedderClass::new("WebAssemblyImports");
+
+impl EmbedderValue for Imports {
+ const CLASS: &'static EmbedderClass<Self> = &IMPORTS_CLASS;
+}
+
+// SAFETY: Visits the cell of every entity of the list.
+unsafe impl Trace for Imports {
+ fn trace(&self, visitor: &mut Visitor) {
+ for &import in self.0.borrow().iter() {
+ match import {
+ ExternValue::Function(address) => EntityRef(address).trace(visitor),
+ ExternValue::Table(address) => EntityRef(address).trace(visitor),
+ ExternValue::Memory(address) => EntityRef(address).trace(visitor),
+ ExternValue::Global(address) => EntityRef(address).trace(visitor),
+ ExternValue::Tag(address) => EntityRef(address).trace(visitor),
+ }
+ }
+ }
+}
+
+impl Imports {
+ pub(crate) fn push(&self, import: ExternValue) {
+ self.0.borrow_mut().push(import);
+ }
+}
+
+/// A value type of the module, in the store's terms (see Store::module_type_identities()).
+pub(crate) fn value_type_in_store(vm: &Vm, module: &CompiledModule, ty: ValType) -> ValType {
+ let ValType::Ref(RefType {
+ nullable,
+ heap: HeapType::Concrete(index),
+ }) = ty
+ else {
+ return ty;
+ };
+ let identities = Agent::the(vm).store().module_type_identities_of(module);
+ ValType::Ref(RefType {
+ nullable,
+ heap: HeapType::Concrete(identities[index as usize]),
+ })
+}
+
+/// The function type at `type_index` of the module, in the store's terms.
+pub(crate) fn function_type_in_store(vm: &Vm, module: &CompiledModule, type_index: u32) -> FuncType {
+ let ty = module.types[type_index as usize]
+ .as_func()
+ .expect("the type of a function import is a function type");
+ FuncType {
+ params: ty
+ .params
+ .iter()
+ .map(|&ty| value_type_in_store(vm, module, ty))
+ .collect(),
+ results: ty
+ .results
+ .iter()
+ .map(|&ty| value_type_in_store(vm, module, ty))
+ .collect(),
+ }
+}
+
+/// The global type of the module, in the store's terms.
+pub(crate) fn global_type_in_store(vm: &Vm, module: &CompiledModule, ty: GlobalType) -> GlobalType {
+ GlobalType {
+ value: value_type_in_store(vm, module, ty.value),
+ mutable: ty.mutable,
+ }
+}
+
+fn link_error<T>(vm: &Vm, message: &str) -> ThrowCompletionOr<T> {
+ let realm = vm.current_realm().expect("reading the imports runs in a realm");
+ Err(throw_webassembly_error(vm, realm, WebAssemblyError::Link, message))
+}
+
+// https://webassembly.github.io/spec/js-api/#read-the-imports
+pub(crate) fn read_the_imports(
+ vm: &Vm,
+ module: &CompiledModule,
+ import_object: Option<Gc<Object>>,
+ builtin_set_names: &[UsvString],
+ imported_string_module: Option<&UsvString>,
+) -> ThrowCompletionOr<Gc<EmbedderCell<Imports>>> {
+ // 1. If module_imports(module) is not empty, and importObject is missing, throw a TypeError exception.
+ if !module.imports.is_empty() && import_object.is_none() {
+ return vm.throw_completion_with_message(
+ ErrorKind::TypeError,
+ "ImportObject must be provided when module has imports".to_string(),
+ );
+ }
+
+ // 2. Let builtinOrStringImports be the ordered map «[ ]».
+ // NB: The keys are UTF-8, as the module names of imports are.
+ let builtin_or_string_imports = MarkedVec::<(String, Gc<Object>)>::new(vm);
+ let contains_key = |key: &str| {
+ builtin_or_string_imports
+ .values()
+ .iter()
+ .any(|(builtin_or_string_import, _)| builtin_or_string_import == key)
+ };
+
+ // 3. For each builtinSetName of builtinSetNames,
+ for builtin_set_name in builtin_set_names {
+ // 3.1. Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:"
+ let builtin_set_qualified_name = format!("wasm:{}", builtin_set_name.to_utf8());
+
+ // 3.2. Assert: builtinOrStringImports does not contain builtinSetQualifiedName
+ assert!(!contains_key(&builtin_set_qualified_name));
+
+ // 3.3. If builtinSetName does not refer to a builtin set, then continue.
+ if !refers_to_a_builtin_set(builtin_set_name) {
+ continue;
+ }
+
+ // 3.4. Let exportsObject be the result of instantiate a builtin set with builtinSetName
+ let exports_object = instantiate_a_builtin_set(vm, builtin_set_name);
+
+ // 3.5. Set builtinOrStringImports[builtinSetQualifiedName] to exportsObject
+ builtin_or_string_imports.push((builtin_set_qualified_name, exports_object));
+ }
+
+ // 4. If importedStringModule is not null,
+ if let Some(imported_string_module) = imported_string_module {
+ // 4.1. Let exportsObject be the result of instantiate imported strings with module and importedStringModule
+ let exports_object = instantiate_imported_strings(vm, module, imported_string_module);
+
+ // 4.2. Set builtinOrStringImports[importedStringModule] to exportsObject
+ let imported_string_module = imported_string_module.to_utf8();
+ let existing = builtin_or_string_imports
+ .values()
+ .iter()
+ .position(|(builtin_or_string_import, _)| *builtin_or_string_import == imported_string_module);
+ match existing {
+ Some(index) => builtin_or_string_imports.set(index, (imported_string_module, exports_object)),
+ None => builtin_or_string_imports.push((imported_string_module, exports_object)),
+ }
+ }
+
+ // 5. Let imports be « ».
+ let imports = IMPORTS_CLASS.allocate(vm, |_| Imports::default());
+ // NB: A module without an import object has no imports (step 1).
+ let Some(import_object) = import_object else {
+ return Ok(imports);
+ };
+ let mut imported_function_count = 0;
+
+ // 6. For each (moduleName, componentName, externtype) of module_imports(module),
+ for import in &module.imports {
+ let module_name = PropertyKey::from(Utf16FlyString::from_utf8(&import.module));
+ let component_name = PropertyKey::from(Utf16FlyString::from_utf8(&import.name));
+
+ let builtin_or_string_import = builtin_or_string_imports
+ .values()
+ .iter()
+ .find(|(builtin_or_string_import, _)| *builtin_or_string_import == import.module)
+ .map(|&(_, exports_object)| exports_object);
+ let value = match builtin_or_string_import {
+ // 6.1. If builtinOrStringImports[moduleName] exists,
+ Some(builtin_or_string_import) => {
+ // 6.1.1. Let o be builtinOrStringImports[moduleName].
+ let mut value = Value::from_object(builtin_or_string_import);
+
+ // 6.1.2. If o is not an Object or if ? HasProperty(o, componentName) is false,
+ if !value.is_object() || !value.as_object().has_property(vm, &component_name)? {
+ // 6.1.2.1. Set o to ? Get(importObject, moduleName).
+ value = import_object.get(vm, &module_name)?;
+ }
+ value
+ }
+ // 6.2. Else,
+ None => {
+ // 6.2.1. Let o be ? Get(importObject, moduleName).
+ import_object.get(vm, &module_name)?
+ }
+ };
+
+ // 6.3. If o is not an Object, throw a TypeError exception.
+ if !value.is_object() {
+ return vm.throw_completion(
+ ErrorKind::TypeError,
+ ErrorType::IsNotAEvaluatedFrom,
+ &[
+ &value.to_utf16_string_without_side_effects(),
+ &"Object",
+ &format!("[wasm import object][\"{}\"]", import.module),
+ ],
+ );
+ }
+
+ // 6.4. Let v be ? Get(o, componentName).
+ let v = value.as_object().get(vm, &component_name)?;
+
+ match &import.description {
+ // 6.5. If externtype is of the form func functype,
+ ImportDescription::Function(type_index) => {
+ // 6.5.1. If IsCallable(v) is false, throw a LinkError exception.
+ if !v.is_function() {
+ let message = ErrorType::IsNotAEvaluatedFrom.message(&[
+ &v.to_utf16_string_without_side_effects(),
+ &"function",
+ &format!("[wasm import object][\"{}\"]", import.name),
+ ]);
+ return link_error(vm, &String::from_utf16_lossy(&message.to_utf16()));
+ }
+
+ // 6.5.2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
+ // 6.5.2.1. Let funcaddr be the value of v's [[FunctionAddress]] internal slot.
+ // 6.5.3. Otherwise,
+ // 6.5.3.1. Create a host function from v and functype, and let funcaddr be the result.
+ // 6.5.3.2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.
+ let function = exported_function_address(v.as_object()).unwrap_or_else(|| {
+ create_host_function(
+ vm,
+ v.as_function(),
+ function_type_in_store(vm, module, *type_index),
+ imported_function_count,
+ )
+ });
+
+ // 6.5.4. Let externfunc be the external value func funcaddr.
+ // 6.5.5. Append externfunc to imports.
+ imports.push(ExternValue::Function(function));
+ imported_function_count += 1;
+ }
+ // 6.6. If externtype is of the form global mut valtype,
+ ImportDescription::Global(ty) => {
+ let ty = global_type_in_store(vm, module, *ty);
+ // 6.6.1. If v implements Global,
+ // 6.6.1.1. Let globaladdr be v.[[Global]].
+ let global = if let Some(global) = Global::from_value(v) {
+ global.address()
+ }
+ // 6.6.2. Otherwise,
+ else {
+ // 6.6.2.1. If valtype is i64 and v is not a BigInt, throw a LinkError exception.
+ if ty.value == ValType::I64 && !v.is_bigint() {
+ return link_error(vm, "Import resolution attempted to use a non-BigInt for an i64 global");
+ }
+ // 6.6.2.2. If valtype is one of i32, f32 or f64 and v is not a Number, throw a LinkError exception.
+ if matches!(ty.value, ValType::I32 | ValType::F32 | ValType::F64) && !v.is_number() {
+ return link_error(
+ vm,
+ "Import resolution attempted to use a non-Number for a numeric global",
+ );
+ }
+ // 6.6.2.3. If valtype is v128, throw a LinkError exception.
+ if ty.value == ValType::V128 {
+ return link_error(vm, "Import resolution attempted to use a value for a V128 global");
+ }
+ // 6.6.2.4. If mut is var, throw a LinkError exception.
+ if ty.mutable {
+ return link_error(vm, "Import resolution attempted to use a value for a mutable global");
+ }
+ // 6.6.2.5. Let value be ToWebAssemblyValue(v, valtype). If this throws a TypeError, catch it, and throw
+ // a LinkError exception.
+ let Ok(value) = to_webassembly_value(vm, v, ty.value) else {
+ return link_error(
+ vm,
+ "Import resolution attempted to use a value of the wrong type for a global",
+ );
+ };
+ // 6.6.2.6. Let store be the surrounding agent's associated store.
+ // 6.6.2.7. Let (store, globaladdr) be global_alloc(store, const valtype, value).
+ // 6.6.2.8. Set the surrounding agent's associated store to store.
+ Agent::the(vm).store().allocate_global(
+ GlobalType {
+ value: ty.value,
+ mutable: false,
+ },
+ value,
+ )
+ };
+
+ // 6.6.3. Let externglobal be global globaladdr.
+ // 6.6.4. Append externglobal to imports.
+ imports.push(ExternValue::Global(global));
+ }
+ // 6.7. If externtype is of the form mem memtype,
+ ImportDescription::Memory(_) => {
+ // 6.7.1. If v does not implement Memory, throw a LinkError exception.
+ let Some(memory) = Memory::from_value(v) else {
+ return link_error(vm, "Expected an instance of WebAssembly.Memory for a memory import");
+ };
+
+ // 6.7.2. Let externmem be the external value mem v.[[Memory]].
+ // 6.7.3. Append externmem to imports.
+ imports.push(ExternValue::Memory(memory.address()));
+ }
+ // 6.8. If externtype is of the form table tabletype,
+ ImportDescription::Table(_) => {
+ // 6.8.1. If v does not implement Table, throw a LinkError exception.
+ let Some(table) = Table::from_value(v) else {
+ return link_error(vm, "Expected an instance of WebAssembly.Table for a table import");
+ };
+
+ // 6.8.2. Let tableaddr be v.[[Table]].
+ // 6.8.3. Let externtable be the external value table tableaddr.
+ // 6.8.4. Append externtable to imports.
+ imports.push(ExternValue::Table(table.address()));
+ }
+ // 6.9. If externtype is of the form tag attribute functype,
+ ImportDescription::Tag(_) => {
+ // 6.9.1. Assert: attribute is exception.
+ // 6.9.2. If v does not implement Tag, throw a LinkError exception.
+ let Some(tag) = Tag::from_value(v) else {
+ return link_error(vm, "Expected an instance of WebAssembly.Tag for a tag import");
+ };
+
+ // 6.9.3. Let tagaddr be v.[[Address]].
+ // 6.9.4. Let externtag be the external value tag tagaddr.
+ // 6.9.5. Append externtag to imports.
+ imports.push(ExternValue::Tag(tag.address()));
+ }
+ }
+ }
+
+ // 7. Return imports.
+ Ok(imports)
+}
+
+// https://webassembly.github.io/spec/js-api/index.html#instantiate-the-core-of-a-webassembly-module
+pub(crate) fn instantiate_the_core_of_a_webassembly_module(
+ vm: &Vm,
+ module: &CompiledModule,
+ imports: &Imports,
+) -> ThrowCompletionOr<InstanceAddress> {
+ // 1. Let store be the surrounding agent's associated store.
+ // 2. Let result be module_instantiate(store, module, imports).
+ // 3. If result is error, throw an appropriate exception type:
+ // * A LinkError exception for most cases which occur during linking.
+ // * If the error came when running the start function, throw a RuntimeError for most errors which occur from
+ // WebAssembly, or the error object propagated from inner ECMAScript code.
+ // * Another error type if appropriate, for example an out-of-memory exception, as documented in the
+ // WebAssembly error mapping.
+ // 4. Let (store, instance) be result.
+ // 5. Set the surrounding agent's associated store to store.
+ // 6. Return instance.
+ let imports = imports.0.borrow().clone();
+ Agent::the(vm)
+ .store()
+ .instantiate(module.clone(), &imports)
+ .map_err(|error| throw_of_instantiation_error(vm, error))
+}
+
+// https://webassembly.github.io/spec/js-api/#create-an-exports-object
+fn create_an_exports_object(vm: &Vm, realm: Gc<Realm>, instance: InstanceAddress) -> Gc<Object> {
+ let cx = CallContext::new(vm, realm);
+ let exports_object = Object::create(vm, realm, None);
+ let attributes = PropertyAttributes::new(Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE);
+
+ // NB: Creating the object of an export may reach the store, so nothing of it stays borrowed across the loop.
+ let module = Agent::the(vm).store().instance(instance).module.clone();
+ for export in &module.exports {
+ let Some(value) = Agent::the(vm).store().instance(instance).export(&export.name) else {
+ continue;
+ };
+ let value = match value {
+ ExternValue::Function(function) => {
+ Value::from_object(create_exported_function(vm, realm, function).upcast::<Object>())
+ }
+ ExternValue::Global(global) => Value::from_object(wrap(&cx, Global::from_address(vm, global))),
+ ExternValue::Memory(memory) => Value::from_object(wrap(&cx, Memory::from_address(vm, memory))),
+ ExternValue::Table(table) => Value::from_object(wrap(&cx, Table::from_address(vm, table))),
+ ExternValue::Tag(tag) => Value::from_object(wrap(&cx, Tag::from_address(vm, realm, tag))),
+ };
+ exports_object.define_direct_property(
+ vm,
+ &PropertyKey::from(Utf16FlyString::from_utf8(&export.name)),
+ value,
+ attributes,
+ );
+ }
+
+ exports_object.set_integrity_level(vm, IntegrityLevel::Frozen).must();
+ exports_object
+}
+
+impl Instance {
+ // https://webassembly.github.io/spec/js-api/#dom-instance-instance
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ module_object: Ref<Module>,
+ import_object: Option<Gc<Object>>,
+ ) -> WebIdlResult<Self> {
+ let vm = cx.vm();
+
+ // 1. Let builtinSetNames be moduleObject.[[BuiltinSets]].
+ let builtin_set_names = module_object.builtin_sets();
+
+ // 2. Let importedStringModule be moduleObject.[[ImportedStringModule]].
+ let imported_string_module = module_object.imported_string_module();
+
+ // 3. Let module be moduleObject.[[Module]].
+ let module = module_object.compiled_module().clone();
+
+ // 4. Read the imports of module with imports importObject, builtinSetNames, and importedStringModule, and let
+ // imports be the result.
+ let imports = read_the_imports(vm, &module, import_object, builtin_set_names, imported_string_module)?;
+
+ // 5. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
+ let instance = instantiate_the_core_of_a_webassembly_module(vm, &module, &imports)?;
+
+ // 6. Initialize this from module and instance.
+ Ok(Self::initialize(vm, cx.realm(), instance))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-an-instance-object
+ pub(crate) fn initialize(vm: &Vm, realm: Gc<Realm>, instance: InstanceAddress) -> Self {
+ // NB: An instance's exports, like its memories and tables, belong to the realm it was created in.
+ Self {
+ instance: EntityRef(instance),
+ exports: create_an_exports_object(vm, realm, instance),
+ }
+ }
+
+ pub(crate) fn address(&self) -> InstanceAddress {
+ self.instance.0
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-instance-exports
+ pub(crate) fn exports(&self, cx: &mut CallContext) -> WebIdlResult<Gc<Object>> {
+ let vm = cx.vm();
+ assert!(
+ wrapper_world_of(vm, cx.realm()) == wrapper_world_of(vm, self.exports.shape().realm()),
+ "Reading a WebAssembly instance's exports from another world"
+ );
+ Ok(self.exports)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/memory.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/memory.rs
new file mode 100644
index 00000000000..4609d2a6350
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/memory.rs
@@ -0,0 +1,582 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Memory, https://webassembly.github.io/spec/js-api/#memories, and its shared memories,
+//! https://webassembly.github.io/threads/js-api/
+//!
+//! A Memory object belongs to the agent, as its memory does, while its [[BufferObject]] belongs to a realm: the object
+//! has a buffer object of its own in every realm that asks for one. It holds them weakly, as a realm that goes away
+//! takes its buffer with it.
+
+use core::cell::RefCell;
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ ArrayBuffer, ArrayBufferShared, DataBlock, DataBlockStorage, ExternalPrimitiveStorage, ForeignCellSlot, Gc, GcWeak,
+ IntegrityLevel, Must, PrimitiveString, RawNativeFunctionResult, Realm, ThrowCompletionOr, Trace, Value, Vm,
+ detach_array_buffer, same_value,
+};
+use libwasm_engine::runtime::MemoryAddress;
+use libwasm_engine::runtime::memory::MemoryInstance;
+use libwasm_engine::types::{AddressType, Limits, MemoryType};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_if_abi};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::web_assembly::{Agent, EntityRef, PAGE_SIZE, host_object, set_host_object};
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-memorydescriptor
+pub(crate) struct MemoryDescriptor {
+ pub(crate) initial: u32,
+ pub(crate) maximum: Option<u32>,
+ pub(crate) shared: bool,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Memory {
+ // [[Memory]]
+ address: EntityRef<MemoryInstance>,
+ #[gc(untraced)]
+ shared: bool,
+ // [[BufferObject]], one per realm.
+ #[gc(untraced)]
+ buffer_objects: RefCell<Vec<GcWeak<ArrayBuffer>>>,
+}
+
+impl Wrappable for Memory {}
+
+fn detach_key(vm: &Vm) -> Value {
+ Value::from_string(PrimitiveString::create_from_utf8(vm, "WebAssembly.Memory"))
+}
+
+impl Memory {
+ // https://webassembly.github.io/spec/js-api/#dom-memory-memory
+ pub(crate) fn construct(cx: &mut CallContext, descriptor: MemoryDescriptor) -> WebIdlResult<Ref<Self>> {
+ // https://webassembly.github.io/threads/js-api/index.html#dom-memory-memory
+ // 3. If maximum is not empty and maximum < initial, throw a RangeError exception.
+ if descriptor.maximum.is_some_and(|maximum| maximum < descriptor.initial) {
+ return Err(Exception::range_error("Initial is larger than maximum."));
+ }
+
+ // 4. Let share be shared if descriptor["shared"] is true and unshared otherwise.
+ // 5. If share is shared and maximum is empty, throw a TypeError exception.
+ if descriptor.shared && descriptor.maximum.is_none() {
+ return Err(Exception::type_error("Maximum has to be specified for shared memory."));
+ }
+
+ // 9. Set the surrounding agent's associated store to store.
+ let memory = Agent::the(cx.vm())
+ .store()
+ .allocate_memory(MemoryType {
+ limits: Limits {
+ min: u64::from(descriptor.initial),
+ max: descriptor.maximum.map(u64::from),
+ address_type: AddressType::I32,
+ shared: descriptor.shared,
+ },
+ })
+ .ok_or_else(|| Exception::type_error("Wasm Memory allocation failed"))?;
+
+ Ok(Self::initialize(cx.vm(), memory))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-a-memory-object
+ fn initialize(vm: &Vm, memory: MemoryAddress) -> Ref<Self> {
+ // 1. Let map be the surrounding agent's associated Memory object cache.
+ assert!(host_object::<()>(memory.cell()).is_none());
+
+ // NB: The buffer of a realm is created when the realm first asks for it.
+ let shared = Agent::the(vm).store().memory(memory).ty.limits.shared;
+ let object = allocate(vm, |_| Self {
+ address: EntityRef(memory),
+ shared,
+ buffer_objects: RefCell::default(),
+ });
+
+ set_host_object(memory.cell(), object);
+ object
+ }
+
+ /// The Memory object of the memory, https://webassembly.github.io/spec/js-api/#create-a-memory-object
+ pub(crate) fn from_address(vm: &Vm, memory: MemoryAddress) -> Ref<Self> {
+ // 1. Let map be the surrounding agent's associated Memory object cache.
+ if let Some(object) = host_object(memory.cell()) {
+ return object;
+ }
+
+ Self::initialize(vm, memory)
+ }
+
+ pub(crate) fn address(&self) -> MemoryAddress {
+ self.address.0
+ }
+
+ fn size(&self, vm: &Vm) -> usize {
+ Agent::the(vm).store().memory(self.address()).size()
+ }
+
+ fn external_storage(this: Ref<Self>, vm: &Vm, fixed_length: bool) -> ExternalPrimitiveStorage {
+ let handle = Agent::the(vm).store().memory(this.address()).primitive_storage_handle();
+ let owner = ForeignCellSlot::empty();
+ // SAFETY: The memory object is a live cell of the heap, which the slot then keeps alive.
+ unsafe { owner.set(Some(NonNull::new_unchecked(this.as_ptr().cast()))) };
+ ExternalPrimitiveStorage::new(owner, handle, fixed_length.then(|| this.size(vm)))
+ }
+
+ // https://webassembly.github.io/threads/js-api/index.html#create-a-fixed-length-memory-buffer
+ fn create_a_fixed_length_memory_buffer(this: Ref<Self>, vm: &Vm, realm: Gc<Realm>) -> Gc<ArrayBuffer> {
+ // 3. If share is shared,
+ if this.shared {
+ // 1. Let block be a Shared Data Block which is identified with the underlying memory of memaddr.
+ // 2. Let buffer be a new SharedArrayBuffer with the internal slots [[ArrayBufferData]] and [[ArrayBufferByteLength]].
+ // 3. Set buffer.[[ArrayBufferData]] to block.
+ // 4. Set buffer.[[ArrayBufferByteLength]] to the length of block.
+ // NOTE: ArrayBufferByteLength should contain the original size regardless of growth.
+ let block = DataBlock::external(Self::external_storage(this, vm, true), ArrayBufferShared::Yes);
+ let buffer = ArrayBuffer::create_from_data_block(vm, realm, block);
+
+ // 5. Perform ! SetIntegrityLevel(buffer, "frozen").
+ buffer.set_integrity_level(vm, IntegrityLevel::Frozen).must();
+
+ return buffer;
+ }
+
+ // 4. Otherwise,
+ // 1. Let block be a Data Block which is identified with the underlying memory of memaddr.
+ // 3. Set buffer.[[ArrayBufferData]] to block.
+ // 4. Set buffer.[[ArrayBufferByteLength]] to the length of block.
+ let block = DataBlock::external(Self::external_storage(this, vm, true), ArrayBufferShared::No);
+ let buffer = ArrayBuffer::create_from_data_block(vm, realm, block);
+ buffer.set_detach_key(detach_key(vm));
+ buffer
+ }
+
+ // https://webassembly.github.io/spec/js-api/#create-a-resizable-memory-buffer
+ fn create_a_resizable_memory_buffer(
+ this: Ref<Self>,
+ vm: &Vm,
+ realm: Gc<Realm>,
+ max_size: u64,
+ ) -> WebIdlResult<Gc<ArrayBuffer>> {
+ // 3. If maxsize > (65536 x 65536),
+ if max_size > 65536 * PAGE_SIZE {
+ // 1. Throw a RangeError exception.
+ return Err(Exception::range_error(
+ "Maximum memory length exceeds 65536 * 65536 bytes",
+ ));
+ }
+
+ // https://webassembly.github.io/threads/js-api/index.html#create-a-resizable-memory-buffer
+ // 5. If share is shared,
+ if this.shared {
+ // 1. Let block be a Shared Data Block which is identified with the underlying memory of memaddr.
+ // 2. Let buffer be a new SharedArrayBuffer with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], and [[ArrayBufferMaxByteLength]].
+ // 3. Set buffer.[[ArrayBufferData]] to block.
+ // AD-HOC: The threads proposal uses the memory type's minimum for both shared and
+ // non-shared memories, but the upstream spec uses the memory instance's current
+ // size. We assume the upstream spec is correct for both cases.
+ // 4. Set buffer.[[ArrayBufferByteLength]] to min.
+ let block = DataBlock::external(Self::external_storage(this, vm, false), ArrayBufferShared::Yes);
+ let buffer = ArrayBuffer::create_from_data_block(vm, realm, block);
+
+ // 5. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
+ buffer.set_max_byte_length(max_size as usize);
+
+ // 6. Perform ! SetIntegrityLevel(buffer, "frozen").
+ buffer.set_integrity_level(vm, IntegrityLevel::Frozen).must();
+
+ // AD-HOC: Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
+ // SharedArrayBuffers can't be detached, but this allows us to bail early from HostGrowSharedArrayBuffer
+ // for SharedArrayBuffers not associated with a WebAssembly memory.
+ buffer.set_detach_key(detach_key(vm));
+
+ // 7. Return buffer.
+ return Ok(buffer);
+ }
+
+ // 6. Otherwise,
+ // 1. Let block be a Data Block which is identified with the underlying memory of memaddr.
+ // 4. Let buffer be a new ArrayBuffer with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferMaxByteLength]], and [[ArrayBufferDetachKey]].
+ // 5. Set buffer.[[ArrayBufferData]] to block.
+ // 2. Let length be the length of block.
+ // 6. Set buffer.[[ArrayBufferByteLength]] to length.
+ let block = DataBlock::external(Self::external_storage(this, vm, false), ArrayBufferShared::No);
+ let buffer = ArrayBuffer::create_from_data_block(vm, realm, block);
+
+ // 7. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
+ buffer.set_max_byte_length(max_size as usize);
+
+ // 8. Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
+ buffer.set_detach_key(detach_key(vm));
+
+ // 9. Return buffer.
+ Ok(buffer)
+ }
+
+ fn live_buffer_objects(&self) -> Vec<Gc<ArrayBuffer>> {
+ let mut buffer_objects = self.buffer_objects.borrow_mut();
+ buffer_objects.retain(|buffer| buffer.get().is_some());
+ buffer_objects.iter().filter_map(GcWeak::get).collect()
+ }
+
+ /// The [[BufferObject]] of the memory in the realm, which the realm's first use creates.
+ fn buffer_object(this: Ref<Self>, vm: &Vm, realm: Gc<Realm>) -> Gc<ArrayBuffer> {
+ if let Some(buffer) = this
+ .live_buffer_objects()
+ .into_iter()
+ .find(|buffer| buffer.shape().realm() == realm)
+ {
+ return buffer;
+ }
+ let buffer = Self::create_a_fixed_length_memory_buffer(this, vm, realm);
+ this.set_buffer_object(vm, buffer);
+ buffer
+ }
+
+ /// Sets the [[BufferObject]] of the memory in the realm of the buffer.
+ fn set_buffer_object(&self, vm: &Vm, buffer: Gc<ArrayBuffer>) {
+ let realm = buffer.shape().realm();
+ let mut buffer_objects = self.buffer_objects.borrow_mut();
+ buffer_objects.retain(|other| other.get().is_some_and(|other| other.shape().realm() != realm));
+ buffer_objects.push(GcWeak::new(vm.heap(), buffer));
+ }
+
+ fn has_buffer_object(&self, buffer: Gc<ArrayBuffer>) -> bool {
+ self.live_buffer_objects().contains(&buffer)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-memory-grow
+ pub(crate) fn grow(this: &Ref<Self>, cx: &mut CallContext, delta: u32) -> WebIdlResult<u32> {
+ // 1. Let memaddr be this.[[Memory]].
+ Self::grow_the_memory_buffer(*this, cx.vm(), u64::from(delta))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#grow-the-memory-buffer
+ fn grow_the_memory_buffer(this: Ref<Self>, vm: &Vm, delta: u64) -> WebIdlResult<u32> {
+ // 1. Let store be the surrounding agent's associated store.
+ // 5. Set the surrounding agent's associated store to store.
+ let previous_size = Agent::the(vm)
+ .store()
+ .memory_mut(this.address())
+ .grow(delta)
+ .ok_or_else(|| {
+ Exception::range_error("Memory.grow() grows past the stated limit of the memory instance")
+ })?;
+
+ refresh_the_memory_buffer(vm, this);
+
+ Ok(previous_size as u32)
+ }
+
+ // https://webassembly.github.io/threads/js-api/index.html#dom-memory-tofixedlengthbuffer
+ pub(crate) fn to_fixed_length_buffer(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Gc<ArrayBuffer>> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Let buffer be this.[[BufferObject]].
+ let buffer = Self::buffer_object(*this, vm, realm);
+
+ // 2. Let memaddr be this.[[Memory]].
+ // 3. If IsSharedArrayBuffer(buffer) is false,
+ if !this.shared {
+ // 1. If IsFixedLengthArrayBuffer(buffer) is true, return buffer.
+ if buffer.is_fixed_length() {
+ return Ok(buffer);
+ }
+
+ // 2. Otherwise,
+ // 1. Let fixedBuffer be the result of creating a fixed length memory buffer from memaddr.
+ let fixed_buffer = Self::create_a_fixed_length_memory_buffer(*this, vm, realm);
+
+ // 2. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
+ detach_array_buffer(vm, buffer, Some(detach_key(vm))).must();
+
+ // 3. Set this.[[BufferObject]] to fixedBuffer.
+ this.set_buffer_object(vm, fixed_buffer);
+
+ // 4. Return fixedBuffer.
+ return Ok(fixed_buffer);
+ }
+
+ // 4. Otherwise,
+ // 1. Let map be the surrounding agent's associated Memory object cache.
+ // 2. Assert: map[memaddr] exists.
+ // 3. Let newMemory be map[memaddr].
+ let new_memory: Ref<Self> = host_object(this.address().cell()).expect("the memory has a Memory object");
+
+ // 4. Let newBufferObject be newMemory.[[BufferObject]].
+ let new_buffer_object = Self::buffer_object(new_memory, vm, realm);
+
+ // 5. Set this.[[BufferObject]] to newBufferObject.
+ this.set_buffer_object(vm, new_buffer_object);
+
+ // 6. Return newBufferObject.
+ Ok(new_buffer_object)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-memory-toresizablebuffer
+ pub(crate) fn to_resizable_buffer(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Gc<ArrayBuffer>> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Let buffer be this.[[BufferObject]].
+ let buffer = Self::buffer_object(*this, vm, realm);
+
+ // 2. If IsFixedLengthArrayBuffer(buffer) is false, return buffer.
+ if !buffer.is_fixed_length() {
+ return Ok(buffer);
+ }
+
+ // 3. Let memaddr be this.[[Memory]].
+ // 4. Let store be the surrounding agent's associated store.
+ // 5. Let memtype be mem_type(store, memaddr).
+ let maximum = Agent::the(vm).store().memory(this.address()).ty.limits.max;
+
+ // 6. If memtype has a max,
+ // 1. Let maxsize be the max value in memtype.
+ // 7. Otherwise,
+ // 1. Let maxsize be 65536 x 65536.
+ let max_size = maximum.unwrap_or(65536) * PAGE_SIZE;
+
+ // 8. Let resizableBuffer be the result of creating a resizable memory buffer from memaddr and maxsize.
+ let resizable_buffer = Self::create_a_resizable_memory_buffer(*this, vm, realm, max_size)?;
+
+ // https://webassembly.github.io/threads/js-api/index.html#dom-memory-toresizablebuffer
+ // 5. If IsSharedArrayBuffer(buffer) is false,
+ // 9. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
+ if !buffer.is_shared_array_buffer() {
+ detach_array_buffer(vm, buffer, Some(detach_key(vm))).must();
+ }
+
+ // 10. Set this.[[BufferObject]] to resizableBuffer.
+ this.set_buffer_object(vm, resizable_buffer);
+
+ // 11. Return resizeableBuffer.
+ Ok(resizable_buffer)
+ }
+
+ // https://webassembly.github.io/threads/js-api/#dom-memory-buffer
+ pub(crate) fn buffer(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<Gc<ArrayBuffer>> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Let memaddr be this.[[Memory]].
+ // 2. Let block be a Data Block which is identified with the underlying memory of memaddr.
+ // 3. If block is a Shared Data Block,
+ if this.shared {
+ // 1. Let map be the surrounding agent's associated Memory object cache.
+ // 2. Assert: map[memaddr] exists.
+ // 3. Let newMemory be map[memaddr].
+ let new_memory: Ref<Self> = host_object(this.address().cell()).expect("the memory has a Memory object");
+
+ // 4. Let newBufferObject be newMemory.[[BufferObject]].
+ let new_buffer_object = Self::buffer_object(new_memory, vm, realm);
+
+ // 5. Set this.[[BufferObject]] to newBufferObject.
+ this.set_buffer_object(vm, new_buffer_object);
+
+ // 6. Return newBufferObject.
+ return Ok(new_buffer_object);
+ }
+
+ // 4. Otherwise,
+ // 1. Return this.[[BufferObject]].
+ Ok(Self::buffer_object(*this, vm, realm))
+ }
+}
+
+// https://webassembly.github.io/spec/js-api/#refresh-the-memory-buffer
+pub(crate) fn refresh_the_memory_buffer(vm: &Vm, memory: Ref<Memory>) {
+ // 1. Let map be the surrounding agent's associated Memory object cache.
+ // 2. Assert: map[memaddr] exists.
+ // 3. Let memory be map[memaddr].
+ // 4. Let buffer be memory.[[BufferObject]].
+ for buffer in memory.live_buffer_objects() {
+ // 5. If IsFixedLengthArrayBuffer(buffer) is true,
+ if buffer.is_fixed_length() {
+ // https://webassembly.github.io/threads/js-api/index.html#refresh-the-memory-buffer
+ // 1. If IsSharedArrayBuffer(buffer) is false,
+ if !buffer.is_shared_array_buffer() {
+ // 1. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
+ detach_array_buffer(vm, buffer, Some(detach_key(vm))).must();
+ }
+
+ // 2. Let newBuffer be the result of creating a fixed length memory buffer from memaddr.
+ // 3. Set memory.[[BufferObject]] to newBuffer.
+ let new_buffer = Memory::create_a_fixed_length_memory_buffer(memory, vm, buffer.shape().realm());
+ memory.set_buffer_object(vm, new_buffer);
+ } else {
+ // 1. Let block be a Data Block which is identified with the underlying memory of memaddr.
+ // AD-HOC: Neither the main spec nor the threads proposal specify that the Data Block should be Shared for
+ // shared Wasm memories, but we do in fact want a Shared Data Block in that case.
+ let is_shared = if buffer.is_shared_array_buffer() {
+ ArrayBufferShared::Yes
+ } else {
+ ArrayBufferShared::No
+ };
+
+ // 2. Set buffer.[[ArrayBufferData]] to block.
+ // 3. Set buffer.[[ArrayBufferByteLength]] to the length of block.
+ buffer.set_data_block(
+ vm,
+ DataBlock::external(Memory::external_storage(memory, vm, false), is_shared),
+ );
+ }
+ }
+}
+
+/// The Memory object whose [[BufferObject]] the buffer is, if its [[ArrayBufferDetachKey]] is "WebAssembly.Memory".
+fn memory_of_buffer(vm: &Vm, buffer: Gc<ArrayBuffer>) -> Option<Ref<Memory>> {
+ if !same_value(buffer.detach_key(), detach_key(vm)) {
+ return None;
+ }
+ // 3. For each memaddr → mem in all Memory object caches,
+ // 1. If SameValue(mem.[[BufferObject]], buffer) is true,
+ // NB: The memory whose [[BufferObject]] the buffer is owns the buffer's storage.
+ let owner = buffer.with_data_block(|block| match &block.byte_buffer {
+ DataBlockStorage::External(storage) => Some(storage.owner()),
+ _ => None,
+ })?;
+ // SAFETY: The owner of external storage is a live cell.
+ let memory = unsafe { cell_if_abi::<Memory>(owner.as_ptr()) }?;
+ // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
+ assert!(memory.has_buffer_object(buffer));
+ Some(memory)
+}
+
+/// The steps that HostResizeArrayBuffer and HostGrowSharedArrayBuffer share: whether the buffer is that of a memory,
+/// and if it is, growing the memory to the new length.
+fn grow_memory_of_buffer(vm: &Vm, buffer: Gc<ArrayBuffer>, new_length: usize) -> ThrowCompletionOr<bool> {
+ let Some(memory) = memory_of_buffer(vm, buffer) else {
+ return Ok(false);
+ };
+ let byte_length = buffer.byte_length();
+
+ // 1. Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
+ assert_eq!(byte_length as u64 % PAGE_SIZE, 0);
+
+ // 2. Let lengthDelta be newLength - buffer.[[ArrayBufferByteLength]].
+ // 3. If lengthDelta < 0 or lengthDelta modulo 65536 is not 0,
+ if new_length < byte_length || !((new_length - byte_length) as u64).is_multiple_of(PAGE_SIZE) {
+ // 1. Throw a RangeError exception.
+ return vm.throw_completion_with_message(
+ libjs_rust::api::ErrorKind::RangeError,
+ "WebAssembly.Memory buffers must be resized by a multiple of the page size".to_string(),
+ );
+ }
+
+ // 4. Let delta be lengthDelta ÷ 65536.
+ let delta = (new_length - byte_length) as u64 / PAGE_SIZE;
+
+ // 5. Grow the memory buffer associated with memaddr by delta.
+ let cx = CallContext::new(vm, buffer.shape().realm());
+ Memory::grow_the_memory_buffer(memory, vm, delta).map_err(|exception| exception.throw(&cx))?;
+ Ok(true)
+}
+
+/// HostResizeArrayBuffer(buffer, newLength), https://webassembly.github.io/spec/js-api/#HostResizeArrayBuffer, which
+/// writes whether it handled the buffer.
+///
+/// # Safety
+///
+/// The pointers must be the VM, a live ArrayBuffer, and a writable bool.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_web_assembly_host_resize_array_buffer(
+ vm: *mut c_void,
+ buffer: *mut c_void,
+ new_length: usize,
+ handled: *mut bool,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the VM and a live buffer.
+ let (vm, buffer) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new_unchecked(buffer.cast())),
+ )
+ };
+ // 1. If buffer.[[ArrayBufferDetachKey]] is "WebAssembly.Memory",
+ // 4. Return handled.
+ // 2. Otherwise, return unhandled.
+ let result = grow_memory_of_buffer(vm, buffer, new_length);
+ if let Ok(was_handled) = result {
+ // SAFETY: The caller passes a writable bool.
+ unsafe { *handled = was_handled };
+ }
+ RawNativeFunctionResult::from_completion(result.map(|_| Value::UNDEFINED))
+}
+
+/// HostGrowSharedArrayBuffer(buffer, newLength), https://webassembly.github.io/threads/js-api/#abstract-operation-hostgrowsharedarraybuffer,
+/// which writes whether it handled the buffer.
+///
+/// # Safety
+///
+/// The pointers must be the VM, a live SharedArrayBuffer, and a writable bool.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_web_assembly_host_grow_shared_array_buffer(
+ vm: *mut c_void,
+ buffer: *mut c_void,
+ new_length: usize,
+ handled: *mut bool,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the VM and a live buffer.
+ let (vm, buffer) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ Gc::from_non_null(NonNull::new_unchecked(buffer.cast::<ArrayBuffer>())),
+ )
+ };
+ // AD-HOC: If buffer.[[ArrayBufferDetachKey]] is "WebAssembly.Memory",
+ let current_byte_length = buffer.byte_length();
+ let result = grow_memory_of_buffer(vm, buffer, new_length).and_then(|was_handled| {
+ if !was_handled {
+ // AD-HOC: Otherwise, return unhandled.
+ return Ok(false);
+ }
+
+ // 4. If newLength < buffer.[[ArrayBufferByteLength]] or newLength > buffer.[[ArrayBufferMaxByteLength]], throw a RangeError exception.
+ // NB: The step cannot throw. Step 3.1.3 threw for a newLength below the byte length, and the buffer's
+ // [[ArrayBufferMaxByteLength]] is the memory's maximum, past which step 3.1.5 failed to grow.
+ if new_length < current_byte_length {
+ return vm.throw_completion(
+ libjs_rust::api::ErrorKind::RangeError,
+ libjs_rust::api::ErrorType::ByteLengthLessThanPreviousByteLength,
+ &[&new_length, &current_byte_length],
+ );
+ }
+ if new_length > buffer.max_byte_length() {
+ return vm.throw_completion(
+ libjs_rust::api::ErrorKind::RangeError,
+ libjs_rust::api::ErrorType::ByteLengthExceedsMaxByteLength,
+ &[&new_length, &buffer.max_byte_length()],
+ );
+ }
+
+ // FIXME: 5. Let agentRecord be the surrounding agent’s Agent Record.
+ // FIXME: 6. Let isLittleEndian be agentRecord.[[LittleEndian]] .
+ // FIXME: 7. Let event be an implementation defined ReadModifyWriteSharedMemory event, whose [[Order]] is "SeqCst", [[Payload]] is NumericToRawBytes(Bigint, newLength, isLittleEndian), [[Block]] is buffer.[[ArrayBufferByteLengthData]], [[ByteIndex]] is 0, and [[ElementSize]] is 8.
+ // FIXME: 8. Let eventsRecord be the EventsRecord in agentRecord.[[CandidateExecution]].[[EventsRecords]] that corresponds to the surrounding agent’s signifier agentRecord.[[Signifier]].
+ // FIXME: 9. Append event to eventsRecord.[[EventsList]].
+ assert_eq!(buffer.byte_length(), new_length);
+
+ // 10. Return handled.
+ Ok(true)
+ });
+ if let Ok(was_handled) = result {
+ // SAFETY: The caller passes a writable bool.
+ unsafe { *handled = was_handled };
+ }
+ RawNativeFunctionResult::from_completion(result.map(|_| Value::UNDEFINED))
+}
+
+impl Memory {
+ /// The Memory object that the value is, if it is the wrapper of one.
+ pub(crate) fn from_value(value: Value) -> Option<Ref<Self>> {
+ crate::web_assembly::implementation_of_value::<Self>(value)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
new file mode 100644
index 00000000000..53e51c1b692
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
@@ -0,0 +1,424 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The WebAssembly JavaScript Interface, https://webassembly.github.io/spec/js-api/, its Web API,
+//! https://webassembly.github.io/spec/web-api/, and its ESM integration,
+//! https://webassembly.github.io/esm-integration/js-api/, on the engine of Libraries/LibWasm/Engine.
+//!
+//! The engine's entities (functions, tables, memories, globals, tags and instances) and its exceptions and GC objects
+//! are cells of the agent's heap. The store keeps none of them alive: each lives while an object that stands for it,
+//! or another entity, refers to it. The engine has each cell keep the object that stands for it alive in turn
+//! (`set_host_object()`), which makes that object the cell's entry in the agent's object caches: the object stays the
+//! same one for as long as both live, and both go away together.
+
+pub(crate) mod exception;
+pub(crate) mod global;
+pub(crate) mod instance;
+pub(crate) mod memory;
+pub(crate) mod module;
+pub(crate) mod module_record;
+pub(crate) mod table;
+pub(crate) mod tag;
+#[allow(
+ clippy::module_inception,
+ reason = "the module of an IDL file is named after it, WebAssembly/WebAssembly.idl"
+)]
+pub(crate) mod web_assembly;
+
+mod builtins;
+mod errors;
+mod exported_function;
+mod gc_object;
+mod values;
+
+use core::cell::{Cell, OnceCell, RefCell, UnsafeCell};
+use core::ffi::{c_char, c_void};
+use core::ptr::NonNull;
+use std::collections::HashMap;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use libjs_rust::api::{
+ EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, GcWeak, Realm, Throw, ThrowCompletionOr,
+ Trace, Value, Visitor, Vm, is_host_instance_of,
+};
+use libwasm_engine::Module as CoreModule;
+use libwasm_engine::runtime::entity::{Entity, Handle};
+use libwasm_engine::runtime::heap::{CellTypeInfo, GcInterface, GcLayout, PrimitiveStorageLayout};
+use libwasm_engine::runtime::{InstantiationError, Store, TagAddress, Trap, Value as WasmValue};
+use libwasm_engine::types::FuncType;
+
+use crate::bindings::conversions::BufferSource;
+use crate::bindings::interface::{Interface, Ref, Wrapped, implementation_of};
+use crate::web_assembly::errors::{WebAssemblyError, throw_webassembly_error};
+use crate::web_assembly::exception::Exception;
+use crate::web_assembly::memory::{Memory, refresh_the_memory_buffer};
+use crate::web_assembly::values::{EXTERNREF, ExternValueBox, to_js_value};
+
+// https://webassembly.github.io/spec/js-api/#page-size
+pub(crate) const PAGE_SIZE: u64 = 65536;
+
+unsafe extern "C" {
+ // The functions of Libraries/LibGC/CAPI.h that the engine uses, with the types of its GcInterface.
+ fn gc_get_layout(layout: *mut GcLayout);
+ fn gc_allocator_create(type_info: *const CellTypeInfo, name: *const c_char, name_length: usize) -> *mut c_void;
+ fn gc_heap_allocate_cell(heap: *mut c_void, allocator: *mut c_void, must_mark: *mut bool) -> *mut c_void;
+ fn gc_heap_defer_gc(heap: *mut c_void);
+ fn gc_heap_undefer_gc(heap: *mut c_void);
+ fn gc_heap_collect_garbage(heap: *mut c_void, collection_type: i32, print_report: bool);
+ fn gc_heap_did_allocate_external_memory(heap: *mut c_void, size: usize);
+ fn gc_root_create(cell: *mut c_void) -> *mut c_void;
+ fn gc_root_destroy(root: *mut c_void);
+ pub(crate) fn gc_visitor_visit_cell(visitor: *mut c_void, cell: *mut c_void);
+ fn gc_visitor_visit_possible_values(visitor: *mut c_void, data: *const u8, size: usize);
+ fn gc_primitive_storage_reserve(
+ size: usize,
+ capacity: usize,
+ zero_fill: bool,
+ guard_size: usize,
+ out_handle: *mut u64,
+ out_layout: *mut PrimitiveStorageLayout,
+ ) -> bool;
+ fn gc_primitive_storage_resize(
+ handle: u64,
+ new_size: usize,
+ zero_fill: bool,
+ out_layout: *mut PrimitiveStorageLayout,
+ ) -> bool;
+ fn gc_primitive_storage_free(handle: u64);
+ fn gc_primitive_storage_data(handle: u64) -> *mut u8;
+}
+
+fn gc_interface(heap: *mut c_void) -> GcInterface {
+ GcInterface {
+ heap,
+ gc_get_layout,
+ gc_allocator_create,
+ gc_heap_allocate_cell,
+ gc_heap_defer_gc,
+ gc_heap_undefer_gc,
+ gc_heap_collect_garbage,
+ gc_heap_did_allocate_external_memory,
+ gc_root_create,
+ gc_root_destroy,
+ gc_visitor_visit_cell,
+ gc_visitor_visit_possible_values,
+ gc_primitive_storage_reserve,
+ gc_primitive_storage_resize,
+ gc_primitive_storage_free,
+ gc_primitive_storage_data,
+ }
+}
+
+/// An entity of the store, which keeps its cell alive where it is traced.
+pub(crate) struct EntityRef<T>(pub(crate) Handle<T>);
+
+impl<T> Clone for EntityRef<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<T> Copy for EntityRef<T> {}
+
+// SAFETY: The handle is the address of the entity's cell, which this visits.
+unsafe impl<T: Entity + 'static> Trace for EntityRef<T> {
+ fn trace(&self, visitor: &mut Visitor) {
+ // SAFETY: The visitor is live while it traces, and the cell is a cell of its heap.
+ unsafe { gc_visitor_visit_cell(visitor.as_raw().cast(), self.0.cell().cast()) };
+ }
+}
+
+/// An exception, a GC object, or another reference that is the address of a cell, which keeps the cell alive where it
+/// is traced.
+#[derive(Clone, Copy)]
+pub(crate) struct CellReference(pub(crate) u64);
+
+// SAFETY: The reference is the address of its cell, which this visits.
+unsafe impl Trace for CellReference {
+ fn trace(&self, visitor: &mut Visitor) {
+ // SAFETY: The visitor is live while it traces, and the reference is the address of a cell of its heap.
+ unsafe { gc_visitor_visit_cell(visitor.as_raw().cast(), self.0 as *mut c_void) };
+ }
+}
+
+/// Values of the store, which may be references that keep cells alive where they are traced, as a conservative scan
+/// of the values would. They live in a cell of their own, which a Gc in a local keeps alive. As allocating the cell can
+/// collect garbage, it is allocated empty, before there are values for it to keep alive.
+pub(crate) struct WasmValues(pub(crate) RefCell<Vec<WasmValue>>);
+
+static WASM_VALUES_CLASS: EmbedderClass<WasmValues> = EmbedderClass::new("WasmValues");
+
+impl EmbedderValue for WasmValues {
+ const CLASS: &'static EmbedderClass<Self> = &WASM_VALUES_CLASS;
+}
+
+impl WasmValues {
+ pub(crate) fn allocate(vm: &Vm) -> Gc<EmbedderCell<WasmValues>> {
+ WASM_VALUES_CLASS.allocate(vm, |_| WasmValues(RefCell::default()))
+ }
+}
+
+// SAFETY: Every cell the values refer to is at an address in their bits, which this visits as a possible value. Only
+// the edges of a cell may be visited so, which is why the values live in one.
+unsafe impl Trace for WasmValues {
+ fn trace(&self, visitor: &mut Visitor) {
+ for value in self.0.borrow().iter() {
+ let (slots, count) = value.to_slots();
+ // SAFETY: The visitor is live while it traces, and the slots are plain data.
+ unsafe {
+ gc_visitor_visit_possible_values(
+ visitor.as_raw().cast(),
+ slots.as_ptr().cast(),
+ count * size_of::<u64>(),
+ );
+ };
+ }
+ }
+}
+
+/// The surrounding agent's associated store, and the agent's caches of the objects that are not the host objects of
+/// cells: the boxes of the host value cache, https://webassembly.github.io/spec/js-api/#host-value-cache
+pub(crate) struct Agent {
+ vm: NonNull<Vm>,
+ // NB: The store must not move once it is attached to the heap.
+ store: Box<UnsafeCell<Store>>,
+ // https://webassembly.github.io/spec/js-api/#javascript-exception-tag
+ js_tag: TagAddress,
+ // NB: The root of the tag's cell, which lives as long as the agent.
+ _js_tag_root: NonNull<c_void>,
+ // NB: The module whose types are the funcTypes of the builtins, https://webassembly.github.io/spec/js-api/#builtins
+ builtin_types_module: OnceCell<CompiledModule>,
+ // NB: An entry whose box is gone is stale. Stale entries go once there are as many of them as live ones.
+ extern_value_boxes: RefCell<HashMap<u64, GcWeak<EmbedderCell<ExternValueBox>>>>,
+ live_extern_value_boxes_after_pruning: Cell<usize>,
+}
+
+thread_local! {
+ static AGENT: Cell<Option<&'static Agent>> = const { Cell::new(None) };
+}
+
+impl Agent {
+ /// The agent of the current thread, which the first use on it creates. Each thread is one agent with one VM and one
+ /// heap, which the agent outlives.
+ pub(crate) fn the(vm: &Vm) -> &'static Agent {
+ if let Some(agent) = AGENT.get() {
+ return agent;
+ }
+ let store_cell = Box::new(UnsafeCell::new(Store::with_heap(Some(gc_interface(
+ vm.heap().raw().cast(),
+ )))));
+ // SAFETY: Nothing else has the store yet.
+ let store = unsafe { &mut *store_cell.get() };
+ store.attach_to_heap();
+
+ // NB: The store is the agent's, whose [[CanBlock]] decides whether memory.atomic.wait may block.
+ store.can_block = libjs_rust::api::agent_can_suspend(vm);
+
+ let js_tag = store.allocate_tag(FuncType {
+ params: vec![EXTERNREF],
+ results: Vec::new(),
+ });
+ // NB: The tag lives as long as the agent, which roots its cell.
+ // SAFETY: The cell is a live cell of the heap.
+ let js_tag_root = NonNull::new(unsafe { gc_root_create(js_tag.cell().cast()) }).expect("a root is allocated");
+
+ // https://webassembly.github.io/spec/js-api/#memory-objects
+ // Whenever memory.grow is executed, refresh the memory buffer of the memory's Memory object, if it has one.
+ store.memory_grow_callback = Some(Rc::new(|memory| {
+ let agent = AGENT.get().expect("a store's callbacks run on the thread of its agent");
+ if let Some(object) = host_object::<EmbedderCell<Wrapped<Memory>>>(memory.cell()) {
+ refresh_the_memory_buffer(agent.vm(), object);
+ }
+ }));
+
+ let agent: &'static Agent = Box::leak(Box::new(Agent {
+ vm: NonNull::from(vm),
+ store: store_cell,
+ js_tag,
+ _js_tag_root: js_tag_root,
+ builtin_types_module: OnceCell::new(),
+ extern_value_boxes: RefCell::default(),
+ live_extern_value_boxes_after_pruning: Cell::new(0),
+ }));
+ AGENT.set(Some(agent));
+ agent
+ }
+
+ /// The agent of the current thread, which must have one.
+ pub(crate) fn current() -> &'static Agent {
+ AGENT.get().expect("the thread has an agent")
+ }
+
+ pub(crate) fn vm(&self) -> &'static Vm {
+ // SAFETY: The VM of the thread outlives its agent.
+ unsafe { self.vm.as_ref() }
+ }
+
+ /// The store, which a call into it can be on the stack below. It belongs to the thread of the agent, and is reached
+ /// the way the engine's C interface reaches it, through a pointer, for as long as any one use lasts: a caller keeps
+ /// the reference no longer than that, as the JavaScript and WebAssembly that run in between reach the store through
+ /// the agent as well.
+ #[allow(
+ clippy::mut_from_ref,
+ reason = "the store is the agent's, as an embedder of the engine holds it"
+ )]
+ pub(crate) fn store(&self) -> &mut Store {
+ // SAFETY: The agent lives as long as the thread, which is the only one that uses its store.
+ unsafe { &mut *self.store.get() }
+ }
+
+ pub(crate) fn js_tag(&self) -> TagAddress {
+ self.js_tag
+ }
+
+ pub(crate) fn builtin_types_module(&self) -> &CompiledModule {
+ self.builtin_types_module.get_or_init(|| {
+ Arc::new(
+ libwasm_engine::compile(&builtins::BUILTIN_TYPES_MODULE_BYTES)
+ .expect("the funcTypes of the builtins are a valid module"),
+ )
+ })
+ }
+
+ pub(crate) fn extern_value_box(&self, value: Value) -> Option<Gc<EmbedderCell<ExternValueBox>>> {
+ self.extern_value_boxes
+ .borrow()
+ .get(&value.to_raw())
+ .and_then(GcWeak::get)
+ }
+
+ pub(crate) fn set_extern_value_box(&self, value: Value, value_box: Gc<EmbedderCell<ExternValueBox>>) {
+ let mut boxes = self.extern_value_boxes.borrow_mut();
+ if boxes.len() >= 2 * self.live_extern_value_boxes_after_pruning.get() + 16 {
+ boxes.retain(|_, weak| weak.get().is_some());
+ self.live_extern_value_boxes_after_pruning.set(boxes.len());
+ }
+ boxes.insert(value.to_raw(), GcWeak::new(self.vm().heap(), value_box));
+ }
+}
+
+/// The object that the cell keeps alive as the one that stands for it, if it has one (`set_host_object()`).
+pub(crate) fn host_object<T>(cell: *mut u8) -> Option<Gc<T>> {
+ // SAFETY: The cell is a live cell of the runtime.
+ let object = unsafe { libwasm_engine::runtime::heap::host_object(cell.cast()) };
+ // SAFETY: Each kind of cell keeps one kind of object, which its cache stores as a cell of that type.
+ NonNull::new(object.cast::<T>()).map(|object| unsafe { Gc::from_non_null(object) })
+}
+
+/// Has the cell keep the object alive as the one that stands for it, for as long as the cell lives.
+pub(crate) fn set_host_object<T>(cell: *mut u8, object: Gc<T>) {
+ // SAFETY: The cell is a live cell of the runtime, and the object a cell of the same heap.
+ unsafe { libwasm_engine::runtime::heap::set_host_object(cell, object.as_ptr().cast()) };
+}
+
+/// The object of the interface that the value is the wrapper of, if it is one.
+pub(crate) fn implementation_of_value<T: Interface>(value: Value) -> Option<Ref<T>> {
+ if !value.is_object() || !is_host_instance_of(&value.as_object(), T::wrapper_class()) {
+ return None;
+ }
+ Some(implementation_of::<T>(value.as_object()))
+}
+
+/// A copy of the bytes held by a buffer, which the algorithms compile: their stableBytes.
+pub(crate) fn stable_bytes_of(bytes: BufferSource) -> Vec<u8> {
+ // SAFETY: Copying the bytes neither runs script nor allocates a cell.
+ unsafe { bytes.with_bytes(<[u8]>::to_vec) }
+}
+
+/// What a compiled WebAssembly module is to its objects: the module, which threads can share.
+pub(crate) type CompiledModule = Arc<CoreModule>;
+
+/// https://webassembly.github.io/spec/js-api/#compile-a-webassembly-module
+/// https://webassembly.github.io/content-security-policy/js-api/#compile-a-webassembly-module
+pub(crate) fn compile_a_webassembly_module(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ bytes: &[u8],
+) -> ThrowCompletionOr<CompiledModule> {
+ host_ensure_can_compile_wasm_bytes(realm)?;
+
+ match libwasm_engine::compile(bytes) {
+ Ok(module) => Ok(Arc::new(module)),
+ Err(error) => Err(throw_webassembly_error(
+ vm,
+ realm,
+ WebAssemblyError::Compile,
+ &error.to_string(),
+ )),
+ }
+}
+
+unsafe extern "C" {
+ /// EnsureCSPDoesNotBlockWasmByteCompilation(realm), which completes with nothing, or throws a CompileError.
+ fn web_bindings_ensure_csp_does_not_block_wasm_byte_compilation(
+ realm: *mut c_void,
+ ) -> libjs_rust::api::RawNativeFunctionResult;
+}
+
+// https://webassembly.github.io/content-security-policy/js-api/#abstract-opdef-hostensurecancompilewasmbytes
+pub(crate) fn host_ensure_can_compile_wasm_bytes(realm: Gc<Realm>) -> ThrowCompletionOr<()> {
+ // 2. Perform EnsureCSPDoesNotBlockWasmByteCompilation(realm)
+ // This algorithm does not return a value, but raises a CompileError exception if the operation cannot complete
+ // successfully.
+ // SAFETY: The realm is live.
+ unsafe { web_bindings_ensure_csp_does_not_block_wasm_byte_compilation(realm.as_ptr().cast()) }
+ .into_completion()
+ .map(|_| ())
+}
+
+/// How instantiating a module or calling a function of the store failed, as the exception it throws,
+/// https://webassembly.github.io/spec/js-api/#error-objects
+pub(crate) fn throw_of_trap(vm: &Vm, trap: Trap) -> Throw {
+ let realm = vm.current_realm().expect("WebAssembly code runs in a realm");
+ let agent = Agent::the(vm);
+ match trap {
+ // https://webassembly.github.io/spec/js-api/#stack-overflow
+ // 6.1. Whenever a stack overflow occurs in WebAssembly code, the same class of exception is thrown as for a stack overflow in JavaScript.
+ Trap::StackExhausted => {
+ thrown(vm.throw_completion(ErrorKind::InternalError, ErrorType::CallStackSizeExceeded, &[]))
+ }
+ Trap::UncaughtException(exception) => {
+ let store = agent.store();
+ // NB: An exception with the JavaScript tag carries a JavaScript value that was thrown into WebAssembly
+ // code, which continues as itself.
+ if store.exception(exception).tag == agent.js_tag() {
+ let payload = store.exception_values(exception)[0];
+ return Throw::new(to_js_value(vm, payload, EXTERNREF).unwrap_or_else(|throw| throw.value()));
+ }
+ // Otherwise, throw the Exception object of the exception.
+ Throw::new(Exception::wrapper_of_address(vm, realm, exception))
+ }
+ // FIXME: Use the convoluted mapping of errors defined in the spec.
+ trap => throw_webassembly_error(
+ vm,
+ realm,
+ WebAssemblyError::Runtime,
+ &format!("Wasm execution trapped (WIP): {}", trap.message()),
+ ),
+ }
+}
+
+pub(crate) fn throw_of_instantiation_error(vm: &Vm, error: InstantiationError) -> Throw {
+ match error {
+ InstantiationError::Link(message) => throw_webassembly_error(
+ vm,
+ vm.current_realm().expect("instantiation runs in a realm"),
+ WebAssemblyError::Link,
+ &message,
+ ),
+ InstantiationError::Trap(trap) => throw_of_trap(vm, trap),
+ }
+}
+
+fn thrown(completion: ThrowCompletionOr<()>) -> Throw {
+ match completion {
+ Err(throw) => throw,
+ Ok(()) => unreachable!("throwing a completion throws"),
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module.rs
new file mode 100644
index 00000000000..eff9c74d136
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module.rs
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Module, https://webassembly.github.io/spec/js-api/#modules
+
+use core::ffi::c_void;
+
+use ak::Utf16String;
+use libjs_rust::api::{ArrayBuffer, ArrayBufferShared, Gc, MarkedVec, Realm, Trace, Value};
+use libwasm_engine::module::{ExternalKind, ImportDescription};
+
+use crate::bindings::conversions::{BufferSource, UsvString};
+use crate::bindings::interface::{Ref, Wrappable};
+use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::web_assembly::builtins::{import_refers_to_a_builtin, validate_builtins_and_imported_strings};
+use crate::web_assembly::errors::{WebAssemblyError, throw_webassembly_error};
+use crate::web_assembly::web_assembly::WebAssemblyCompileOptions;
+use crate::web_assembly::{CompiledModule, compile_a_webassembly_module, implementation_of_value, stable_bytes_of};
+
+unsafe extern "C" {
+ /// The current Realm's corresponding agent cluster, as the ID it has if it has one.
+ fn web_bindings_current_agent_cluster(agent_cluster: *mut u64) -> bool;
+
+ /// The realm's corresponding agent cluster, as the ID it has if it has one.
+ fn web_bindings_agent_cluster_of_realm(realm: *mut c_void, agent_cluster: *mut u64) -> bool;
+}
+
+fn current_agent_cluster() -> Option<u64> {
+ let mut agent_cluster = 0;
+ // SAFETY: The agent cluster is written if there is one.
+ unsafe { web_bindings_current_agent_cluster(&raw mut agent_cluster) }.then_some(agent_cluster)
+}
+
+fn agent_cluster_of_realm(realm: Gc<Realm>) -> Option<u64> {
+ let mut agent_cluster = 0;
+ // SAFETY: The realm is live, and the agent cluster is written if there is one.
+ unsafe { web_bindings_agent_cluster_of_realm(realm.as_ptr().cast(), &raw mut agent_cluster) }
+ .then_some(agent_cluster)
+}
+
+/// https://webassembly.github.io/spec/js-api/#enumdef-importexportkind
+#[derive(Clone, Copy)]
+pub(crate) enum ImportExportKind {
+ Function,
+ Table,
+ Memory,
+ Global,
+}
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-moduleexportdescriptor
+pub(crate) struct ModuleExportDescriptor {
+ pub(crate) name: UsvString,
+ pub(crate) kind: ImportExportKind,
+}
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-moduleimportdescriptor
+pub(crate) struct ModuleImportDescriptor {
+ pub(crate) module: UsvString,
+ pub(crate) name: UsvString,
+ pub(crate) kind: ImportExportKind,
+}
+
+fn import_export_kind(kind: ExternalKind) -> Option<ImportExportKind> {
+ match kind {
+ ExternalKind::Function => Some(ImportExportKind::Function),
+ ExternalKind::Table => Some(ImportExportKind::Table),
+ ExternalKind::Memory => Some(ImportExportKind::Memory),
+ ExternalKind::Global => Some(ImportExportKind::Global),
+ ExternalKind::Tag => None,
+ }
+}
+
+fn kind_of_import(description: &ImportDescription) -> ExternalKind {
+ match description {
+ ImportDescription::Function(_) => ExternalKind::Function,
+ ImportDescription::Table(_) => ExternalKind::Table,
+ ImportDescription::Memory(_) => ExternalKind::Memory,
+ ImportDescription::Global(_) => ExternalKind::Global,
+ ImportDescription::Tag(_) => ExternalKind::Tag,
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Module {
+ // [[Module]]
+ #[gc(untraced)]
+ module: CompiledModule,
+ // [[Bytes]]
+ #[gc(untraced)]
+ bytes: Vec<u8>,
+ // [[BuiltinSets]]
+ #[gc(untraced)]
+ builtin_sets: Vec<UsvString>,
+ // [[ImportedStringModule]]
+ #[gc(untraced)]
+ imported_string_module: Option<UsvString>,
+}
+
+impl Wrappable for Module {}
+
+impl Module {
+ /// https://webassembly.github.io/spec/js-api/#construct-a-webassembly-module-object
+ pub(crate) fn new(
+ module: CompiledModule,
+ bytes: Vec<u8>,
+ builtin_sets: Vec<UsvString>,
+ imported_string_module: Option<UsvString>,
+ ) -> Self {
+ Self {
+ module,
+ bytes,
+ builtin_sets,
+ imported_string_module,
+ }
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-module-module
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ bytes: BufferSource,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<Self> {
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
+ let stable_bytes = stable_bytes_of(bytes);
+
+ // 2. Compile the WebAssembly module stableBytes and store the result as module.
+ // 3. If module is error, throw a CompileError exception.
+ let module = compile_a_webassembly_module(cx.vm(), cx.realm(), &stable_bytes)?;
+
+ // 4. Let builtinSetNames be options["builtins"].
+ let builtin_set_names = options.builtins;
+
+ // 5. Let importedStringModule be options["importedStringConstants"].
+ let imported_string_module = options.imported_string_constants;
+
+ // 6. If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns
+ // false, throw a CompileError exception.
+ if !validate_builtins_and_imported_strings(
+ cx.vm(),
+ &module,
+ &builtin_set_names,
+ imported_string_module.as_ref(),
+ ) {
+ return Err(throw_webassembly_error(
+ cx.vm(),
+ cx.realm(),
+ WebAssemblyError::Compile,
+ "Invalid builtin or imported string",
+ )
+ .into());
+ }
+
+ // 7. Set this.[[Module]] to module.
+ // 8. Set this.[[Bytes]] to stableBytes.
+ // 9. Set this.[[BuiltinSets]] to builtinSetNames.
+ // 10. Set this.[[ImportedStringModule]] to importedStringModule.
+ Ok(Self::new(
+ module,
+ stable_bytes,
+ builtin_set_names,
+ imported_string_module,
+ ))
+ }
+
+ pub(crate) fn from_value(value: Value) -> Option<Ref<Self>> {
+ implementation_of_value(value)
+ }
+
+ pub(crate) fn compiled_module(&self) -> &CompiledModule {
+ &self.module
+ }
+
+ pub(crate) fn builtin_sets(&self) -> &[UsvString] {
+ &self.builtin_sets
+ }
+
+ pub(crate) fn imported_string_module(&self) -> Option<&UsvString> {
+ self.imported_string_module.as_ref()
+ }
+
+ // https://webassembly.github.io/threads/js-api/index.html#dom-module-exports
+ pub(crate) fn exports(_: &mut CallContext, module_object: Ref<Self>) -> WebIdlResult<Vec<ModuleExportDescriptor>> {
+ // 1. Let module be moduleObject.[[Module]].
+ // 2. Let exports be « ».
+ // 3. For each (name, type) of module_exports(module),
+ let exports = module_object
+ .module
+ .exports
+ .iter()
+ .filter_map(|export| {
+ // 3.1. Let kind be the string value of the extern type type.
+ // FIXME: Exporting tags.
+ let kind = import_export_kind(export.kind)?;
+
+ // 3.2. Let obj be «[ "name" → name, "kind" → kind ]».
+ // 3.3. Append obj to exports.
+ Some(ModuleExportDescriptor {
+ name: UsvString::from_utf8(&export.name),
+ kind,
+ })
+ })
+ .collect();
+
+ // 4. Return exports.
+ Ok(exports)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-module-imports
+ pub(crate) fn imports(_: &mut CallContext, module_object: Ref<Self>) -> WebIdlResult<Vec<ModuleImportDescriptor>> {
+ // 1. Let module be moduleObject.[[Module]].
+ let module = &module_object.module;
+
+ // 2. Let builtinSetNames be moduleObject.[[BuiltinSets]].
+ let builtin_set_names = &module_object.builtin_sets;
+
+ // 3. Let importedStringModule be moduleObject.[[ImportedStringModule]].
+ let imported_string_module = module_object.imported_string_module.as_ref().map(UsvString::to_utf8);
+
+ // 4. Let imports be « ».
+ // 5. For each (moduleName, name, type) of module_imports(module),
+ let imports = module
+ .imports
+ .iter()
+ .filter_map(|import| {
+ // 1. If find a builtin for (moduleName, name, type) and builtinSetNames is not null, then continue.
+ if import_refers_to_a_builtin(import, builtin_set_names) {
+ return None;
+ }
+
+ // 2. If importedStringModule is not null and moduleName equals importedStringModule, then continue.
+ if imported_string_module.as_ref() == Some(&import.module) {
+ return None;
+ }
+
+ // 3. Let kind be the string value of the extern type type.
+ // FIXME: Importing tags.
+ let kind = import_export_kind(kind_of_import(&import.description))?;
+
+ // 4. Let obj be «[ "module" → moduleName, "name" → name, "kind" → kind ]».
+ // 5. Append obj to imports.
+ Some(ModuleImportDescriptor {
+ module: UsvString::from_utf8(&import.module),
+ name: UsvString::from_utf8(&import.name),
+ kind,
+ })
+ })
+ .collect();
+
+ // 6. Return imports.
+ Ok(imports)
+ }
+
+ // https://webassembly.github.io/threads/js-api/index.html#dom-module-customsections
+ pub(crate) fn custom_sections<'vm>(
+ cx: &mut CallContext<'vm>,
+ module_object: Ref<Self>,
+ section_name: Utf16String,
+ ) -> WebIdlResult<MarkedVec<'vm, Gc<ArrayBuffer>>> {
+ // 1. Let bytes be moduleObject.[[Bytes]].
+ // 2. Let customSections be « ».
+ let module = &module_object.module;
+ let custom_sections = MarkedVec::new(cx.vm());
+
+ // 3. For each custom section customSection of bytes, interpreted according to the module grammar,
+ for section in &module.custom_sections {
+ if Utf16String::from_utf8(&section.name) != section_name {
+ continue;
+ }
+ // 3.3.1. Append a new ArrayBuffer containing a copy of the bytes in bytes for the range matched by this customsec production to customSections.
+ let contents = &module.bytes[section.contents.start as usize..section.contents.end as usize];
+ custom_sections.push(ArrayBuffer::create_from_bytes(
+ cx.vm(),
+ cx.realm(),
+ contents,
+ ArrayBufferShared::No,
+ ));
+ }
+
+ // 4. Return customSections.
+ Ok(custom_sections)
+ }
+}
+
+impl Serializable for Module {
+ // https://webassembly.github.io/spec/web-api/#ref-for-serialization-steps
+ fn serialization_steps(
+ &self,
+ _: &mut CallContext,
+ serialized: &mut SerializationWriter,
+ for_storage: bool,
+ ) -> WebIdlResult<()> {
+ // 1. If forStorage is true, throw a "DataCloneError" DOMException.
+ if for_storage {
+ return Err(Exception::Dom(
+ "DataCloneError",
+ Utf16String::from_utf8("WebAssembly Module instances may not be serialized for storage"),
+ ));
+ }
+
+ // 2. Set serialized.[[Bytes]] to the sub-serialization of value.[[Bytes]].
+ serialized.write_bytes(&self.bytes);
+
+ // 3. Set serialized.[[AgentCluster]] to the current Realm’s corresponding agent cluster.
+ serialized.write_optional_u64(current_agent_cluster());
+
+ Ok(())
+ }
+
+ // https://webassembly.github.io/spec/web-api/#ref-for-deserialization-steps
+ fn deserialization_steps(cx: &mut CallContext, serialized: &mut SerializationReader) -> WebIdlResult<Self> {
+ // 1. Let bytes be the sub-deserialization of serialized.[[Bytes]].
+ // 2. Set value.[[Bytes]] to bytes.
+ let bytes = serialized.read_bytes()?;
+
+ // 3. If targetRealm’s corresponding agent cluster is not serialized.[[AgentCluster]], then throw a "DataCloneError" DOMException.
+ let agent_cluster = serialized.read_optional_u64()?;
+ if agent_cluster.is_none() || agent_cluster != agent_cluster_of_realm(cx.realm()) {
+ return Err(Exception::Dom(
+ "DataCloneError",
+ Utf16String::from_utf8("Cannot deserialize WebAssembly Module outside its agent cluster"),
+ ));
+ }
+
+ // 4. Compile a WebAssembly module from bytes and set value.[[Module]] to the result.
+ let module = compile_a_webassembly_module(cx.vm(), cx.realm(), &bytes)?;
+ Ok(Self::new(module, bytes, Vec::new(), None))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module_record.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module_record.rs
new file mode 100644
index 00000000000..6a4a22e45e1
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/module_record.rs
@@ -0,0 +1,633 @@
+/*
+ * Copyright (c) 2025, Glenn Skrzypczak <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The WebAssembly Module Record of the ESM integration, https://webassembly.github.io/esm-integration/js-api/: a
+//! host module whose abstract methods are those of WebAssembly modules.
+
+use core::cell::Cell;
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+use ak::Utf16FlyString;
+use libjs_rust::api::{
+ EmbedderCell, EmbedderClass, EmbedderValue, ErrorType, ForeignCellSlot, Gc, HostModule, InitializeBindingHint,
+ JS_HOST_CLASS_MODULE, JS_RESOLVED_BINDING_BINDING_NAME, JS_RESOLVED_BINDING_NULL, JSCompletion, JSHostClass,
+ JSHostModuleHooks, JSModule, JSPromiseCapability, JSResolvedBinding, JSStringSink, Module as ModuleRecord,
+ ModuleEnvironment, ModuleRequest, Must, RawNativeFunctionResult, Realm, ThrowCompletionOr, Trace, Value, Vm,
+ completion_into_abi, host_module_class_of,
+};
+use libwasm_engine::module::ImportDescription;
+use libwasm_engine::runtime::ExternValue;
+use libwasm_engine::types::{GlobalType, ValType};
+
+use crate::bindings::interface::{Ref, allocate, realm_arguments};
+use crate::web_assembly::errors::{WebAssemblyError, throw_webassembly_error};
+use crate::web_assembly::exported_function::{create_host_function, exported_function_address};
+use crate::web_assembly::global::Global;
+use crate::web_assembly::instance::{
+ Imports, Instance, function_type_in_store, global_type_in_store, instantiate_the_core_of_a_webassembly_module,
+};
+use crate::web_assembly::memory::Memory;
+use crate::web_assembly::module::Module;
+use crate::web_assembly::table::Table;
+use crate::web_assembly::tag::Tag;
+use crate::web_assembly::values::{to_js_value, to_webassembly_value};
+use crate::web_assembly::{Agent, compile_a_webassembly_module};
+
+/// The fields that a WebAssembly Module Record has besides those of a Cyclic Module Record.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+struct WebAssemblyModuleRecord {
+ // [[Instance]]
+ instance: Cell<Option<Ref<Instance>>>,
+ // [[ModuleSource]]
+ module_source: Ref<Module>,
+ // AD-HOC: The export name list, which never changes.
+ #[gc(untraced)]
+ export_name_list: Vec<Utf16FlyString>,
+}
+
+static WEBASSEMBLY_MODULE_RECORD_CLASS: EmbedderClass<WebAssemblyModuleRecord> =
+ EmbedderClass::new("WebAssemblyModuleRecord");
+
+impl EmbedderValue for WebAssemblyModuleRecord {
+ const CLASS: &'static EmbedderClass<Self> = &WEBASSEMBLY_MODULE_RECORD_CLASS;
+}
+
+static WEBASSEMBLY_MODULE_HOOKS: JSHostModuleHooks = JSHostModuleHooks {
+ get_exported_names: Some(get_exported_names),
+ resolve_export: Some(resolve_export),
+ initialize_environment: Some(initialize_environment),
+ execute_module: Some(execute_module),
+};
+
+static WEBASSEMBLY_MODULE_CLASS: JSHostClass = JSHostClass::new(
+ JS_HOST_CLASS_MODULE,
+ "WebAssemblyModule",
+ None,
+ (&raw const WEBASSEMBLY_MODULE_HOOKS).cast(),
+ 0,
+);
+
+fn is_webassembly_module_record(module: &ModuleRecord) -> bool {
+ host_module_class_of(module).is_some_and(|class| core::ptr::eq(class, &raw const WEBASSEMBLY_MODULE_CLASS))
+}
+
+fn data_of_webassembly_module_record(module: &ModuleRecord) -> Gc<EmbedderCell<WebAssemblyModuleRecord>> {
+ let module = module
+ .downcast_ref::<HostModule>()
+ .expect("a WebAssembly Module Record is a host module");
+ let data = module
+ .host_data()
+ .get()
+ .expect("a WebAssembly Module Record has its fields");
+ // SAFETY: The host data of a WebAssembly Module Record is the cell of its fields.
+ unsafe { WEBASSEMBLY_MODULE_RECORD_CLASS.downcast(data) }.expect("a WebAssembly Module Record has its fields")
+}
+
+/// # Safety
+///
+/// `module` must be a live WebAssembly Module Record.
+unsafe fn module_record_from_abi<'a>(module: *mut JSModule) -> &'a ModuleRecord {
+ // SAFETY: The caller passes a live module.
+ unsafe { &*module.cast::<ModuleRecord>() }
+}
+
+fn link_error<T>(vm: &Vm, realm: Gc<Realm>, message: &str) -> ThrowCompletionOr<T> {
+ Err(throw_webassembly_error(vm, realm, WebAssemblyError::Link, message))
+}
+
+// https://webassembly.github.io/esm-integration/js-api/index.html#parse-a-webassembly-module
+fn parse_a_webassembly_module(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ bytes: &[u8],
+ filename: String,
+ host_defined: ForeignCellSlot,
+) -> ThrowCompletionOr<Gc<HostModule>> {
+ // NB: The hooks of the record reach the store through the agent of the thread, which this ensures there is.
+ Agent::the(vm);
+
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
+ let stable_bytes = bytes.to_vec();
+
+ // 2. Compile the WebAssembly module stableBytes and store the result as module.
+ // 3. If module is error, throw a CompileError exception.
+ // NOTE: When integrating with the JS String Builtins proposal, builtinSetNames should be passed in the following
+ // step as « "js-string" » and importedStringModule as null.
+ let module = compile_a_webassembly_module(vm, realm, &stable_bytes)?;
+
+ // 5. Let requestedModules be a set.
+ let mut requested_modules: Vec<ModuleRequest> = Vec::new();
+
+ // 6. For each (moduleName, name, type) in module_imports(module.[[Module]]),
+ for import in &module.imports {
+ // 1. If moduleName starts with the prefix "wasm-js:",
+ if import.module.starts_with("wasm-js:") {
+ // 1. Throw a LinkError exception.
+ return link_error(vm, realm, "Import with invalid module name");
+ }
+
+ // 2. If name starts with the prefix "wasm:" or "wasm-js:",
+ if import.name.starts_with("wasm:") || import.name.starts_with("wasm-js:") {
+ // 1. Throw a LinkError exception.
+ return link_error(vm, realm, "Import with invalid name");
+ }
+
+ // NOTE: The following step only applies when integrating with the JS String Builtins proposal.
+ // FIXME: 3. If Find a builtin with (moduleName, name, type) and builtins module.[[BuiltinSets]] is not null,
+ // then continue.
+
+ // 4. Append moduleName to requestedModules.
+ let module_name = Utf16FlyString::from_utf8(&import.module);
+ if !requested_modules
+ .iter()
+ .any(|request| request.module_specifier == module_name)
+ {
+ requested_modules.push(ModuleRequest::new(module_name));
+ }
+ }
+
+ // 7. For each (name, type) in module_exports(module.[[Module]])
+ for export in &module.exports {
+ // 1. If name starts with the prefix "wasm:" or "wasm-js:",
+ if export.name.starts_with("wasm:") || export.name.starts_with("wasm-js:") {
+ // 1. Throw a LinkError exception.
+ return link_error(vm, realm, "Export with invalid name");
+ }
+ }
+
+ // https://webassembly.github.io/esm-integration/js-api/index.html#export-name-list
+ // 1. Let module be record’s [[ModuleSource]] internal slot.
+ // 2. Let exports be an empty list.
+ // 3. For each(name, type) in module_exports(module.[[Module]])
+ // 1. Append name to the end of exports.
+ // 4. Return exports.
+ let export_name_list = module
+ .exports
+ .iter()
+ .map(|export| Utf16FlyString::from_utf8(&export.name))
+ .collect();
+
+ // 4. Construct a WebAssembly module object from module and bytes, and let module be the result.
+ let module_source = allocate(vm, |_| Module::new(module, stable_bytes, Vec::new(), None));
+
+ // 8. Let moduleRecord be { [[Instance]]: ~empty~, [[Realm]]: realm, [[Environment]]: ~empty~,
+ // [[Namespace]]: ~empty~, [[ModuleSource]]: module, [[HostDefined]]: hostDefined,
+ // [[Status]]: "new", [[EvaluationError]]: undefined, [[DFSIndex]]: undefined,
+ // [[DFSAncestorIndex]]: undefined, [[RequestedModules]]: requestedModules,
+ // [[LoadedModules]]: « », [[CycleRoot]]: ~empty~, [[HasTLA]]: false,
+ // [[AsyncEvaluation]]: false, [[TopLevelCapability]]: ~empty~ [[AsyncParentModules]]: « »,
+ // [[PendingAsyncDependencies]]: ~empty~, }.
+ let data = WEBASSEMBLY_MODULE_RECORD_CLASS.allocate(vm, |_| WebAssemblyModuleRecord {
+ instance: Cell::new(None),
+ module_source,
+ export_name_list,
+ });
+ let host_data = ForeignCellSlot::empty();
+ // SAFETY: The fields are a live cell of the heap, which the slot then keeps alive.
+ unsafe { host_data.set(Some(NonNull::new_unchecked(data.as_ptr().cast()))) };
+ let module_record = HostModule::create(
+ vm,
+ realm,
+ &WEBASSEMBLY_MODULE_CLASS,
+ filename,
+ requested_modules,
+ host_defined,
+ host_data,
+ );
+
+ // 9. Set module.[[ModuleRecord]] to moduleRecord.
+ // NB: Nothing reads [[ModuleRecord]], which would keep the record alive from the module object.
+
+ // 10. Return moduleRecord.
+ Ok(module_record)
+}
+
+/// Parses a WebAssembly module, https://webassembly.github.io/esm-integration/js-api/index.html#parse-a-webassembly-module,
+/// for HTML's create a WebAssembly module script, and writes the WebAssembly Module Record.
+///
+/// # Safety
+///
+/// The pointers must be the VM, a live realm, `length` readable bytes, `filename_length` bytes of UTF-8, a live cell
+/// or null, and a writable module pointer.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_web_assembly_parse_a_webassembly_module(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ bytes: *const u8,
+ length: usize,
+ filename: *const u8,
+ filename_length: usize,
+ host_defined: *mut c_void,
+ module_record: *mut *mut c_void,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the VM, a live realm, and the bytes.
+ let (vm, realm, bytes, filename) = unsafe {
+ let (vm, realm) = realm_arguments(vm, realm);
+ (
+ vm,
+ realm,
+ ak::slice_from_raw_parts(bytes, length),
+ String::from_utf8_lossy(ak::slice_from_raw_parts(filename, filename_length)).into_owned(),
+ )
+ };
+ let host_defined_slot = ForeignCellSlot::empty();
+ // SAFETY: The caller passes a live cell or null, which the slot then keeps alive.
+ unsafe { host_defined_slot.set(NonNull::new(host_defined)) };
+ let result = parse_a_webassembly_module(vm, realm, bytes, filename, host_defined_slot).map(|record| {
+ // SAFETY: The caller passes a writable module pointer.
+ unsafe { *module_record = record.as_ptr().cast() };
+ Value::UNDEFINED
+ });
+ RawNativeFunctionResult::from_completion(result)
+}
+
+fn append_to_string_sink(sink: &JSStringSink, name: &Utf16FlyString) {
+ let code_units = name.to_utf16();
+ let append = sink.append.expect("a string sink appends");
+ // SAFETY: The sink takes the code units for the call.
+ unsafe { append(sink.context, code_units.as_ptr(), code_units.len()) };
+}
+
+// https://webassembly.github.io/esm-integration/js-api/index.html#get-exported-names
+unsafe extern "C" fn get_exported_names(module: *mut JSModule, names: *mut JSStringSink) {
+ // 1. Let record be this WebAssembly Module Record.
+ // SAFETY: The runtime passes the record and a sink that outlives the call.
+ let (record, names) = unsafe { (module_record_from_abi(module), &*names) };
+
+ // 2. Return the export name list of record.
+ for name in &data_of_webassembly_module_record(record).export_name_list {
+ append_to_string_sink(names, name);
+ }
+}
+
+// https://webassembly.github.io/esm-integration/js-api/index.html#resolve-export
+unsafe extern "C" fn resolve_export(
+ module: *mut JSModule,
+ export_name: *const u16,
+ export_name_length: usize,
+ out: *mut JSResolvedBinding,
+) {
+ // 1. Let record be this WebAssembly Module Record.
+ // SAFETY: The runtime passes the record, the code units of the name, and an out record.
+ let (record, export_name, out) = unsafe {
+ (
+ module_record_from_abi(module),
+ Utf16FlyString::from_utf16(if export_name_length == 0 {
+ &[]
+ } else {
+ ak::slice_from_raw_parts(export_name, export_name_length)
+ }),
+ &mut *out,
+ )
+ };
+
+ // 2. If the export name list of record contains exportName, return { [[Module]]: record, [[BindingName]]: exportName }.
+ if data_of_webassembly_module_record(record)
+ .export_name_list
+ .contains(&export_name)
+ {
+ out.module = module;
+ out.r#type = JS_RESOLVED_BINDING_BINDING_NAME;
+ append_to_string_sink(&out.binding_name, &export_name);
+ return;
+ }
+
+ // 3. Otherwise, return null.
+ out.r#type = JS_RESOLVED_BINDING_NULL;
+}
+
+// https://webassembly.github.io/esm-integration/js-api/index.html#module-declaration-environment-setup
+unsafe extern "C" fn initialize_environment(module: *mut JSModule) -> JSCompletion {
+ let vm = Agent::current().vm();
+
+ // 1. Let record be this WebAssembly Module Record.
+ // SAFETY: The runtime passes the record.
+ let record = unsafe { module_record_from_abi(module) };
+
+ // 2. Let env be NewModuleEnvironment(null).
+ let environment = ModuleEnvironment::create(vm, None);
+
+ // 3. Set record.[[Environment]] to env.
+ record.set_environment(environment);
+
+ // 4. For each name in the export name list of record,
+ for name in &data_of_webassembly_module_record(record).export_name_list {
+ // 1. Perform !env.CreateImmutableBinding(name, true).
+ environment.create_immutable_binding(vm, name, true).must();
+ }
+
+ completion_into_abi(Ok(()))
+}
+
+// https://webassembly.github.io/esm-integration/js-api/index.html#module-execution
+unsafe extern "C" fn execute_module(module: *mut JSModule, capability: *mut JSPromiseCapability) -> JSCompletion {
+ // 1. Assert: promiseCapability was not provided.
+ assert!(capability.is_null());
+
+ // 2. Let record be this WebAssembly Module Record.
+ // SAFETY: The runtime passes the record.
+ let record = unsafe { module_record_from_abi(module) };
+ completion_into_abi(execute_webassembly_module_record(Agent::current().vm(), record))
+}
+
+fn execute_webassembly_module_record(vm: &Vm, record: &ModuleRecord) -> ThrowCompletionOr<()> {
+ let record_data = data_of_webassembly_module_record(record);
+ let realm = record.realm();
+
+ // 3. Let module be record.[[ModuleSource]].[[Module]].
+ let module = record_data.module_source.compiled_module().clone();
+
+ // 4. Let imports be « ».
+ let imports = libjs_rust::api::Root::new(vm, Imports::default());
+ let mut imported_function_count = 0;
+
+ // 5. For each (importedModuleName, name, importtype) in module_imports(module),
+ for import in &module.imports {
+ // NOTE: The following step only applies when integrating with the JS String Builtins proposal.
+ // FIXME: 1. If Find a builtin with (importedModuleName, name) and builtins module.[[BuiltinSets]] is not null, then continue.
+
+ // 2. Let importedModule be GetImportedModule(record, importedModuleName).
+ let imported_module = record
+ .as_cyclic_module()
+ .expect("a host module is a Cyclic Module Record")
+ .get_imported_module(&ModuleRequest::new(Utf16FlyString::from_utf8(&import.module)));
+
+ // 3. Let resolution be importedModule.ResolveExport(name).
+ let resolution = imported_module.resolve_export(vm, &Utf16FlyString::from_utf8(&import.name));
+
+ // 4. Assert: resolution is a ResolvedBinding Record, as validated during environment initialization.
+ assert!(resolution.is_valid());
+
+ // 5. Let resolvedModule be resolution.\[[Module]].
+ let resolved_module = resolution.module.expect("a resolved binding has a module");
+
+ // 6. Let resolvedName be resolution.[[BindingName]].
+ let resolved_name = &resolution.export_name;
+
+ // 7. If resolvedModule is a WebAssembly Module Record,
+ if is_webassembly_module_record(&resolved_module) {
+ // 1. If resolvedModule.[[Instance]] is ~empty~, throw a {LinkError} exception.
+ let Some(resolved_instance) = data_of_webassembly_module_record(&resolved_module).instance.get() else {
+ return link_error(vm, realm, "Module has not been instantiated");
+ };
+
+ // 2. Assert: resolvedModule.[[Instance]] is a WebAssembly Instance object.
+ // 3. Assert: resolvedModule.[[ModuleSource]] is a WebAssembly Module object.
+ // 4. Let module be resolvedModule.[[ModuleSource]].[[Module]].
+ // 5. Let externval be instance_export(resolvedModule.[[Instance]], resolvedName).
+ // https://webassembly.github.io/spec/core/appendix/embedding.html#embed-instance-export
+ // 6. Assert: externval is not error.
+ let externval = Agent::the(vm)
+ .store()
+ .instance(resolved_instance.address())
+ .export(&String::from_utf16_lossy(&resolved_name.to_utf16()))
+ .expect("a WebAssembly module record exports what its export name list names");
+
+ // 7. Assert: module_exports(module) contains an element (resolvedName, type).
+ // 8. Let externtype be the value of type for the element (resolvedName, type) in module_exports(module).
+ // 9. If importtype is not an extern subtype of externtype, throw a LinkError exception.
+ // NB: Instantiation checks the type of every import, and throws that LinkError.
+
+ // 10. Append externval to imports.
+ imports.get().push(externval);
+ }
+ // 8. Otherwise,
+ else {
+ // 1. Let env be resolvedModule.[[Environment]].
+ let environment = resolved_module
+ .environment()
+ .expect("a linked module has an environment");
+
+ // 2. Let v be ?env.GetBindingValue(resolvedName, true).
+ let v = environment.get_binding_value(vm, resolved_name, true)?;
+
+ let import = match &import.description {
+ // 3. If importtype is of the form func functype,
+ ImportDescription::Function(type_index) => {
+ // 1. If IsCallable(v) is false, throw a LinkError exception.
+ if !v.is_function() {
+ let message = ErrorType::NotAFunction.message(&[&v.to_utf16_string_without_side_effects()]);
+ return link_error(vm, realm, &String::from_utf16_lossy(&message.to_utf16()));
+ }
+
+ // 2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
+ // 1. Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.
+ // 3. Otherwise,
+ // 1. Create a host function from v and functype, and let funcaddr be the result.
+ // 2. Let index be the number of external functions in imports, defining the index of the host function funcaddr.
+ let function = exported_function_address(v.as_object()).unwrap_or_else(|| {
+ create_host_function(
+ vm,
+ v.as_function(),
+ function_type_in_store(vm, &module, *type_index),
+ imported_function_count,
+ )
+ });
+
+ // 4. Let externfunc be the external value func funcaddr.
+ // 5. Append externfunc to imports.
+ ExternValue::Function(function)
+ }
+
+ // 4. If importtype is of the form global mut valtype,
+ ImportDescription::Global(ty) => {
+ let GlobalType {
+ value: valtype,
+ mutable,
+ } = global_type_in_store(vm, &module, *ty);
+
+ // 1. Let store be the surrounding agent’s associated store.
+ // 2. If v implements Global,
+ let global = if let Some(global) = Global::from_value(v) {
+ // 1. Let globaladdr be v.[[Global]].
+ let global = global.address();
+
+ // 2. Let targetmut valuetype be global_type(store, globaladdr).
+ let target_is_mutable = Agent::the(vm).store().global(global).ty.mutable;
+
+ // 3. If mut is const and targetmut is var, throw a LinkError exception.
+ if !mutable && target_is_mutable {
+ return link_error(vm, realm, "Mutable globals are not supported for immutable imports");
+ }
+ global
+ }
+ // 3. Otherwise,
+ else {
+ // AD-HOC: If valtype is i64 and v is a Number, throw a LinkError exception.
+ if valtype == ValType::I64 && v.is_number() {
+ return link_error(
+ vm,
+ realm,
+ "Import resolution attempted to cast a Number to a BigInteger",
+ );
+ }
+
+ // AD-HOC: If valtype is not i64 and v is a BigInt, throw a LinkError exception.
+ if valtype != ValType::I64 && v.is_bigint() {
+ return link_error(
+ vm,
+ realm,
+ "Import resolution attempted to cast a BigInteger to a Number",
+ );
+ }
+
+ // 1. If valtype is v128, throw a LinkError exception.
+ if valtype == ValType::V128 {
+ return link_error(vm, realm, "V128 is not supported as a global value type");
+ }
+
+ // 2. If mut is var, throw a LinkError exception.
+ if mutable {
+ return link_error(vm, realm, "Variable global value types are not supported");
+ }
+
+ // 3. Let value be ?ToWebAssemblyValue(v, valtype).
+ let value = to_webassembly_value(vm, v, valtype)?;
+
+ // 4. Let(store, globaladdr) be global_alloc(store, mut valtype, value).
+ // 5. Set the surrounding agent’s associated store to store.
+ Agent::the(vm).store().allocate_global(
+ GlobalType {
+ value: valtype,
+ mutable,
+ },
+ value,
+ )
+ };
+
+ // 4. Let externglobal be global globaladdr.
+ // 5. Append externglobal to imports.
+ ExternValue::Global(global)
+ }
+
+ // 5. If importtype is of the form mem memtype,
+ ImportDescription::Memory(_) => {
+ // 1. If v does not implement Memory, throw a LinkError exception.
+ let Some(memory) = Memory::from_value(v) else {
+ return link_error(
+ vm,
+ realm,
+ "Expected an instance of WebAssembly.Memory for a memory import",
+ );
+ };
+
+ // 2. Let externmem be the external value mem v.[[Memory]].
+ // 3. Append externmem to imports.
+ ExternValue::Memory(memory.address())
+ }
+
+ // 6. If importtype is of the form table tabletype,
+ ImportDescription::Table(_) => {
+ // 1. If v does not implement Table, throw a LinkError exception.
+ let Some(table) = Table::from_value(v) else {
+ return link_error(
+ vm,
+ realm,
+ "Expected an instance of WebAssembly.Table for a table import",
+ );
+ };
+
+ // 2. Let tableaddr be v.[[Table]].
+ // 3. Let externtable be the external value table tableaddr.
+ // 4. Append externtable to imports.
+ ExternValue::Table(table.address())
+ }
+
+ // 7. If importtype is of the form tag attribute functype,
+ ImportDescription::Tag(_) => {
+ // 1. Assert: attribute is exception.
+ // 2. If v does not implement Tag, throw a LinkError exception.
+ let Some(tag) = Tag::from_value(v) else {
+ return link_error(vm, realm, "Expected an instance of WebAssembly.Tag for a tag import");
+ };
+
+ // 3. Let tagaddr be v.[[Address]].
+ // 4. Let externtag be the external value tag tagaddr.
+ // 5. Append externtag to imports.
+ ExternValue::Tag(tag.address())
+ }
+ };
+ imports.get().push(import);
+ }
+
+ if matches!(import.description, ImportDescription::Function(_)) {
+ imported_function_count += 1;
+ }
+ }
+
+ // 6. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
+ let instance_address = instantiate_the_core_of_a_webassembly_module(vm, &module, imports.get())?;
+
+ // 7. Set record.[[Instance]] to instance.
+ let instance = allocate(vm, |_| Instance::initialize(vm, realm, instance_address));
+ record_data.instance.set(Some(instance));
+
+ let environment = record.environment().expect("an evaluated module has an environment");
+
+ // 8. For each (name, externtype) of module_exports(module),
+ // NB: Converting a global's value may reach the store, so nothing of it stays borrowed across the conversion.
+ for export in &module.exports {
+ let name = Utf16FlyString::from_utf8(&export.name);
+ let externval = Agent::the(vm)
+ .store()
+ .instance(instance_address)
+ .export(&export.name)
+ .expect("an instance has every export of its module");
+
+ // 1. If externtype is of the form global mut globaltype,
+ if let ExternValue::Global(global) = externval {
+ // 1. Assert: externval is of the form global globaladdr.
+ // 2. Let global globaladdr be externval.
+ // 3. Let global_value be global_read(store, globaladdr).
+ let (global_value, globaltype) = {
+ let global = Agent::the(vm).store().global(global);
+ (global.get(), global.ty.value)
+ };
+
+ // 4. If globaltype is not v128,
+ if globaltype != ValType::V128 {
+ // NOTE: The condition above leaves unsupported JS values as uninitialized in TDZ and therefore as a
+ // reference error on access. When integrating with shared globals, they may be excluded here
+ // similarly to v128 above.
+
+ // 1. Perform !record.[[Environment]].InitializeBinding(name, ToJSValue(global_value)).
+ let value = to_js_value(vm, global_value, globaltype)?;
+ environment
+ .initialize_binding(vm, &name, value, InitializeBindingHint::Normal)
+ .must();
+
+ // FIXME: 2. If mut is var, then associate all future mutations of globaladdr with the ECMA-262 binding record
+ // for name in record.[[Environment]], such that record.[[Environment]].GetBindingValue(resolution.[[BindingName]], true)
+ // always returns ToJSValue(global_read(store, globaladdr)) for the current surrounding agent’s associated store store.
+ }
+ }
+ // 2. Otherwise,
+ else {
+ // 1. Perform !record.[[Environment]].InitializeBinding(name, !Get(instance.[[Exports]], name)).
+ let exports = instance
+ .exports(&mut crate::bindings::CallContext::new(vm, realm))
+ .ok()
+ .expect("an instance has its exports");
+ let value = exports
+ .get(vm, &libjs_rust::api::PropertyKey::from(name.clone()))
+ .must();
+ environment
+ .initialize_binding(vm, &name, value, InitializeBindingHint::Normal)
+ .must();
+ }
+ }
+
+ // NOTE: The linking semantics here for Wasm to Wasm modules are identical to the WebAssembly JS API semantics as if
+ // passing the the exports object as the imports object in instantiation. When linking Wasm module imports to
+ // JS module exports, the JS API semantics are exactly followed as well. It is only in the case of importing
+ // Wasm from JS that WebAssembly.Global unwrapping is observable on the WebAssembly Module Record Environment
+ // Record.
+
+ Ok(())
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/table.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/table.rs
new file mode 100644
index 00000000000..4addf99958e
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/table.rs
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Table, https://webassembly.github.io/spec/js-api/#tables
+
+use libjs_rust::api::{BigInt, Trace, Value, Vm};
+use libwasm_engine::runtime::{TableAddress, TableInstance, Value as WasmValue};
+use libwasm_engine::types::{AddressType as CoreAddressType, HeapType, Limits, RefType, TableType, ValType};
+
+use crate::bindings::conversions::to_unsigned_long_enforcing_range;
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::web_assembly::values::{default_webassembly_value, to_js_value, to_webassembly_value};
+use crate::web_assembly::{Agent, EntityRef, host_object, implementation_of_value, set_host_object};
+
+/// https://webassembly.github.io/spec/js-api/#enumdef-addresstype
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AddressType {
+ I32,
+ I64,
+}
+
+/// https://webassembly.github.io/spec/js-api/#enumdef-tablekind
+#[derive(Clone, Copy)]
+pub(crate) enum TableKind {
+ Externref,
+ Anyfunc,
+}
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-tabledescriptor
+pub(crate) struct TableDescriptor {
+ pub(crate) element: TableKind,
+ pub(crate) initial: Value,
+ pub(crate) maximum: Option<Value>,
+ pub(crate) address: Option<AddressType>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Table {
+ // [[Table]]
+ address: EntityRef<TableInstance>,
+}
+
+impl Wrappable for Table {}
+
+// https://webassembly.github.io/spec/js-api/#addressvaluetou64
+fn address_value_to_u64(vm: &Vm, value: Value, address64: bool) -> WebIdlResult<u64> {
+ if address64 {
+ let n = value.to_bigint(vm)?;
+
+ return n
+ .to_u64_if_exact()
+ .ok_or_else(|| Exception::type_error("The table address value is out of range"));
+ }
+
+ Ok(u64::from(to_unsigned_long_enforcing_range(vm, value)?))
+}
+
+// https://webassembly.github.io/spec/js-api/#u64toaddressvalue
+fn u64_to_address_value(vm: &Vm, value: u64, address64: bool) -> Value {
+ if address64 {
+ return Value::from_bigint(BigInt::create_from_u64(vm, value));
+ }
+
+ Value::from_f64(value as f64)
+}
+
+impl Table {
+ // https://webassembly.github.io/spec/js-api/#dom-table-table
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ descriptor: TableDescriptor,
+ value: Option<Value>,
+ ) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+
+ // 1. Let elementtype be ToValueType(descriptor["element"]).
+ // NB: The TableKind enumeration only has reference types.
+ let element = RefType {
+ nullable: true,
+ heap: match descriptor.element {
+ TableKind::Externref => HeapType::Extern,
+ TableKind::Anyfunc => HeapType::Func,
+ },
+ };
+
+ // 3. If descriptor["address"] exists, let addrtype be descriptor["address"]; otherwise, let addrtype be "i32".
+ let address64 = descriptor.address == Some(AddressType::I64);
+
+ // 4. Let initial be ? AddressValueToU64(descriptor["initial"], addrtype).
+ let initial = address_value_to_u64(vm, descriptor.initial, address64)?;
+
+ let maximum = descriptor
+ .maximum
+ .map(|maximum| address_value_to_u64(vm, maximum, address64))
+ .transpose()?;
+
+ if maximum.is_some_and(|maximum| maximum < initial) {
+ return Err(Exception::range_error(
+ "Maximum should not be less than initial in table type",
+ ));
+ }
+
+ let reference = reference_of(Self::value_or_default(vm, ValType::Ref(element), value)?);
+
+ // 11. Let (store, tableaddr) be table_alloc(store, type, ref). If allocation fails, throw a RangeError exception.
+ // 12. Set the surrounding agent's associated store to store.
+ let table = Agent::the(vm)
+ .store()
+ .allocate_table(
+ TableType {
+ element,
+ limits: Limits {
+ min: initial,
+ max: maximum,
+ address_type: if address64 {
+ CoreAddressType::I64
+ } else {
+ CoreAddressType::I32
+ },
+ shared: false,
+ },
+ },
+ reference,
+ )
+ .ok_or_else(|| Exception::range_error("Wasm Table allocation failed"))?;
+
+ // 13. Initialize this from tableaddr.
+ Ok(Self::initialize(vm, table))
+ }
+
+ fn value_or_default(vm: &Vm, ty: ValType, value: Option<Value>) -> WebIdlResult<WasmValue> {
+ Ok(match value {
+ None => default_webassembly_value(vm, ty),
+ Some(value) => to_webassembly_value(vm, value, ty)?,
+ })
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-a-table-object
+ fn initialize(vm: &Vm, table: TableAddress) -> Ref<Self> {
+ // 2. Assert: map[tableaddr] doesn't exist.
+ assert!(host_object::<()>(table.cell()).is_none());
+
+ // 3. Set table.[[Table]] to tableaddr.
+ let object = allocate(vm, |_| Self {
+ address: EntityRef(table),
+ });
+
+ // 4. Set map[tableaddr] to table.
+ set_host_object(table.cell(), object);
+ object
+ }
+
+ /// The Table object of the table, https://webassembly.github.io/spec/js-api/#create-a-table-object
+ pub(crate) fn from_address(vm: &Vm, table: TableAddress) -> Ref<Self> {
+ if let Some(object) = host_object(table.cell()) {
+ return object;
+ }
+
+ Self::initialize(vm, table)
+ }
+
+ pub(crate) fn from_value(value: Value) -> Option<Ref<Self>> {
+ implementation_of_value(value)
+ }
+
+ pub(crate) fn address(&self) -> TableAddress {
+ self.address.0
+ }
+
+ fn ty(&self, vm: &Vm) -> TableType {
+ Agent::the(vm).store().table(self.address()).ty
+ }
+
+ fn is_address64(&self, vm: &Vm) -> bool {
+ self.ty(vm).limits.address_type == CoreAddressType::I64
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-table-grow
+ pub(crate) fn grow(&self, cx: &mut CallContext, delta: Value, value: Option<Value>) -> WebIdlResult<Value> {
+ let vm = cx.vm();
+
+ // 3. Let initialSize be table_size(store, tableaddr).
+ let ty = self.ty(vm);
+ let address64 = ty.limits.address_type == CoreAddressType::I64;
+
+ let delta = address_value_to_u64(vm, delta, address64)?;
+
+ // 7. Otherwise,
+ let reference = reference_of(Self::value_or_default(vm, ValType::Ref(ty.element), value)?);
+
+ // 10. Set the surrounding agent's associated store to result.
+ let initial_size = Agent::the(vm)
+ .store()
+ .table_mut(self.address())
+ .grow(delta, reference)
+ .ok_or_else(|| Exception::range_error("Failed to grow table"))?;
+
+ Ok(u64_to_address_value(vm, initial_size, address64))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-table-length
+ pub(crate) fn length(&self, cx: &mut CallContext) -> WebIdlResult<Value> {
+ let vm = cx.vm();
+
+ let length = Agent::the(vm).store().table(self.address()).elements.len() as u64;
+
+ Ok(u64_to_address_value(vm, length, self.is_address64(vm)))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-table-get
+ pub(crate) fn get(&self, cx: &mut CallContext, index: Value) -> WebIdlResult<Value> {
+ let vm = cx.vm();
+
+ // 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
+ let ty = self.ty(vm);
+
+ if matches!(ty.element.heap, HeapType::Exn | HeapType::NoExn) {
+ return Err(Exception::type_error("Cannot get an exnref table element"));
+ }
+
+ let index = address_value_to_u64(vm, index, ty.limits.address_type == CoreAddressType::I64)?;
+
+ // 6. Let result be table_read(store, tableaddr, index64).
+ // 7. If result is error, throw a RangeError exception.
+ let reference = usize::try_from(index)
+ .ok()
+ .and_then(|index| {
+ Agent::the(vm)
+ .store()
+ .table(self.address())
+ .elements
+ .get(index)
+ .copied()
+ })
+ .ok_or_else(|| Exception::range_error("Table element index out of range"))?;
+
+ Ok(to_js_value(vm, WasmValue::Ref(reference), ValType::Ref(ty.element))?)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-table-set
+ pub(crate) fn set(&self, cx: &mut CallContext, index: Value, value: Option<Value>) -> WebIdlResult<()> {
+ let vm = cx.vm();
+
+ // 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
+ let ty = self.ty(vm);
+
+ if matches!(ty.element.heap, HeapType::Exn | HeapType::NoExn) {
+ return Err(Exception::type_error("Cannot set an exnref table element"));
+ }
+
+ let index = address_value_to_u64(vm, index, ty.limits.address_type == CoreAddressType::I64)?;
+
+ // 7. Otherwise,
+ let reference = reference_of(Self::value_or_default(vm, ValType::Ref(ty.element), value)?);
+
+ // 8. Let store be table_write(store, tableaddr, index64, ref).
+ // 9. If store is error, throw a RangeError exception.
+ // 10. Set the surrounding agent's associated store to store.
+ let element = usize::try_from(index)
+ .ok()
+ .and_then(|index| Agent::the(vm).store().table_mut(self.address()).elements.get_mut(index))
+ .ok_or_else(|| Exception::range_error("Table element index out of range"))?;
+ *element = reference;
+ Ok(())
+ }
+}
+
+fn reference_of(value: WasmValue) -> u64 {
+ match value {
+ WasmValue::Ref(reference) => reference,
+ _ => unreachable!("a table holds references"),
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/tag.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/tag.rs
new file mode 100644
index 00000000000..7ad29599999
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/tag.rs
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Tag, https://webassembly.github.io/spec/js-api/#tags
+
+use libjs_rust::api::{Gc, Realm, Trace, Value, Vm};
+use libwasm_engine::runtime::{TagAddress, TagInstance};
+use libwasm_engine::types::FuncType;
+
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::realm_data::realm_data;
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::web_assembly::global::ValueType;
+use crate::web_assembly::{Agent, EntityRef, host_object, implementation_of_value, set_host_object};
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-tagtype
+pub(crate) struct TagType {
+ pub(crate) parameters: Vec<ValueType>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Tag {
+ // [[Address]]
+ address: EntityRef<TagInstance>,
+}
+
+impl Wrappable for Tag {}
+
+impl Tag {
+ // https://webassembly.github.io/spec/js-api/#dom-tag-tag
+ pub(crate) fn construct(cx: &mut CallContext, r#type: TagType) -> WebIdlResult<Ref<Self>> {
+ // 1. Let parameters be type["parameters"].
+ // 2. Let wasmParameters be «».
+ // 3. For each type of parameters,
+ // 1. Append ToValueType(type) to wasmParameters.
+ let parameters = r#type
+ .parameters
+ .iter()
+ .map(|parameter| parameter.to_value_type())
+ .collect();
+
+ // 4. Let store be the surrounding agent's associated store.
+ // 5. Let (store, tagAddress) be tag_alloc(store, « wasmParameters » → « »).
+ // 6. Set the surrounding agent's associated store to store.
+ let tag = Agent::the(cx.vm()).store().allocate_tag(FuncType {
+ params: parameters,
+ results: Vec::new(),
+ });
+
+ // 7. Initialize this from tagAddress.
+ Ok(Self::initialize(cx.vm(), tag))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#initialize-a-tag-object
+ fn initialize(vm: &Vm, tag: TagAddress) -> Ref<Self> {
+ // 1. Let map be the surrounding agent's associated tag object cache.
+ // 3. Set tag.[[Address]] to tagAddress.
+ let object = allocate(vm, |_| Self {
+ address: EntityRef(tag),
+ });
+
+ // 4. Set map[tagAddress] to tag.
+ set_host_object(tag.cell(), object);
+ object
+ }
+
+ /// The Tag object of the tag in the realm, https://webassembly.github.io/spec/js-api/#create-a-tag-object
+ pub(crate) fn from_address(vm: &Vm, realm: Gc<Realm>, tag: TagAddress) -> Ref<Self> {
+ // NB: The JavaScript exception tag lives as long as the agent, while a Tag object belongs to the realm it is
+ // first wrapped in, so every realm has a Tag object of its own for it.
+ if tag == Agent::the(vm).js_tag() {
+ let data = realm_data(vm, realm);
+ if let Some(object) = data.webassembly_js_tag.get() {
+ return object;
+ }
+ let object = allocate(vm, |_| Self {
+ address: EntityRef(tag),
+ });
+ data.webassembly_js_tag.set(Some(object));
+ return object;
+ }
+
+ // 1. Let map be the surrounding agent's associated tag object cache.
+ // 2. If map[tagAddress] exists,
+ // 1. Return map[tagAddress].
+ if let Some(object) = host_object(tag.cell()) {
+ return object;
+ }
+
+ // 3. Let tag be a new Tag.
+ // 4. Initialize tag from tagAddress.
+ // 5. Return tag.
+ Self::initialize(vm, tag)
+ }
+
+ pub(crate) fn from_value(value: Value) -> Option<Ref<Self>> {
+ implementation_of_value(value)
+ }
+
+ pub(crate) fn address(&self) -> TagAddress {
+ self.address.0
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/values.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/values.rs
new file mode 100644
index 00000000000..0ea93821e8c
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/values.rs
@@ -0,0 +1,275 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The conversions between JavaScript values and WebAssembly values, https://webassembly.github.io/spec/js-api/#tojsvalue
+//!
+//! References are encoded so that their kind shows in their low bits: an i31 has bit 0 set, and a host value has bits
+//! 1:0 equal to 0b10. A host value is the address of a cell with bit 1 set, which keeps the cell alive wherever
+//! WebAssembly keeps the reference. Functions, structs, arrays and exceptions are the addresses of their cells.
+
+use core::ptr::NonNull;
+
+use libjs_rust::api::{
+ Array, BigInt, CellHeader, CellKind, EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, Gc, Object,
+ ThrowCompletionOr, Trace, Value, Vm,
+};
+use libwasm_engine::runtime::Value as WasmValue;
+use libwasm_engine::types::{HeapType, RefType, ValType};
+
+use crate::web_assembly::Agent;
+use crate::web_assembly::exported_function::{create_exported_function, exported_function_address};
+use crate::web_assembly::gc_object::{create_exported_gc_object, exported_gc_object_address};
+
+const I31_REFERENCE_BIT: u64 = 0b01;
+const HOST_REFERENCE_TAG: u64 = 0b10;
+const REFERENCE_TAG_MASK: u64 = 0b11;
+
+/// A JavaScript value that is not a cell, boxed so that WebAssembly can refer to it as a host value.
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct ExternValueBox {
+ value: Value,
+}
+
+static EXTERN_VALUE_BOX_CLASS: EmbedderClass<ExternValueBox> = EmbedderClass::new("ExternValueBox");
+
+impl EmbedderValue for ExternValueBox {
+ const CLASS: &'static EmbedderClass<Self> = &EXTERN_VALUE_BOX_CLASS;
+}
+
+pub(crate) const EXTERNREF: ValType = ValType::Ref(RefType {
+ nullable: true,
+ heap: HeapType::Extern,
+});
+
+fn host_reference_of(vm: &Vm, value: Value) -> u64 {
+ let cell = if value.is_cell() {
+ value.as_cell().as_ptr().cast::<u8>()
+ } else {
+ // NB: A value gets the same box while references to the box keep it alive, so that it converts to the same
+ // reference.
+ let agent = Agent::the(vm);
+ let value_box = agent.extern_value_box(value).unwrap_or_else(|| {
+ let value_box = EXTERN_VALUE_BOX_CLASS.allocate(vm, |_| ExternValueBox { value });
+ agent.set_extern_value_box(value, value_box);
+ value_box
+ });
+ value_box.as_ptr().cast::<u8>()
+ };
+ cell as u64 | HOST_REFERENCE_TAG
+}
+
+fn value_of_host_reference(reference: u64) -> Value {
+ let address = (reference & !REFERENCE_TAG_MASK) as *mut CellHeader;
+ // SAFETY: A host reference is the address of a live cell, which starts with its header.
+ let kind = unsafe { (*address).kind };
+ // SAFETY: The kind of the cell says what it is.
+ unsafe {
+ match kind {
+ CellKind::Object => Value::from_object(Gc::from_non_null(NonNull::new_unchecked(address.cast::<Object>()))),
+ CellKind::PrimitiveString => Value::from_string(Gc::from_non_null(NonNull::new_unchecked(address.cast()))),
+ CellKind::Symbol => Value::from_symbol(Gc::from_non_null(NonNull::new_unchecked(address.cast()))),
+ CellKind::BigInt => Value::from_bigint(Gc::from_non_null(NonNull::new_unchecked(address.cast()))),
+ CellKind::Other => {
+ let value_box: Gc<EmbedderCell<ExternValueBox>> =
+ Gc::from_non_null(NonNull::new_unchecked(address.cast()));
+ value_box.value
+ }
+ CellKind::Accessor => unreachable!("an accessor is no JavaScript value"),
+ }
+ }
+}
+
+fn i31_reference_of(value: Value) -> Option<u64> {
+ const I31_MINIMUM: f64 = -((1 << 30) as f64);
+ const I31_MAXIMUM: f64 = ((1 << 30) - 1) as f64;
+ if !value.is_number() {
+ return None;
+ }
+ let number = value.as_f64();
+ if !(I31_MINIMUM..=I31_MAXIMUM).contains(&number)
+ || number != number.trunc()
+ || (number == 0.0 && number.is_sign_negative())
+ {
+ return None;
+ }
+ Some((u64::from((number as i32 as u32) & 0x7fff_ffff) << 1) | I31_REFERENCE_BIT)
+}
+
+fn value_of_i31_reference(reference: u64) -> i32 {
+ // The value is in bits 31:1, so an arithmetic shift of the low 32 bits sign-extends it.
+ (reference as u32 as i32) >> 1
+}
+
+/// The internal form of a JavaScript value as a reference of the any hierarchy: an i31 reference for a Number in its
+/// range, the struct or array of an Exported GC Object, and otherwise a host reference.
+fn internalized_reference_of(vm: &Vm, value: Value) -> u64 {
+ if let Some(reference) = i31_reference_of(value) {
+ return reference;
+ }
+ if value.is_object()
+ && let Some(address) = exported_gc_object_address(value.as_object())
+ {
+ return address;
+ }
+ host_reference_of(vm, value)
+}
+
+/// Whether a reference type is of the func hierarchy, whose references are functions.
+fn is_function_reference_type(vm: &Vm, heap: HeapType) -> bool {
+ match heap {
+ HeapType::Concrete(identity) => Agent::the(vm).store().is_function_type(identity),
+ HeapType::Func | HeapType::NoFunc => true,
+ _ => false,
+ }
+}
+
+fn type_error<T>(vm: &Vm, message: &str) -> ThrowCompletionOr<T> {
+ vm.throw_completion_with_message(ErrorKind::TypeError, message.to_string())
+}
+
+// https://webassembly.github.io/spec/js-api/#towebassemblyvalue
+fn to_webassembly_reference(vm: &Vm, value: Value, ty: RefType) -> ThrowCompletionOr<u64> {
+ // If v is null: if the type is nullable, return ref.null of its heap type, and otherwise throw a TypeError.
+ if value.is_null() {
+ if !ty.nullable {
+ return type_error(vm, "Cannot convert null to a non-nullable reference");
+ }
+ return Ok(0);
+ }
+
+ match ty.heap {
+ HeapType::Exn | HeapType::NoExn => {
+ return type_error(vm, "Cannot convert a JavaScript value to an exception reference");
+ }
+ HeapType::NoFunc | HeapType::NoExtern | HeapType::None | HeapType::Bottom => {
+ return type_error(vm, "Only null converts to a bottom reference type");
+ }
+ // NB: An externref keeps the bits of the anyref it externalizes.
+ HeapType::Extern => return Ok(internalized_reference_of(vm, value)),
+ _ => {}
+ }
+
+ // If the type is of the func hierarchy, only an Exported Function of a matching type converts, to its function.
+ if is_function_reference_type(vm, ty.heap) {
+ if value.is_function()
+ && let Some(address) = exported_function_address(value.as_object())
+ {
+ let store = Agent::the(vm).store();
+ let reference = store.function_reference(address);
+ if store.reference_matches(reference, ty.heap) {
+ return Ok(reference);
+ }
+ }
+ return type_error(vm, "Cannot convert the value to a function reference of this type");
+ }
+
+ // Otherwise the type is of the any hierarchy: the internal form of v converts if it matches the type.
+ let reference = internalized_reference_of(vm, value);
+ if !Agent::the(vm).store().reference_matches(reference, ty.heap) {
+ return type_error(vm, "Cannot convert the value to a reference of this type");
+ }
+ Ok(reference)
+}
+
+/// ToWebAssemblyValue(v, type), https://webassembly.github.io/spec/js-api/#towebassemblyvalue, for a type in the store's
+/// terms (see Store::module_type_identities()).
+pub(crate) fn to_webassembly_value(vm: &Vm, value: Value, ty: ValType) -> ThrowCompletionOr<WasmValue> {
+ Ok(match ty {
+ ValType::I64 => WasmValue::I64(value.to_bigint_int64(vm)?),
+ ValType::I32 => WasmValue::I32(value.to_i32(vm)?),
+ ValType::F64 => WasmValue::F64(value.to_double(vm)?.to_bits()),
+ ValType::F32 => WasmValue::F32((value.to_double(vm)? as f32).to_bits()),
+ ValType::V128 => return type_error(vm, "Cannot convert a javascript value to a vector value"),
+ ValType::Ref(ty) => WasmValue::Ref(to_webassembly_reference(vm, value, ty)?),
+ })
+}
+
+/// DefaultValue(valuetype), https://webassembly.github.io/spec/js-api/#defaultvalue
+pub(crate) fn default_webassembly_value(vm: &Vm, ty: ValType) -> WasmValue {
+ // 1. If valuetype equals externref, return ToWebAssemblyValue(undefined, valuetype).
+ if let ValType::Ref(RefType {
+ heap: HeapType::Extern, ..
+ }) = ty
+ {
+ return WasmValue::Ref(host_reference_of(vm, Value::UNDEFINED));
+ }
+
+ // 2. Return DefaultValue(valuetype).
+ WasmValue::default_for(ty)
+}
+
+/// ToJSValue(w), https://webassembly.github.io/spec/js-api/#tojsvalue, for a value of the type, which is in the store's
+/// terms.
+pub(crate) fn to_js_value(vm: &Vm, value: WasmValue, ty: ValType) -> ThrowCompletionOr<Value> {
+ let reference = match (value, ty) {
+ (WasmValue::I64(value), _) => return Ok(Value::from_bigint(BigInt::create_from_i64(vm, value))),
+ (WasmValue::I32(value), _) => return Ok(Value::from_i32(value)),
+ (WasmValue::F64(bits), _) => return Ok(Value::from_f64(f64::from_bits(bits))),
+ (WasmValue::F32(bits), _) => return Ok(Value::from_f64(f64::from(f32::from_bits(bits)))),
+ (WasmValue::V128(_), _) => return type_error(vm, "Cannot convert a vector value to a javascript value"),
+ (WasmValue::Ref(reference), _) => reference,
+ };
+ let ValType::Ref(ty) = ty else {
+ unreachable!("a reference has a reference type");
+ };
+
+ if matches!(ty.heap, HeapType::Exn | HeapType::NoExn) {
+ return type_error(vm, "Cannot convert an exception reference to a javascript value");
+ }
+
+ // 1. If w is of the form ref.null t, return null.
+ if reference == 0 {
+ return Ok(Value::NULL);
+ }
+
+ // 2. If w is of the form ref.func funcaddr, return the result of creating a new Exported Function from funcaddr.
+ if is_function_reference_type(vm, ty.heap) {
+ let function = Agent::the(vm)
+ .store()
+ .function_from_reference(reference)
+ .expect("a function reference that is not null is a function");
+ let realm = vm.current_realm().expect("a conversion runs in a realm");
+ return Ok(Value::from_object(
+ create_exported_function(vm, realm, function).upcast::<Object>(),
+ ));
+ }
+
+ // 3. If w is of the form ref.i31 u31, return 𝔽(signed_31(u31)).
+ if reference & I31_REFERENCE_BIT != 0 {
+ return Ok(Value::from_i32(value_of_i31_reference(reference)));
+ }
+
+ // 4. If w is of the form ref.host hostaddr, return the result of retrieving a host value from hostaddr.
+ // NB: An externref of a host value keeps the bits of the host reference.
+ if reference & REFERENCE_TAG_MASK == HOST_REFERENCE_TAG {
+ return Ok(value_of_host_reference(reference));
+ }
+
+ // 5. If w is of the form ref.struct structaddr or ref.array arrayaddr, return the result of creating a new Exported
+ // GC Object from it.
+ Ok(Value::from_object(create_exported_gc_object(vm, reference)))
+}
+
+/// The JavaScript value of the results of a call: undefined for none, the one result, or an array of them.
+pub(crate) fn results_to_js_value(vm: &Vm, results: &[WasmValue], types: &[ValType]) -> ThrowCompletionOr<Value> {
+ match results {
+ [] => Ok(Value::UNDEFINED),
+ [result] => to_js_value(vm, *result, types[0]),
+ _ => {
+ let values = libjs_rust::api::MarkedVec::with_capacity(vm, results.len());
+ for (result, ty) in results.iter().zip(types) {
+ values.push(to_js_value(vm, *result, *ty)?);
+ }
+ let realm = vm.current_realm().expect("a conversion runs in a realm");
+ Ok(Value::from_object(
+ Array::create_from(vm, realm, &values.values()).upcast::<Object>(),
+ ))
+ }
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs
new file mode 100644
index 00000000000..128df518040
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/web_assembly.rs
@@ -0,0 +1,582 @@
+/*
+ * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
+ * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The WebAssembly namespace, https://webassembly.github.io/spec/js-api/#webassembly-namespace, and its streaming
+//! functions, https://webassembly.github.io/spec/web-api/index.html#streaming-modules
+
+use core::cell::RefCell;
+use core::ffi::c_void;
+use std::sync::Arc;
+
+use libjs_rust::api::{
+ Attribute, EmbedderClass, EmbedderValue, Gc, Object, PropertyAttributes, PropertyKey, RawNativeFunctionResult,
+ Realm, Trace, Value, Visitor, Vm,
+};
+
+#[cfg(web_idl_bindings)]
+use crate::bindings::conversions::ToJs;
+use crate::bindings::conversions::{BufferSource, UsvString};
+use crate::bindings::interface::{Ref, allocate, wrap};
+use crate::bindings::promise::{
+ TaskSource, WebIdlPromise, create_promise, in_parallel, queue_a_task, react_to_promise, reject_promise,
+ resolve_promise,
+};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::web_assembly::builtins::validate_builtins_and_imported_strings;
+use crate::web_assembly::errors::{WebAssemblyError, error_constructor, throw_webassembly_error};
+use crate::web_assembly::instance::{Instance, instantiate_the_core_of_a_webassembly_module, read_the_imports};
+use crate::web_assembly::module::Module;
+use crate::web_assembly::tag::Tag;
+use crate::web_assembly::{Agent, CompiledModule, compile_a_webassembly_module, stable_bytes_of};
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-webassemblyinstantiatedsource
+pub(crate) struct WebAssemblyInstantiatedSource {
+ pub(crate) module: Ref<Module>,
+ pub(crate) instance: Ref<Instance>,
+}
+
+impl WebAssemblyInstantiatedSource {
+ fn into_js(self, cx: &CallContext) -> libjs_rust::api::ThrowCompletionOr<Value> {
+ // NB: The generated bindings convert the dictionary, which a build of the crate on its own leaves out.
+ #[cfg(web_idl_bindings)]
+ return ToJs::to_js(self, cx);
+ #[cfg(not(web_idl_bindings))]
+ {
+ let _ = (self, cx);
+ unreachable!("only the generated bindings resolve a promise with the dictionary")
+ }
+ }
+}
+
+/// https://webassembly.github.io/spec/js-api/#dictdef-webassemblycompileoptions
+#[derive(Clone, Default, Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct WebAssemblyCompileOptions {
+ #[gc(untraced)]
+ pub(crate) imported_string_constants: Option<UsvString>,
+ #[gc(untraced)]
+ pub(crate) builtins: Vec<UsvString>,
+}
+
+static COMPILE_OPTIONS_CLASS: EmbedderClass<WebAssemblyCompileOptions> =
+ EmbedderClass::new("WebAssemblyCompileOptions");
+
+impl EmbedderValue for WebAssemblyCompileOptions {
+ const CLASS: &'static EmbedderClass<Self> = &COMPILE_OPTIONS_CLASS;
+}
+
+pub(crate) struct WebAssembly;
+
+/// The bytes that asynchronously compiling a module compiles in parallel, the options it compiles them with, and what
+/// compiling them results in.
+struct CompileJob {
+ bytes: RefCell<Vec<u8>>,
+ options: RefCell<WebAssemblyCompileOptions>,
+ result: RefCell<Option<Result<CompiledModule, Value>>>,
+}
+
+// SAFETY: The exception that compiling the bytes throws is the one cell the job holds.
+unsafe impl Trace for CompileJob {
+ fn trace(&self, visitor: &mut Visitor) {
+ if let Some(Err(exception)) = &*self.result.borrow() {
+ exception.trace(visitor);
+ }
+ }
+}
+
+static COMPILE_JOB_CLASS: EmbedderClass<CompileJob> = EmbedderClass::new("WebAssemblyCompileJob");
+
+impl EmbedderValue for CompileJob {
+ const CLASS: &'static EmbedderClass<Self> = &COMPILE_JOB_CLASS;
+}
+
+/// https://webassembly.github.io/spec/js-api/#asynchronously-compile-a-webassembly-module
+fn asynchronously_compile_a_webassembly_module(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ bytes: Vec<u8>,
+ options: WebAssemblyCompileOptions,
+ task_source: TaskSource,
+) -> WebIdlPromise {
+ // 1. Let promise be a new Promise.
+ let promise = create_promise(vm, realm);
+
+ // 2. Run the following steps in parallel:
+ let job = COMPILE_JOB_CLASS.allocate(vm, |_| CompileJob {
+ bytes: RefCell::new(bytes),
+ options: RefCell::new(options),
+ result: RefCell::new(None),
+ });
+ in_parallel(
+ vm,
+ realm,
+ (promise, job, task_source),
+ |vm, (promise, job, task_source)| {
+ // 1. Compile the WebAssembly module bytes and store the result as module.
+ let realm = vm.current_realm().expect("the steps run in the realm of the promise");
+ let result = compile_a_webassembly_module(vm, realm, &job.bytes.borrow()).map_err(|throw| throw.value());
+ *job.result.borrow_mut() = Some(result);
+
+ // 2. Queue a task on taskSource, if provided, to perform the following steps:
+ queue_a_task(vm, realm, task_source, (promise, job), |vm, (promise, job)| {
+ let realm = crate::bindings::promise::promise_realm(promise);
+
+ // 1. If module is error, reject promise with a CompileError exception and return.
+ let module = match job.result.take().expect("the module is compiled before the task runs") {
+ Ok(module) => module,
+ Err(exception) => {
+ reject_promise(vm, promise, exception);
+ return;
+ }
+ };
+
+ let options = job.options.take();
+
+ // 2. Let builtinSetNames be options["builtins"].
+ let builtin_set_names = options.builtins;
+
+ // 3. Let importedStringModule be options["importedStringConstants"].
+ let imported_string_module = options.imported_string_constants;
+
+ // 4. If validating builtins and imported strings for module with builtinSetNames and importedStringModule is
+ // false, reject promise with a CompileError exception.
+ if !validate_builtins_and_imported_strings(
+ vm,
+ &module,
+ &builtin_set_names,
+ imported_string_module.as_ref(),
+ ) {
+ let throw = throw_webassembly_error(
+ vm,
+ realm,
+ WebAssemblyError::Compile,
+ "Invalid builtin or imported string",
+ );
+ reject_promise(vm, promise, throw.value());
+ }
+ // 5. Otherwise,
+ else {
+ // 1. Construct a WebAssembly module object from module, bytes, builtinSetNames, importedStringModule, and
+ // let moduleObject be the result.
+ let bytes = job.bytes.take();
+ let module_object = allocate(vm, |_| {
+ Module::new(module, bytes, builtin_set_names, imported_string_module)
+ });
+
+ // 2. Resolve promise with moduleObject.
+ let cx = CallContext::new(vm, realm);
+ resolve_promise(vm, promise, Value::from_object(wrap(&cx, module_object)));
+ }
+ });
+ },
+ );
+
+ // 3. Return promise.
+ promise
+}
+
+/// https://webassembly.github.io/spec/js-api/#asynchronously-instantiate-a-webassembly-module
+fn asynchronously_instantiate_a_webassembly_module(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ module_object: Ref<Module>,
+ import_object: Option<Gc<Object>>,
+) -> WebIdlPromise {
+ // 1. Let promise be a new promise.
+ let promise = create_promise(vm, realm);
+
+ // 2. Let module be moduleObject.[[Module]].
+ let module = module_object.compiled_module().clone();
+
+ // 3. Let builtinSetNames be moduleObject.[[BuiltinSets]].
+ let builtin_set_names = module_object.builtin_sets();
+
+ // 4. Let importedStringModule be moduleObject.[[ImportedStringModule]].
+ let imported_string_module = module_object.imported_string_module();
+
+ // 5. Read the imports of module with imports importObject, builtinSetNames and importedStringModule, and let imports
+ // be the result. If this operation throws an exception, catch it, reject promise with the exception, and return
+ // promise.
+ let imports = match read_the_imports(vm, &module, import_object, builtin_set_names, imported_string_module) {
+ Ok(imports) => imports,
+ Err(throw) => {
+ reject_promise(vm, promise, throw.value());
+ return promise;
+ }
+ };
+
+ // 6. Run the following steps in parallel:
+ // 1. Queue a task to perform the following steps: Note: Implementation-specific work may be performed here.
+ queue_a_task(
+ vm,
+ realm,
+ TaskSource::Unspecified,
+ (promise, module_object, imports),
+ |vm, (promise, module_object, imports)| {
+ let realm = crate::bindings::promise::promise_realm(promise);
+ let module = module_object.compiled_module().clone();
+
+ // 1. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
+ // If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
+ let instance = match instantiate_the_core_of_a_webassembly_module(vm, &module, &imports) {
+ Ok(instance) => instance,
+ Err(throw) => {
+ reject_promise(vm, promise, throw.value());
+ return;
+ }
+ };
+
+ // 2. Let instanceObject be a new Instance.
+ // 3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
+ let instance_object = allocate(vm, |_| Instance::initialize(vm, realm, instance));
+
+ // 4. Resolve promise with instanceObject.
+ let cx = CallContext::new(vm, realm);
+ resolve_promise(vm, promise, Value::from_object(wrap(&cx, instance_object)));
+ },
+ );
+
+ // 7. Return promise.
+ promise
+}
+
+/// https://webassembly.github.io/spec/js-api/#instantiate-a-promise-of-a-module
+fn instantiate_a_promise_of_a_module(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ promise_of_module: WebIdlPromise,
+ import_object: Option<Gc<Object>>,
+) -> WebIdlPromise {
+ // 1. Let promise be a new Promise.
+ let promise = create_promise(vm, realm);
+
+ // FIXME: Spec should use react to promise here instead of separate upon fulfillment and upon rejection steps
+
+ react_to_promise(
+ vm,
+ promise_of_module,
+ (promise, import_object),
+ // 2. Upon fulfillment of promiseOfModule with value module:
+ Some(|cx: &CallContext, (promise, import_object), module_value: Value| {
+ let module_object = Module::from_value(module_value).expect("the promise is fulfilled with a Module");
+
+ // 1. Instantiate the WebAssembly module module importing importObject, and let innerPromise be the result.
+ let realm = crate::bindings::promise::promise_realm(promise);
+ let inner_promise =
+ asynchronously_instantiate_a_webassembly_module(cx.vm(), realm, module_object, import_object);
+
+ react_to_promise(
+ cx.vm(),
+ inner_promise,
+ (promise, module_object),
+ // 2. Upon fulfillment of innerPromise with value instance.
+ Some(|cx: &CallContext, (promise, module_object), instance_value: Value| {
+ let instance = crate::web_assembly::implementation_of_value::<Instance>(instance_value)
+ .expect("the promise is fulfilled with an Instance");
+
+ // 1. Let result be the WebAssemblyInstantiatedSource value «[ "module" → module, "instance" → instance ]».
+ let result = WebAssemblyInstantiatedSource {
+ module: module_object,
+ instance,
+ }
+ .into_js(&CallContext::new(
+ cx.vm(),
+ crate::bindings::promise::promise_realm(promise),
+ ))?;
+
+ // 2. Resolve promise with result.
+ resolve_promise(cx.vm(), promise, result);
+ Ok(Value::UNDEFINED)
+ }),
+ // 3. Upon rejection of innerPromise with reason reason.
+ Some(|cx: &CallContext, (promise, _), reason: Value| {
+ // 1. Reject promise with reason.
+ reject_promise(cx.vm(), promise, reason);
+ Ok(Value::UNDEFINED)
+ }),
+ );
+ Ok(Value::UNDEFINED)
+ }),
+ // 3. Upon rejection of promiseOfModule with reason reason:
+ Some(|cx: &CallContext, (promise, _), reason: Value| {
+ // 1. Reject promise with reason.
+ reject_promise(cx.vm(), promise, reason);
+ Ok(Value::UNDEFINED)
+ }),
+ );
+
+ // 4. Return promise.
+ promise
+}
+
+unsafe extern "C" {
+ /// Steps 1 to 8 of compiling a potential WebAssembly response: the checks of the Response object, then consuming
+ /// its body as an ArrayBuffer, whose promise, a WebIDL::Promise, it writes. Throws the TypeError of a check that
+ /// fails.
+ fn web_bindings_consume_webassembly_response(
+ realm: *mut c_void,
+ unwrapped_source: u64,
+ body_promise: *mut *mut c_void,
+ ) -> RawNativeFunctionResult;
+}
+
+/// https://webassembly.github.io/spec/web-api/index.html#compile-a-potential-webassembly-response
+fn compile_a_potential_webassembly_response(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ source: WebIdlPromise,
+ options: WebAssemblyCompileOptions,
+) -> WebIdlPromise {
+ // Note: This algorithm accepts a Response object, or a promise for one, and compiles and instantiates the resulting bytes of the response.
+ // This compilation can be performed in the background and in a streaming manner.
+ // If the Response is not CORS-same-origin, does not represent an ok status, or does not match the `application/wasm` MIME type,
+ // the returned promise will be rejected with a TypeError; if compilation or instantiation fails,
+ // the returned promise will be rejected with a CompileError or other relevant error type, depending on the cause of failure.
+
+ // 1. Let returnValue be a new promise
+ let return_value = create_promise(vm, realm);
+
+ // NB: The reactions hold the options in a cell of their own, as what they capture is traced.
+ let options = COMPILE_OPTIONS_CLASS.allocate(vm, |_| options);
+
+ react_to_promise(
+ vm,
+ source,
+ (return_value, options),
+ // 2. Upon fulfillment of source with value unwrappedSource:
+ Some(|cx: &CallContext, (return_value, options), unwrapped_source: Value| {
+ let realm = crate::bindings::promise::promise_realm(return_value);
+ let mut body_promise = core::ptr::null_mut();
+ // SAFETY: The realm is live, and the promise is written before the completion is normal.
+ let consumed = unsafe {
+ web_bindings_consume_webassembly_response(
+ realm.as_ptr().cast(),
+ unwrapped_source.to_raw(),
+ &raw mut body_promise,
+ )
+ }
+ .into_completion();
+ if let Err(throw) = consumed {
+ reject_promise(cx.vm(), return_value, throw.value());
+ return Ok(Value::UNDEFINED);
+ }
+ // SAFETY: LibWeb wrote the WebIDL::Promise of the body.
+ let body_promise = unsafe { crate::bindings::promise::promise_from_abi(body_promise) };
+
+ react_to_promise(
+ cx.vm(),
+ body_promise,
+ (return_value, options),
+ // 9. Upon fulfillment of bodyPromise with value bodyArrayBuffer:
+ Some(|cx: &CallContext, (return_value, options), body_array_buffer: Value| {
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bodyArrayBuffer.
+ let bytes = crate::bindings::conversions::buffer_source_type_of(body_array_buffer)
+ .expect("a body consumed as an ArrayBuffer is one");
+ let stable_bytes = stable_bytes_of(bytes);
+
+ // 2. Asynchronously compile the WebAssembly module stableBytes using the networking task source and options
+ // and resolve returnValue with the result.
+ let realm = crate::bindings::promise::promise_realm(return_value);
+ let result = asynchronously_compile_a_webassembly_module(
+ cx.vm(),
+ realm,
+ stable_bytes,
+ (*options).clone(),
+ TaskSource::Networking,
+ );
+ resolve_promise(cx.vm(), return_value, Value::from_object(result.promise()));
+ Ok(Value::UNDEFINED)
+ }),
+ // 10. Upon rejection of bodyPromise with reason reason:
+ Some(|cx: &CallContext, (return_value, _), reason: Value| {
+ // 1. Reject returnValue with reason.
+ reject_promise(cx.vm(), return_value, reason);
+ Ok(Value::UNDEFINED)
+ }),
+ );
+ Ok(Value::UNDEFINED)
+ }),
+ // 3. Upon rejection of source with reason reason:
+ Some(|cx: &CallContext, (return_value, _), reason: Value| {
+ // 1. Reject returnValue with reason.
+ reject_promise(cx.vm(), return_value, reason);
+ Ok(Value::UNDEFINED)
+ }),
+ );
+
+ // 4. Return returnValue.
+ return_value
+}
+
+impl WebAssembly {
+ // https://webassembly.github.io/spec/js-api/#error-objects
+ pub(crate) fn initialize(cx: &mut CallContext, namespace_object: Gc<Object>) {
+ let vm = cx.vm();
+
+ // 1. Let namespaceObject be the namespace object.
+ // 2. For each error of « "CompileError", "LinkError", "RuntimeError" »,
+ // 2.1. Let constructor be a new object, implementing the NativeError Object Structure, with NativeError set to error.
+ // 2.2. ! DefineMethodProperty(namespaceObject, error, constructor, false).
+ let attributes = PropertyAttributes::new(Attribute::WRITABLE | Attribute::CONFIGURABLE);
+ for error in WebAssemblyError::ALL {
+ let constructor = error_constructor(vm, cx.realm(), error);
+ namespace_object.define_direct_property(
+ vm,
+ &PropertyKey::from_utf8(error.name()),
+ Value::from_object(constructor),
+ attributes,
+ );
+ }
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-webassembly-jstag
+ pub(crate) fn js_tag(cx: &mut CallContext) -> WebIdlResult<Ref<Tag>> {
+ // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.
+ // 2. Let JSTagObject be the result of creating a Tag object from JSTagAddr.
+ // 3. Return JSTagObject.
+ let tag = Agent::the(cx.vm()).js_tag();
+ Ok(Tag::from_address(cx.vm(), cx.realm(), tag))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-webassembly-validate
+ pub(crate) fn validate(
+ cx: &mut CallContext,
+ bytes: BufferSource,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<bool> {
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
+ let stable_bytes = stable_bytes_of(bytes);
+
+ // 2. Compile stableBytes as a WebAssembly module and store the results as module.
+ let module = libwasm_engine::compile(&stable_bytes);
+
+ // 3. If module is error, return false.
+ let Ok(module) = module else {
+ return Ok(false);
+ };
+ let module: CompiledModule = Arc::new(module);
+
+ // 4. Let builtinSetNames be options["builtins"].
+ let builtin_set_names = &options.builtins;
+
+ // 5. Let importedStringModule be options["importedStringConstants"].
+ let imported_string_module = options.imported_string_constants.as_ref();
+
+ // 6. If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns
+ // false, return false.
+ if !validate_builtins_and_imported_strings(cx.vm(), &module, builtin_set_names, imported_string_module) {
+ return Ok(false);
+ }
+
+ // 7. Return true.
+ Ok(true)
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-webassembly-compile
+ pub(crate) fn compile(
+ cx: &mut CallContext,
+ bytes: BufferSource,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<WebIdlPromise> {
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
+ let stable_bytes = stable_bytes_of(bytes);
+
+ // 2. Asynchronously compile a WebAssembly module from stableBytes using options and return the result.
+ Ok(asynchronously_compile_a_webassembly_module(
+ cx.vm(),
+ cx.realm(),
+ stable_bytes,
+ options,
+ TaskSource::Unspecified,
+ ))
+ }
+
+ // https://webassembly.github.io/spec/web-api/index.html#dom-webassembly-compilestreaming
+ pub(crate) fn compile_streaming(
+ cx: &mut CallContext,
+ source: WebIdlPromise,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<WebIdlPromise> {
+ // The compileStreaming(source, options) method, when invoked, returns the result of compiling a potential
+ // WebAssembly response with source using options.
+ Ok(compile_a_potential_webassembly_response(
+ cx.vm(),
+ cx.realm(),
+ source,
+ options,
+ ))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate
+ // https://webassembly.github.io/content-security-policy/js-api/#dom-webassembly-instantiate
+ pub(crate) fn instantiate_bytes(
+ cx: &mut CallContext,
+ bytes: BufferSource,
+ import_object: Option<Gc<Object>>,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<WebIdlPromise> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
+ let stable_bytes = stable_bytes_of(bytes);
+
+ // 2. Perform HostEnsureCanCompileWasmBytes()
+ crate::web_assembly::host_ensure_can_compile_wasm_bytes(realm)?;
+
+ // 3. Asynchronously compile a WebAssembly module from stableBytes using options and let promiseOfModule be the
+ // result.
+ let promise_of_module =
+ asynchronously_compile_a_webassembly_module(vm, realm, stable_bytes, options, TaskSource::Unspecified);
+
+ // 4. Instantiate promiseOfModule with imports importObject and return the result.
+ Ok(instantiate_a_promise_of_a_module(
+ vm,
+ realm,
+ promise_of_module,
+ import_object,
+ ))
+ }
+
+ // https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate-moduleobject-importobject
+ pub(crate) fn instantiate_module(
+ cx: &mut CallContext,
+ module_object: Ref<Module>,
+ import_object: Option<Gc<Object>>,
+ _: Option<Value>,
+ ) -> WebIdlResult<WebIdlPromise> {
+ // 1. Asynchronously instantiate the WebAssembly module moduleObject importing importObject, and return the result.
+ Ok(asynchronously_instantiate_a_webassembly_module(
+ cx.vm(),
+ cx.realm(),
+ module_object,
+ import_object,
+ ))
+ }
+
+ // https://webassembly.github.io/spec/web-api/index.html#dom-webassembly-instantiatestreaming
+ pub(crate) fn instantiate_streaming(
+ cx: &mut CallContext,
+ source: WebIdlPromise,
+ import_object: Option<Gc<Object>>,
+ options: WebAssemblyCompileOptions,
+ ) -> WebIdlResult<WebIdlPromise> {
+ // The instantiateStreaming(source, importObject, options) method, when invoked, performs the following steps:
+
+ // 1. Let promiseOfModule be the result of compiling a potential WebAssembly response with source using options.
+ let promise_of_module = compile_a_potential_webassembly_response(cx.vm(), cx.realm(), source, options);
+
+ // 2. Return the result of instantiating the promise of a module promiseOfModule with imports importObject.
+ Ok(instantiate_a_promise_of_a_module(
+ cx.vm(),
+ cx.realm(),
+ promise_of_module,
+ import_object,
+ ))
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index 0c828fcad6f..4b6e6f8b333 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -107,6 +107,7 @@ void web_bindings_serialize_u32(RustSerializationWriter*, u32);
void web_bindings_serialize_f64(RustSerializationWriter*, double);
void web_bindings_serialize_bool(RustSerializationWriter*, bool);
void web_bindings_serialize_i64(RustSerializationWriter*, i64);
+void web_bindings_serialize_optional_u64(RustSerializationWriter*, bool has_value, u64);
void web_bindings_serialize_utf16_string(RustSerializationWriter*, FlatPtr string);
void web_bindings_serialize_bytes(RustSerializationWriter*, ReadonlyBytes);
JSCompletion web_bindings_deserialize_value(RustSerializationReader*);
@@ -114,6 +115,7 @@ JSCompletion web_bindings_deserialize_u32(RustSerializationReader*, u32* out_val
JSCompletion web_bindings_deserialize_f64(RustSerializationReader*, double* out_value);
JSCompletion web_bindings_deserialize_bool(RustSerializationReader*, bool* out_value);
JSCompletion web_bindings_deserialize_i64(RustSerializationReader*, i64* out_value);
+JSCompletion web_bindings_deserialize_optional_u64(RustSerializationReader*, bool* out_has_value, u64* out_value);
JSCompletion web_bindings_deserialize_bytes(RustSerializationReader*, void* bytes, void (*append)(void*, u8 const*, size_t));
JSCompletion web_bindings_deserialize_utf16_string(RustSerializationReader*, FlatPtr* out_string);
void web_bindings_serialize_inline_object_header(RustSerializationWriter*, u16 interface_name);
@@ -215,6 +217,11 @@ void web_bindings_serialize_i64(RustSerializationWriter* writer, i64 value)
writer->serialized.encode(value);
}
+void web_bindings_serialize_optional_u64(RustSerializationWriter* writer, bool has_value, u64 value)
+{
+ writer->serialized.encode(has_value ? Optional<u64> { value } : Optional<u64> {});
+}
+
void web_bindings_serialize_utf16_string(RustSerializationWriter* writer, FlatPtr string)
{
writer->serialized.encode(Utf16String::from_raw(string));
@@ -251,6 +258,15 @@ JSCompletion web_bindings_deserialize_i64(RustSerializationReader* reader, i64*
return deserialize_plain_value(reader, out_value);
}
+JSCompletion web_bindings_deserialize_optional_u64(RustSerializationReader* reader, bool* out_has_value, u64* out_value)
+{
+ Optional<u64> value;
+ auto result = deserialize_plain_value(reader, &value);
+ *out_has_value = value.has_value();
+ *out_value = value.value_or(0);
+ return result;
+}
+
JSCompletion web_bindings_deserialize_bytes(RustSerializationReader* reader, void* bytes, void (*append)(void*, u8 const*, size_t))
{
ByteBuffer buffer;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index c63c3663c2d..32aea2e0e84 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -976,16 +976,7 @@ set(SOURCES
WebLocks/LockManager.cpp
WebLocks/LockRequest.cpp
WebLocks/NavigatorLocks.cpp
- WebAssembly/Builtins.cpp
- WebAssembly/Exception.cpp
- WebAssembly/Global.cpp
- WebAssembly/Instance.cpp
- WebAssembly/Memory.cpp
- WebAssembly/Module.cpp
- WebAssembly/Table.cpp
- WebAssembly/Tag.cpp
WebAssembly/WebAssembly.cpp
- WebAssembly/WebAssemblyModule.cpp
WebAudio/AnalyserNode.cpp
WebAudio/AudioParamMap.cpp
WebAudio/AudioWorklet.cpp
@@ -1133,7 +1124,7 @@ target_sources(LibWeb PRIVATE $<TARGET_OBJECTS:LibJSObjects>)
target_compile_definitions(LibWeb PRIVATE LibJS_EXPORTS)
target_link_libraries(LibWeb PUBLIC LibCompositing LibWebCommon LibJSHeaders)
-target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasm LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
+target_link_libraries(LibWeb PRIVATE LibCore LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibXML LibURL LibTLS LibRequests LibGC LibImageDecoderClient LibThreading LibXml2::LibXml2)
# LibWeb still includes ANGLE's GLES headers for WebGL constants and types, but
# the actual GL entry points live in the Compositor. Copy only ANGLE's compile
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
index 75fa8b15215..89d9215bef4 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
+++ b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
@@ -485,7 +485,7 @@ JS::ThrowCompletionOr<void> ensure_csp_does_not_block_wasm_byte_compilation(JS::
// 4. If result is "Blocked", throw a WebAssembly.CompileError exception.
if (result == Directives::Directive::Result::Blocked) {
- return realm.vm().throw_completion<WebAssembly::CompileError>("Blocked by Content Security Policy"sv);
+ return JS::throw_completion(WebAssembly::create_compile_error(realm, "Blocked by Content Security Policy"_utf16));
}
return {};
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index c13b98118ac..9b84ffc5ffd 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1194,23 +1194,6 @@ class ViewTransition;
}
-namespace Web::WebAssembly {
-
-class Global;
-class Instance;
-class Memory;
-class Module;
-class Table;
-class Tag;
-
-namespace Detail {
-
-class WebAssemblyCache;
-
-}
-
-}
-
namespace Web::WebAudio {
class AudioBuffer;
diff --git a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
index ae9596ecbea..b2b6156ce73 100644
--- a/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
+++ b/Libraries/LibWeb/HTML/Scripting/ModuleScript.cpp
@@ -13,7 +13,7 @@
#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/HTML/Scripting/ModuleScript.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/WebAssembly/WebAssemblyModule.h>
+#include <LibWeb/WebAssembly/WebAssembly.h>
#include <LibWeb/WebIDL/DOMException.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
diff --git a/Libraries/LibWeb/WebAssembly/BindingsGlue.h b/Libraries/LibWeb/WebAssembly/BindingsGlue.h
deleted file mode 100644
index 10d238b7dd4..00000000000
--- a/Libraries/LibWeb/WebAssembly/BindingsGlue.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16String.h>
-#include <AK/Vector.h>
-#include <LibGC/Forward.h>
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibJS/Runtime/Completion.h>
-#include <LibJS/Runtime/Value.h>
-#include <LibWeb/Bindings/Forward.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWeb/WebIDL/Promise.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAssembly {
-
-class Exception;
-class Global;
-class Instance;
-class Memory;
-class Module;
-class Table;
-class Tag;
-
-}
-
-namespace Web::Bindings {
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Global>> construct_global(JS::Realm&, GlobalDescriptor const&, Optional<JS::Value>);
-WEB_API WebIDL::ExceptionOr<JS::Value> value(JS::Realm&, WebAssembly::Global&);
-WEB_API WebIDL::ExceptionOr<void> set_value(JS::Realm&, WebAssembly::Global&, JS::Value);
-WEB_API WebIDL::ExceptionOr<JS::Value> value_of(JS::Realm&, WebAssembly::Global&);
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Tag>> construct_tag(JS::Realm&, TagType const&);
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Exception>> construct_exception(JS::Realm&, WebAssembly::Tag&, GC::RootVector<JS::Value> const& payload, ExceptionOptions const&);
-WEB_API WebIDL::ExceptionOr<JS::Value> get_arg(WebAssembly::Exception&, WebAssembly::Tag&, u32 index);
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Instance>> construct_instance(JS::Realm&, WebAssembly::Module&, GC::Ptr<JS::Object> import_object);
-WEB_API GC::Ref<JS::Object const> exports(JS::Realm&, GC::Ref<WebAssembly::Instance>);
-WEB_API JS::ThrowCompletionOr<void> initialize_webassembly_export_binding(JS::Realm&, JS::Environment&, Utf16FlyString const& name, GC::Ref<WebAssembly::Instance>);
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebAssembly::Table>> construct_table(JS::Realm&, TableDescriptor const&, Optional<JS::Value>);
-WEB_API JS::Value table(JS::Realm&, GC::Ref<WebAssembly::Table>);
-WEB_API WebIDL::ExceptionOr<JS::Value> grow(JS::Realm&, WebAssembly::Table&, JS::Value delta_value, Optional<JS::Value>);
-WEB_API WebIDL::ExceptionOr<JS::Value> get(JS::Realm&, WebAssembly::Table&, JS::Value index_value);
-WEB_API WebIDL::ExceptionOr<void> set(JS::Realm&, WebAssembly::Table&, JS::Value index_value, Optional<JS::Value>);
-WEB_API WebIDL::ExceptionOr<JS::Value> length(JS::Realm&, WebAssembly::Table&);
-
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile(JS::Realm&, WebIDL::BufferSource bytes);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile_streaming(JS::Realm&, GC::Ref<WebIDL::Promise> source);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, WebIDL::BufferSource bytes, GC::Ptr<JS::Object> import_object);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, GC::Ref<WebAssembly::Module>, GC::Ptr<JS::Object> import_object);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::Realm&, GC::Ref<WebIDL::Promise> source, GC::Ptr<JS::Object> import_object);
-WEB_API WebAssembly::Exception* exception_from_value(JS::Value);
-WEB_API WebAssembly::Global* global_from_value(JS::Value);
-WEB_API WebAssembly::Instance* instance_from_value(JS::Value);
-WEB_API WebAssembly::Memory* memory_from_value(JS::Value);
-WEB_API WebAssembly::Module* module_from_value(JS::Value);
-WEB_API WebAssembly::Table* table_from_value(JS::Value);
-WEB_API WebAssembly::Tag* tag_from_value(JS::Value);
-WEB_API void resolve_webassembly_module_promise(JS::Realm&, WebIDL::Promise&, GC::Ref<WebAssembly::Module>);
-WEB_API void resolve_webassembly_instance_promise(JS::Realm&, WebIDL::Promise&, GC::Ref<WebAssembly::Instance>);
-WEB_API GC::Ref<JS::Object> create_webassembly_instantiated_source(JS::Realm&, GC::Ref<WebAssembly::Module>, GC::Ref<WebAssembly::Instance>);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> array_buffer_for_webassembly_response(JS::Realm&, Fetch::Response const&);
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Builtins.cpp b/Libraries/LibWeb/WebAssembly/Builtins.cpp
deleted file mode 100644
index f35efea1378..00000000000
--- a/Libraries/LibWeb/WebAssembly/Builtins.cpp
+++ /dev/null
@@ -1,725 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/Array.h>
-#include <AK/HashTable.h>
-#include <AK/NeverDestroyed.h>
-#include <AK/Utf16View.h>
-#include <AK/Vector.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibJS/Runtime/ValueInlines.h>
-#include <LibWeb/WebAssembly/Builtins.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly::Detail {
-
-using Wasm::Runtime::HeapKind;
-using Wasm::Runtime::HostError;
-using Wasm::Runtime::ValueKind;
-using WasmValue = Wasm::Runtime::Value;
-using WasmValueType = Wasm::Runtime::ValueType;
-
-static constexpr auto js_string_builtin_set_name = "js-string"sv;
-static constexpr auto js_string_builtin_set_qualified_name = "wasm:js-string"sv;
-
-// The funcTypes of the builtins, each in a recursion group of its own, as the types of a module that has nothing else.
-// The store gives types the same identity wherever they are equivalent, so an import matches the funcType of a builtin
-// exactly when the identity of its type is the identity of that funcType.
-enum BuiltinTypeIndex : u32 {
- // (rec (type (array (mut i16)))).0
- ArrayType,
- // (rec (type (func (param externref) (result (ref extern))))).0
- ExternrefToRefExtern,
- // (rec (type (func (param externref) (result i32)))).0
- ExternrefToI32,
- // (rec (type (func (param (ref null arrayType) i32 i32) (result (ref extern))))).0
- ArrayI32I32ToRefExtern,
- // (rec (type (func (param externref (ref null arrayType) i32) (result i32)))).0
- ExternrefArrayI32ToI32,
- // (rec (type (func (param i32) (result (ref extern))))).0
- I32ToRefExtern,
- // (rec (type (func (param externref i32) (result i32)))).0
- ExternrefI32ToI32,
- // (rec (type (func (param externref externref) (result (ref extern))))).0
- ExternrefExternrefToRefExtern,
- // (rec (type (func (param externref i32 i32) (result (ref extern))))).0
- ExternrefI32I32ToRefExtern,
- // (rec (type (func (param externref externref) (result i32)))).0
- ExternrefExternrefToI32,
-};
-
-static constexpr Array<u8, 75> builtin_types_module_bytes {
- // Magic and version.
- 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
- // The type section: 65 bytes, 10 types.
- 0x01, 0x41, 0x0a,
- // array (mut i16)
- 0x5e, 0x77, 0x01,
- // func (param externref) (result (ref extern))
- 0x60, 0x01, 0x6f, 0x01, 0x64, 0x6f,
- // func (param externref) (result i32)
- 0x60, 0x01, 0x6f, 0x01, 0x7f,
- // func (param (ref null 0) i32 i32) (result (ref extern))
- 0x60, 0x03, 0x63, 0x00, 0x7f, 0x7f, 0x01, 0x64, 0x6f,
- // func (param externref (ref null 0) i32) (result i32)
- 0x60, 0x03, 0x6f, 0x63, 0x00, 0x7f, 0x01, 0x7f,
- // func (param i32) (result (ref extern))
- 0x60, 0x01, 0x7f, 0x01, 0x64, 0x6f,
- // func (param externref i32) (result i32)
- 0x60, 0x02, 0x6f, 0x7f, 0x01, 0x7f,
- // func (param externref externref) (result (ref extern))
- 0x60, 0x02, 0x6f, 0x6f, 0x01, 0x64, 0x6f,
- // func (param externref i32 i32) (result (ref extern))
- 0x60, 0x03, 0x6f, 0x7f, 0x7f, 0x01, 0x64, 0x6f,
- // func (param externref externref) (result i32)
- 0x60, 0x02, 0x6f, 0x6f, 0x01, 0x7f
-};
-
-static Wasm::Runtime::Module const& builtin_types_module()
-{
- static NeverDestroyed<NonnullRefPtr<Wasm::Runtime::Module>> module { MUST(Wasm::Runtime::Module::compile(builtin_types_module_bytes)) };
- return *module.get();
-}
-
-// The store-wide identity of the type at `type_index` of a module.
-static u32 type_identity(Wasm::Runtime::Module const& module, u32 type_index)
-{
- WasmValueType reference_type { ValueKind::Reference, HeapKind::Concrete, false, type_index };
- return WebAssemblyCache::the().store().canonical_value_type(module, reference_type).type_index;
-}
-
-using BuiltinSteps = ErrorOr<void, HostError> (*)(JS::VM&, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results);
-
-struct Builtin {
- StringView name;
- BuiltinTypeIndex function_type;
- BuiltinSteps steps;
-};
-
-static constexpr auto externref = WasmValueType::reference(HeapKind::Extern);
-
-static HostError trap(StringView message)
-{
- return HostError { ByteString { message } };
-}
-
-static JS::Value js_value_of(JS::VM& vm, WasmValue value)
-{
- return MUST(to_js_value(vm, value, externref));
-}
-
-static WasmValue string_reference(JS::VM& vm, Utf16View const& string)
-{
- return MUST(to_webassembly_value(vm, JS::PrimitiveString::create(vm, string), externref));
-}
-
-static WasmValue string_reference(JS::VM& vm, Utf16String const& string)
-{
- return MUST(to_webassembly_value(vm, JS::PrimitiveString::create(vm, string), externref));
-}
-
-static WasmValue string_reference(JS::VM& vm, Vector<char16_t> const& code_units)
-{
- if (code_units.is_empty())
- return string_reference(vm, Utf16View {});
- return string_reference(vm, Utf16View { code_units.data(), code_units.size() });
-}
-
-static u32 unsigned_i32(WasmValue value)
-{
- return static_cast<u32>(value.to_i32());
-}
-
-// https://webassembly.github.io/spec/js-api/#abstract-opdef-unwrapstring
-static ErrorOr<GC::Ref<JS::PrimitiveString>, HostError> unwrap_string(JS::VM& vm, WasmValue v)
-{
- auto value = js_value_of(vm, v);
-
- // 1. If v is not a String,
- if (!value.is_string()) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("Expected a string"sv);
- }
-
- // 2. Return v
- return value.as_string();
-}
-
-// https://webassembly.github.io/spec/js-api/#abstract-opdef-fromcharcode
-static Utf16String from_char_code(i32 v)
-{
- // 1. Assert: v is of type i32.
- // 2. Return ! Call(String.fromCharCode, undefined, « ToJSValue(v) »).
- char16_t code_unit = static_cast<u16>(v);
- return Utf16String::from_utf16({ &code_unit, 1 });
-}
-
-// https://webassembly.github.io/spec/js-api/#abstract-opdef-charcodeat
-static i32 char_code_at(Utf16View const& string, u32 index)
-{
- // 1. Assert: index is of type i32.
- // 2. Return ! Call(String.prototype.charCodeAt, string, « ToJSValue(index) »).
- return string.code_unit_at(index);
-}
-
-namespace JSStringBuiltins {
-
-// https://webassembly.github.io/spec/js-api/#js-string-cast
-static ErrorOr<void, HostError> cast(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. Return ? UnwrapString(v)
- TRY(unwrap_string(vm, arguments[0]));
- results[0] = arguments[0];
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-test
-static ErrorOr<void, HostError> test(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. If v is not a String,
- if (!js_value_of(vm, arguments[0]).is_string()) {
- // 1. Return 0.
- results[0] = WasmValue::from_i32(0);
- return {};
- }
-
- // 2. Return 1.
- results[0] = WasmValue::from_i32(1);
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-fromcharcodearray
-static ErrorOr<void, HostError> from_char_code_array(JS::VM& vm, Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto array = arguments[0];
- // NB: The indices are unsigned, as everywhere else in WebAssembly.
- auto start = unsigned_i32(arguments[1]);
- auto end = unsigned_i32(arguments[2]);
-
- // 1. If array is null,
- if (array.is_null_reference()) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The array is null"sv);
- }
-
- // 2. Let length be the number of elements in array.
- auto length = store.array_length(array.reference_bits());
-
- // 3. If start > end or end > length,
- if (start > end || end > length) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The range is out of the array's bounds"sv);
- }
-
- // 4. Let result be the empty string.
- Vector<char16_t> result;
- result.ensure_capacity(end - start);
-
- // 5. Let i be start.
- // 6. While i < end:
- for (auto i = start; i < end; ++i) {
- // 1. Let charCode be the value of the element stored at index i in array.
- auto char_code = static_cast<i32>(store.array_element(array.reference_bits(), i));
-
- // 2. Let charCodeString be FromCharCode(charCode).
- // 3. Let result be the concatenation of result and charCodeString.
- // NB: FromCharCode() makes a string of one code unit, which is the code unit itself here.
- result.unchecked_append(static_cast<u16>(char_code));
-
- // 4. Set i to i + 1.
- }
-
- // 7. Return result.
- results[0] = string_reference(vm, result);
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-intocharcodearray
-static ErrorOr<void, HostError> into_char_code_array(JS::VM& vm, Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto array = arguments[1];
- auto start = unsigned_i32(arguments[2]);
-
- // 1. If array is null,
- if (array.is_null_reference()) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The array is null"sv);
- }
-
- // 2. Let string be ? UnwrapString(string).
- auto string = TRY(unwrap_string(vm, arguments[0]))->utf16_string_view();
-
- // 3. Let stringLength be the length of string.
- auto string_length = string.length_in_code_units();
-
- // 4. Let arrayLength be the number of elements in array.
- auto array_length = store.array_length(array.reference_bits());
-
- // 5. If start + stringLength > arrayLength,
- if (static_cast<u64>(start) + string_length > array_length) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The string does not fit in the array"sv);
- }
-
- // 6. Let i be 0.
- // 7. While i < stringLength:
- for (u32 i = 0; i < string_length; ++i) {
- // 1. Let charCode be CharCodeAt(string, i).
- auto char_code = Detail::char_code_at(string, i);
-
- // 2. Set the element at index start + i in array to ToWebAssemblyValue(charCode, i32).
- store.set_array_element(array.reference_bits(), start + i, static_cast<u32>(char_code));
-
- // 3. Set i to i + 1.
- }
-
- // 8. Return stringLength.
- results[0] = WasmValue::from_i32(static_cast<i32>(string_length));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-fromcharcode
-static ErrorOr<void, HostError> from_char_code(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. Return FromCharCode(v).
- results[0] = string_reference(vm, Detail::from_char_code(arguments[0].to_i32()));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-fromcodepoint
-static ErrorOr<void, HostError> from_code_point(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto v = unsigned_i32(arguments[0]);
-
- // 1. If v > 0x10ffff,
- if (v > 0x10ffff) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The code point is out of range"sv);
- }
-
- // 2. Return ! Call(String.fromCodePoint, undefined, « ToJSValue(v) »).
- results[0] = string_reference(vm, Utf16String::from_code_point(v));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-charcodeat
-static ErrorOr<void, HostError> char_code_at(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto index = unsigned_i32(arguments[1]);
-
- // 1. Let string be ? UnwrapString(string).
- auto string = TRY(unwrap_string(vm, arguments[0]))->utf16_string_view();
-
- // 2. Let length be the length of string.
- auto length = string.length_in_code_units();
-
- // 3. If index >= length,
- if (index >= length) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The index is out of the string's bounds"sv);
- }
-
- // 4. Return CharCodeAt(string, index).
- results[0] = WasmValue::from_i32(Detail::char_code_at(string, index));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-codepointat
-static ErrorOr<void, HostError> code_point_at(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto index = unsigned_i32(arguments[1]);
-
- // 1. Let string be ? UnwrapString(string).
- auto string = TRY(unwrap_string(vm, arguments[0]))->utf16_string_view();
-
- // 2. Let length be the length of string.
- auto length = string.length_in_code_units();
-
- // 3. If index >= length,
- if (index >= length) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("The index is out of the string's bounds"sv);
- }
-
- // 4. Return ! Call(String.prototype.codePointAt, string, « ToJSValue(index) »).
- results[0] = WasmValue::from_i32(static_cast<i32>(string.code_point_at(index)));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-length
-static ErrorOr<void, HostError> length(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. Let string be ? UnwrapString(v).
- auto string = TRY(unwrap_string(vm, arguments[0]));
-
- // 2. Return the length of string.
- results[0] = WasmValue::from_i32(static_cast<i32>(string->length_in_utf16_code_units()));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-concat
-static ErrorOr<void, HostError> concat(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. Let first be ? UnwrapString(first).
- auto first = TRY(unwrap_string(vm, arguments[0]));
-
- // 2. Let second be ? UnwrapString(second).
- auto second = TRY(unwrap_string(vm, arguments[1]));
-
- // 3. Return ! Call(String.prototype.concat, first, « second »).
- auto first_view = first->utf16_string_view();
- auto second_view = second->utf16_string_view();
- Vector<char16_t> result;
- result.ensure_capacity(first_view.length_in_code_units() + second_view.length_in_code_units());
- for (size_t index = 0; index < first_view.length_in_code_units(); ++index)
- result.unchecked_append(first_view.code_unit_at(index));
- for (size_t index = 0; index < second_view.length_in_code_units(); ++index)
- result.unchecked_append(second_view.code_unit_at(index));
- results[0] = string_reference(vm, result);
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-substring
-static ErrorOr<void, HostError> substring(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // NB: The indices are unsigned, as everywhere else in WebAssembly.
- auto start = unsigned_i32(arguments[1]);
- auto end = unsigned_i32(arguments[2]);
-
- // 1. Let string be ? UnwrapString(string).
- auto string = TRY(unwrap_string(vm, arguments[0]))->utf16_string_view();
-
- // 2. Let length be the length of string.
- auto length = string.length_in_code_units();
-
- // 3. If start > end or start > length,
- if (start > end || start > length) {
- // 1. Return the empty string.
- results[0] = string_reference(vm, Utf16View {});
- return {};
- }
-
- // 4. Return ! Call(String.prototype.substring, string, « ToJSValue(start), ToJSValue(end) »).
- // NB: start <= end here, and String.prototype.substring clamps end to the length.
- auto clamped_end = min<size_t>(end, length);
- results[0] = string_reference(vm, string.substring_view(start, clamped_end - start));
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-equals
-static ErrorOr<void, HostError> equals(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- auto first = js_value_of(vm, arguments[0]);
- auto second = js_value_of(vm, arguments[1]);
-
- // 1. If first is not null and first is not a String,
- if (!first.is_null() && !first.is_string()) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("Expected a string or null"sv);
- }
-
- // 2. If second is not null and second is not a String,
- if (!second.is_null() && !second.is_string()) {
- // 1. Throw a RuntimeError exception as if a trap was executed.
- return trap("Expected a string or null"sv);
- }
-
- // 3. If IsStrictlyEqual(first, second) is true,
- bool strictly_equal = first.is_null() || second.is_null()
- ? first.is_null() && second.is_null()
- : first.as_string().utf16_string_view() == second.as_string().utf16_string_view();
- if (strictly_equal) {
- // 1. Return 1.
- results[0] = WasmValue::from_i32(1);
- return {};
- }
-
- // 4. Return 0.
- results[0] = WasmValue::from_i32(0);
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#js-string-compare
-static ErrorOr<void, HostError> compare(JS::VM& vm, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
- // 1. Let first be ? UnwrapString(first).
- auto first = TRY(unwrap_string(vm, arguments[0]))->utf16_string_view();
-
- // 2. Let second be ? UnwrapString(second).
- auto second = TRY(unwrap_string(vm, arguments[1]))->utf16_string_view();
-
- // 3. If IsStrictlyEqual(first, second) is true,
- if (first == second) {
- // 1. Return 0.
- results[0] = WasmValue::from_i32(0);
- return {};
- }
-
- // 4. If ! IsLessThan(first, second, true) is true,
- // NB: IsLessThan() compares two strings by their code units.
- if ((first <=> second) < 0) {
- // 1. Return -1.
- results[0] = WasmValue::from_i32(-1);
- return {};
- }
-
- // 5. Return 1.
- results[0] = WasmValue::from_i32(1);
- return {};
-}
-
-}
-
-// https://webassembly.github.io/spec/js-api/#string-builtins
-static constexpr Array js_string_builtins {
- Builtin { "cast"sv, ExternrefToRefExtern, JSStringBuiltins::cast },
- Builtin { "test"sv, ExternrefToI32, JSStringBuiltins::test },
- Builtin { "fromCharCodeArray"sv, ArrayI32I32ToRefExtern, JSStringBuiltins::from_char_code_array },
- Builtin { "intoCharCodeArray"sv, ExternrefArrayI32ToI32, JSStringBuiltins::into_char_code_array },
- Builtin { "fromCharCode"sv, I32ToRefExtern, JSStringBuiltins::from_char_code },
- // INTEROP: The funcType of fromCodePoint has a (ref extern) result in other implementations, where the spec has an
- // externref result.
- Builtin { "fromCodePoint"sv, I32ToRefExtern, JSStringBuiltins::from_code_point },
- Builtin { "charCodeAt"sv, ExternrefI32ToI32, JSStringBuiltins::char_code_at },
- Builtin { "codePointAt"sv, ExternrefI32ToI32, JSStringBuiltins::code_point_at },
- Builtin { "length"sv, ExternrefToI32, JSStringBuiltins::length },
- Builtin { "concat"sv, ExternrefExternrefToRefExtern, JSStringBuiltins::concat },
- Builtin { "substring"sv, ExternrefI32I32ToRefExtern, JSStringBuiltins::substring },
- Builtin { "equals"sv, ExternrefExternrefToI32, JSStringBuiltins::equals },
- Builtin { "compare"sv, ExternrefExternrefToI32, JSStringBuiltins::compare },
-};
-
-bool refers_to_a_builtin_set(Utf16String const& builtin_set_name)
-{
- return builtin_set_name == js_string_builtin_set_name;
-}
-
-// https://webassembly.github.io/spec/js-api/#get-the-builtins-for-a-builtin-set
-static ReadonlySpan<Builtin> get_the_builtins_for_a_builtin_set(Utf16String const& builtin_set_name)
-{
- // 1. Return a list of (name, funcType, steps) for the set with name builtinSetName defined within this section.
- VERIFY(refers_to_a_builtin_set(builtin_set_name));
- return js_string_builtins.span();
-}
-
-// https://webassembly.github.io/spec/js-api/#validate-builtin-set-names
-static bool validate_builtin_set_names(ReadonlySpan<Utf16String> builtin_set_names)
-{
- // 1. If builtinSetNames contains any duplicates, return false.
- HashTable<Utf16String> seen_names;
- for (auto const& builtin_set_name : builtin_set_names) {
- if (seen_names.set(builtin_set_name) != HashSetResult::InsertedNewEntry)
- return false;
- }
-
- // 2. Return true.
- return true;
-}
-
-// https://webassembly.github.io/spec/js-api/#find-a-builtin
-static Builtin const* find_a_builtin(Wasm::Runtime::Import const& import, ReadonlySpan<Utf16String> builtin_set_names)
-{
- // 1. Assert: validate builtin set names builtinSetNames is true.
- VERIFY(validate_builtin_set_names(builtin_set_names));
-
- // 2. Let importModuleName be import[0].
- auto import_module_name = import.module;
-
- // 3. Let importName be import[1].
- auto import_name = import.name;
-
- // 4. For each builtinSetName of builtinSetNames,
- for (auto const& builtin_set_name : builtin_set_names) {
- // 1. If builtinSetName does not refer to a builtin set, then continue.
- if (!refers_to_a_builtin_set(builtin_set_name))
- continue;
-
- // 2. Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:".
- auto builtin_set_qualified_name = js_string_builtin_set_qualified_name;
-
- // 3. If importModuleName equals builtinSetQualifiedName,
- if (import_module_name == builtin_set_qualified_name) {
- // 1. Let builtins be the result of get the builtins for a builtin set builtinSetName.
- auto builtins = get_the_builtins_for_a_builtin_set(builtin_set_name);
-
- // 2. For each builtin of builtins,
- for (auto const& builtin : builtins) {
- // 1. Let builtinName be builtin[0].
- // 2. If importName equals builtinName, return (builtinSetName, builtin).
- if (import_name == builtin.name)
- return &builtin;
- }
- }
- }
-
- // 5. Return null.
- return nullptr;
-}
-
-bool import_refers_to_a_builtin(Wasm::Runtime::Import const& import, ReadonlySpan<Utf16String> builtin_set_names)
-{
- return find_a_builtin(import, builtin_set_names) != nullptr;
-}
-
-// https://webassembly.github.io/spec/js-api/#validate-an-import-for-builtins
-static bool validate_an_import_for_builtins(Wasm::Runtime::Module const& module, Wasm::Runtime::Import const& import, ReadonlySpan<Utf16String> builtin_set_names)
-{
- // 1. Assert: validate builtin set names builtinSetNames is true.
- VERIFY(validate_builtin_set_names(builtin_set_names));
-
- // 2. Let maybeBuiltin be the result of finding a builtin for import and builtinSetNames.
- auto const* maybe_builtin = find_a_builtin(import, builtin_set_names);
-
- // 3. If maybeBuiltin is null, return true.
- if (!maybe_builtin)
- return true;
-
- // 4. Let importExternType be import[2].
- auto const& import_extern_type = import.type;
-
- // 5. Let builtinFuncType be maybeBuiltin[1][1].
- auto builtin_func_type = maybe_builtin->function_type;
-
- // 6. Let builtinExternType be func |builtinFuncType|.
- // 7. Return match_externtype(builtinExternType, importExternType).
- // NB: The funcType of a builtin is final and has no supertypes, so it only matches the import's type if both are
- // the same type.
- if (import_extern_type.kind != Wasm::Runtime::ExternKind::Function)
- return false;
- return type_identity(module, import_extern_type.type_index) == type_identity(builtin_types_module(), builtin_func_type);
-}
-
-// https://webassembly.github.io/spec/js-api/#validate-builtins-and-imported-string-for-a-webassembly-module
-bool validate_builtins_and_imported_strings(Wasm::Runtime::Module const& module, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module)
-{
- // 1. If validating builtin set names for builtinSetNames is false, return false.
- if (!validate_builtin_set_names(builtin_set_names))
- return false;
-
- Optional<String> imported_string_module_utf8;
- if (imported_string_module.has_value())
- imported_string_module_utf8 = imported_string_module->to_utf8();
-
- // 2. For each import of module_imports(module),
- for (size_t import_index = 0; import_index < module.import_count(); ++import_index) {
- auto import = module.import(import_index);
-
- // 1. If importedStringModule is not null and import[0] equals importedStringModule,
- if (imported_string_module_utf8.has_value() && import.module == imported_string_module_utf8->bytes_as_string_view()) {
- // 1. Let importExternType be import[2].
- auto const& import_extern_type = import.type;
-
- // 2. Let stringExternType be global ref extern.
- // 3. If match_externtype(stringExternType, importExternType) is false, return false
- // NB: An immutable global matches if (ref extern) is a subtype of the import's value type, which then is
- // (ref extern) or externref.
- if (import_extern_type.kind != Wasm::Runtime::ExternKind::Global
- || import_extern_type.is_mutable
- || import_extern_type.value_type.kind != ValueKind::Reference
- || import_extern_type.value_type.heap != HeapKind::Extern) {
- return false;
- }
- }
- // 2. Else,
- else {
- // 1. If validating an import for builtins with import and builtinSetNames is false, return false.
- if (!validate_an_import_for_builtins(module, import, builtin_set_names))
- return false;
- }
- }
-
- // 3. Return true.
- return true;
-}
-
-// https://webassembly.github.io/spec/js-api/#create-a-builtin-function
-static Wasm::Runtime::Entity create_a_builtin_function(JS::VM& vm, BuiltinTypeIndex function_type, BuiltinSteps steps, u32 index)
-{
- // 1. Let hostfunc be a host function which executes steps when called.
- auto host_function = [&vm, steps](Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) -> ErrorOr<void, HostError> {
- return steps(vm, store, arguments, results);
- };
-
- // 2. Let store be the surrounding agent's associated store.
- // 3. Let (store, funcaddr) be func_alloc(store, funcType, hostfunc).
- // 4. Set the surrounding agent's associated store to store.
- // 5. Return funcaddr.
- // NB: The index is the builtin's position in its set, which names the Exported Function made for it.
- auto type = function_type_in_store(builtin_types_module(), function_type);
- return WebAssemblyCache::the().store().allocate_host_function(type, move(host_function), index);
-}
-
-// https://webassembly.github.io/spec/js-api/#instantiate-a-builtin-set
-GC::Ref<JS::Object> instantiate_a_builtin_set(JS::VM& vm, Utf16String const& builtin_set_name)
-{
- auto& realm = *vm.current_realm();
-
- // 1. Let builtins be the result of get the builtins for a builtin set builtinSetName.
- auto builtins = get_the_builtins_for_a_builtin_set(builtin_set_name);
-
- // 2. Let exportsObject be OrdinaryObjectCreate(null).
- auto exports_object = JS::Object::create(realm, nullptr);
-
- // 3. For each (name, funcType, steps) of builtins,
- for (size_t index = 0; index < builtins.size(); ++index) {
- auto const& builtin = builtins[index];
-
- // 1. Let funcaddr be the result of create a builtin function with funcType and steps.
- auto funcaddr = create_a_builtin_function(vm, builtin.function_type, builtin.steps, static_cast<u32>(index));
-
- // 2. Let func be the result of creating a new Exported Function from funcaddr.
- auto func = create_native_function(realm, funcaddr);
-
- // 3. Let value be func.
- JS::Value value = func;
-
- // 4. Let status be ! CreateDataProperty(exportsObject, name, value).
- auto status = MUST(exports_object->create_data_property(Utf16FlyString::from_utf8(builtin.name), value));
-
- // 5. Assert: status is true.
- VERIFY(status);
- }
-
- // 4. Return exportsObject.
- return exports_object;
-}
-
-// https://webassembly.github.io/spec/js-api/#instantiate-imported-strings
-GC::Ref<JS::Object> instantiate_imported_strings(JS::VM& vm, Wasm::Runtime::Module const& module, Utf16String const& imported_string_module)
-{
- auto& realm = *vm.current_realm();
-
- // 1. Assert: importedStringModule is not null.
- auto imported_string_module_utf8 = imported_string_module.to_utf8();
-
- // 2. Let exportsObject be OrdinaryObjectCreate(null).
- auto exports_object = JS::Object::create(realm, nullptr);
-
- // 3. For each (moduleName, componentName, externtype) of module_imports(module),
- for (size_t import_index = 0; import_index < module.import_count(); ++import_index) {
- auto import = module.import(import_index);
-
- // 1. If moduleName does not equal importedStringModule, then continue.
- if (import.module != imported_string_module_utf8.bytes_as_string_view())
- continue;
-
- // 2. Let stringConstant be componentName.
- auto string_constant = Utf16String::from_utf8(import.name);
-
- // 3. Let status be ! CreateDataProperty(exportsObject, stringConstant, stringConstant).
- auto status = MUST(exports_object->create_data_property(Utf16FlyString::from_utf16(string_constant.utf16_view()), JS::PrimitiveString::create(vm, string_constant)));
-
- // 4. Assert: status is true.
- VERIFY(status);
- }
-
- // 4. Return exportsObject.
- return exports_object;
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Builtins.h b/Libraries/LibWeb/WebAssembly/Builtins.h
deleted file mode 100644
index 3697785142f..00000000000
--- a/Libraries/LibWeb/WebAssembly/Builtins.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Span.h>
-#include <AK/Utf16String.h>
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibWasm/Runtime.h>
-
-namespace Web::WebAssembly::Detail {
-
-bool validate_builtins_and_imported_strings(Wasm::Runtime::Module const&, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module);
-
-// Whether finding a builtin for the import and builtinSetNames does not return null.
-bool import_refers_to_a_builtin(Wasm::Runtime::Import const&, ReadonlySpan<Utf16String> builtin_set_names);
-
-bool refers_to_a_builtin_set(Utf16String const& builtin_set_name);
-GC::Ref<JS::Object> instantiate_a_builtin_set(JS::VM&, Utf16String const& builtin_set_name);
-
-GC::Ref<JS::Object> instantiate_imported_strings(JS::VM&, Wasm::Runtime::Module const&, Utf16String const& imported_string_module);
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Exception.cpp b/Libraries/LibWeb/WebAssembly/Exception.cpp
deleted file mode 100644
index 0d28a387cb4..00000000000
--- a/Libraries/LibWeb/WebAssembly/Exception.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/Error.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/Exception.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Exception.h>
-#include <LibWeb/WebAssembly/Tag.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Exception);
-
-GC::Ref<Exception> Exception::create(u64 exception, Optional<Utf16String> stack)
-{
- // https://webassembly.github.io/spec/js-api/#initialize-an-exception-object
- // 1. Let map be the surrounding agent's associated exception object cache.
- // 2. Assert: map[exnAddr] doesn't exist.
- auto& cache = Detail::WebAssemblyCache::the();
- VERIFY(!cache.exception_object(exception));
-
- // 3. Set exn.[[Address]] to exnAddr.
- // 4. Set map[exnAddr] to exn.
- // 5. Let store be the surrounding agent's associated store.
- // 6. Let tagaddr be exn_tag(store, exnAddr).
- // 7. Let payload be exn_read(store, exnAddr).
- // 8. Set exn.[[Type]] to tagaddr.
- // 9. Set exn.[[Payload]] to payload.
- // NB: The payload of an exception never changes, so getArg() reads it from the store.
- auto tag = cache.store().exception_tag(exception);
- auto object = GC::Heap::the().allocate<Exception>(exception, tag, move(stack));
- cache.set_exception_object(exception, object);
- return object;
-}
-
-// https://webassembly.github.io/spec/js-api/#create-an-exception-object
-GC::Ref<Exception> Exception::from_address(u64 exception)
-{
- // 1. Let map be the surrounding agent's associated exception object cache.
- // 2. If map[exnAddr] exists,
- // 1. Return map[exnAddr].
- if (auto object = Detail::WebAssemblyCache::the().exception_object(exception))
- return *object;
-
- // 3. Let exn be a new Exception.
- // 4. Initialize exn from exnAddr.
- // 5. Set exn.[[Stack]] to undefined.
- // 6. Return exn.
- return create(exception, {});
-}
-
-Exception::Exception(u64 exception, Wasm::Runtime::Entity tag, Optional<Utf16String> stack)
- : m_exception(exception)
- , m_tag(tag)
- , m_stack(move(stack))
-{
-}
-
-void Exception::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- // NB: An exception reference is the address of the exception's cell.
- visitor.visit(reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(m_exception)));
- visitor.visit(m_tag);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-exception-is
-bool Exception::is(Tag const& tag) const
-{
- // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]], return false.
- // 2. Return true.
- return m_tag.ptr() == tag.address();
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-exception-stack
-Variant<Utf16String, Empty> Exception::stack() const
-{
- // 1. Return this.[[Stack]].
- if (m_stack.has_value())
- return *m_stack;
- return Empty {};
-}
-
-}
-
-namespace Web::Bindings {
-
-// https://webassembly.github.io/spec/js-api/#dom-exception-exception
-WebIDL::ExceptionOr<GC::Ref<WebAssembly::Exception>> construct_exception(JS::Realm& realm, WebAssembly::Tag& exception_tag, GC::RootVector<JS::Value> const& payload, ExceptionOptions const& options)
-{
- auto& vm = realm.vm();
- auto& cache = WebAssembly::Detail::WebAssemblyCache::the();
- auto& store = cache.store();
-
- // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.
- // 2. If exceptionTag.[[Address]] is equal to JSTagAddr,
- // 1. Throw a TypeError.
- if (exception_tag.address() == cache.js_tag())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot construct an exception with the JavaScript tag"_utf16 };
-
- // 3. Let store be the surrounding agent's associated store.
- // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).
- auto types = store.tag_parameters(exception_tag.address());
-
- // 5. If types's size is not payload's size,
- // 1. Throw a TypeError.
- if (types.size() != payload.size())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("The tag takes {} values, not {}", types.size(), payload.size()) };
-
- // 6. Let wasmPayload be « ».
- // NB: The converted values may refer to new cells, which this vector keeps alive until they are in the exception.
- Wasm::Runtime::Values wasm_payload;
-
- // 7. For each value and resultType of payload and types, paired linearly,
- for (size_t index = 0; index < payload.size(); ++index) {
- // 1. If resultType is v128 or exnref,
- // 1. Throw a TypeError.
- // 2. Append ? ToWebAssemblyValue(value, resultType) to wasmPayload.
- // NB: ToWebAssemblyValue throws the TypeError for v128 and exnref.
- wasm_payload.append(TRY(WebAssembly::Detail::to_webassembly_value(vm, payload[index], types[index])));
- }
-
- // 8. Let (store, exceptionAddr) be exn_alloc(store, exceptionTag.[[Address]], wasmPayload).
- // 9. Set the surrounding agent's associated store to store.
- auto exception = store.allocate_exception(exception_tag.address(), wasm_payload);
-
- // 10. Initialize this from exceptionAddr.
- // 11. If options["traceStack"] is true,
- // 1. Set this.[[Stack]] to either a DOMString representation of the current call stack or undefined.
- // 12. Otherwise,
- // 1. Set this.[[Stack]] to undefined.
- Optional<Utf16String> stack;
- if (options.trace_stack) {
- auto error = JS::Error::create(realm);
- stack = error->stack_string();
- }
- return WebAssembly::Exception::create(exception, move(stack));
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-exception-getarg
-WebIDL::ExceptionOr<JS::Value> get_arg(WebAssembly::Exception& exception, WebAssembly::Tag& exception_tag, u32 index)
-{
- auto& store = WebAssembly::Detail::WebAssemblyCache::the().store();
-
- // 1. If this.[[Type]] is not equal to exceptionTag.[[Address]],
- // 1. Throw a TypeError.
- if (exception.tag_address() != exception_tag.address())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The exception does not have this tag"_utf16 };
-
- // 2. Let payload be this.[[Payload]].
- auto payload = store.exception_values(exception.address());
-
- // 3. If index ≥ payload's size,
- // 1. Throw a RangeError.
- if (index >= payload.size())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, Utf16String::formatted("The exception has {} values", payload.size()) };
-
- // 4. Let [types] → [] be tag_type(store, exceptionTag.[[Address]]).
- auto types = store.tag_parameters(exception_tag.address());
-
- // 5. If types[index] matches v128 or exnref,
- // 1. Throw a TypeError.
- // 6. Return ToJSValue(payload[index]).
- // NB: ToJSValue throws the TypeError for v128 and exnref.
- return TRY(WebAssembly::Detail::to_js_value(JS::VM::the(), payload[index], types[index]));
-}
-
-WebAssembly::Exception* exception_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Exception>(&value.as_object()) : nullptr;
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Exception.h b/Libraries/LibWeb/WebAssembly/Exception.h
deleted file mode 100644
index 2eee84bdafd..00000000000
--- a/Libraries/LibWeb/WebAssembly/Exception.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <AK/Utf16String.h>
-#include <AK/Variant.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly {
-
-class Tag;
-
-// https://webassembly.github.io/spec/js-api/#exceptions
-class Exception : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Exception, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Exception);
-
-public:
- static GC::Ref<Exception> create(u64 exception, Optional<Utf16String> stack);
- // The Exception object of an exception, which is the same object for as long as it lives.
- static GC::Ref<Exception> from_address(u64 exception);
-
- u64 address() const { return m_exception; }
- Wasm::Runtime::Entity tag_address() const { return m_tag.ptr(); }
-
- bool is(Tag const&) const;
- Variant<Utf16String, Empty> stack() const;
-
-private:
- Exception(u64 exception, Wasm::Runtime::Entity tag, Optional<Utf16String> stack);
-
- virtual void visit_edges(Visitor&) override;
-
- u64 m_exception { 0 };
- GC::Ptr<GC::ForeignCell> m_tag;
- Optional<Utf16String> m_stack;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Exception.idl b/Libraries/LibWeb/WebAssembly/Exception.idl
index 7a8aefb9d42..37eafa6aaa8 100644
--- a/Libraries/LibWeb/WebAssembly/Exception.idl
+++ b/Libraries/LibWeb/WebAssembly/Exception.idl
@@ -4,10 +4,10 @@ dictionary ExceptionOptions {
};
// https://webassembly.github.io/spec/js-api/#exception
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Exception {
- [ImplementedInBindings] constructor(Tag exceptionTag, sequence<any> payload, optional ExceptionOptions options = {});
- [ImplementedInBindings] any getArg(Tag exceptionTag, [EnforceRange] unsigned long index);
+ constructor(Tag exceptionTag, sequence<any> payload, optional ExceptionOptions options = {});
+ any getArg(Tag exceptionTag, [EnforceRange] unsigned long index);
boolean is(Tag exceptionTag);
readonly attribute (DOMString or undefined) stack;
};
diff --git a/Libraries/LibWeb/WebAssembly/Global.cpp b/Libraries/LibWeb/WebAssembly/Global.cpp
deleted file mode 100644
index 8d77e79595b..00000000000
--- a/Libraries/LibWeb/WebAssembly/Global.cpp
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/Global.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Global.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Global);
-
-// https://webassembly.github.io/spec/js-api/#dom-global-global
-GC::Ref<Global> Global::create(GlobalDescriptor const& descriptor, Wasm::Runtime::Value value)
-{
- // 1. Let mutable be descriptor["mutable"].
- // 2. Let valuetype be ToValueType(descriptor["value"]).
- // NB: The bindings reject v128 before getting here.
- VERIFY(descriptor.value.kind != Wasm::Runtime::ValueKind::V128);
-
- // 6. If mutable is true, let globaltype be var valuetype; otherwise, let globaltype be const valuetype.
- // 7. Let store be the current agent’s associated store.
- // 8. Let (store, globaladdr) be global_alloc(store, globaltype, value).
- // 9. Set the current agent’s associated store to store.
- auto global = Detail::WebAssemblyCache::the().store().allocate_global(descriptor.value, descriptor.mutable_, value);
-
- // 10. Initialize this from globaladdr.
- return Global::create(global);
-}
-
-GC::Ref<Global> Global::create(Wasm::Runtime::Entity global)
-{
- // https://webassembly.github.io/spec/js-api/#initialize-a-global-object
- auto& cache = Detail::WebAssemblyCache::the();
- VERIFY(!cache.global_object(global));
- auto object = GC::Heap::the().allocate<Global>(global);
- cache.set_global_object(global, object);
- return object;
-}
-
-Global::Global(Wasm::Runtime::Entity global)
- : m_global(global)
-{
-}
-
-void Global::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_global.ptr());
-}
-
-GlobalType Global::type() const
-{
- // 1. Let store be the current agent’s associated store.
- // 2. Let globaladdr be global.[[Global]].
- // 3. Let globaltype be global_type(store, globaladdr).
- bool is_mutable = false;
- auto value_type = Detail::WebAssemblyCache::the().store().global_type(m_global.ptr(), is_mutable);
- return GlobalType { value_type, is_mutable };
-}
-
-WebIDL::ExceptionOr<Wasm::Runtime::ValueType> Global::value_type() const
-{
- // 4. If globaltype is of the form mut v128, throw a TypeError.
- auto global_type = type();
- if (global_type.value.kind == Wasm::Runtime::ValueKind::V128)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "V128 is not supported as a global value type"_utf16 };
- return global_type.value;
-}
-
-WebIDL::ExceptionOr<Wasm::Runtime::Value> Global::value() const
-{
- (void)TRY(value_type());
-
- // 5. Let value be global_read(store, globaladdr).
- // 6. Return value.
- return Detail::WebAssemblyCache::the().store().global_get(m_global.ptr());
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-global-value
-WebIDL::ExceptionOr<void> Global::set_value(Wasm::Runtime::Value value)
-{
- // NB: Steps 1 to 6 run in the bindings, which check the type before converting the value.
- // 7. Let store be global_write(store, globaladdr, value).
- // 8. If store is error, throw a RangeError exception.
- // 9. Set the current agent’s associated store to store.
- // NB: The store cannot fail, because the bindings checked the type.
- Detail::WebAssemblyCache::the().store().global_set(m_global.ptr(), value);
- return {};
-}
-
-}
-
-namespace Web::Bindings {
-
-// https://webassembly.github.io/spec/js-api/#tovaluetype
-Wasm::Runtime::ValueType to_value_type(ValueType type)
-{
- using Wasm::Runtime::HeapKind;
- using Wasm::Runtime::ValueKind;
- switch (type) {
- case ValueType::I32:
- return Wasm::Runtime::ValueType::scalar(ValueKind::I32);
- case ValueType::I64:
- return Wasm::Runtime::ValueType::scalar(ValueKind::I64);
- case ValueType::F32:
- return Wasm::Runtime::ValueType::scalar(ValueKind::F32);
- case ValueType::F64:
- return Wasm::Runtime::ValueType::scalar(ValueKind::F64);
- case ValueType::V128:
- return Wasm::Runtime::ValueType::scalar(ValueKind::V128);
- case ValueType::Anyfunc:
- return Wasm::Runtime::ValueType::reference(HeapKind::Function);
- case ValueType::Externref:
- return Wasm::Runtime::ValueType::reference(HeapKind::Extern);
- }
-
- VERIFY_NOT_REACHED();
-}
-
-static WebAssembly::GlobalDescriptor global_descriptor_from_bindings(GlobalDescriptor const& descriptor)
-{
- return {
- .value = to_value_type(descriptor.value),
- .mutable_ = descriptor.mutable_,
- };
-}
-
-WebIDL::ExceptionOr<GC::Ref<WebAssembly::Global>> construct_global(JS::Realm& realm, GlobalDescriptor const& descriptor, Optional<JS::Value> value)
-{
- auto global_descriptor = global_descriptor_from_bindings(descriptor);
- if (global_descriptor.value.kind == Wasm::Runtime::ValueKind::V128)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "V128 is not supported as a global value type"_utf16 };
-
- // FIXME: https://github.com/WebAssembly/spec/issues/1861
- // Is there a difference between *missing* and undefined for optional any values?
- auto wasm_value = !value.has_value()
- ? WebAssembly::Detail::default_webassembly_value(realm.vm(), global_descriptor.value)
- : TRY(WebAssembly::Detail::to_webassembly_value(realm.vm(), *value, global_descriptor.value));
-
- return WebAssembly::Global::create(global_descriptor, wasm_value);
-}
-
-// https://webassembly.github.io/spec/js-api/#getglobalvalue
-static WebIDL::ExceptionOr<JS::Value> get_global_value(JS::Realm& realm, WebAssembly::Global& global)
-{
- auto value = TRY(global.value());
- auto value_type = TRY(global.value_type());
- return TRY(WebAssembly::Detail::to_js_value(realm.vm(), value, value_type));
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-global-value
-WebIDL::ExceptionOr<JS::Value> value(JS::Realm& realm, WebAssembly::Global& global)
-{
- return get_global_value(realm, global);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-global-value
-WebIDL::ExceptionOr<void> set_value(JS::Realm& realm, WebAssembly::Global& global, JS::Value the_given_value)
-{
- // 1. Let store be the current agent’s associated store.
- // 2. Let globaladdr be this.[[Global]].
- // 3. Let mut valuetype be global_type(store, globaladdr).
- // 4. If valuetype is v128, throw a TypeError.
- // 5. If mut is const, throw a TypeError.
- auto global_type = global.type();
- auto value_type = global_type.value;
- if (value_type.kind == Wasm::Runtime::ValueKind::V128)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a V128 global"_utf16 };
-
- if (!global_type.mutable_)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a const global"_utf16 };
-
- // 6. Let value be ? ToWebAssemblyValue(the given value, valuetype).
- auto value = TRY(WebAssembly::Detail::to_webassembly_value(realm.vm(), the_given_value, value_type));
- return global.set_value(value);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-global-valueof
-WebIDL::ExceptionOr<JS::Value> value_of(JS::Realm& realm, WebAssembly::Global& global)
-{
- return get_global_value(realm, global);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Global.h b/Libraries/LibWeb/WebAssembly/Global.h
deleted file mode 100644
index 8da96e2ae0e..00000000000
--- a/Libraries/LibWeb/WebAssembly/Global.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2024, Andrew Kaster <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::Bindings {
-
-enum class ValueType : u8;
-
-// https://webassembly.github.io/spec/js-api/#tovaluetype
-Wasm::Runtime::ValueType to_value_type(ValueType);
-
-}
-
-namespace Web::WebAssembly {
-
-struct GlobalDescriptor {
- Wasm::Runtime::ValueType value;
- bool mutable_ { false };
-};
-
-struct GlobalType {
- Wasm::Runtime::ValueType value;
- bool mutable_ { false };
-};
-
-class Global : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Global, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Global);
-
-public:
- static GC::Ref<Global> create(GlobalDescriptor const&, Wasm::Runtime::Value);
- static GC::Ref<Global> create(Wasm::Runtime::Entity global);
-
- GlobalType type() const;
- WebIDL::ExceptionOr<Wasm::Runtime::Value> value() const;
- WebIDL::ExceptionOr<Wasm::Runtime::ValueType> value_type() const;
- WebIDL::ExceptionOr<void> set_value(Wasm::Runtime::Value);
-
- Wasm::Runtime::Entity address() const { return m_global.ptr(); }
-
-private:
- explicit Global(Wasm::Runtime::Entity global);
-
- virtual void visit_edges(Visitor&) override;
-
- GC::Ptr<GC::ForeignCell> m_global;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Global.idl b/Libraries/LibWeb/WebAssembly/Global.idl
index 7f251089faf..c5e924e8e52 100644
--- a/Libraries/LibWeb/WebAssembly/Global.idl
+++ b/Libraries/LibWeb/WebAssembly/Global.idl
@@ -16,9 +16,9 @@ dictionary GlobalDescriptor {
};
// https://webassembly.github.io/spec/js-api/#global
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Global {
- [ImplementedInBindings] constructor(GlobalDescriptor descriptor, optional any v);
- [ImplementedInBindings, NeedsCallerRealm] any valueOf();
- [ImplementedInBindings, NeedsCallerRealm] attribute any value;
+ constructor(GlobalDescriptor descriptor, optional any v);
+ [NeedsCallerRealm] any valueOf();
+ [NeedsCallerRealm] attribute any value;
};
diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cpp
deleted file mode 100644
index 45cfc3dbe5b..00000000000
--- a/Libraries/LibWeb/WebAssembly/Instance.cpp
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <LibGC/Heap.h>
-#include <LibGC/Root.h>
-#include <LibGC/WeakInlines.h>
-#include <LibJS/Runtime/Environment.h>
-#include <LibJS/Runtime/NativeFunction.h>
-#include <LibJS/Runtime/Object.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/HostDefined.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Global.h>
-#include <LibWeb/WebAssembly/Instance.h>
-#include <LibWeb/WebAssembly/Memory.h>
-#include <LibWeb/WebAssembly/Module.h>
-#include <LibWeb/WebAssembly/Table.h>
-#include <LibWeb/WebAssembly/Tag.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Instance);
-
-// https://webassembly.github.io/spec/js-api/#dom-instance-instance
-WebIDL::ExceptionOr<GC::Ref<Instance>> Instance::create(JS::Realm& realm, Module& module_object, GC::Ptr<JS::Object> import_object)
-{
- // 1. Let builtinSetNames be moduleObject.[[BuiltinSets]].
- auto const& builtin_set_names = module_object.builtin_sets();
-
- // 2. Let importedStringModule be moduleObject.[[ImportedStringModule]].
- auto const& imported_string_module = module_object.imported_string_module();
-
- // 3. Let module be moduleObject.[[Module]].
- auto const& module = *module_object.compiled_module()->module;
-
- // 4. Read the imports of module with imports importObject, builtinSetNames, and importedStringModule, and let
- // imports be the result.
- // 5. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
- auto instance = TRY(Detail::instantiate_module(realm.vm(), module, import_object, builtin_set_names, imported_string_module));
-
- // 6. Initialize this from module and instance.
- return Instance::create(realm, instance);
-}
-
-GC::Ref<Instance> Instance::create(JS::Realm& realm, Wasm::Runtime::Entity instance)
-{
- return GC::Heap::the().allocate<Instance>(Bindings::host_defined_wrapper_world(realm), instance);
-}
-
-Instance::Instance(Bindings::WrapperWorld& wrapper_world, Wasm::Runtime::Entity instance)
- : m_instance(instance)
- , m_wrapper_world(wrapper_world)
-{
-}
-
-GC::Ref<Global> Instance::global_instance(Wasm::Runtime::Entity global)
-{
- if (auto object = Detail::WebAssemblyCache::the().global_object(global))
- return *object;
- return Global::create(global);
-}
-
-GC::Ref<Memory> Instance::memory_instance(Wasm::Runtime::Entity memory)
-{
- auto& cache = Detail::WebAssemblyCache::the();
- if (auto object = cache.memory_object(memory))
- return *object;
- auto shared = cache.store().memory_limits(memory).shared ? Memory::Shared::Yes : Memory::Shared::No;
- return Memory::create(memory, shared);
-}
-
-GC::Ref<Table> Instance::table_instance(Wasm::Runtime::Entity table)
-{
- if (auto object = Detail::WebAssemblyCache::the().table_object(table))
- return *object;
- return Table::create(table);
-}
-
-void Instance::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_instance);
- visitor.visit(m_wrapper_world);
-}
-
-}
-
-namespace Web::Bindings {
-
-WebIDL::ExceptionOr<GC::Ref<WebAssembly::Instance>> construct_instance(JS::Realm& realm, WebAssembly::Module& module, GC::Ptr<JS::Object> import_object)
-{
- return WebAssembly::Instance::create(realm, module, import_object);
-}
-
-struct InstanceExportsCache {
- GC::Weak<WebAssembly::Instance> instance;
- GC::Weak<JS::Object> exports;
-};
-
-static Vector<InstanceExportsCache>& instance_exports_caches()
-{
- static NeverDestroyed<Vector<InstanceExportsCache>> caches;
- return *caches;
-}
-
-static void prune_instance_exports_caches()
-{
- instance_exports_caches().remove_all_matching([](auto const& cache) {
- return !cache.instance;
- });
-}
-
-static InstanceExportsCache& instance_exports_cache_for(WebAssembly::Instance& instance)
-{
- auto& caches = instance_exports_caches();
- prune_instance_exports_caches();
-
- for (auto& cache : caches) {
- if (cache.instance.ptr() == GC::Ref { instance })
- return cache;
- }
-
- caches.append(InstanceExportsCache { instance, {} });
- return caches.last();
-}
-
-static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::Instance& instance)
-{
- auto exports = GC::make_root(JS::Object::create(realm, nullptr));
-
- // https://webassembly.github.io/spec/js-api/#create-an-exports-object
- for (auto& export_ : WebAssembly::Detail::WebAssemblyCache::the().store().instance_exports(instance.instance_address())) {
- auto name = Utf16FlyString::from_utf8(export_.name);
- auto address = export_.value.entity.ptr();
-
- switch (export_.value.kind) {
- case Wasm::Runtime::ExternKind::Function: {
- auto object = WebAssembly::Detail::create_native_function(realm, address);
- exports->define_direct_property(name, object, JS::default_attributes);
- break;
- }
- case Wasm::Runtime::ExternKind::Global:
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, instance.global_instance(address)), JS::default_attributes);
- break;
- case Wasm::Runtime::ExternKind::Memory:
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, instance.memory_instance(address)), JS::default_attributes);
- break;
- case Wasm::Runtime::ExternKind::Table:
- exports->define_direct_property(name, table(realm, instance.table_instance(address)), JS::default_attributes);
- break;
- case Wasm::Runtime::ExternKind::Tag:
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, WebAssembly::Tag::from_address(realm, address)), JS::default_attributes);
- break;
- }
- }
-
- MUST(exports->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
- return GC::Ref { *exports };
-}
-
-GC::Ref<JS::Object const> exports(JS::Realm& realm, GC::Ref<WebAssembly::Instance> instance)
-{
- // NB: An instance's exports, like its memories and tables, belong to the world it was created in.
- VERIFY(&host_defined_wrapper_world(realm) == &instance->wrapper_world());
-
- auto& cache = instance_exports_cache_for(instance);
- if (cache.exports)
- return cache.exports.ptr().as_nonnull();
-
- auto exports = create_exports_object(realm, instance);
- cache.exports = exports;
- return exports;
-}
-
-JS::ThrowCompletionOr<void> initialize_webassembly_export_binding(JS::Realm& realm, JS::Environment& environment, Utf16FlyString const& name, GC::Ref<WebAssembly::Instance> instance)
-{
- auto exports = Bindings::exports(realm, instance);
- return environment.initialize_binding(realm.vm(), name, TRY(exports->get(JS::PropertyKey { name })), JS::Environment::InitializeBindingHint::Normal);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Instance.h b/Libraries/LibWeb/WebAssembly/Instance.h
deleted file mode 100644
index 8ef9f5e810e..00000000000
--- a/Libraries/LibWeb/WebAssembly/Instance.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::WebAssembly {
-
-class Instance : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Instance, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Instance);
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<Instance>> create(JS::Realm&, Module& module, GC::Ptr<JS::Object> import_object);
- static GC::Ref<Instance> create(JS::Realm&, Wasm::Runtime::Entity instance);
-
- Wasm::Runtime::Entity instance_address() const { return m_instance.ptr(); }
- // The world of the realm the instance was created in, the only one whose realms may read its exports.
- Bindings::WrapperWorld const& wrapper_world() const { return *m_wrapper_world; }
- GC::Ref<Global> global_instance(Wasm::Runtime::Entity);
- GC::Ref<Memory> memory_instance(Wasm::Runtime::Entity);
- GC::Ref<Table> table_instance(Wasm::Runtime::Entity);
-
-private:
- Instance(Bindings::WrapperWorld&, Wasm::Runtime::Entity instance);
-
- virtual void visit_edges(Visitor&) override;
-
- GC::Ptr<GC::ForeignCell> m_instance;
- GC::Ref<Bindings::WrapperWorld> m_wrapper_world;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Instance.idl b/Libraries/LibWeb/WebAssembly/Instance.idl
index 022e6cc0d3a..a95cdfc665c 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.idl
+++ b/Libraries/LibWeb/WebAssembly/Instance.idl
@@ -1,7 +1,7 @@
// https://webassembly.github.io/spec/js-api/#instances
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Instance {
- [ImplementedInBindings] constructor(Module module, optional object importObject);
+ constructor(Module module, optional object importObject);
- [ImplementedInBindings] readonly attribute object exports;
+ readonly attribute object exports;
};
diff --git a/Libraries/LibWeb/WebAssembly/Memory.cpp b/Libraries/LibWeb/WebAssembly/Memory.cpp
deleted file mode 100644
index 2892154c7ab..00000000000
--- a/Libraries/LibWeb/WebAssembly/Memory.cpp
+++ /dev/null
@@ -1,459 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <AK/NeverDestroyed.h>
-#include <LibGC/Root.h>
-#include <LibGC/WeakInlines.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/WebAssembly/Memory.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Memory);
-
-struct MemoryBufferCache {
- GC::Weak<Memory> memory;
- GC::Weak<JS::ArrayBuffer> primary_buffer;
- Vector<GC::Weak<JS::ArrayBuffer>> live_buffer_objects;
-};
-
-static Vector<MemoryBufferCache>& memory_buffer_caches()
-{
- static NeverDestroyed<Vector<MemoryBufferCache>> caches;
- return *caches;
-}
-
-static void prune_memory_buffer_cache(MemoryBufferCache& cache)
-{
- cache.live_buffer_objects.remove_all_matching([](auto const& buffer) { return !buffer; });
-}
-
-static void prune_memory_buffer_caches()
-{
- memory_buffer_caches().remove_all_matching([](auto const& cache) {
- return !cache.memory;
- });
-}
-
-static MemoryBufferCache& memory_buffer_cache_for(Memory const& memory)
-{
- auto& caches = memory_buffer_caches();
- prune_memory_buffer_caches();
-
- for (auto& cache : caches) {
- if (cache.memory.ptr() == GC::Ref { memory })
- return cache;
- }
-
- caches.append(MemoryBufferCache { const_cast<Memory&>(memory), {}, {} });
- return caches.last();
-}
-
-static size_t memory_size(Memory& memory)
-{
- return Memory::cache().store().memory(memory.address()).size();
-}
-
-static JS::DataBlock::ExternalPrimitiveStorage external_memory_storage(Memory& memory, bool fixed_length)
-{
- auto handle = Memory::cache().store().memory_primitive_storage_handle(memory.address());
- if (fixed_length)
- return JS::DataBlock::ExternalPrimitiveStorage { GC::Ref<GC::Cell> { memory }, handle, memory_size(memory) };
- return JS::DataBlock::ExternalPrimitiveStorage { GC::Ref<GC::Cell> { memory }, handle };
-}
-
-static GC::Ref<JS::ArrayBuffer> create_a_fixed_length_memory_buffer(JS::VM& vm, JS::Realm& buffer_realm, Memory& memory)
-{
- GC::Ptr<JS::ArrayBuffer> array_buffer;
- // https://webassembly.github.io/threads/js-api/index.html#create-a-fixed-length-memory-buffer
- // 3. If share is shared,
- if (memory.is_shared()) {
- // 1. Let block be a Shared Data Block which is identified with the underlying memory of memaddr.
- // 2. Let buffer be a new SharedArrayBuffer with the internal slots [[ArrayBufferData]] and [[ArrayBufferByteLength]].
- // 3. Set buffer.[[ArrayBufferData]] to block.
- // 4. Set buffer.[[ArrayBufferByteLength]] to the length of block.
- // NOTE: ArrayBufferByteLength should contain the original size regardless of growth.
- array_buffer = JS::ArrayBuffer::create(buffer_realm, JS::DataBlock { external_memory_storage(memory, true), JS::DataBlock::Shared::Yes });
- VERIFY(array_buffer->byte_length() == memory_size(memory));
-
- // 5. Perform ! SetIntegrityLevel(buffer, "frozen").
- MUST(array_buffer->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
- } else {
- // 4. Otherwise,
- array_buffer = JS::ArrayBuffer::create(buffer_realm, JS::DataBlock { external_memory_storage(memory, true), JS::DataBlock::Shared::No });
- array_buffer->set_detach_key(JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string));
- }
-
- return array_buffer.as_nonnull();
-}
-
-// https://webassembly.github.io/spec/js-api/#create-a-resizable-memory-buffer
-static JS::ThrowCompletionOr<GC::Ref<JS::ArrayBuffer>> create_a_resizable_memory_buffer(JS::VM& vm, JS::Realm& buffer_realm, Memory& memory, size_t max_size)
-{
- // 3. If maxsize > (65536 x 65536),
- if (max_size > (65536 * Detail::page_size)) {
- // 1. Throw a RangeError exception.
- return vm.throw_completion<JS::RangeError>("Maximum memory length exceeds 65536 * 65536 bytes"_utf16);
- }
-
- // https://webassembly.github.io/threads/js-api/index.html#create-a-resizable-memory-buffer
- // 5. If share is shared,
- if (memory.is_shared()) {
- // 1. Let block be a Shared Data Block which is identified with the underlying memory of memaddr.
- // 2. Let buffer be a new SharedArrayBuffer with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], and [[ArrayBufferMaxByteLength]].
- // 3. Set buffer.[[ArrayBufferData]] to block.
- auto buffer = JS::ArrayBuffer::create(buffer_realm, JS::DataBlock { external_memory_storage(memory, false), JS::DataBlock::Shared::Yes });
-
- // AD-HOC: The threads proposal uses the memory type's minimum for both shared and
- // non-shared memories, but the upstream spec uses the memory instance's current
- // size. We assume the upstream spec is correct for both cases.
- // 4. Set buffer.[[ArrayBufferByteLength]] to min.
- VERIFY(buffer->byte_length() == memory_size(memory));
-
- // 5. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
- buffer->set_max_byte_length(max_size);
-
- // 6. Perform ! SetIntegrityLevel(buffer, "frozen").
- MUST(buffer->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
-
- // AD-HOC: Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
- // SharedArrayBuffers can't be detached, but this allows us to bail early from HostGrowSharedArrayBuffer
- // for SharedArrayBuffers not associated with a WebAssembly memory.
- buffer->set_detach_key(JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string));
-
- // 7. Return buffer.
- return buffer;
- }
-
- // 6. Otherwise,
- // 1. Let block be a Data Block which is identified with the underlying memory of memaddr.
- // 4. Let buffer be a new ArrayBuffer with the internal slots [[ArrayBufferData]], [[ArrayBufferByteLength]], [[ArrayBufferMaxByteLength]], and [[ArrayBufferDetachKey]].
- // 5. Set buffer.[[ArrayBufferData]] to block.
- auto buffer = JS::ArrayBuffer::create(buffer_realm, JS::DataBlock { external_memory_storage(memory, false), JS::DataBlock::Shared::No });
-
- // 2. Let length be the length of block.
- // 6. Set buffer.[[ArrayBufferByteLength]] to length.
- VERIFY(buffer->byte_length() == memory_size(memory));
-
- // 7. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
- buffer->set_max_byte_length(max_size);
-
- // 8. Set buffer.[[ArrayBufferDetachKey]] to "WebAssembly.Memory".
- buffer->set_detach_key(JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string));
-
- // 9. Return buffer.
- return buffer;
-}
-
-static void set_buffer_object_for_realm(JS::Realm&, Memory&, GC::Ref<JS::ArrayBuffer>);
-
-static GC::Ref<JS::ArrayBuffer> buffer_object_for_realm(JS::Realm& buffer_realm, Memory& memory)
-{
- auto& cache = memory_buffer_cache_for(memory);
-
- if (cache.primary_buffer && &buffer_realm == &cache.primary_buffer->shape().realm())
- return GC::Ref { *cache.primary_buffer };
-
- prune_memory_buffer_cache(cache);
- for (auto const& buffer : cache.live_buffer_objects) {
- if (&buffer->shape().realm() == &buffer_realm)
- return GC::Ref { *buffer };
- }
-
- auto buffer = create_a_fixed_length_memory_buffer(buffer_realm.vm(), buffer_realm, memory);
- set_buffer_object_for_realm(buffer_realm, memory, buffer);
- return buffer;
-}
-
-static void set_buffer_object_for_realm(JS::Realm& buffer_realm, Memory& memory, GC::Ref<JS::ArrayBuffer> buffer)
-{
- auto& cache = memory_buffer_cache_for(memory);
-
- if (!cache.primary_buffer || &buffer_realm == &cache.primary_buffer->shape().realm()) {
- cache.primary_buffer = buffer;
- return;
- }
-
- prune_memory_buffer_cache(cache);
- for (auto& live_buffer : cache.live_buffer_objects) {
- if (&live_buffer->shape().realm() == &buffer_realm) {
- live_buffer = buffer;
- return;
- }
- }
-
- cache.live_buffer_objects.append(buffer);
-}
-
-static void refresh_buffer_object(Memory& memory, GC::Ref<JS::ArrayBuffer> buffer)
-{
- auto& vm = buffer->shape().realm().vm();
-
- // 4. Let buffer be memory.[[BufferObject]].
-
- // 5. If IsFixedLengthArrayBuffer(buffer) is true,
- if (buffer->is_fixed_length()) {
- // https://webassembly.github.io/threads/js-api/index.html#refresh-the-memory-buffer
- // 1. If IsSharedArrayBuffer(buffer) is false,
- if (!buffer->is_shared_array_buffer()) {
- // 1. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
- MUST(JS::detach_array_buffer(vm, *buffer, JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string)));
- }
-
- // 2. Let newBuffer be the result of creating a fixed length memory buffer from memaddr.
- // 3. Set memory.[[BufferObject]] to newBuffer.
- set_buffer_object_for_realm(buffer->shape().realm(), memory, create_a_fixed_length_memory_buffer(vm, buffer->shape().realm(), memory));
- } else {
- // 1. Let block be a Data Block which is identified with the underlying memory of memaddr.
- // AD-HOC: Neither the main spec nor the threads proposal specify that the Data Block should be Shared for
- // shared Wasm memories, but we do in fact want a Shared Data Block in that case.
- auto is_shared = buffer->is_shared_array_buffer() ? JS::DataBlock::Shared::Yes : JS::DataBlock::Shared::No;
-
- // 2. Set buffer.[[ArrayBufferData]] to block.
- // 3. Set buffer.[[ArrayBufferByteLength]] to the length of block.
- buffer->set_data_block({ external_memory_storage(memory, false), is_shared });
- }
-}
-
-static void refresh_buffer_objects(Memory& memory)
-{
- auto& cache = memory_buffer_cache_for(memory);
- GC::RootVector<GC::Ref<JS::ArrayBuffer>> buffer_objects;
-
- if (cache.primary_buffer)
- buffer_objects.append(GC::Ref { *cache.primary_buffer });
-
- prune_memory_buffer_cache(cache);
- for (auto const& buffer : cache.live_buffer_objects) {
- bool already_appended = false;
- for (auto const& buffer_object : buffer_objects) {
- if (buffer_object == buffer.ptr()) {
- already_appended = true;
- break;
- }
- }
- if (!already_appended)
- buffer_objects.append(GC::Ref { *buffer });
- }
-
- for (auto buffer : buffer_objects)
- refresh_buffer_object(memory, buffer);
-}
-
-WebIDL::ExceptionOr<GC::Ref<Memory>> Memory::create(MemoryDescriptor const& descriptor)
-{
- // https://webassembly.github.io/threads/js-api/index.html#dom-memory-memory
- // 3. If maximum is not empty and maximum < initial, throw a RangeError exception.
- if (descriptor.maximum.has_value() && descriptor.maximum.value() < descriptor.initial) {
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Initial is larger than maximum."_utf16 };
- }
-
- // 4. Let share be shared if descriptor["shared"] is true and unshared otherwise.
- // 5. If share is shared and maximum is empty, throw a TypeError exception.
- auto shared = descriptor.shared;
- if (shared && !descriptor.maximum.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Maximum has to be specified for shared memory."_utf16 };
-
- Wasm::Runtime::Limits limits {
- .minimum = descriptor.initial,
- .maximum = descriptor.maximum.value_or(0),
- .has_maximum = descriptor.maximum.has_value(),
- .address64 = false,
- .shared = shared,
- };
-
- auto memory = cache().store().allocate_memory(limits);
- if (!memory.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Wasm Memory allocation failed"_utf16 };
-
- return Memory::create(*memory, shared ? Shared::Yes : Shared::No);
-}
-
-GC::Ref<Memory> Memory::create(Wasm::Runtime::Entity memory, Shared shared)
-{
- // https://webassembly.github.io/spec/js-api/#initialize-a-memory-object
- VERIFY(!cache().memory_object(memory));
- auto object = GC::Heap::the().allocate<Memory>(memory, shared);
- cache().set_memory_object(memory, object);
- return object;
-}
-
-WebIDL::ExceptionOr<GC::Ref<Memory>> Memory::create_for_constructor(JS::Object&, MemoryDescriptor const& descriptor)
-{
- return Memory::create(descriptor);
-}
-
-Memory::Memory(Wasm::Runtime::Entity memory, Shared shared)
- : m_memory(memory)
- , m_shared(shared)
-{
-}
-
-void Memory::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_memory);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-memory-grow
-WebIDL::ExceptionOr<u32> Memory::grow(u32 delta)
-{
- auto previous_size = cache().store().grow_memory(address(), delta);
- if (previous_size < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Memory.grow() grows past the stated limit of the memory instance"_utf16 };
-
- refresh_the_memory_buffer(*this);
-
- return static_cast<u32>(previous_size);
-}
-
-// https://webassembly.github.io/threads/js-api/index.html#dom-memory-tofixedlengthbuffer
-WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::to_fixed_length_buffer(JS::Realm& realm)
-{
- auto& vm = realm.vm();
- auto& buffer_realm = realm;
-
- // 1. Let buffer be this.[[BufferObject]].
- auto buffer = buffer_object_for_realm(buffer_realm, *this);
-
- // 2. Let memaddr be this.[[Memory]].
- // 3. If IsSharedArrayBuffer(buffer) is false,
- if (!is_shared()) {
- // 1. If IsFixedLengthArrayBuffer(buffer) is true, return buffer.
- if (buffer->is_fixed_length())
- return buffer;
-
- // 2. Otherwise,
- // 1. Let fixedBuffer be the result of creating a fixed length memory buffer from memaddr.
- auto fixed_buffer = create_a_fixed_length_memory_buffer(vm, buffer_realm, *this);
-
- // 2. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
- MUST(JS::detach_array_buffer(vm, *buffer, JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string)));
-
- // 3. Set this.[[BufferObject]] to fixedBuffer.
- set_buffer_object_for_realm(buffer_realm, *this, fixed_buffer);
-
- // 4. Return fixedBuffer.
- return fixed_buffer;
- }
-
- // 4. Otherwise,
- // 1. Let map be the surrounding agent's associated Memory object cache.
- // 2. Assert: map[memaddr] exists.
- // 3. Let newMemory be map[memaddr].
- auto new_memory = cache().memory_object(address());
- VERIFY(new_memory);
-
- // 4. Let newBufferObject be newMemory.[[BufferObject]].
- auto new_buffer_object = buffer_object_for_realm(buffer_realm, *new_memory);
-
- // 5. Set this.[[BufferObject]] to newBufferObject.
- set_buffer_object_for_realm(buffer_realm, *this, new_buffer_object);
-
- // 6. Return newBufferObject.
- return new_buffer_object;
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-memory-toresizablebuffer
-WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::to_resizable_buffer(JS::Realm& realm)
-{
- auto& vm = realm.vm();
- auto& buffer_realm = realm;
-
- // 1. Let buffer be this.[[BufferObject]].
- auto buffer = buffer_object_for_realm(buffer_realm, *this);
-
- // 2. If IsFixedLengthArrayBuffer(buffer) is false, return buffer.
- if (!buffer->is_fixed_length())
- return buffer;
-
- // 3. Let memaddr be this.[[Memory]].
- // 4. Let store be the surrounding agent's associated store.
- // 5. Let memtype be mem_type(store, memaddr).
- auto limits = cache().store().memory_limits(address());
-
- // 6. If memtype has a max,
- // 1. Let maxsize be the max value in memtype.
- // 7. Otherwise,
- // 1. Let maxsize be 65536 x 65536.
- size_t max_size = limits.maximum_if_any().value_or(65536) * Detail::page_size;
-
- // 8. Let resizableBuffer be the result of creating a resizable memory buffer from memaddr and maxsize.
- auto resizable_buffer = TRY(create_a_resizable_memory_buffer(vm, buffer_realm, *this, max_size));
-
- // https://webassembly.github.io/threads/js-api/index.html#dom-memory-toresizablebuffer
- // 5. If IsSharedArrayBuffer(buffer) is false,
- // 9. Perform ! DetachArrayBuffer(buffer, "WebAssembly.Memory").
- if (!buffer->is_shared_array_buffer())
- MUST(JS::detach_array_buffer(vm, *buffer, JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string)));
-
- // 10. Set this.[[BufferObject]] to resizableBuffer.
- set_buffer_object_for_realm(buffer_realm, *this, resizable_buffer);
-
- // 11. Return resizeableBuffer.
- return resizable_buffer;
-}
-
-// https://webassembly.github.io/threads/js-api/#dom-memory-buffer
-WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::buffer(JS::Realm& realm)
-{
- auto& buffer_realm = realm;
-
- // 1. Let memaddr be this.[[Memory]].
- // 2. Let block be a Data Block which is identified with the underlying memory of memaddr.
- // 3. If block is a Shared Data Block,
- if (is_shared()) {
- // 1. Let map be the surrounding agent's associated Memory object cache.
- // 2. Assert: map[memaddr] exists.
- // 3. Let newMemory be map[memaddr].
- auto new_memory = cache().memory_object(address());
- VERIFY(new_memory);
-
- // 4. Let newBufferObject be newMemory.[[BufferObject]].
- auto new_buffer_object = buffer_object_for_realm(buffer_realm, *new_memory);
-
- // 5. Set this.[[BufferObject]] to newBufferObject.
- set_buffer_object_for_realm(buffer_realm, *this, new_buffer_object);
-
- // 6. Return newBufferObject.
- return new_buffer_object;
- }
-
- // 4. Otherwise,
- // 1. Return this.[[BufferObject]].
- return buffer_object_for_realm(buffer_realm, *this);
-}
-
-bool memory_has_buffer_object(Memory const& memory, JS::ArrayBuffer const& buffer)
-{
- auto& cache = memory_buffer_cache_for(memory);
-
- if (cache.primary_buffer.ptr() == GC::Ref { buffer })
- return true;
-
- prune_memory_buffer_cache(cache);
- for (auto const& live_buffer : cache.live_buffer_objects) {
- if (live_buffer.ptr() == GC::Ref { buffer })
- return true;
- }
-
- return false;
-}
-
-// https://webassembly.github.io/spec/js-api/#refresh-the-memory-buffer
-void refresh_the_memory_buffer(Memory& memory)
-{
- // 1. Let map be the surrounding agent's associated Memory object cache.
- // 2. Assert: map[memaddr] exists.
- // 3. Let memory be map[memaddr].
- refresh_buffer_objects(memory);
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Memory.h b/Libraries/LibWeb/WebAssembly/Memory.h
deleted file mode 100644
index ea410bb9781..00000000000
--- a/Libraries/LibWeb/WebAssembly/Memory.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Memory.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace JS {
-
-class ArrayBuffer;
-class Realm;
-
-}
-
-namespace Web::WebAssembly {
-
-using MemoryDescriptor = Bindings::MemoryDescriptor;
-
-class Memory : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Memory, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Memory);
-
- enum class Shared {
- No,
- Yes,
- };
-
-public:
- static WebIDL::ExceptionOr<GC::Ref<Memory>> create(MemoryDescriptor const&);
- static GC::Ref<Memory> create(Wasm::Runtime::Entity memory, Shared);
- static WebIDL::ExceptionOr<GC::Ref<Memory>> create_for_constructor(JS::Object&, MemoryDescriptor const&);
-
- WebIDL::ExceptionOr<u32> grow(u32 delta);
- WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> to_fixed_length_buffer(JS::Realm&);
- WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> to_resizable_buffer(JS::Realm&);
- WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> buffer(JS::Realm&);
-
- Wasm::Runtime::Entity address() const { return m_memory.ptr(); }
- bool is_shared() const { return m_shared == Shared::Yes; }
- static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }
-
-private:
- Memory(Wasm::Runtime::Entity memory, Shared shared);
-
- virtual void visit_edges(Visitor&) override;
-
- GC::Ptr<GC::ForeignCell> m_memory;
- Shared m_shared { Shared::No };
-};
-
-bool memory_has_buffer_object(Memory const&, JS::ArrayBuffer const&);
-void refresh_the_memory_buffer(Memory&);
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Memory.idl b/Libraries/LibWeb/WebAssembly/Memory.idl
index 46cfe92f3e9..d3b79f181a4 100644
--- a/Libraries/LibWeb/WebAssembly/Memory.idl
+++ b/Libraries/LibWeb/WebAssembly/Memory.idl
@@ -7,7 +7,7 @@ dictionary MemoryDescriptor {
};
// https://webassembly.github.io/spec/js-api/#memories
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Memory {
constructor(MemoryDescriptor descriptor);
diff --git a/Libraries/LibWeb/WebAssembly/Module.cpp b/Libraries/LibWeb/WebAssembly/Module.cpp
deleted file mode 100644
index 86efed8bba6..00000000000
--- a/Libraries/LibWeb/WebAssembly/Module.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/Module.h>
-#include <LibWeb/Bindings/PrincipalHostDefined.h>
-#include <LibWeb/Bindings/WebAssembly.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/StructuredSerialize.h>
-#include <LibWeb/WebAssembly/Builtins.h>
-#include <LibWeb/WebAssembly/Module.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/Buffers.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Module);
-
-static Optional<Bindings::ImportExportKind> import_export_kind(Wasm::Runtime::ExternKind kind)
-{
- switch (kind) {
- case Wasm::Runtime::ExternKind::Function:
- return Bindings::ImportExportKind::Function;
- case Wasm::Runtime::ExternKind::Table:
- return Bindings::ImportExportKind::Table;
- case Wasm::Runtime::ExternKind::Memory:
- return Bindings::ImportExportKind::Memory;
- case Wasm::Runtime::ExternKind::Global:
- return Bindings::ImportExportKind::Global;
- case Wasm::Runtime::ExternKind::Tag:
- return {};
- }
- VERIFY_NOT_REACHED();
-}
-
-GC::Ref<Module> Module::create()
-{
- return GC::Heap::the().allocate<Module>();
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-module-module
-WebIDL::ExceptionOr<GC::Ref<Module>> Module::create(JS::Realm& realm, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const& options)
-{
- auto& vm = realm.vm();
-
- // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
- auto stable_bytes_or_error = WebIDL::get_buffer_source_copy(bytes);
- if (stable_bytes_or_error.is_error()) {
- VERIFY(stable_bytes_or_error.error().code() == ENOMEM);
- return vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
- }
- auto stable_bytes = stable_bytes_or_error.release_value();
-
- // 2. Compile the WebAssembly module stableBytes and store the result as module.
- // 3. If module is error, throw a CompileError exception.
- auto module = TRY(Detail::compile_a_webassembly_module(realm, stable_bytes));
-
- // 4. Let builtinSetNames be options["builtins"].
- auto const& builtin_set_names = options.builtins;
-
- // 5. Let importedStringModule be options["importedStringConstants"].
- auto const& imported_string_module = options.imported_string_constants;
-
- // 6. If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns
- // false, throw a CompileError exception.
- if (!Detail::validate_builtins_and_imported_strings(*module->module, builtin_set_names, imported_string_module))
- return vm.throw_completion<CompileError>("Invalid builtin or imported string"sv);
-
- // 7. Set this.[[Module]] to module.
- // 8. Set this.[[Bytes]] to stableBytes.
- // 9. Set this.[[BuiltinSets]] to builtinSetNames.
- // 10. Set this.[[ImportedStringModule]] to importedStringModule.
- return GC::Heap::the().allocate<Module>(move(module), move(stable_bytes), builtin_set_names, imported_string_module);
-}
-
-Module::Module(NonnullRefPtr<Detail::CompiledWebAssemblyModule> compiled_module, ByteBuffer bytes, Vector<Utf16String> builtin_sets, Optional<Utf16String> imported_string_module)
- : m_compiled_module(move(compiled_module))
- , m_bytes(move(bytes))
- , m_builtin_sets(move(builtin_sets))
- , m_imported_string_module(move(imported_string_module))
-{
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-module-imports
-WebIDL::ExceptionOr<Vector<Bindings::ModuleImportDescriptor>> Module::imports(GC::Ref<Module> module_object)
-{
- // 1. Let module be moduleObject.[[Module]].
- auto& module = *module_object->m_compiled_module->module;
-
- // 2. Let builtinSetNames be moduleObject.[[BuiltinSets]].
- auto const& builtin_set_names = module_object->m_builtin_sets;
-
- // 3. Let importedStringModule be moduleObject.[[ImportedStringModule]].
- Optional<String> imported_string_module;
- if (module_object->m_imported_string_module.has_value())
- imported_string_module = module_object->m_imported_string_module->to_utf8();
-
- // 4. Let imports be « ».
- Vector<Bindings::ModuleImportDescriptor> import_objects;
-
- // 5. For each (moduleName, name, type) of module_imports(module),
- auto import_count = module.import_count();
- import_objects.ensure_capacity(import_count);
- for (size_t index = 0; index < import_count; ++index) {
- auto import = module.import(index);
-
- // 1. If find a builtin for (moduleName, name, type) and builtinSetNames is not null, then continue.
- if (Detail::import_refers_to_a_builtin(import, builtin_set_names))
- continue;
-
- // 2. If importedStringModule is not null and moduleName equals importedStringModule, then continue.
- if (imported_string_module.has_value() && import.module == imported_string_module->bytes_as_string_view())
- continue;
-
- // 3. Let kind be the string value of the extern type type.
- auto kind = import_export_kind(import.type.kind);
- if (!kind.has_value()) {
- dbgln("Not yet implemented: importing tags");
- continue;
- }
-
- // 4. Let obj be «[ "module" → moduleName, "name" → name, "kind" → kind ]».
- Bindings::ModuleImportDescriptor descriptor {
- .kind = *kind,
- .module = Utf16String::from_utf8(import.module),
- .name = Utf16String::from_utf8(import.name),
- };
-
- // 5. Append obj to imports.
- import_objects.append(move(descriptor));
- }
-
- // 6. Return imports.
- return import_objects;
-}
-
-// https://webassembly.github.io/threads/js-api/index.html#dom-module-exports
-WebIDL::ExceptionOr<Vector<Bindings::ModuleExportDescriptor>> Module::exports(GC::Ref<Module> module_object)
-{
- // 1. Let module be moduleObject.[[Module]].
- // 2. Let exports be « ».
- Vector<Bindings::ModuleExportDescriptor> export_objects;
-
- // 3. For each (name, type) of module_exports(module),
- auto& module = *module_object->m_compiled_module->module;
- auto export_count = module.export_count();
- export_objects.ensure_capacity(export_count);
- for (size_t index = 0; index < export_count; ++index) {
- auto entry = module.module_export(index);
- // 3.1. Let kind be the string value of the extern type type.
- auto kind = import_export_kind(entry.type.kind);
- if (!kind.has_value()) {
- dbgln("Not yet implemented: exporting tags");
- continue;
- }
-
- // 3.2. Let obj be «[ "name" → name, "kind" → kind ]».
- Bindings::ModuleExportDescriptor descriptor {
- .kind = *kind,
- .name = Utf16String::from_utf8(entry.name),
- };
-
- // 3.3. Append obj to exports.
- export_objects.append(move(descriptor));
- }
-
- // 4. Return exports.
- return export_objects;
-}
-
-WebIDL::ExceptionOr<Vector<ByteBuffer>> Module::custom_sections(GC::Ref<Module> module_object, Utf16String section_name)
-{
- Vector<ByteBuffer> matching_sections;
-
- auto& module = *module_object->m_compiled_module->module;
- for (size_t index = 0; index < module.custom_section_count(); ++index) {
- auto section = module.custom_section(index);
- auto name = Utf16String::from_utf8(section.name);
- if (section_name == name)
- matching_sections.append(MUST(ByteBuffer::copy(section.contents)));
- }
-
- return matching_sections;
-}
-
-// https://webassembly.github.io/threads/js-api/index.html#dom-module-customsections
-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<JS::ArrayBuffer>>> Module::custom_sections(JS::Realm& realm, GC::Ref<Module> module_object, Utf16String section_name)
-{
- // 1. Let bytes be moduleObject.[[Bytes]].
- // 2. Let customSections be « ».
- GC::RootVector<GC::Ref<JS::ArrayBuffer>> array_buffers;
-
- // 3. For each custom section customSection of bytes, interpreted according to the module grammar,
- auto custom_sections = TRY(Module::custom_sections(module_object, move(section_name)));
- for (auto& section : custom_sections) {
- // 3.3.1. Append a new ArrayBuffer containing a copy of the bytes in bytes for the range matched by this customsec production to customSections.
- array_buffers.append(JS::ArrayBuffer::create(realm, move(section)));
- }
-
- // 4. Return customSections.
- return array_buffers;
-}
-
-// https://webassembly.github.io/spec/web-api/#ref-for-serialization-steps
-WebIDL::ExceptionOr<void> Module::serialization_steps(HTML::StructuredSerializeWriter& serialized, bool for_storage, HTML::SerializationMemory&)
-{
- // 1. If forStorage is true, throw a "DataCloneError" DOMException.
- if (for_storage)
- return WebIDL::DataCloneError::create("WebAssembly Module instances may not be serialized for storage"_utf16);
-
- // 2. Set serialized.[[Bytes]] to the sub-serialization of value.[[Bytes]].
- serialized.encode(m_bytes);
-
- // 3. Set serialized.[[AgentCluster]] to the current Realm’s corresponding agent cluster.
- serialized.encode(HTML::current_settings_object().agent_cluster_id());
-
- return {};
-}
-
-// https://webassembly.github.io/spec/web-api/#ref-for-deserialization-steps
-WebIDL::ExceptionOr<void> Module::deserialization_steps(JS::Realm& realm, HTML::StructuredSerializeReader& serialized, HTML::DeserializationMemory&)
-{
- // 1. Let bytes be the sub-deserialization of serialized.[[Bytes]].
- auto bytes = TRY(HTML::decode_or_throw_data_clone_error<ByteBuffer>(realm, serialized));
-
- // 2. Set value.[[Bytes]] to bytes.
- m_bytes = move(bytes);
-
- // 3. If targetRealm’s corresponding agent cluster is not serialized.[[AgentCluster]], then throw a "DataCloneError" DOMException.
- auto agent_cluster = TRY(HTML::decode_or_throw_data_clone_error<Optional<u64>>(realm, serialized));
- auto target_agent_cluster = Bindings::principal_host_defined_environment_settings_object(realm).agent_cluster_id();
- if (!agent_cluster.has_value() || agent_cluster != target_agent_cluster)
- return WebIDL::DataCloneError::create("Cannot deserialize WebAssembly Module outside its agent cluster"_utf16);
-
- // 4. Compile a WebAssembly module from bytes and set value.[[Module]] to the result.
- m_compiled_module = TRY(Detail::compile_a_webassembly_module(realm, m_bytes));
-
- return {};
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Module.h b/Libraries/LibWeb/WebAssembly/Module.h
deleted file mode 100644
index 20a6d602ef4..00000000000
--- a/Libraries/LibWeb/WebAssembly/Module.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <AK/Utf16String.h>
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Bindings/Module.h>
-#include <LibWeb/Bindings/Serializable.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::WebAssembly {
-
-class Module
- : public Bindings::GCAllocatedWrappable
- , public Bindings::Serializable {
- WEB_WRAPPABLE(Module, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Module);
-
-public:
- static GC::Ref<Module> create(); // Should only be used for structured serialization.
- static WebIDL::ExceptionOr<GC::Ref<Module>> create(JS::Realm&, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const&);
- static WebIDL::ExceptionOr<Vector<Bindings::ModuleImportDescriptor>> imports(GC::Ref<Module>);
- static WebIDL::ExceptionOr<Vector<Bindings::ModuleExportDescriptor>> exports(GC::Ref<Module>);
- static WebIDL::ExceptionOr<GC::RootVector<GC::Ref<JS::ArrayBuffer>>> custom_sections(JS::Realm&, GC::Ref<Module>, Utf16String section_name);
- static WebIDL::ExceptionOr<Vector<ByteBuffer>> custom_sections(GC::Ref<Module>, Utf16String section_name);
-
- NonnullRefPtr<Detail::CompiledWebAssemblyModule> compiled_module() const { return *m_compiled_module; }
- Vector<Utf16String> const& builtin_sets() const { return m_builtin_sets; }
- Optional<Utf16String> const& imported_string_module() const { return m_imported_string_module; }
-
-private:
- Module() = default;
- Module(NonnullRefPtr<Detail::CompiledWebAssemblyModule>, ByteBuffer, Vector<Utf16String> builtin_sets, Optional<Utf16String> imported_string_module);
-
- virtual WebIDL::ExceptionOr<void> serialization_steps(HTML::StructuredSerializeWriter&, bool for_storage, HTML::SerializationMemory&) override;
- virtual WebIDL::ExceptionOr<void> deserialization_steps(JS::Realm&, HTML::StructuredSerializeReader&, HTML::DeserializationMemory&) override;
-
- RefPtr<Detail::CompiledWebAssemblyModule> m_compiled_module;
- ByteBuffer m_bytes;
- Vector<Utf16String> m_builtin_sets;
- Optional<Utf16String> m_imported_string_module;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Module.idl b/Libraries/LibWeb/WebAssembly/Module.idl
index b59d242b084..6b39d522d7f 100644
--- a/Libraries/LibWeb/WebAssembly/Module.idl
+++ b/Libraries/LibWeb/WebAssembly/Module.idl
@@ -17,7 +17,7 @@ dictionary ModuleImportDescriptor {
};
// https://webassembly.github.io/spec/js-api/#modules
-[LegacyNamespace=WebAssembly, Exposed=*, Serializable]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust, Serializable]
interface Module {
// FIXME: Bytes should be an AllowSharedBufferSource;
constructor(BufferSource bytes, optional WebAssemblyCompileOptions options = {});
diff --git a/Libraries/LibWeb/WebAssembly/Table.cpp b/Libraries/LibWeb/WebAssembly/Table.cpp
deleted file mode 100644
index d39373aefd9..00000000000
--- a/Libraries/LibWeb/WebAssembly/Table.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibCrypto/BigInt/SignedBigInteger.h>
-#include <LibCrypto/BigInt/UnsignedBigInteger.h>
-#include <LibGC/Heap.h>
-#include <LibJS/Runtime/BigInt.h>
-#include <LibJS/Runtime/VM.h>
-#include <LibWeb/Bindings/Table.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Table.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Table);
-
-WebIDL::ExceptionOr<GC::Ref<Table>> Table::create(Wasm::Runtime::ValueType element_type, bool address64, u64 initial, Optional<u64> maximum, u64 reference)
-{
- if (maximum.has_value() && maximum.value() < initial)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Maximum should not be less than initial in table type"_utf16 };
-
- Wasm::Runtime::Limits limits {
- .minimum = initial,
- .maximum = maximum.value_or(0),
- .has_maximum = maximum.has_value(),
- .address64 = address64,
- .shared = false,
- };
-
- // 11. Let (store, tableaddr) be table_alloc(store, type, ref). If allocation fails, throw a RangeError exception.
- auto table = cache().store().allocate_table(element_type, limits, reference);
- if (!table.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Wasm Table allocation failed"_utf16 };
-
- // 12. Set the surrounding agent's associated store to store.
- // NOTE: The store is updated in-place.
-
- // 13. Initialize this from tableaddr.
- return Table::create(*table);
-}
-
-GC::Ref<Table> Table::create(Wasm::Runtime::Entity table)
-{
- // https://webassembly.github.io/spec/js-api/#initialize-a-table-object
- // 1. Let map be the surrounding agent's associated Table object cache.
- // 2. Assert: map[tableaddr] doesn't exist.
- VERIFY(!cache().table_object(table));
-
- // 3. Set table.[[Table]] to tableaddr.
- auto object = GC::Heap::the().allocate<Table>(table);
-
- // 4. Set map[tableaddr] to table.
- cache().set_table_object(table, object);
- return object;
-}
-
-Table::Table(Wasm::Runtime::Entity table)
- : m_table(table)
-{
-}
-
-void Table::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_table);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-table-grow
-WebIDL::ExceptionOr<u64> Table::grow(u64 delta, u64 reference)
-{
- // 3. Let initialSize be table_size(store, tableaddr).
- // 4. Let (limits, elementType) be table_type(tableaddr).
- // 7. Let result be table_grow(store, tableaddr, delta, ref).
- // 8. If result is error, throw a RangeError exception.
- auto initial_size = cache().store().grow_table(address(), delta, reference);
- if (initial_size < 0)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Failed to grow table"_utf16 };
-
- // 10. Set the surrounding agent's associated store to result.
- // NOTE: The store is updated in-place.
-
- return static_cast<u64>(initial_size);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-table-get
-WebIDL::ExceptionOr<u64> Table::get(u64 index) const
-{
- // 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
- // 4. If elementtype matches exnref, throw a TypeError exception.
- auto heap = element_type().heap;
- if (heap == Wasm::Runtime::HeapKind::Exception || heap == Wasm::Runtime::HeapKind::NoException)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot get an exnref table element"_utf16 };
-
- // 6. Let result be table_read(store, tableaddr, index64).
- // 7. If result is error, throw a RangeError exception.
- auto result = cache().store().table_get(address(), index);
- if (!result.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Table element index out of range"_utf16 };
- return *result;
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-table-set
-WebIDL::ExceptionOr<void> Table::set(u64 index, u64 reference)
-{
- // 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
- // 4. If elementtype matches exnref, throw a TypeError exception.
- auto heap = element_type().heap;
- if (heap == Wasm::Runtime::HeapKind::Exception || heap == Wasm::Runtime::HeapKind::NoException)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set an exnref table element"_utf16 };
-
- // 8. Let store be table_write(store, tableaddr, index64, ref).
- // 9. If store is error, throw a RangeError exception.
- if (!cache().store().table_set(address(), index, reference))
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Table element index out of range"_utf16 };
-
- // 10. Set the surrounding agent's associated store to store.
- // NOTE: The store is updated in-place.
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-table-length
-u64 Table::length() const
-{
- return cache().store().table_size(address());
-}
-
-bool Table::is_address64() const
-{
- return cache().store().table_limits(address()).address64;
-}
-
-Wasm::Runtime::ValueType Table::element_type() const
-{
- return cache().store().table_element_type(address());
-}
-
-}
-
-namespace Web::Bindings {
-
-static Wasm::Runtime::ValueType table_kind_to_value_type(TableKind kind)
-{
- switch (kind) {
- case TableKind::Externref:
- return Wasm::Runtime::ValueType::reference(Wasm::Runtime::HeapKind::Extern);
- case TableKind::Anyfunc:
- return Wasm::Runtime::ValueType::reference(Wasm::Runtime::HeapKind::Function);
- }
- VERIFY_NOT_REACHED();
-}
-
-// https://webassembly.github.io/spec/js-api/#addressvaluetou64
-static WebIDL::ExceptionOr<u64> address_value_to_u64(JS::VM& vm, JS::Value value, bool address64)
-{
- if (address64) {
- // 1. If addrtype is i64, then:
- // 1.1. Let n be ? ToBigInt(value).
- auto bigint = TRY(value.to_bigint(vm));
-
- // 1.2. If n < 0 or n >= 2^64, throw a TypeError exception.
- if (bigint->big_integer().is_negative())
- return vm.throw_completion<JS::TypeError>("Table size must be non-negative"sv);
- auto string = TRY_OR_THROW_OOM(vm, bigint->big_integer().to_base(10));
- auto number = string.to_number<u64>();
- if (!number.has_value())
- return vm.throw_completion<JS::TypeError>("Table size is too large"sv);
-
- // 1.3. Return n.
- return *number;
- }
-
- // 2. Otherwise:
- // 2.1. Assert: addrtype is i32.
- // 2.2. Let n be ? Web IDL's convert a JavaScript value to an IDL value of type [EnforceRange] unsigned long, given value.
- auto n = TRY(WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, value, WebIDL::EnforceRange::Yes));
-
- // 2.3. Return n.
- return n;
-}
-
-static JS::Value table_limit_to_js_value(JS::VM& vm, u64 value, bool address64)
-{
- if (address64)
- return JS::BigInt::create(vm, ::Crypto::SignedBigInteger { ::Crypto::UnsignedBigInteger { value } });
- return JS::Value { static_cast<u32>(value) };
-}
-
-WebIDL::ExceptionOr<GC::Ref<WebAssembly::Table>> construct_table(JS::Realm& realm, TableDescriptor const& descriptor, Optional<JS::Value> value)
-{
- auto& vm = realm.vm();
-
- // 1. Let elementtype be ToValueType(descriptor["element"]).
- auto element_type = table_kind_to_value_type(descriptor.element);
-
- // 2. If elementtype is not a reftype, throw a TypeError exception.
- // NOTE: The TableKind IDL enum only accepts reference types.
-
- // 3. If descriptor["address"] exists, let addrtype be descriptor["address"]; otherwise, let addrtype be "i32".
- auto address64 = descriptor.address.value_or(AddressType::I32) == AddressType::I64;
-
- // 4. Let initial be ? AddressValueToU64(descriptor["initial"], addrtype).
- auto initial = TRY(address_value_to_u64(vm, descriptor.initial, address64));
-
- // 5. If descriptor["maximum"] exists, let maximum be ? AddressValueToU64(descriptor["maximum"], addrtype); otherwise, let maximum be empty.
- auto maximum = descriptor.maximum.has_value()
- ? Optional<u64> { TRY(address_value_to_u64(vm, descriptor.maximum.value(), address64)) }
- : Optional<u64> {};
-
- auto reference_value = !value.has_value()
- ? WebAssembly::Detail::default_webassembly_value(vm, element_type)
- : TRY(WebAssembly::Detail::to_webassembly_value(vm, *value, element_type));
-
- return WebAssembly::Table::create(element_type, address64, initial, maximum, reference_value.reference_bits());
-}
-
-JS::Value table(JS::Realm& realm, GC::Ref<WebAssembly::Table> table)
-{
- return wrap(host_defined_wrapper_world(realm), realm, table);
-}
-
-static WebIDL::ExceptionOr<u64> value_to_table_reference(JS::Realm& realm, WebAssembly::Table& table, Optional<JS::Value> value)
-{
- auto element_type = table.element_type();
- auto reference_value = !value.has_value()
- ? WebAssembly::Detail::default_webassembly_value(realm.vm(), element_type)
- : TRY(WebAssembly::Detail::to_webassembly_value(realm.vm(), *value, element_type));
- return reference_value.reference_bits();
-}
-
-WebIDL::ExceptionOr<JS::Value> grow(JS::Realm& realm, WebAssembly::Table& table, JS::Value delta_value, Optional<JS::Value> value)
-{
- auto& vm = realm.vm();
- auto address64 = table.is_address64();
- auto delta = TRY(address_value_to_u64(vm, delta_value, address64));
- auto reference = TRY(value_to_table_reference(realm, table, value));
- auto initial_size = TRY(table.grow(delta, reference));
- return table_limit_to_js_value(vm, initial_size, address64);
-}
-
-WebIDL::ExceptionOr<JS::Value> get(JS::Realm& realm, WebAssembly::Table& table, JS::Value index_value)
-{
- auto& vm = realm.vm();
- auto index = TRY(address_value_to_u64(vm, index_value, table.is_address64()));
- auto reference = TRY(table.get(index));
- return TRY(WebAssembly::Detail::to_js_value(vm, Wasm::Runtime::Value::from_reference(reference), table.element_type()));
-}
-
-WebIDL::ExceptionOr<void> set(JS::Realm& realm, WebAssembly::Table& table, JS::Value index_value, Optional<JS::Value> value)
-{
- auto& vm = realm.vm();
- auto index = TRY(address_value_to_u64(vm, index_value, table.is_address64()));
- auto reference = TRY(value_to_table_reference(realm, table, value));
- return table.set(index, reference);
-}
-
-WebIDL::ExceptionOr<JS::Value> length(JS::Realm& realm, WebAssembly::Table& table)
-{
- return table_limit_to_js_value(realm.vm(), table.length(), table.is_address64());
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Table.h b/Libraries/LibWeb/WebAssembly/Table.h
deleted file mode 100644
index e931558216a..00000000000
--- a/Libraries/LibWeb/WebAssembly/Table.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Optional.h>
-#include <LibGC/Ptr.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::WebAssembly {
-
-class Table : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Table, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Table);
-
-public:
- // A table's elements are references, as their bits.
- static WebIDL::ExceptionOr<GC::Ref<Table>> create(Wasm::Runtime::ValueType element_type, bool address64, u64 initial, Optional<u64> maximum, u64 reference);
- static GC::Ref<Table> create(Wasm::Runtime::Entity table);
-
- WebIDL::ExceptionOr<u64> grow(u64 delta, u64 reference);
- WebIDL::ExceptionOr<u64> get(u64 index) const;
- WebIDL::ExceptionOr<void> set(u64 index, u64 reference);
- u64 length() const;
- bool is_address64() const;
- Wasm::Runtime::ValueType element_type() const;
-
- Wasm::Runtime::Entity address() const { return m_table.ptr(); }
- static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }
-
-private:
- explicit Table(Wasm::Runtime::Entity table);
-
- virtual void visit_edges(Visitor&) override;
-
- GC::Ptr<GC::ForeignCell> m_table;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Table.idl b/Libraries/LibWeb/WebAssembly/Table.idl
index da00f4b1bfd..eba5945fdf9 100644
--- a/Libraries/LibWeb/WebAssembly/Table.idl
+++ b/Libraries/LibWeb/WebAssembly/Table.idl
@@ -18,14 +18,14 @@ dictionary TableDescriptor {
};
// https://webassembly.github.io/spec/js-api/#tables
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Table {
- [ImplementedInBindings] constructor(TableDescriptor descriptor, optional any value);
+ constructor(TableDescriptor descriptor, optional any value);
- [ImplementedInBindings, NeedsCallerRealm] AddressValue grow(AddressValue delta, optional any value);
+ [NeedsCallerRealm] AddressValue grow(AddressValue delta, optional any value);
- [ImplementedInBindings, NeedsCallerRealm] any get(AddressValue index);
- [ImplementedInBindings, NeedsCallerRealm] undefined set(AddressValue index, optional any value);
+ [NeedsCallerRealm] any get(AddressValue index);
+ [NeedsCallerRealm] undefined set(AddressValue index, optional any value);
- [ImplementedInBindings, NeedsCallerRealm] readonly attribute AddressValue length;
+ [NeedsCallerRealm] readonly attribute AddressValue length;
};
diff --git a/Libraries/LibWeb/WebAssembly/Tag.cpp b/Libraries/LibWeb/WebAssembly/Tag.cpp
deleted file mode 100644
index fe3406dd720..00000000000
--- a/Libraries/LibWeb/WebAssembly/Tag.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/Bindings/HostDefined.h>
-#include <LibWeb/Bindings/Tag.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Global.h>
-#include <LibWeb/WebAssembly/Tag.h>
-
-namespace Web::WebAssembly {
-
-GC_DEFINE_ALLOCATOR(Tag);
-
-// https://webassembly.github.io/spec/js-api/#dom-tag-tag
-GC::Ref<Tag> Tag::create(ReadonlySpan<Wasm::Runtime::ValueType> parameters)
-{
- // 4. Let store be the surrounding agent's associated store.
- // 5. Let (store, tagAddress) be tag_alloc(store, « wasmParameters » → « »).
- // 6. Set the surrounding agent's associated store to store.
- auto tag = Detail::WebAssemblyCache::the().store().allocate_tag(parameters);
-
- // 7. Initialize this from tagAddress.
- return from_address_in_agent(tag);
-}
-
-GC::Ref<Tag> Tag::from_address(JS::Realm& realm, Wasm::Runtime::Entity tag)
-{
- // NB: The JavaScript exception tag lives as long as the agent, while a Tag object belongs to the realm it is first
- // wrapped in, so every realm has a Tag object of its own for it.
- if (tag == Detail::WebAssemblyCache::the().js_tag()) {
- auto& host_defined = Bindings::host_defined_of(realm);
- if (!host_defined.wasm_js_tag)
- host_defined.wasm_js_tag = GC::Heap::the().allocate<Tag>(tag);
- return *host_defined.wasm_js_tag;
- }
- return from_address_in_agent(tag);
-}
-
-// https://webassembly.github.io/spec/js-api/#create-a-tag-object
-GC::Ref<Tag> Tag::from_address_in_agent(Wasm::Runtime::Entity tag)
-{
- // 1. Let map be the surrounding agent's associated tag object cache.
- // 2. If map[tagAddress] exists,
- // 1. Return map[tagAddress].
- auto& cache = Detail::WebAssemblyCache::the();
- if (auto object = cache.tag_object(tag))
- return *object;
-
- // 3. Let tag be a new Tag.
- // 4. Initialize tag from tagAddress.
- // https://webassembly.github.io/spec/js-api/#initialize-a-tag-object
- // 3. Set tag.[[Address]] to tagAddress.
- auto object = GC::Heap::the().allocate<Tag>(tag);
-
- // 4. Set map[tagAddress] to tag.
- cache.set_tag_object(tag, object);
-
- // 5. Return tag.
- return object;
-}
-
-Tag::Tag(Wasm::Runtime::Entity tag)
- : m_tag(tag)
-{
-}
-
-void Tag::visit_edges(Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_tag);
-}
-
-}
-
-namespace Web::Bindings {
-
-// https://webassembly.github.io/spec/js-api/#dom-tag-tag
-WebIDL::ExceptionOr<GC::Ref<WebAssembly::Tag>> construct_tag(JS::Realm&, TagType const& type)
-{
- // 1. Let parameters be type["parameters"].
- // 2. Let wasmParameters be «».
- Vector<Wasm::Runtime::ValueType> parameters;
- parameters.ensure_capacity(type.parameters.size());
-
- // 3. For each type of parameters,
- for (auto parameter : type.parameters) {
- // 1. Append ToValueType(type) to wasmParameters.
- parameters.unchecked_append(to_value_type(parameter));
- }
-
- return WebAssembly::Tag::create(parameters);
-}
-
-WebAssembly::Tag* tag_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Tag>(&value.as_object()) : nullptr;
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Tag.h b/Libraries/LibWeb/WebAssembly/Tag.h
deleted file mode 100644
index e7486ec0333..00000000000
--- a/Libraries/LibWeb/WebAssembly/Tag.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-
-namespace Web::WebAssembly {
-
-// https://webassembly.github.io/spec/js-api/#tag
-class Tag : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Tag, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Tag);
-
-public:
- static GC::Ref<Tag> create(ReadonlySpan<Wasm::Runtime::ValueType> parameters);
- // The Tag object of a tag, which is the same object for as long as it lives.
- static GC::Ref<Tag> from_address(JS::Realm&, Wasm::Runtime::Entity tag);
-
- Wasm::Runtime::Entity address() const { return m_tag.ptr(); }
-
-private:
- explicit Tag(Wasm::Runtime::Entity tag);
-
- // The Tag object of a tag other than the JavaScript exception tag, from the agent's tag object cache.
- static GC::Ref<Tag> from_address_in_agent(Wasm::Runtime::Entity tag);
-
- virtual void visit_edges(Visitor&) override;
-
- GC::Ptr<GC::ForeignCell> m_tag;
-};
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/Tag.idl b/Libraries/LibWeb/WebAssembly/Tag.idl
index a052a1f7733..409ffc17fcd 100644
--- a/Libraries/LibWeb/WebAssembly/Tag.idl
+++ b/Libraries/LibWeb/WebAssembly/Tag.idl
@@ -4,7 +4,7 @@ dictionary TagType {
};
// https://webassembly.github.io/spec/js-api/#tag
-[LegacyNamespace=WebAssembly, Exposed=*]
+[LegacyNamespace=WebAssembly, Exposed=*, ImplementedIn=Rust]
interface Tag {
- [ImplementedInBindings] constructor(TagType type);
+ constructor(TagType type);
};
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
index 0c63176901e..2c12abf5e88 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
@@ -1,1760 +1,149 @@
/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/ByteBuffer.h>
-#include <AK/MemoryStream.h>
-#include <AK/NeverDestroyed.h>
-#include <AK/ScopeGuard.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf16String.h>
-#include <LibCrypto/BigInt/SignedBigInteger.h>
-#include <LibGC/ConservativeVector.h>
-#include <LibGC/DeferGC.h>
-#include <LibGC/Heap.h>
#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/Agent.h>
-#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayBuffer.h>
-#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/Error.h>
-#include <LibJS/Runtime/ErrorConstructor.h>
-#include <LibJS/Runtime/Intrinsics.h>
-#include <LibJS/Runtime/Iterator.h>
-#include <LibJS/Runtime/NativeFunction.h>
-#include <LibJS/Runtime/Object.h>
+#include <LibJS/Runtime/HostModule.h>
+#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
-#include <LibJS/Runtime/ValueInlines.h>
-#include <LibWeb/Bindings/HostDefined.h>
-#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
-#include <LibWeb/Bindings/WebAssembly.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/Bindings/PrincipalHostDefined.h>
#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Response.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/Platform/EventLoopPlugin.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Builtins.h>
-#include <LibWeb/WebAssembly/Exception.h>
-#include <LibWeb/WebAssembly/Global.h>
-#include <LibWeb/WebAssembly/Instance.h>
-#include <LibWeb/WebAssembly/Memory.h>
-#include <LibWeb/WebAssembly/Module.h>
-#include <LibWeb/WebAssembly/Table.h>
-#include <LibWeb/WebAssembly/Tag.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/Buffers.h>
-#include <LibWeb/WebIDL/ExceptionOrUtils.h>
#include <LibWeb/WebIDL/Promise.h>
-namespace Web::WebAssembly {
-
-static GC::Ref<WebIDL::Promise> asynchronously_compile_webassembly_module(JS::Realm&, ByteBuffer, Bindings::WebAssemblyCompileOptions const&, HTML::Task::Source = HTML::Task::Source::Unspecified);
-static GC::Ref<WebIDL::Promise> instantiate_promise_of_module(JS::Realm&, GC::Ref<WebIDL::Promise>, GC::Ptr<JS::Object> import_object);
-static GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm&, GC::Ref<Module>, GC::Ptr<JS::Object> import_object);
-static GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm&, GC::Ref<WebIDL::Promise>, Bindings::WebAssemblyCompileOptions const&);
-
-namespace Detail {
-
-using WasmValue = Wasm::Runtime::Value;
-using WasmValueType = Wasm::Runtime::ValueType;
-using Wasm::Runtime::HeapKind;
-using Wasm::Runtime::ValueKind;
-
-// Exceptions and GC objects are the cells their references are the addresses of.
-static GC::ForeignCell* cell_of_reference(u64 reference)
-{
- return reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(reference));
-}
-
-// NB: The objects of the caches are the ones the runtime keeps alive with their cells (Store::set_host_object()). The
-// platform objects among them are C++ cells, and the others foreign cells.
-template<typename T>
-static GC::Ptr<T> cell_object(void* object)
-{
- return static_cast<T*>(static_cast<GC::Cell*>(object));
-}
-
-template<typename T>
-static GC::Ptr<T> foreign_cell_object(void* object)
-{
- return static_cast<T*>(static_cast<GC::ForeignCell*>(object));
-}
-
-GC::Ptr<JS::NativeFunction> WebAssemblyCache::function_object(Entity function) const { return foreign_cell_object<JS::NativeFunction>(m_store->host_object(function)); }
-void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object) { m_store->set_host_object(function, object); }
-GC::Ptr<Global> WebAssemblyCache::global_object(Entity global) const { return cell_object<Global>(m_store->host_object(global)); }
-void WebAssemblyCache::set_global_object(Entity global, Global& object) { m_store->set_host_object(global, object); }
-GC::Ptr<Memory> WebAssemblyCache::memory_object(Entity memory) const { return cell_object<Memory>(m_store->host_object(memory)); }
-void WebAssemblyCache::set_memory_object(Entity memory, Memory& object)
-{
- m_store->set_host_object(memory, object);
- if (m_memory_objects.size() >= 2 * m_live_memory_objects_after_pruning + 16) {
- m_memory_objects.remove_all_matching([](auto& weak) { return !weak; });
- m_live_memory_objects_after_pruning = m_memory_objects.size();
- }
- m_memory_objects.append(object);
-}
-GC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return cell_object<Table>(m_store->host_object(table)); }
-void WebAssemblyCache::set_table_object(Entity table, Table& object) { m_store->set_host_object(table, object); }
-void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const
-{
- for (auto& memory : m_memory_objects) {
- if (memory)
- callback(*memory);
- }
-}
-GC::Ptr<Tag> WebAssemblyCache::tag_object(Entity tag) const { return cell_object<Tag>(m_store->host_object(tag)); }
-void WebAssemblyCache::set_tag_object(Entity tag, Tag& object) { m_store->set_host_object(tag, object); }
-GC::Ptr<Exception> WebAssemblyCache::exception_object(u64 exception) const { return cell_object<Exception>(m_store->host_object(cell_of_reference(exception))); }
-void WebAssemblyCache::set_exception_object(u64 exception, Exception& object) { m_store->set_host_object(cell_of_reference(exception), object); }
-GC::Ptr<JS::Object> WebAssemblyCache::gc_object(u64 object) const { return foreign_cell_object<JS::Object>(m_store->host_object(cell_of_reference(object))); }
-void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object) { m_store->set_host_object(cell_of_reference(object), gc_object); }
-
-WebAssemblyCache::~WebAssemblyCache() = default;
-
-WebAssemblyCache& WebAssemblyCache::the()
-{
- // NB: Each thread is one agent with one heap. The cache lives as long as the thread, so it is never destroyed after
- // the heap.
- static thread_local WebAssemblyCache* cache = nullptr;
- if (!cache)
- cache = new WebAssemblyCache(GC::Heap::the());
- return *cache;
-}
-
-WebAssemblyCache::WebAssemblyCache(GC::Heap& heap)
- : m_store(make<Wasm::Runtime::Store>(heap))
-{
- // NB: The store is the agent's, whose [[CanBlock]] decides whether memory.atomic.wait may block.
- m_store->set_can_block(JS::agent_can_suspend(JS::VM::the()));
-
- Array<WasmValueType, 1> js_tag_parameters { WasmValueType::reference(HeapKind::Extern) };
- m_js_tag_root = GC::Root<GC::ForeignCell> { m_store->allocate_tag(js_tag_parameters) };
-
- // https://webassembly.github.io/spec/js-api/#memory-objects
- // Whenever memory.grow is executed, refresh the memory buffer of the memory's Memory object, if it has one.
- m_store->set_memory_grow_callback([this](Entity memory) {
- if (auto object = memory_object(memory))
- refresh_the_memory_buffer(*object);
- });
-}
-
-}
-
-// https://webassembly.github.io/spec/js-api/#error-objects
-void initialize(JS::Object& self, JS::Realm& realm)
-{
- // 1. Let namespaceObject be the namespace object.
- auto& namespace_object = self;
-
- // 2. For each error of « "CompileError", "LinkError", "RuntimeError" »,
- // 2.1. Let constructor be a new object, implementing the NativeError Object Structure, with NativeError set to error.
- // 2.2. ! DefineMethodProperty(namespaceObject, error, constructor, false).
- u8 attr = JS::Attribute::Writable | JS::Attribute::Configurable;
-
-#define __WASM_ENUMERATE(ClassName, FullClassName) \
- namespace_object.define_intrinsic_accessor(#ClassName##_utf16_fly_string, attr, [](auto& realm) -> JS::Value { \
- return &Bindings::ensure_web_constructor<ClassName>(realm, FullClassName##_utf16_fly_string); \
- });
- WASM_ENUMERATE_NATIVE_ERRORS
-#undef __WASM_ENUMERATE
-
- // https://webassembly.github.io/spec/js-api/#dom-webassembly-jstag
- // NB: A regular attribute of a namespace is an accessor property of the namespace object.
- Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> js_tag_getter = [](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
- // 1. Let JSTagAddr be the result of getting the JavaScript exception tag.
- // 2. Let JSTagObject be the result of creating a Tag object from JSTagAddr.
- // 3. Return JSTagObject.
- auto& current_realm = *vm.current_realm();
- auto tag = Tag::from_address(current_realm, Detail::WebAssemblyCache::the().js_tag());
- return Bindings::wrap(Bindings::host_defined_wrapper_world(current_realm), current_realm, tag);
- };
- namespace_object.define_native_accessor(realm, "JSTag"_utf16_fly_string, move(js_tag_getter), Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-webassembly-validate
-bool validate(JS::Realm& realm, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const& options)
-{
- // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
- auto stable_bytes = WebIDL::get_buffer_source_copy(bytes);
- if (stable_bytes.is_error()) {
- VERIFY(stable_bytes.error().code() == ENOMEM);
- return false;
- }
-
- // 2. Compile stableBytes as a WebAssembly module and store the results as module.
- (void)realm;
- auto module = Wasm::Runtime::Module::compile(stable_bytes.value());
-
- // 3. If module is error, return false.
- if (module.is_error())
- return false;
-
- // 4. Let builtinSetNames be options["builtins"].
- auto const& builtin_set_names = options.builtins;
-
- // 5. Let importedStringModule be options["importedStringConstants"].
- auto const& imported_string_module = options.imported_string_constants;
-
- // 6. If validating builtins and imported strings for module with builtinSetNames and importedStringModule returns
- // false, return false.
- if (!Detail::validate_builtins_and_imported_strings(*module.value(), builtin_set_names, imported_string_module))
- return false;
-
- // 7. Return true.
- return true;
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-webassembly-compile
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile(JS::Realm& realm, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const& options)
-{
- auto& vm = realm.vm();
-
- // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
- auto stable_bytes = WebIDL::get_buffer_source_copy(bytes);
- if (stable_bytes.is_error()) {
- VERIFY(stable_bytes.error().code() == ENOMEM);
- return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
- }
-
- // 2. Asynchronously compile a WebAssembly module from stableBytes using options and return the result.
- return asynchronously_compile_webassembly_module(realm, stable_bytes.release_value(), options);
-}
-
-// https://webassembly.github.io/spec/web-api/index.html#dom-webassembly-compilestreaming
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile_streaming(JS::Realm& realm, GC::Ref<WebIDL::Promise> source, Bindings::WebAssemblyCompileOptions const& options)
-{
- // The compileStreaming(source, options) method, when invoked, returns the result of compiling a potential
- // WebAssembly response with source using options.
- return compile_potential_webassembly_response(realm, source, options);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate
-// https://webassembly.github.io/content-security-policy/js-api/#dom-webassembly-instantiate
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm& realm, WebIDL::BufferSource bytes, GC::Ptr<JS::Object> import_object, Bindings::WebAssemblyCompileOptions const& options)
-{
- auto& vm = realm.vm();
-
- // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
- auto stable_bytes = WebIDL::get_buffer_source_copy(bytes);
- if (stable_bytes.is_error()) {
- VERIFY(stable_bytes.error().code() == ENOMEM);
- return WebIDL::create_rejected_promise_from_exception(realm, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)));
- }
-
- // 2. Perform HostEnsureCanCompileWasmBytes()
- TRY(Detail::host_ensure_can_compile_wasm_bytes(realm));
-
- // 3. Asynchronously compile a WebAssembly module from stableBytes using options and let promiseOfModule be the
- // result.
- auto promise_of_module = asynchronously_compile_webassembly_module(realm, stable_bytes.release_value(), options);
-
- // 4. Instantiate promiseOfModule with imports importObject and return the result.
- return instantiate_promise_of_module(realm, promise_of_module, import_object);
-}
-
-// https://webassembly.github.io/spec/js-api/#dom-webassembly-instantiate-moduleobject-importobject
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm& realm, GC::Ref<Module> module_object, GC::Ptr<JS::Object> import_object, Optional<JS::Value> const&)
-{
- // 1. Asynchronously instantiate the WebAssembly module moduleObject importing importObject, and return the result.
- return asynchronously_instantiate_webassembly_module(realm, module_object, import_object);
-}
-
-// https://webassembly.github.io/spec/web-api/index.html#dom-webassembly-instantiatestreaming
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::Realm& realm, GC::Ref<WebIDL::Promise> source, GC::Ptr<JS::Object> import_object, Bindings::WebAssemblyCompileOptions const& options)
-{
- // The instantiateStreaming(source, importObject, options) method, when invoked, performs the following steps:
-
- // 1. Let promiseOfModule be the result of compiling a potential WebAssembly response with source using options.
- auto promise_of_module = compile_potential_webassembly_response(realm, source, options);
-
- // 2. Return the result of instantiating the promise of a module promiseOfModule with imports importObject.
- return instantiate_promise_of_module(realm, promise_of_module, import_object);
-}
-
-namespace Detail {
-
-// References are encoded so that their kind shows in their low bits: an i31 has bit 0 set, and a host value has bits
-// 1:0 equal to 0b10. A host value is the address of a cell with bit 1 set, which keeps the cell alive wherever
-// WebAssembly keeps the reference.
-static constexpr u64 I31_REFERENCE_BIT = 0b01;
-static constexpr u64 HOST_REFERENCE_TAG = 0b10;
-static constexpr u64 REFERENCE_TAG_MASK = 0b11;
-
-// A JavaScript value that is not a cell, boxed so that WebAssembly can refer to it as a host value.
-class ExternValueBox final : public GC::Cell {
- GC_CELL(ExternValueBox, GC::Cell);
- GC_DECLARE_ALLOCATOR(ExternValueBox);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- JS::Value value() const { return m_value; }
-
-private:
- explicit ExternValueBox(JS::Value value)
- : m_value(value)
- {
- }
-
- virtual void visit_edges(Visitor& visitor) override
- {
- Base::visit_edges(visitor);
- visitor.visit(m_value);
- }
-
- JS::Value m_value;
-};
-
-GC_DEFINE_ALLOCATOR(ExternValueBox);
-
-GC::Ptr<ExternValueBox> WebAssemblyCache::extern_value_box(JS::Value value) const
-{
- auto box = m_extern_value_boxes.get(value);
- return box.has_value() ? box->ptr() : nullptr;
-}
-
-void WebAssemblyCache::set_extern_value_box(JS::Value value, ExternValueBox& box)
-{
- if (m_extern_value_boxes.size() >= 2 * m_live_extern_value_boxes_after_pruning + 16) {
- m_extern_value_boxes.remove_all_matching([](auto&, auto& weak) { return !weak; });
- m_live_extern_value_boxes_after_pruning = m_extern_value_boxes.size();
- }
- m_extern_value_boxes.set(value, box);
-}
-
-static u64 host_reference_of(JS::VM& vm, JS::Value value)
-{
- GC::Cell const* cell = nullptr;
- if (value.is_cell()) {
- cell = &value.as_cell();
- } else {
- // NB: A value gets the same box while references to the box keep it alive, so that it converts to the same
- // reference.
- auto& cache = WebAssemblyCache::the();
- auto box = cache.extern_value_box(value);
- if (!box) {
- box = vm.heap().allocate<ExternValueBox>(value);
- cache.set_extern_value_box(value, *box);
- }
- cell = box.ptr();
- }
- return static_cast<u64>(reinterpret_cast<FlatPtr>(cell)) | HOST_REFERENCE_TAG;
-}
-
-static JS::Value value_of_host_reference(u64 reference)
-{
- auto address = static_cast<FlatPtr>(reference & ~REFERENCE_TAG_MASK);
- switch (reinterpret_cast<GC::ForeignCell const*>(address)->cell_kind()) {
- case GC::CellKind::Object:
- return JS::Value(reinterpret_cast<JS::Object const*>(address));
- case GC::CellKind::PrimitiveString:
- return JS::Value(reinterpret_cast<JS::PrimitiveString const*>(address));
- case GC::CellKind::Symbol:
- return JS::Value(reinterpret_cast<JS::Symbol const*>(address));
- case GC::CellKind::BigInt:
- return JS::Value(reinterpret_cast<JS::BigInt const*>(address));
- case GC::CellKind::Other:
- return reinterpret_cast<ExternValueBox const*>(address)->value();
- case GC::CellKind::Accessor:
- break;
- }
- VERIFY_NOT_REACHED();
-}
-
-static Optional<u64> i31_reference_of(JS::Value value)
-{
- static constexpr double I31_MINIMUM = -(1 << 30);
- static constexpr double I31_MAXIMUM = (1 << 30) - 1;
- if (!value.is_number())
- return {};
- auto number = value.as_double();
- if (number < I31_MINIMUM || number > I31_MAXIMUM || number != trunc(number) || (number == 0 && signbit(number)))
- return {};
- return (static_cast<u64>(static_cast<u32>(static_cast<i32>(number)) & 0x7fff'ffff) << 1) | I31_REFERENCE_BIT;
-}
-
-static i32 value_of_i31_reference(u64 reference)
-{
- // The value is in bits 31:1, so an arithmetic shift of the low 32 bits sign-extends it.
- return static_cast<i32>(static_cast<u32>(reference)) >> 1;
-}
-
-// https://webassembly.github.io/spec/js-api/#exported-gc-object
-// An Exported GC Object stands for a struct or an array, whose reference is the address of its cell. The object keeps
-// that cell as its host data, and has no properties, no prototype, and no way to get either.
-struct ExportedGCObjectTraits {
- static JS::ThrowCompletionOr<JS::Object*> get_prototype_of(JS::HostObject const&)
- {
- // 1. Return null.
- return nullptr;
- }
-
- static JS::ThrowCompletionOr<bool> set_prototype_of(JS::HostObject const& object, JS::Object*)
- {
- // 1. Throw a TypeError.
- return object.vm().throw_completion<JS::TypeError>("Cannot set the prototype of a WebAssembly GC object"_utf16);
- }
-
- static JS::ThrowCompletionOr<bool> is_extensible(JS::HostObject const&)
- {
- // 1. Return false.
- return false;
- }
-
- static JS::ThrowCompletionOr<bool> prevent_extensions(JS::HostObject const& object)
- {
- // 1. Throw a TypeError.
- return object.vm().throw_completion<JS::TypeError>("Cannot prevent extensions of a WebAssembly GC object"_utf16);
- }
-
- static JS::ThrowCompletionOr<Optional<JS::PropertyDescriptor>> get_own_property(JS::HostObject const&, JS::PropertyKey const&)
- {
- // 1. Return undefined.
- return Optional<JS::PropertyDescriptor> {};
- }
-
- static JS::ThrowCompletionOr<bool> define_own_property(JS::HostObject const& object, JS::PropertyKey const&, JS::PropertyDescriptor&, Optional<JS::PropertyDescriptor>*)
- {
- // 1. Throw a TypeError.
- return object.vm().throw_completion<JS::TypeError>("Cannot define properties of a WebAssembly GC object"_utf16);
- }
-
- static JS::ThrowCompletionOr<bool> has_property(JS::HostObject const&, JS::PropertyKey const&)
- {
- // 1. Return false.
- return false;
- }
+extern "C" {
- static JS::ThrowCompletionOr<JS::Value> get(JS::HostObject const&, JS::PropertyKey const&, JS::Value, JS::CacheableGetPropertyMetadata*, JS::Object::PropertyLookupPhase)
- {
- // 1. Return undefined.
- return JS::js_undefined();
- }
+// The entry points of the WebAssembly JavaScript Interface, in Libraries/LibWeb/Bindings/Rust/src/web_assembly.
+void* web_rust_web_assembly_create_compile_error(JSVM*, void* realm, FlatPtr message);
+JSCompletion web_rust_web_assembly_host_resize_array_buffer(JSVM*, JSObject* buffer, size_t new_length, bool* handled);
+JSCompletion web_rust_web_assembly_host_grow_shared_array_buffer(JSVM*, JSObject* buffer, size_t new_length, bool* handled);
+JSCompletion web_rust_web_assembly_parse_a_webassembly_module(JSVM*, void* realm, u8 const* bytes, size_t length, u8 const* filename, size_t filename_length, void* host_defined, JSModule** module_record);
- static JS::ThrowCompletionOr<bool> set(JS::HostObject const& object, JS::PropertyKey const&, JS::Value, JS::Value, JS::CacheableSetPropertyMetadata*, JS::Object::PropertyLookupPhase)
- {
- // 1. Throw a TypeError.
- return object.vm().throw_completion<JS::TypeError>("Cannot set properties of a WebAssembly GC object"_utf16);
- }
-
- static JS::ThrowCompletionOr<bool> delete_property(JS::HostObject const& object, JS::PropertyKey const&)
- {
- // 1. Throw a TypeError.
- return object.vm().throw_completion<JS::TypeError>("Cannot delete properties of a WebAssembly GC object"_utf16);
- }
-
- static JS::ThrowCompletionOr<GC::RootVector<JS::Value>> own_property_keys(JS::HostObject const&)
- {
- // 1. Let keys be a new empty list.
- // 2. Return keys.
- return GC::RootVector<JS::Value> {};
- }
-};
-
-static constexpr JSHostObjectHooks exported_gc_object_hooks = JS::make_host_object_hooks<ExportedGCObjectTraits>();
-static constexpr JSHostClass exported_gc_object_host_class = JS::make_host_class(JS_HOST_CLASS_OBJECT, "WebAssemblyGCObject"sv, nullptr, &exported_gc_object_hooks, nullptr, JS_HOST_CLASS_NOT_CACHEABLE_FOR_PROPERTY_ABSENCE);
-
-// https://webassembly.github.io/spec/js-api/#create-a-new-exported-gc-object
-static GC::Ref<JS::Object> create_exported_gc_object(JS::VM& vm, u64 reference)
-{
- // 1. Assert: objectaddr is a struct or array address.
- // 2. Let map be the current agent's associated exported GC object cache.
- // 3. If map[objectaddr] exists, return map[objectaddr].
- auto& cache = WebAssemblyCache::the();
- if (auto object = cache.gc_object(reference))
- return *object;
-
- // 4. Let object be a new Exported GC Object, with [[ObjectAddress]] set to objectaddr and [[ObjectKind]] set to
- // objectKind.
- auto* cell = reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(reference));
- auto object = JS::HostObject::create(*vm.current_realm(), exported_gc_object_host_class, nullptr, {}, cell);
-
- // 5. Set map[objectaddr] to object.
- cache.set_gc_object(reference, object);
-
- // 6. Return object.
- return object;
-}
-
-Optional<u64> exported_gc_object_address(JS::Object const& object)
-{
- if (!JS::is_host_instance_of(object, exported_gc_object_host_class))
- return {};
- return static_cast<u64>(reinterpret_cast<FlatPtr>(JS::host_data_of(object).ptr()));
+// What the WebAssembly JavaScript Interface asks of LibWeb, declared on the Rust side in
+// Libraries/LibWeb/Bindings/Rust/src/web_assembly.
+JSCompletion web_bindings_ensure_csp_does_not_block_wasm_byte_compilation(void* realm);
+JSCompletion web_bindings_consume_webassembly_response(void* realm, JSValue unwrapped_source, void** body_promise);
+bool web_bindings_current_agent_cluster(u64* agent_cluster);
+bool web_bindings_agent_cluster_of_realm(void* realm, u64* agent_cluster);
}
-// https://webassembly.github.io/spec/js-api/#run-a-host-function
-static JS::ThrowCompletionOr<void> run_a_host_function(JS::VM& vm, JS::FunctionObject& function, Wasm::Runtime::FunctionType const& type, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results)
-{
-
- // 1. Let functype be the type of the host function.
- // 2. Let [parameters] → [results] be functype.
- // 3. If parameters or results contain v128 or exnref, throw a TypeError.
- // NB: The conversions below throw that TypeError.
-
- // 4. Let jsArguments be « ».
- GC::RootVector<JS::Value> js_arguments;
-
- // 5. For each arg of arguments, append ! ToJSValue(arg) to jsArguments.
- for (size_t index = 0; index < arguments.size(); ++index)
- js_arguments.append(TRY(to_js_value(vm, arguments[index], type.parameters[index])));
-
- // 6. Let ret be ? Call(func, undefined, jsArguments).
- auto ret = TRY(JS::call(vm, function, JS::js_undefined(), js_arguments.span()));
-
- // 7. Let resultsSize be results's size.
- // 8. If resultsSize is 0, return « ».
- if (type.results.is_empty())
- return {};
-
- // NB: The converted values may refer to new cells, which this vector keeps alive until they are in the results.
- Wasm::Runtime::Values converted;
-
- // 9. Otherwise, if resultsSize is 1, return « ? ToWebAssemblyValue(ret, results[0]) ».
- if (type.results.size() == 1) {
- converted.append(TRY(to_webassembly_value(vm, ret, type.results.first())));
- }
- // 10. Otherwise,
- else {
- // 1. Let method be ? GetMethod(ret, %Symbol.iterator%).
- auto method = TRY(ret.get_method(vm, vm.names.iterator));
-
- // 2. If method is undefined, throw a TypeError.
- if (!method)
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, ret.to_utf16_string_without_side_effects());
-
- // 3. Let values be ? IteratorToList(? GetIteratorFromMethod(ret, method)).
- auto values = TRY(JS::iterator_to_list(vm, TRY(JS::get_iterator_from_method(vm, ret, *method))));
-
- // 4. Let wasmValues be a new, empty list.
- // 5. If values's size is not resultsSize, throw a TypeError exception.
- if (values.size() != type.results.size())
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Invalid number of return values for multi-value wasm return of {} objects", type.results.size()));
-
- // 6. For each value and resultType in values and results, paired linearly, append ToWebAssemblyValue(value, resultType) to wasmValues.
- for (size_t index = 0; index < values.size(); ++index)
- converted.append(TRY(to_webassembly_value(vm, values[index], type.results[index])));
- }
-
- // 7. Return wasmValues.
- for (size_t index = 0; index < converted.size(); ++index)
- results[index] = converted[index];
- return {};
-}
-
-// https://webassembly.github.io/spec/js-api/#create-a-host-function
-Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& function, Wasm::Runtime::FunctionType type, size_t function_index)
-{
- auto& cache = WebAssemblyCache::the();
-
- // 1. Assert: IsCallable(func).
- // 2. Let stored settings be the incumbent settings object.
- // 3. Let hostfunc be a host function which performs the following steps when called with arguments arguments:
- // NB: The function's entity visits what the steps capture, which keeps the JavaScript function alive with it.
- auto host_function = [&vm, function = GC::Ref { function }, type](Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) -> ErrorOr<void, Wasm::Runtime::HostError> {
- auto result = run_a_host_function(vm, function, type, arguments, results);
- if (!result.is_error())
- return {};
-
- // https://webassembly.github.io/spec/js-api/#create-a-host-function
- // If the steps threw an exception v,
- auto value = result.error_value();
-
- // 1. If v implements Exception, let address be v.[[Address]].
- if (auto* exception = Bindings::exception_from_value(value))
- return Wasm::Runtime::HostError::exception(exception->address());
-
- // 2. Otherwise,
- // 1. Let type be the JavaScript exception tag.
- // 2. Let payload be ! ToWebAssemblyValue(v, externref).
- // 3. Let (store, address) be exn_alloc(store, type, « payload »).
- // 3. Throw a WebAssembly exception with address, which WebAssembly code can catch, and which is v again once it
- // leaves WebAssembly.
- Array<WasmValue, 1> payload { MUST(to_webassembly_value(vm, value, WasmValueType::reference(HeapKind::Extern))) };
- return Wasm::Runtime::HostError::exception(store.allocate_exception(WebAssemblyCache::the().js_tag(), payload));
- };
- return cache.store().allocate_host_function(type, move(host_function), static_cast<u32>(function_index));
-}
-
-Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const& module, u32 type_index)
-{
- auto& store = WebAssemblyCache::the().store();
- auto type = module.function_type(type_index);
- VERIFY(type.has_value());
- for (auto& parameter : type->parameters)
- parameter = store.canonical_value_type(module, parameter);
- for (auto& result : type->results)
- result = store.canonical_value_type(module, result);
- return type.release_value();
-}
-
-// https://webassembly.github.io/spec/js-api/#read-the-imports
-JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_imports(JS::VM& vm, Wasm::Runtime::Module const& module, GC::Ptr<JS::Object> import_object, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module)
-{
- auto& store = WebAssemblyCache::the().store();
-
- // 1. If module_imports(module) is not empty, and importObject is missing, throw a TypeError exception.
- auto import_count = module.import_count();
- if (import_count != 0 && !import_object)
- return vm.throw_completion<JS::TypeError>("ImportObject must be provided when module has imports"_utf16);
-
- // 2. Let builtinOrStringImports be the ordered map «[ ]».
- // NB: The keys are UTF-8, as the module names of imports are.
- OrderedHashMap<String, GC::Root<JS::Object>> builtin_or_string_imports;
-
- // 3. For each builtinSetName of builtinSetNames,
- for (auto const& builtin_set_name : builtin_set_names) {
- // 3.1. Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:"
- auto builtin_set_qualified_name = MUST(String::formatted("wasm:{}", builtin_set_name));
-
- // 3.2. Assert: builtinOrStringImports does not contain builtinSetQualifiedName
- VERIFY(!builtin_or_string_imports.contains(builtin_set_qualified_name));
-
- // 3.3. If builtinSetName does not refer to a builtin set, then continue.
- if (!refers_to_a_builtin_set(builtin_set_name))
- continue;
-
- // 3.4. Let exportsObject be the result of instantiate a builtin set with builtinSetName
- auto exports_object = instantiate_a_builtin_set(vm, builtin_set_name);
-
- // 3.5. Set builtinOrStringImports[builtinSetQualifiedName] to exportsObject
- builtin_or_string_imports.set(builtin_set_qualified_name, GC::make_root(exports_object));
- }
-
- // 4. If importedStringModule is not null,
- if (imported_string_module.has_value()) {
- // 4.1. Let exportsObject be the result of instantiate imported strings with module and importedStringModule
- auto exports_object = instantiate_imported_strings(vm, module, *imported_string_module);
-
- // 4.2. Set builtinOrStringImports[importedStringModule] to exportsObject
- builtin_or_string_imports.set(imported_string_module->to_utf8(), GC::make_root(exports_object));
- }
-
- // 5. Let imports be « ».
- // NB: The host functions and globals made for the imports are referenced from here only until the instance
- // holds them, and the steps below run user code (getters, valueOf) that may collect garbage.
- GC::ConservativeVector<Wasm::Runtime::Extern> imports;
- imports.ensure_capacity(import_count);
- size_t imported_function_count = 0;
-
- // 6. For each (moduleName, componentName, externtype) of module_imports(module),
- for (size_t import_index = 0; import_index < import_count; ++import_index) {
- auto import = module.import(import_index);
- dbgln_if(LIBWEB_WASM_DEBUG, "Trying to resolve {}::{}", import.module, import.name);
-
- auto module_name = Utf16FlyString::from_utf8(import.module);
- auto component_name = Utf16FlyString::from_utf8(import.name);
- JS::Value value;
-
- // 6.1. If builtinOrStringImports[moduleName] exists,
- if (auto builtin_or_string_import = builtin_or_string_imports.get(MUST(String::from_utf8(import.module))); builtin_or_string_import.has_value()) {
- // 6.1.1. Let o be builtinOrStringImports[moduleName].
- value = builtin_or_string_import->ptr();
-
- // 6.1.2. If o is not an Object or if ? HasProperty(o, componentName) is false,
- if (!value.is_object() || !TRY(value.as_object().has_property(component_name))) {
- // 6.1.2.1. Set o to ? Get(importObject, moduleName).
- value = TRY(import_object->get(module_name));
- }
- }
- // 6.2. Else,
- else {
- // 6.2.1. Let o be ? Get(importObject, moduleName).
- value = TRY(import_object->get(module_name));
- }
-
- // 6.3. If o is not an Object, throw a TypeError exception.
- if (!value.is_object())
- return vm.throw_completion<JS::TypeError>(JS::ErrorType::IsNotAEvaluatedFrom, value.to_utf16_string_without_side_effects(), "Object"_string, MUST(String::formatted("[wasm import object][\"{}\"]", import.module)));
- auto const& object = value.as_object();
-
- // 6.4. Let v be ? Get(o, componentName).
- auto import_ = TRY(object.get(component_name));
-
- switch (import.type.kind) {
- // 6.5. If externtype is of the form func functype,
- case Wasm::Runtime::ExternKind::Function: {
- // 6.5.1. If IsCallable(v) is false, throw a LinkError exception.
- if (!import_.is_function())
- return vm.throw_completion<LinkError>(JS::ErrorType::IsNotAEvaluatedFrom, import_, "function"_string, MUST(String::formatted("[wasm import object][\"{}\"]", import.name)));
- auto& function = import_.as_function();
-
- Wasm::Runtime::Entity address = nullptr;
- // 6.5.2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
- if (auto exported_address = exported_function_address(function); exported_address.has_value()) {
- // 6.5.2.1. Let funcaddr be the value of v's [[FunctionAddress]] internal slot.
- address = *exported_address;
- }
- // 6.5.3. Otherwise,
- else {
- // 6.5.3.1. Create a host function from v and functype, and let funcaddr be the result.
- // 6.5.3.2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.
- address = create_host_function(vm, function, function_type_in_store(module, import.type.type_index), imported_function_count);
- }
-
- // 6.5.4. Let externfunc be the external value func funcaddr.
- // 6.5.5. Append externfunc to imports.
- imports.unchecked_append({ Wasm::Runtime::ExternKind::Function, address });
- ++imported_function_count;
- break;
- }
- // 6.6. If externtype is of the form global mut valtype,
- case Wasm::Runtime::ExternKind::Global: {
- auto value_type = store.canonical_value_type(module, import.type.value_type);
- Wasm::Runtime::Entity address = nullptr;
- // 6.6.1. If v implements Global,
- if (auto* global = Bindings::global_from_value(import_)) {
- // 6.6.1.1. Let globaladdr be v.[[Global]].
- address = global->address();
- }
- // 6.6.2. Otherwise,
- else {
- // 6.6.2.1. If valtype is i64 and v is not a BigInt, throw a LinkError exception.
- if (value_type.kind == ValueKind::I64 && !import_.is_bigint())
- return vm.throw_completion<LinkError>("Import resolution attempted to use a non-BigInt for an i64 global"sv);
- // 6.6.2.2. If valtype is one of i32, f32 or f64 and v is not a Number, throw a LinkError exception.
- if ((value_type.kind == ValueKind::I32 || value_type.kind == ValueKind::F32 || value_type.kind == ValueKind::F64) && !import_.is_number())
- return vm.throw_completion<LinkError>("Import resolution attempted to use a non-Number for a numeric global"sv);
- // 6.6.2.3. If valtype is v128, throw a LinkError exception.
- if (value_type.kind == ValueKind::V128)
- return vm.throw_completion<LinkError>("Import resolution attempted to use a value for a V128 global"sv);
- // 6.6.2.4. If mut is var, throw a LinkError exception.
- if (import.type.is_mutable)
- return vm.throw_completion<LinkError>("Import resolution attempted to use a value for a mutable global"sv);
- // 6.6.2.5. Let value be ToWebAssemblyValue(v, valtype). If this throws a TypeError, catch it, and throw
- // a LinkError exception.
- auto value = to_webassembly_value(vm, import_, value_type);
- if (value.is_error())
- return vm.throw_completion<LinkError>("Import resolution attempted to use a value of the wrong type for a global"sv);
- // 6.6.2.6. Let store be the surrounding agent's associated store.
- // 6.6.2.7. Let (store, globaladdr) be global_alloc(store, const valtype, value).
- // 6.6.2.8. Set the surrounding agent's associated store to store.
- address = store.allocate_global(value_type, false, value.release_value());
- }
-
- // 6.6.3. Let externglobal be global globaladdr.
- // 6.6.4. Append externglobal to imports.
- imports.unchecked_append({ Wasm::Runtime::ExternKind::Global, address });
- break;
- }
- // 6.7. If externtype is of the form mem memtype,
- case Wasm::Runtime::ExternKind::Memory: {
- // 6.7.1. If v does not implement Memory, throw a LinkError exception.
- auto* memory = Bindings::memory_from_value(import_);
- if (!memory)
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Memory for a memory import"sv);
-
- // 6.7.2. Let externmem be the external value mem v.[[Memory]].
- // 6.7.3. Append externmem to imports.
- imports.unchecked_append({ Wasm::Runtime::ExternKind::Memory, memory->address() });
- break;
- }
- // 6.8. If externtype is of the form table tabletype,
- case Wasm::Runtime::ExternKind::Table: {
- // 6.8.1. If v does not implement Table, throw a LinkError exception.
- auto* table = Bindings::table_from_value(import_);
- if (!table)
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Table for a table import"sv);
-
- // 6.8.2. Let tableaddr be v.[[Table]].
- // 6.8.3. Let externtable be the external value table tableaddr.
- // 6.8.4. Append externtable to imports.
- imports.unchecked_append({ Wasm::Runtime::ExternKind::Table, table->address() });
- break;
- }
- // 6.9. If externtype is of the form tag attribute functype,
- case Wasm::Runtime::ExternKind::Tag: {
- // 6.9.1. Assert: attribute is exception.
- // 6.9.2. If v does not implement Tag, throw a LinkError exception.
- auto* tag = Bindings::tag_from_value(import_);
- if (!tag)
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Tag for a tag import"sv);
-
- // 6.9.3. Let tagaddr be v.[[Address]].
- // 6.9.4. Let externtag be the external value tag tagaddr.
- // 6.9.5. Append externtag to imports.
- imports.unchecked_append({ Wasm::Runtime::ExternKind::Tag, tag->address() });
- break;
- }
- }
- }
-
- // 7. Return imports.
- return imports;
-}
+namespace Web::WebAssembly {
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm::Runtime::Module const& module, GC::Ptr<JS::Object> import_object, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module)
-{
- auto imports = TRY(read_the_imports(vm, module, import_object, builtin_set_names, imported_string_module));
- return instantiate_core_module(vm, module, imports);
-}
+using namespace JS::HostABI;
-// https://webassembly.github.io/spec/js-api/index.html#instantiate-the-core-of-a-webassembly-module
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_core_module(JS::VM& vm, Wasm::Runtime::Module const& module, ReadonlySpan<Wasm::Runtime::Extern> imports)
+GC::Ref<JS::Object> create_compile_error(JS::Realm& realm, Utf16String const& message)
{
- // 1. Let store be the surrounding agent's associated store.
- // 2. Let result be module_instantiate(store, module, imports).
- // 3. If result is error, throw an appropriate exception type:
- // * A LinkError exception for most cases which occur during linking.
- // * If the error came when running the start function, throw a RuntimeError for most errors which occur from
- // WebAssembly, or the error object propagated from inner ECMAScript code.
- // * Another error type if appropriate, for example an out-of-memory exception, as documented in the
- // WebAssembly error mapping.
- // 4. Let (store, instance) be result.
- // 5. Set the surrounding agent's associated store to store.
- // 6. Return instance.
- auto result = WebAssemblyCache::the().store().instantiate(module, imports);
- if (result.is_error())
- return completion_of_failure(vm, result.error());
- return result.value();
+ auto* error = web_rust_web_assembly_create_compile_error(vm_to_abi(realm.vm()), &realm, message.raw_identity());
+ return *object_from_abi(static_cast<JSObject*>(error));
}
-// https://webassembly.github.io/spec/js-api/#compile-a-webassembly-module
-// https://webassembly.github.io/content-security-policy/js-api/#compile-a-webassembly-module
-JS::ThrowCompletionOr<NonnullRefPtr<CompiledWebAssemblyModule>> compile_a_webassembly_module(JS::Realm& realm, ReadonlyBytes data)
+static JS::ThrowCompletionOr<JS::HandledByHost> handled_by_host(JSCompletion completion, bool handled)
{
- auto& vm = realm.vm();
- TRY(host_ensure_can_compile_wasm_bytes(realm));
-
- auto module = Wasm::Runtime::Module::compile(data);
- if (module.is_error())
- return vm.throw_completion<CompileError>(module.error());
- return make_ref_counted<CompiledWebAssemblyModule>(module.release_value());
+ TRY(completion_from_abi<void>(completion));
+ return handled ? JS::HandledByHost::Handled : JS::HandledByHost::Unhandled;
}
-// https://webassembly.github.io/spec/js-api/#HostResizeArrayBuffer
JS::ThrowCompletionOr<JS::HandledByHost> host_resize_array_buffer(JS::VM& vm, JS::ArrayBuffer& buffer, size_t new_length)
{
- // 1. If buffer.[[ArrayBufferDetachKey]] is "WebAssembly.Memory",
- auto detach_key = buffer.detach_key();
- if (detach_key.is_string() && detach_key.as_string() == JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string)) {
- // 3. For each memaddr → mem in all Memory object caches,
- GC::Ptr<Memory> memory;
- Detail::WebAssemblyCache::the().for_each_memory_object([&](Memory& candidate) {
- // 1. If SameValue(mem.[[BufferObject]], buffer) is true,
- if (memory_has_buffer_object(candidate, buffer)) {
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(!memory);
- memory = candidate;
- }
- });
-
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(memory);
-
- // NB: We perform the following steps for mem after the loop above, because growing mem can collect garbage, and
- // that removes finalized Memory objects from the caches we iterate.
-
- // 1. Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
- VERIFY(buffer.byte_length() % page_size == 0);
-
- // 2. Let lengthDelta be newLength - buffer.[[ArrayBufferByteLength]].
- auto length_delta = new_length - buffer.byte_length();
-
- // 3. If lengthDelta < 0 or lengthDelta modulo 65536 is not 0,
- if (new_length < buffer.byte_length() || length_delta % page_size != 0) {
- // 1. Throw a RangeError exception.
- return vm.throw_completion<JS::RangeError>("WebAssembly.Memory buffers must be resized by a multiple of the page size"sv);
- }
-
- // 4. Let delta be lengthDelta ÷ 65536.
- auto delta = length_delta / page_size;
-
- // 5. Grow the memory buffer associated with memaddr by delta.
- // FIXME: "Grow the memory buffer" is a separate algorithm from the Memory#grow() method.
- TRY(WebIDL::throw_dom_exception_if_needed(vm, buffer.shape().realm(), [&] {
- return memory->grow(delta);
- }));
-
- // 4. Return handled.
- return JS::HandledByHost::Handled;
- }
-
- // 2. Otherwise, return unhandled.
- return JS::HandledByHost::Unhandled;
+ bool handled = false;
+ auto completion = web_rust_web_assembly_host_resize_array_buffer(vm_to_abi(vm), object_to_abi(&buffer), new_length, &handled);
+ return handled_by_host(completion, handled);
}
-// https://webassembly.github.io/threads/js-api/#abstract-operation-hostgrowsharedarraybuffer
JS::ThrowCompletionOr<JS::HandledByHost> host_grow_shared_array_buffer(JS::VM& vm, JS::ArrayBuffer& buffer, size_t new_length)
{
- // AD-HOC: If buffer.[[ArrayBufferDetachKey]] is "WebAssembly.Memory",
- auto detach_key = buffer.detach_key();
- if (detach_key.is_string() && detach_key.as_string() == JS::PrimitiveString::create(vm, "WebAssembly.Memory"_utf16_fly_string)) {
- auto current_byte_length = buffer.byte_length();
-
- // 3. For each memaddr → mem in all Memory object caches,
- GC::Ptr<Memory> memory;
- Detail::WebAssemblyCache::the().for_each_memory_object([&](Memory& candidate) {
- // 1. If SameValue(mem.[[BufferObject]], buffer) is true,
- if (memory_has_buffer_object(candidate, buffer)) {
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(!memory);
- memory = candidate;
- }
- });
-
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(memory);
-
- // NB: We perform the following steps for mem after the loop above, because growing mem can collect garbage, and
- // that removes finalized Memory objects from the caches we iterate.
-
- // 1. Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
- VERIFY(buffer.byte_length() % page_size == 0);
-
- // 2. Let lengthDelta be newLength - buffer.[[ArrayBufferByteLength]].
- auto length_delta = new_length - buffer.byte_length();
-
- // 3. If lengthDelta < 0 or lengthDelta modulo 65536 is not 0,
- if (new_length < buffer.byte_length() || length_delta % page_size != 0) {
- // 1. Throw a RangeError exception.
- return vm.throw_completion<JS::RangeError>("WebAssembly.Memory buffers must be resized by a multiple of the page size"sv);
- }
-
- // 4. Let delta be lengthDelta ÷ 65536.
- auto delta = length_delta / page_size;
-
- // 5. Grow the memory buffer associated with memaddr by delta.
- // FIXME: "Grow the memory buffer" is a separate algorithm from the Memory#grow() method.
- TRY(WebIDL::throw_dom_exception_if_needed(vm, buffer.shape().realm(), [&] {
- return memory->grow(delta);
- }));
-
- // 4. If newLength < buffer.[[ArrayBufferByteLength]] or newLength > buffer.[[ArrayBufferMaxByteLength]], throw a RangeError exception.
- if (new_length < current_byte_length)
- return vm.throw_completion<JS::RangeError>(JS::ErrorType::ByteLengthLessThanPreviousByteLength, new_length, current_byte_length);
- if (new_length > buffer.max_byte_length())
- return vm.throw_completion<JS::RangeError>(JS::ErrorType::ByteLengthExceedsMaxByteLength, new_length, buffer.max_byte_length());
-
- // FIXME: 5. Let agentRecord be the surrounding agent’s Agent Record.
- // FIXME: 6. Let isLittleEndian be agentRecord.[[LittleEndian]] .
- // FIXME: 7. Let event be an implementation defined ReadModifyWriteSharedMemory event, whose [[Order]] is "SeqCst", [[Payload]] is NumericToRawBytes(Bigint, newLength, isLittleEndian), [[Block]] is buffer.[[ArrayBufferByteLengthData]], [[ByteIndex]] is 0, and [[ElementSize]] is 8.
- // FIXME: 8. Let eventsRecord be the EventsRecord in agentRecord.[[CandidateExecution]].[[EventsRecords]] that corresponds to the surrounding agent’s signifier agentRecord.[[Signifier]].
- // FIXME: 9. Append event to eventsRecord.[[EventsList]].
- VERIFY(buffer.byte_length() == new_length);
-
- // 10. Return handled.
- return JS::HandledByHost::Handled;
- }
-
- // AD-HOC: Otherwise, return unhandled.
- return JS::HandledByHost::Unhandled;
+ bool handled = false;
+ auto completion = web_rust_web_assembly_host_grow_shared_array_buffer(vm_to_abi(vm), object_to_abi(&buffer), new_length, &handled);
+ return handled_by_host(completion, handled);
}
-namespace {
-
-// The internal slots of an Exported Function: its [[FunctionAddress]], and the steps that call into the store.
-class ExportedFunctionHostData final : public GC::Cell {
- GC_CELL(ExportedFunctionHostData, GC::Cell);
- GC_DECLARE_ALLOCATOR(ExportedFunctionHostData);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- using Behavior = AK::Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>;
-
- Wasm::Runtime::Entity function_address() const { return m_function.ptr(); }
-
- JS::ThrowCompletionOr<JS::Value> call(JS::VM& vm) const
- {
- VERIFY(m_behavior);
- return m_behavior(vm);
- }
-
-private:
- ExportedFunctionHostData(Behavior behavior, Wasm::Runtime::Entity function)
- : m_behavior(move(behavior))
- , m_function(function)
- {
- }
-
- virtual void visit_edges(Visitor& visitor) override
- {
- Base::visit_edges(visitor);
- visitor.visit_possible_values(m_behavior.raw_capture_range());
- visitor.visit(m_function);
- }
-
- Behavior m_behavior;
- // The function, which an Exported Function keeps alive.
- GC::Ptr<GC::ForeignCell> m_function;
-};
-
-GC_DEFINE_ALLOCATOR(ExportedFunctionHostData);
-
-struct ExportedFunctionTraits {
- static JS::ThrowCompletionOr<JS::Value> call(JS::HostFunction& function, JS::VM& vm)
- {
- auto* host_data = JS::host_data_if<ExportedFunctionHostData>(function);
- VERIFY(host_data);
- return host_data->call(vm);
- }
-};
-
-constexpr JSHostFunctionHooks exported_function_hooks = JS::make_host_function_hooks<ExportedFunctionTraits>();
-constexpr JSHostClass exported_function_host_class = JS::make_host_class(JS_HOST_CLASS_FUNCTION, "ExportedWasmFunction"sv, nullptr, &exported_function_hooks, nullptr, 0);
-
-}
-
-GC::Ref<JS::HostFunction> create_exported_function(JS::Realm& realm, Utf16FlyString name, size_t length, Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> behavior, Wasm::Runtime::Entity function)
+JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ReadonlyBytes bytes, JS::Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined)
{
- auto host_data = realm.heap().allocate<ExportedFunctionHostData>(move(behavior), function);
- return JS::HostFunction::create(realm, exported_function_host_class, move(name), static_cast<i32>(length), {}, host_data);
+ JSModule* module_record = nullptr;
+ auto completion = web_rust_web_assembly_parse_a_webassembly_module(vm_to_abi(realm.vm()), &realm, bytes.data(), bytes.size(),
+ reinterpret_cast<u8 const*>(filename.characters_without_null_termination()), filename.length(), host_defined.ptr(), &module_record);
+ TRY(completion_from_abi<void>(completion));
+ return static_cast<JS::HostModule&>(*module_from_abi(module_record));
}
-Optional<Wasm::Runtime::Entity> exported_function_address(JS::FunctionObject const& function)
-{
- if (auto const* host_data = JS::host_data_if<ExportedFunctionHostData>(function))
- return host_data->function_address();
- return {};
}
-// https://www.w3.org/TR/wasm-js-api-2/#name-of-the-webassembly-function
-Utf16FlyString name_of_webassembly_function(Wasm::Runtime::Entity function)
-{
- // 1. Let store be the surrounding agent's associated store.
- // 2. Let funcinst be store.funcs[funcaddr].
- // 3. If funcinst is of the form {type functype, hostcode hostfunc},
- // 1. Assert: hostfunc is a JavaScript object and IsCallable(hostfunc) is true.
- // 2. Let index be the index of the host function funcaddr.
- // 4. Otherwise,
- // 1. Let moduleinst be funcinst.module.
- // 2. Assert: funcaddr is contained in moduleinst.funcaddrs.
- // 3. Let index be the index of moduleinst.funcaddrs where funcaddr is found.
- auto& cache = WebAssemblyCache::the();
- auto index = cache.store().function_index(function);
- if (!index.has_value())
- index = cache.store().host_function_index(function);
- VERIFY(index.has_value());
-
- // 5. Return ! ToString(index).
- auto name = Utf16String::number(*index);
- return Utf16FlyString::from_utf16(name.utf16_view());
-}
+extern "C" {
-// https://webassembly.github.io/spec/js-api/#a-new-exported-function
-GC::Ref<JS::NativeFunction> create_native_function(JS::Realm& realm, Wasm::Runtime::Entity function)
+JSCompletion web_bindings_ensure_csp_does_not_block_wasm_byte_compilation(void* realm)
{
- auto& cache = WebAssemblyCache::the();
- if (auto object = cache.function_object(function))
- return *object;
-
- auto type = cache.store().function_type(function);
- auto length = type.parameters.size();
-
- auto object = create_exported_function(
- realm,
- name_of_webassembly_function(function),
- length,
- [function, type = move(type)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
- // https://webassembly.github.io/spec/js-api/#call-an-exported-function
- // NB: The converted arguments may refer to new cells, which this vector keeps alive during the call.
- Wasm::Runtime::Values arguments;
- arguments.ensure_capacity(type.parameters.size());
- for (size_t index = 0; index < type.parameters.size(); ++index)
- arguments.unchecked_append(TRY(to_webassembly_value(vm, vm.argument(index), type.parameters[index])));
-
- auto result = WebAssemblyCache::the().store().invoke(function, arguments);
- if (result.is_error())
- return completion_of_failure(vm, result.error());
-
- auto& values = result.value();
- if (values.is_empty())
- return JS::js_undefined();
-
- if (values.size() == 1)
- return to_js_value(vm, values.first(), type.results.first());
-
- GC::RootVector<JS::Value> js_result_values;
- js_result_values.ensure_capacity(values.size());
- for (size_t index = 0; index < values.size(); ++index)
- js_result_values.unchecked_append(TRY(to_js_value(vm, values[index], type.results[index])));
- return JS::Value(JS::Array::create_from(*vm.current_realm(), js_result_values));
- },
- function);
-
- cache.set_function_object(function, object);
- return object;
-}
-
-// The internal form of a JavaScript value as a reference of the any hierarchy: an i31 reference for a Number in its
-// range, the struct or array of an Exported GC Object, and otherwise a host reference.
-static u64 internalized_reference_of(JS::VM& vm, JS::Value value)
-{
- if (auto reference = i31_reference_of(value); reference.has_value())
- return *reference;
- if (value.is_object()) {
- if (auto address = exported_gc_object_address(value.as_object()); address.has_value())
- return *address;
- }
- return host_reference_of(vm, value);
-}
-
-// Whether a reference type is of the func hierarchy, whose references are functions.
-static bool is_function_reference_type(WasmValueType type)
-{
- if (type.heap == HeapKind::Concrete)
- return WebAssemblyCache::the().store().is_function_type(type.type_index);
- return type.heap == HeapKind::Function || type.heap == HeapKind::NoFunction;
-}
-
-// https://webassembly.github.io/spec/js-api/#towebassemblyvalue
-static JS::ThrowCompletionOr<u64> to_webassembly_reference(JS::VM& vm, JS::Value value, WasmValueType type)
-{
- auto& store = WebAssemblyCache::the().store();
-
- // If v is null: if the type is nullable, return ref.null of its heap type, and otherwise throw a TypeError.
- if (value.is_null()) {
- if (!type.nullable)
- return vm.throw_completion<JS::TypeError>("Cannot convert null to a non-nullable reference"_utf16);
- return 0;
- }
-
- switch (type.heap) {
- case HeapKind::Exception:
- case HeapKind::NoException:
- return vm.throw_completion<JS::TypeError>("Cannot convert a JavaScript value to an exception reference"_utf16);
- case HeapKind::NoFunction:
- case HeapKind::NoExtern:
- case HeapKind::None:
- return vm.throw_completion<JS::TypeError>("Only null converts to a bottom reference type"_utf16);
- case HeapKind::Extern:
- // NB: An externref keeps the bits of the anyref it externalizes.
- return internalized_reference_of(vm, value);
- default:
- break;
- }
-
- // If the type is of the func hierarchy, only an Exported Function of a matching type converts, to its function.
- if (is_function_reference_type(type)) {
- if (value.is_function()) {
- if (auto address = exported_function_address(value.as_function()); address.has_value()) {
- auto reference = store.function_reference(*address);
- if (store.reference_matches(reference, type))
- return reference;
- }
- }
- return vm.throw_completion<JS::TypeError>("Cannot convert the value to a function reference of this type"_utf16);
- }
-
- // Otherwise the type is of the any hierarchy: the internal form of v converts if it matches the type.
- auto reference = internalized_reference_of(vm, value);
- if (!store.reference_matches(reference, type))
- return vm.throw_completion<JS::TypeError>("Cannot convert the value to a reference of this type"_utf16);
- return reference;
+ return JS::HostABI::completion_to_abi(Web::ContentSecurityPolicy::ensure_csp_does_not_block_wasm_byte_compilation(*static_cast<JS::Realm*>(realm)));
}
-// https://webassembly.github.io/spec/js-api/#towebassemblyvalue
-JS::ThrowCompletionOr<WasmValue> to_webassembly_value(JS::VM& vm, JS::Value value, WasmValueType type)
+static bool write_agent_cluster(Optional<u64> agent_cluster_id, u64* agent_cluster)
{
-
- switch (type.kind) {
- case ValueKind::I64: {
- auto bigint = TRY(value.to_bigint(vm));
- return WasmValue::from_i64(bigint->big_integer().to_i64());
- }
- case ValueKind::I32:
- return WasmValue::from_i32(TRY(value.to_i32(vm)));
- case ValueKind::F64:
- return WasmValue::from_f64(TRY(value.to_double(vm)));
- case ValueKind::F32:
- return WasmValue::from_f32(static_cast<float>(TRY(value.to_double(vm))));
- case ValueKind::V128:
- return vm.throw_completion<JS::TypeError>("Cannot convert a javascript value to a vector value"_utf16);
- case ValueKind::Reference:
- return WasmValue::from_reference(TRY(to_webassembly_reference(vm, value, type)));
- }
- VERIFY_NOT_REACHED();
-}
-
-// https://webassembly.github.io/spec/js-api/#defaultvalue
-WasmValue default_webassembly_value(JS::VM& vm, WasmValueType type)
-{
- // 1. If valuetype equals externref, return ToWebAssemblyValue(undefined, valuetype).
- if (type.kind == ValueKind::Reference && type.heap == HeapKind::Extern)
- return MUST(to_webassembly_value(vm, JS::js_undefined(), type));
-
- // 2. Return DefaultValue(valuetype).
- return WasmValue::default_for(type);
-}
-
-// https://webassembly.github.io/spec/js-api/#tojsvalue
-JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM& vm, WasmValue wasm_value, WasmValueType type)
-{
-
- switch (type.kind) {
- case ValueKind::I64:
- return JS::BigInt::create(vm, ::Crypto::SignedBigInteger { wasm_value.to_i64() });
- case ValueKind::I32:
- return JS::Value(wasm_value.to_i32());
- case ValueKind::F64:
- return JS::Value(wasm_value.to_f64());
- case ValueKind::F32:
- return JS::Value(static_cast<double>(wasm_value.to_f32()));
- case ValueKind::V128:
- return vm.throw_completion<JS::TypeError>("Cannot convert a vector value to a javascript value"_utf16);
- case ValueKind::Reference:
- break;
- }
-
- if (type.heap == HeapKind::Exception || type.heap == HeapKind::NoException)
- return vm.throw_completion<JS::TypeError>("Cannot convert an exception reference to a javascript value"_utf16);
-
- auto reference = wasm_value.reference_bits();
-
- // 1. If w is of the form ref.null t, return null.
- if (reference == 0)
- return JS::js_null();
-
- // 2. If w is of the form ref.func funcaddr, return the result of creating a new Exported Function from funcaddr.
- if (is_function_reference_type(type))
- return create_native_function(*vm.current_realm(), WebAssemblyCache::the().store().function_from_reference(reference));
-
- // 3. If w is of the form ref.i31 u31, return 𝔽(signed_31(u31)).
- if (reference & I31_REFERENCE_BIT)
- return JS::Value(value_of_i31_reference(reference));
-
- // 4. If w is of the form ref.host hostaddr, return the result of retrieving a host value from hostaddr.
- // NB: An externref of a host value keeps the bits of the host reference.
- if ((reference & REFERENCE_TAG_MASK) == HOST_REFERENCE_TAG)
- return value_of_host_reference(reference);
-
- // 5. If w is of the form ref.struct structaddr or ref.array arrayaddr, return the result of creating a new Exported
- // GC Object from it.
- return create_exported_gc_object(vm, reference);
-}
-
-// https://webassembly.github.io/spec/js-api/#error-objects
-JS::Completion completion_of_failure(JS::VM& vm, Wasm::Runtime::Failure const& failure)
-{
- switch (failure.kind) {
- case Wasm::Runtime::FailureKind::LinkError:
- return vm.throw_completion<LinkError>(failure.message);
- case Wasm::Runtime::FailureKind::StackExhausted:
- // https://webassembly.github.io/spec/js-api/#stack-overflow
- // 6.1. Whenever a stack overflow occurs in WebAssembly code, the same class of exception is thrown as for a stack overflow in JavaScript.
- return vm.throw_completion<JS::InternalError>(JS::ErrorType::CallStackSizeExceeded);
- case Wasm::Runtime::FailureKind::Exception: {
- // An exception with the JavaScript tag carries a JavaScript value that was thrown into WebAssembly code, which
- // continues as itself.
- auto& cache = WebAssemblyCache::the();
- auto& store = cache.store();
- if (store.exception_tag(failure.exception) == cache.js_tag()) {
- auto payload = store.exception_values(failure.exception);
- return JS::throw_completion(MUST(to_js_value(vm, payload.first(), WasmValueType::reference(HeapKind::Extern))));
- }
- // Otherwise, throw the Exception object of the exception.
- auto& realm = *vm.current_realm();
- auto exception = Exception::from_address(failure.exception);
- return JS::throw_completion(Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, exception));
- }
- case Wasm::Runtime::FailureKind::Trap:
- // FIXME: Use the convoluted mapping of errors defined in the spec.
- return vm.throw_completion<RuntimeError>(Utf16String::formatted("Wasm execution trapped (WIP): {}", failure.message));
- }
- VERIFY_NOT_REACHED();
-}
-
-// https://webassembly.github.io/content-security-policy/js-api/#abstract-opdef-hostensurecancompilewasmbytes
-JS::ThrowCompletionOr<void> host_ensure_can_compile_wasm_bytes(JS::Realm& realm)
-{
- // 2. Perform EnsureCSPDoesNotBlockWasmByteCompilation(realm)
- // This algorithm does not return a value, but raises a CompileError exception if the operation cannot complete
- // successfully.
- return ContentSecurityPolicy::ensure_csp_does_not_block_wasm_byte_compilation(realm);
-}
-
+ if (!agent_cluster_id.has_value())
+ return false;
+ *agent_cluster = *agent_cluster_id;
+ return true;
}
-// https://webassembly.github.io/spec/js-api/#asynchronously-compile-a-webassembly-module
-GC::Ref<WebIDL::Promise> asynchronously_compile_webassembly_module(JS::Realm& realm, ByteBuffer bytes, Bindings::WebAssemblyCompileOptions const& options, HTML::Task::Source task_source)
+// The current Realm's corresponding agent cluster.
+bool web_bindings_current_agent_cluster(u64* agent_cluster)
{
- // 1. Let promise be a new Promise.
- auto promise = WebIDL::create_promise(realm);
-
- // 2. Run the following steps in parallel:
- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), [&realm, bytes = move(bytes), promise, options, task_source]() mutable {
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- // 1. Compile the WebAssembly module bytes and store the result as module.
- auto module_or_error = Detail::compile_a_webassembly_module(realm, bytes);
-
- // 2. Queue a task on taskSource, if provided, to perform the following steps:
- HTML::queue_a_task(task_source, nullptr, nullptr, GC::create_function(GC::Heap::the(), [&realm, bytes = move(bytes), promise, options = move(options), module_or_error = move(module_or_error)]() mutable {
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- auto& realm = HTML::relevant_realm(*promise->promise());
-
- // 1. If module is error, reject promise with a CompileError exception and return.
- if (module_or_error.is_error()) {
- WebIDL::reject_promise(promise, module_or_error.error_value());
- return;
- }
- auto module = module_or_error.release_value();
-
- // 2. Let builtinSetNames be options["builtins"].
- auto& builtin_set_names = options.builtins;
-
- // 3. Let importedStringModule be options["importedStringConstants"].
- auto& imported_string_module = options.imported_string_constants;
-
- // 4. If validating builtins and imported strings for module with builtinSetNames and importedStringModule is
- // false, reject promise with a CompileError exception.
- if (!Detail::validate_builtins_and_imported_strings(*module->module, builtin_set_names, imported_string_module)) {
- WebIDL::reject_promise(promise, realm.vm().throw_completion<CompileError>("Invalid builtin or imported string"sv).value());
- }
-
- // 5. Otherwise,
- else {
- // 1. Construct a WebAssembly module object from module, bytes, builtinSetNames, importedStringModule, and
- // let moduleObject be the result.
- auto module_object = GC::Heap::the().allocate<Module>(move(module), move(bytes), move(builtin_set_names), move(imported_string_module));
-
- // 2. Resolve promise with moduleObject.
- Bindings::resolve_webassembly_module_promise(realm, promise, module_object);
- }
- }));
- }));
-
- // 3. Return promise.
- return promise;
+ return write_agent_cluster(Web::HTML::current_settings_object().agent_cluster_id(), agent_cluster);
}
-// https://webassembly.github.io/spec/js-api/#asynchronously-instantiate-a-webassembly-module
-GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm& realm, GC::Ref<Module> module_object, GC::Ptr<JS::Object> import_object)
+// The realm's corresponding agent cluster.
+bool web_bindings_agent_cluster_of_realm(void* realm, u64* agent_cluster)
{
- // 1. Let promise be a new promise.
- auto promise = WebIDL::create_promise(realm);
-
- // 2. Let module be moduleObject.[[Module]].
- auto module = module_object->compiled_module();
-
- // 3. Let builtinSetNames be moduleObject.[[BuiltinSets]].
- auto const& builtin_set_names = module_object->builtin_sets();
-
- // 4. Let importedStringModule be moduleObject.[[ImportedStringModule]].
- auto const& imported_string_module = module_object->imported_string_module();
-
- // 5. Read the imports of module with imports importObject, builtinSetNames and importedStringModule, and let imports
- // be the result. If this operation throws an exception, catch it, reject promise with the exception, and return
- // promise.
- auto imports_or_error = Detail::read_the_imports(realm.vm(), *module->module, import_object, builtin_set_names, imported_string_module);
- if (imports_or_error.is_error()) {
- WebIDL::reject_promise(promise, imports_or_error.error_value());
- return promise;
- }
-
- // 6. Run the following steps in parallel:
- // 1. Queue a task to perform the following steps: Note: Implementation-specific work may be performed here.
- HTML::queue_a_task(HTML::Task::Source::Unspecified, nullptr, nullptr, GC::create_function(GC::Heap::the(), [&realm, promise, module, imports = imports_or_error.release_value()]() {
- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);
- auto& realm = HTML::relevant_realm(*promise->promise());
-
- // 1. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
- // If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
- auto result = Detail::instantiate_core_module(realm.vm(), *module->module, imports);
- if (result.is_error()) {
- WebIDL::reject_promise(promise, result.error_value());
- return;
- }
- auto instance = result.release_value();
-
- // 2. Let instanceObject be a new Instance.
- // 3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
- // FIXME: Investigate whether we are doing all the proper steps for "initialize an instance object"
- auto instance_object = Instance::create(realm, instance);
-
- // 4. Resolve promise with instanceObject.
- Bindings::resolve_webassembly_instance_promise(realm, promise, instance_object);
- }));
-
- // 7. Return promise.
- return promise;
-}
-
-// https://webassembly.github.io/spec/js-api/#instantiate-a-promise-of-a-module
-GC::Ref<WebIDL::Promise> instantiate_promise_of_module(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise_of_module, GC::Ptr<JS::Object> import_object)
-{
- // 1. Let promise be a new Promise.
- auto promise = WebIDL::create_promise(realm);
-
- // FIXME: Spec should use react to promise here instead of separate upon fulfillment and upon rejection steps
-
- // 2. Upon fulfillment of promiseOfModule with value module:
- auto fulfillment_steps = GC::create_function(GC::Heap::the(), [promise, import_object](JS::Value module_value) -> WebIDL::ExceptionOr<JS::Value> {
- auto* module = Bindings::module_from_value(module_value);
- VERIFY(module);
- auto module_object = GC::Ref { *module };
-
- // 1. Instantiate the WebAssembly module module importing importObject, and let innerPromise be the result.
- auto& realm = HTML::relevant_realm(*promise->promise());
- auto inner_promise = asynchronously_instantiate_webassembly_module(realm, module_object, import_object);
-
- // 2. Upon fulfillment of innerPromise with value instance.
- auto instantiate_fulfillment_steps = GC::create_function(GC::Heap::the(), [promise, module_object](JS::Value instance_value) -> WebIDL::ExceptionOr<JS::Value> {
- auto& realm = HTML::relevant_realm(*promise->promise());
- auto* instance = Bindings::instance_from_value(instance_value);
- VERIFY(instance);
-
- // 1. Let result be the WebAssemblyInstantiatedSource value «[ "module" → module, "instance" → instance ]».
- auto result = Bindings::create_webassembly_instantiated_source(realm, module_object, GC::Ref { *instance });
-
- // 2. Resolve promise with result.
- WebIDL::resolve_promise(promise, result);
-
- return JS::js_undefined();
- });
-
- // 3. Upon rejection of innerPromise with reason reason.
- auto instantiate_rejection_steps = GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
- // 1. Reject promise with reason.
- WebIDL::reject_promise(promise, reason);
-
- return JS::js_undefined();
- });
-
- WebIDL::react_to_promise(inner_promise, instantiate_fulfillment_steps, instantiate_rejection_steps);
-
- return JS::js_undefined();
- });
-
- // 3. Upon rejection of promiseOfModule with reason reason:
- auto rejection_steps = GC::create_function(GC::Heap::the(), [promise](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
- // 1. Reject promise with reason.
- WebIDL::reject_promise(promise, reason);
-
- return JS::js_undefined();
- });
-
- WebIDL::react_to_promise(promise_of_module, fulfillment_steps, rejection_steps);
-
- // 4. Return promise.
- return promise;
+ auto& settings = Web::Bindings::principal_host_defined_environment_settings_object(*static_cast<JS::Realm*>(realm));
+ return write_agent_cluster(settings.agent_cluster_id(), agent_cluster);
}
// https://webassembly.github.io/spec/web-api/index.html#compile-a-potential-webassembly-response
-GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm& realm, GC::Ref<WebIDL::Promise> source, Bindings::WebAssemblyCompileOptions const& options)
+JSCompletion web_bindings_consume_webassembly_response(void* realm_pointer, JSValue unwrapped_source_value, void** body_promise)
{
+ using namespace Web;
+ auto& realm = *static_cast<JS::Realm*>(realm_pointer);
auto& vm = realm.vm();
-
- // Note: This algorithm accepts a Response object, or a promise for one, and compiles and instantiates the resulting bytes of the response.
- // This compilation can be performed in the background and in a streaming manner.
- // If the Response is not CORS-same-origin, does not represent an ok status, or does not match the `application/wasm` MIME type,
- // the returned promise will be rejected with a TypeError; if compilation or instantiation fails,
- // the returned promise will be rejected with a CompileError or other relevant error type, depending on the cause of failure.
-
- // 1. Let returnValue be a new promise
- auto return_value = WebIDL::create_promise(realm);
-
- // 2. Upon fulfillment of source with value unwrappedSource:
- auto fulfillment_steps = GC::create_function(GC::Heap::the(), [&vm, return_value, options](JS::Value unwrapped_source) -> WebIDL::ExceptionOr<JS::Value> {
- auto& realm = HTML::relevant_realm(*return_value->promise());
-
- // 1. Let response be unwrappedSource’s response.
- auto* response_object = unwrapped_source.is_object()
- ? Bindings::impl_from<Fetch::Response>(&unwrapped_source.as_object())
- : nullptr;
- if (!response_object) {
- WebIDL::reject_promise(return_value, vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Response").value());
- return JS::js_undefined();
- }
- auto response = response_object->response();
-
- // 2. Let mimeType be the result of getting `Content-Type` from response’s header list.
- // 3. If mimeType is null, reject returnValue with a TypeError and abort these substeps.
- // 4. Remove all HTTP tab or space byte from the start and end of mimeType.
- // 5. If mimeType is not a byte-case-insensitive match for `application/wasm`, reject returnValue with a TypeError and abort these substeps.
- // Note: extra parameters are not allowed, including the empty `application/wasm;`.
- // FIXME: Validate these extra constraints that are not checked by extract_mime_type()
- if (auto mime = Fetch::Infrastructure::extract_mime_type(response->header_list()); !mime.has_value() || mime.value().essence() != "application/wasm"sv) {
- WebIDL::reject_promise(return_value, vm.throw_completion<JS::TypeError>("Response does not match the application/wasm MIME type"_utf16).value());
- return JS::js_undefined();
- }
-
- // 6. If response is not CORS-same-origin, reject returnValue with a TypeError and abort these substeps.
- if (!response->is_cors_same_origin()) {
- WebIDL::reject_promise(return_value, vm.throw_completion<JS::TypeError>("Response is not CORS-same-origin"_utf16).value());
- return JS::js_undefined();
- }
-
- // 7. If response’s status is not an ok status, reject returnValue with a TypeError and abort these substeps.
- if (!response_object->ok()) {
- WebIDL::reject_promise(return_value, vm.throw_completion<JS::TypeError>("Response does not represent an ok status"_utf16).value());
- return JS::js_undefined();
- }
-
- // 8. Consume response’s body as an ArrayBuffer, and let bodyPromise be the result.
- auto body_promise_or_error = Bindings::array_buffer_for_webassembly_response(realm, *response_object);
- if (body_promise_or_error.is_error()) {
- WebIDL::reject_promise_with_exception(return_value, body_promise_or_error.release_error());
- return JS::js_undefined();
- }
- auto body_promise = body_promise_or_error.release_value();
-
- // 9. Upon fulfillment of bodyPromise with value bodyArrayBuffer:
- auto body_fulfillment_steps = GC::create_function(GC::Heap::the(), [&vm, return_value, options](JS::Value body_array_buffer) -> WebIDL::ExceptionOr<JS::Value> {
- // 1. Let stableBytes be a copy of the bytes held by the buffer bodyArrayBuffer.
- VERIFY(body_array_buffer.is_object());
- auto stable_bytes = WebIDL::get_buffer_source_copy(body_array_buffer.as_object());
- if (stable_bytes.is_error()) {
- VERIFY(stable_bytes.error().code() == ENOMEM);
- WebIDL::reject_promise(return_value, vm.throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory)).value());
- return JS::js_undefined();
- }
-
- // 2. Asynchronously compile the WebAssembly module stableBytes using the networking task source and options
- // and resolve returnValue with the result.
- auto result = asynchronously_compile_webassembly_module(HTML::relevant_realm(*return_value->promise()), stable_bytes.release_value(), options, HTML::Task::Source::Networking);
-
- // Need to manually convert WebIDL promise to an ECMAScript value here to resolve
- WebIDL::resolve_promise(return_value, result->promise());
-
- return JS::js_undefined();
- });
-
- // 10. Upon rejection of bodyPromise with reason reason:
- auto body_rejection_steps = GC::create_function(GC::Heap::the(), [return_value](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
- // 1. Reject returnValue with reason.
- WebIDL::reject_promise(return_value, reason);
- return JS::js_undefined();
- });
-
- WebIDL::react_to_promise(body_promise, body_fulfillment_steps, body_rejection_steps);
-
- return JS::js_undefined();
- });
-
- // 3. Upon rejection of source with reason reason:
- auto rejection_steps = GC::create_function(GC::Heap::the(), [return_value](JS::Value reason) -> WebIDL::ExceptionOr<JS::Value> {
- // 1. Reject returnValue with reason.
- WebIDL::reject_promise(return_value, reason);
-
- return JS::js_undefined();
- });
-
- WebIDL::react_to_promise(source, fulfillment_steps, rejection_steps);
-
- // 4. Return returnValue.
- return return_value;
-}
-
-namespace {
-
-// The name of each error type, and the name under which Bindings::Intrinsics keeps its prototype and constructor.
-template<typename NativeError>
-struct NativeErrorNames;
-
-#define __WASM_ENUMERATE(ClassName, FullClassName) \
- template<> \
- struct NativeErrorNames<ClassName> { \
- static constexpr StringView constructor_class_name = #ClassName "Constructor"sv; \
- static Utf16FlyString name() { return #ClassName##_utf16_fly_string; } \
- static Utf16FlyString intrinsic_name() { return FullClassName##_utf16_fly_string; } \
+ auto unwrapped_source = JS::HostABI::value_from_abi(unwrapped_source_value);
+ auto type_error = [&](Utf16String message) {
+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<void> { vm.throw_completion<JS::TypeError>(move(message)) });
};
-WASM_ENUMERATE_NATIVE_ERRORS
-#undef __WASM_ENUMERATE
-
-template<typename NativeError>
-JS::Object& native_error_prototype(JS::Realm& realm)
-{
- return Bindings::ensure_web_prototype<NativeError>(realm, NativeErrorNames<NativeError>::intrinsic_name());
-}
-
-// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
-// The LibJS implementation looks the intrinsic default prototype up in JS::Intrinsics, whereas these error types keep
-// theirs in Bindings::Intrinsics.
-template<typename NativeError>
-JS::ThrowCompletionOr<GC::Ref<JS::Error>> ordinary_create_native_error_from_constructor(JS::VM& vm, JS::FunctionObject const& constructor)
-{
- auto& realm = *vm.current_realm();
-
- // 2. Let proto be ? GetPrototypeFromConstructor(constructor, intrinsicDefaultProto).
- auto prototype = TRY([&]() -> JS::ThrowCompletionOr<GC::Ref<JS::Object>> {
- // https://tc39.es/ecma262/#sec-getprototypefromconstructor
-
- // 2. Let proto be ? Get(constructor, "prototype").
- auto prototype = TRY(constructor.get(vm.names.prototype));
-
- // 3. If Type(proto) is not Object, then
- if (!prototype.is_object()) {
- // a. Let realm be ? GetFunctionRealm(constructor).
- auto* realm = TRY(JS::get_function_realm(vm, constructor));
-
- // b. Set proto to realm's intrinsic object named intrinsicDefaultProto.
- prototype = &native_error_prototype<NativeError>(*realm);
- }
-
- // 4. Return proto.
- return prototype.as_object();
- }());
-
- // 3. If internalSlotsList is present, let slotsList be internalSlotsList.
- // 4. Else, let slotsList be a new empty List.
- // 5. Return OrdinaryObjectCreate(proto, slotsList).
- return JS::Error::create(realm, prototype);
-}
-
-template<typename NativeError>
-struct NativeErrorConstructorTraits {
- // 20.5.6.1.1 NativeError ( message [ , options ] ), https://tc39.es/ecma262/#sec-nativeerror
- static JS::ThrowCompletionOr<JS::Value> call(JS::HostFunction& constructor, JS::VM& vm)
- {
- // 1. If NewTarget is undefined, let newTarget be the active function object; else let newTarget be NewTarget.
- return TRY(construct(constructor, vm, constructor));
- }
-
- // 20.5.6.1.1 NativeError ( message [ , options ] ), https://tc39.es/ecma262/#sec-nativeerror
- static JS::ThrowCompletionOr<GC::Ref<JS::Object>> construct(JS::HostFunction&, JS::VM& vm, JS::FunctionObject& new_target)
- {
- auto message = vm.argument(0);
- auto options = vm.argument(1);
- // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%NativeError.prototype%", « [[ErrorData]] »).
- auto error = TRY(ordinary_create_native_error_from_constructor<NativeError>(vm, new_target));
-
- // 3. If message is not undefined, then
- if (!message.is_undefined()) {
- // a. Let msg be ? ToString(message).
- auto msg = TRY(message.to_utf16_string(vm));
-
- // b. Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg).
- error->create_non_enumerable_data_property_or_throw(vm.names.message, JS::PrimitiveString::create(vm, move(msg)));
- }
-
- // 4. Perform ? InstallErrorCause(O, options).
- TRY(error->install_error_cause(options));
-
- // 5. Return O.
- return error;
- }
-};
-
-template<typename NativeError>
-constexpr JSHostFunctionHooks native_error_constructor_hooks = JS::make_host_function_hooks<NativeErrorConstructorTraits<NativeError>>();
-
-template<typename NativeError>
-constexpr JSHostClass native_error_constructor_host_class = JS::make_host_class(JS_HOST_CLASS_FUNCTION, NativeErrorNames<NativeError>::constructor_class_name, nullptr, &native_error_constructor_hooks<NativeError>, nullptr, JS_HOST_CLASS_HAS_CONSTRUCTOR);
-
-struct NativeErrorPrototypeAndConstructor {
- GC::Ref<JS::Object> prototype;
- GC::Ref<JS::HostFunction> constructor;
-};
-
-template<typename NativeError>
-NativeErrorPrototypeAndConstructor create_native_error_prototype_and_constructor(JS::Realm& realm)
-{
- auto& vm = realm.vm();
- auto name = NativeErrorNames<NativeError>::name();
- u8 const attr = JS::Attribute::Writable | JS::Attribute::Configurable;
-
- // 20.5.6.3 Properties of the NativeError Prototype Objects, https://tc39.es/ecma262/#sec-properties-of-the-nativeerror-prototype-objects
- auto prototype = JS::Object::create(realm, realm.intrinsics().error_prototype());
- prototype->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, name), attr);
- prototype->define_direct_property(vm.names.message, JS::PrimitiveString::create(vm, Utf16String {}), attr);
-
- // 20.5.6.2 Properties of the NativeError Constructors, https://tc39.es/ecma262/#sec-properties-of-the-nativeerror-constructors
- auto constructor = JS::HostFunction::create_without_own_properties(realm, native_error_constructor_host_class<NativeError>, name, realm.intrinsics().error_constructor());
- constructor->define_direct_property(vm.names.prototype, prototype, 0);
- constructor->define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, name), JS::Attribute::Configurable);
- constructor->define_direct_property(vm.names.length, JS::Value(1), JS::Attribute::Configurable);
-
- prototype->define_direct_property(vm.names.constructor, constructor, attr);
- return { prototype, constructor };
-}
-
-}
-
-#define __WASM_ENUMERATE(ClassName, FullClassName) \
- GC::Ref<JS::Error> ClassName::create(JS::Realm& realm) \
- { \
- return JS::Error::create(realm, native_error_prototype<ClassName>(realm)); \
- } \
- \
- GC::Ref<JS::Error> ClassName::create(JS::Realm& realm, Utf16String message) \
- { \
- return JS::Error::create(realm, native_error_prototype<ClassName>(realm), move(message)); \
- } \
- \
- GC::Ref<JS::Error> ClassName::create(JS::Realm& realm, StringView message) \
- { \
- return create(realm, Utf16String::from_utf8(message)); \
- }
-WASM_ENUMERATE_NATIVE_ERRORS
-#undef __WASM_ENUMERATE
-
-}
-
-namespace Web::Bindings {
-
-WebAssembly::Global* global_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Global>(&value.as_object()) : nullptr;
-}
-
-WebAssembly::Instance* instance_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Instance>(&value.as_object()) : nullptr;
-}
-
-WebAssembly::Memory* memory_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Memory>(&value.as_object()) : nullptr;
-}
-
-WebAssembly::Module* module_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Module>(&value.as_object()) : nullptr;
-}
-
-WebAssembly::Table* table_from_value(JS::Value value)
-{
- return value.is_object() ? Bindings::impl_from<WebAssembly::Table>(&value.as_object()) : nullptr;
-}
-
-void resolve_webassembly_module_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::Ref<WebAssembly::Module> module)
-{
- WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, module));
-}
-
-void resolve_webassembly_instance_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::Ref<WebAssembly::Instance> instance)
-{
- WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, instance));
-}
-
-GC::Ref<JS::Object> create_webassembly_instantiated_source(JS::Realm& realm, GC::Ref<WebAssembly::Module> module, GC::Ref<WebAssembly::Instance> instance)
-{
- // NB: The WebAssemblyInstantiatedSource dictionary converts to an ordinary object, whose prototype is
- // %Object.prototype%.
- auto result = JS::Object::create(realm, realm.intrinsics().object_prototype());
- result->define_direct_property("module"_utf16_fly_string, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, module), JS::default_attributes);
- result->define_direct_property("instance"_utf16_fly_string, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, instance), JS::default_attributes);
- return result;
-}
-
-WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> array_buffer_for_webassembly_response(JS::Realm& realm, Fetch::Response const& response)
-{
+ // 1. Let response be unwrappedSource’s response.
+ auto* response_object = unwrapped_source.is_object()
+ ? Bindings::impl_from<Fetch::Response>(&unwrapped_source.as_object())
+ : nullptr;
+ if (!response_object)
+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<void> { vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Response") });
+ auto response = response_object->response();
+
+ // 2. Let mimeType be the result of getting `Content-Type` from response’s header list.
+ // 3. If mimeType is null, reject returnValue with a TypeError and abort these substeps.
+ // 4. Remove all HTTP tab or space byte from the start and end of mimeType.
+ // 5. If mimeType is not a byte-case-insensitive match for `application/wasm`, reject returnValue with a TypeError and abort these substeps.
+ // Note: extra parameters are not allowed, including the empty `application/wasm;`.
+ // FIXME: Validate these extra constraints that are not checked by extract_mime_type()
+ if (auto mime = Fetch::Infrastructure::extract_mime_type(response->header_list()); !mime.has_value() || mime.value().essence() != "application/wasm"sv)
+ return type_error("Response does not match the application/wasm MIME type"_utf16);
+
+ // 6. If response is not CORS-same-origin, reject returnValue with a TypeError and abort these substeps.
+ if (!response->is_cors_same_origin())
+ return type_error("Response is not CORS-same-origin"_utf16);
+
+ // 7. If response’s status is not an ok status, reject returnValue with a TypeError and abort these substeps.
+ if (!response_object->ok())
+ return type_error("Response does not represent an ok status"_utf16);
+
+ // 8. Consume response’s body as an ArrayBuffer, and let bodyPromise be the result.
auto promise = WebIDL::create_promise(realm);
- response.array_buffer(promise);
- return promise;
+ response_object->array_buffer(promise);
+ *body_promise = promise.ptr();
+ return JS::HostABI::completion_to_abi(JS::ThrowCompletionOr<void> {});
}
-
-#define __WASM_ENUMERATE(ClassName, FullClassName) \
- template<> \
- void Intrinsics::create_web_prototype_and_constructor<WebAssembly::ClassName>(JS::Realm & realm) \
- { \
- auto [prototype, constructor] = WebAssembly::create_native_error_prototype_and_constructor<WebAssembly::ClassName>(realm); \
- m_prototypes.set(FullClassName##_utf16_fly_string, prototype); \
- m_constructors.set(FullClassName##_utf16_fly_string, constructor); \
- }
-WASM_ENUMERATE_NATIVE_ERRORS
-#undef __WASM_ENUMERATE
-
}
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h
index 9008cb06b43..41615fcf028 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h
@@ -1,162 +1,34 @@
/*
- * Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
- * Copyright (c) 2023, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
-#include <AK/HashMap.h>
-#include <AK/HashTable.h>
-#include <AK/NonnullOwnPtr.h>
-#include <AK/NonnullRefPtr.h>
-#include <AK/Optional.h>
-#include <AK/RefCounted.h>
-#include <LibGC/ConservativeVector.h>
-#include <LibGC/Root.h>
-#include <LibGC/Weak.h>
+#include <AK/Span.h>
+#include <AK/StringView.h>
+#include <AK/Utf16String.h>
+#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
#include <LibJS/Runtime/Completion.h>
-#include <LibJS/Runtime/HostFunction.h>
-#include <LibJS/Runtime/NativeFunction.h>
-#include <LibJS/Runtime/Value.h>
-#include <LibURL/URL.h>
-#include <LibWasm/Runtime.h>
-#include <LibWeb/Bindings/Forward.h>
-#include <LibWeb/Export.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/Buffers.h>
+#include <LibJS/Runtime/VM.h>
+// What LibWeb's C++ code asks of the WebAssembly JavaScript Interface, which is implemented in Rust
+// (Libraries/LibWeb/Bindings/Rust/src/web_assembly).
namespace Web::WebAssembly {
-class Exception;
-class Tag;
+// A WebAssembly.CompileError in the realm.
+GC::Ref<JS::Object> create_compile_error(JS::Realm&, Utf16String const& message);
-WEB_API void initialize(JS::Object&, JS::Realm&);
+// https://webassembly.github.io/spec/js-api/#HostResizeArrayBuffer
+JS::ThrowCompletionOr<JS::HandledByHost> host_resize_array_buffer(JS::VM&, JS::ArrayBuffer&, size_t new_length);
-WEB_API bool validate(JS::Realm&, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const&);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile(JS::Realm&, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const&);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile_streaming(JS::Realm&, GC::Ref<WebIDL::Promise> source, Bindings::WebAssemblyCompileOptions const&);
+// https://webassembly.github.io/threads/js-api/#abstract-operation-hostgrowsharedarraybuffer
+JS::ThrowCompletionOr<JS::HandledByHost> host_grow_shared_array_buffer(JS::VM&, JS::ArrayBuffer&, size_t new_length);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, WebIDL::BufferSource bytes, GC::Ptr<JS::Object> import_object, Bindings::WebAssemblyCompileOptions const&);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm&, GC::Ref<Module> module_object, GC::Ptr<JS::Object> import_object, Optional<JS::Value> const& ignored);
-WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::Realm&, GC::Ref<WebIDL::Promise> source, GC::Ptr<JS::Object> import_object, Bindings::WebAssemblyCompileOptions const&);
-
-namespace Detail {
-
-class ExternValueBox;
-
-struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule> {
- explicit CompiledWebAssemblyModule(NonnullRefPtr<Wasm::Runtime::Module> module)
- : module(move(module))
- {
- }
-
- NonnullRefPtr<Wasm::Runtime::Module> module;
-};
-
-// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, Table, Tag, Exception, and
-// Exported GC Object caches.
-// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. The
-// caches are the runtime's link from a cell to the object that stands for it (Store::set_host_object()), which keeps
-// the object alive in turn, so that the object stays the same one for as long as both live, and both go away together.
-class WebAssemblyCache {
- AK_MAKE_NONCOPYABLE(WebAssemblyCache);
- AK_MAKE_NONMOVABLE(WebAssemblyCache);
- AK_ALLOC_WITH_KMALLOC;
-
-public:
- using Entity = Wasm::Runtime::Entity;
-
- // The cache of the current thread's agent.
- static WebAssemblyCache& the();
-
- Wasm::Runtime::Store& store() { return *m_store; }
-
- // The tag of the exceptions that carry JavaScript values through WebAssembly code, as their only (externref)
- // value.
- Entity js_tag() const { return m_js_tag_root.ptr(); }
-
- GC::Ptr<JS::NativeFunction> function_object(Entity function) const;
- void set_function_object(Entity function, JS::NativeFunction&);
- GC::Ptr<WebAssembly::Global> global_object(Entity global) const;
- void set_global_object(Entity global, WebAssembly::Global&);
- GC::Ptr<WebAssembly::Memory> memory_object(Entity memory) const;
- void set_memory_object(Entity memory, WebAssembly::Memory&);
- GC::Ptr<WebAssembly::Table> table_object(Entity table) const;
- void set_table_object(Entity table, WebAssembly::Table&);
- GC::Ptr<WebAssembly::Tag> tag_object(Entity tag) const;
- void set_tag_object(Entity tag, WebAssembly::Tag&);
- // Exceptions and GC objects are references, which are the addresses of their cells.
- GC::Ptr<WebAssembly::Exception> exception_object(u64 exception) const;
- void set_exception_object(u64 exception, WebAssembly::Exception&);
- GC::Ptr<JS::Object> gc_object(u64 object) const;
- void set_gc_object(u64 object, JS::Object&);
- void for_each_memory_object(Function<void(WebAssembly::Memory&)> const&) const;
- // The host value cache, for JavaScript values that are not cells: the box that stands for a value in WebAssembly,
- // which it converts to for as long as the box lives.
- GC::Ptr<ExternValueBox> extern_value_box(JS::Value) const;
- void set_extern_value_box(JS::Value, ExternValueBox&);
-
-private:
- explicit WebAssemblyCache(GC::Heap&);
- ~WebAssemblyCache();
-
- NonnullOwnPtr<Wasm::Runtime::Store> m_store;
- GC::Root<GC::ForeignCell> m_js_tag_root;
- // NB: An entry whose object is gone is stale. Stale entries go once there are as many of them as live ones.
- Vector<GC::Weak<WebAssembly::Memory>> m_memory_objects;
- size_t m_live_memory_objects_after_pruning { 0 };
- HashMap<JS::Value, GC::Weak<ExternValueBox>> m_extern_value_boxes;
- size_t m_live_extern_value_boxes_after_pruning { 0 };
-};
-
-// https://webassembly.github.io/spec/js-api/#exported-function
-GC::Ref<JS::HostFunction> create_exported_function(JS::Realm&, Utf16FlyString name, size_t length, ESCAPING Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> behavior, Wasm::Runtime::Entity function);
-
-// The value of the function's [[FunctionAddress]] internal slot, if it has one and is therefore an Exported Function.
-Optional<Wasm::Runtime::Entity> exported_function_address(JS::FunctionObject const&);
-
-// The value of the object's [[ObjectAddress]] internal slot, if it has one and is therefore an Exported GC Object.
-Optional<u64> exported_gc_object_address(JS::Object const&);
-
-// The function type at `type_index` of a module, in the store's terms (see Store::canonical_value_type()).
-Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const&, u32 type_index);
-JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_imports(JS::VM&, Wasm::Runtime::Module const&, GC::Ptr<JS::Object> import_object, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module);
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM&, Wasm::Runtime::Module const&, GC::Ptr<JS::Object> import_object, ReadonlySpan<Utf16String> builtin_set_names, Optional<Utf16String> const& imported_string_module);
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_core_module(JS::VM&, Wasm::Runtime::Module const&, ReadonlySpan<Wasm::Runtime::Extern> imports);
-Wasm::Runtime::Entity create_host_function(JS::VM&, JS::FunctionObject& function, Wasm::Runtime::FunctionType type, size_t function_index);
-JS::ThrowCompletionOr<NonnullRefPtr<CompiledWebAssemblyModule>> compile_a_webassembly_module(JS::Realm&, ReadonlyBytes);
-Utf16FlyString name_of_webassembly_function(Wasm::Runtime::Entity function);
-GC::Ref<JS::NativeFunction> create_native_function(JS::Realm&, Wasm::Runtime::Entity function);
-JS::ThrowCompletionOr<Wasm::Runtime::Value> to_webassembly_value(JS::VM&, JS::Value value, Wasm::Runtime::ValueType type);
-Wasm::Runtime::Value default_webassembly_value(JS::VM&, Wasm::Runtime::ValueType type);
-JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM&, Wasm::Runtime::Value wasm_value, Wasm::Runtime::ValueType type);
-JS::Completion completion_of_failure(JS::VM&, Wasm::Runtime::Failure const&);
-JS::ThrowCompletionOr<void> host_ensure_can_compile_wasm_bytes(JS::Realm&);
-JS::ThrowCompletionOr<JS::HandledByHost> host_resize_array_buffer(JS::VM&, JS::ArrayBuffer&, size_t);
-JS::ThrowCompletionOr<JS::HandledByHost> host_grow_shared_array_buffer(JS::VM&, JS::ArrayBuffer&, size_t);
-
-inline constexpr size_t page_size = 65536;
-
-}
-
-#define WASM_ENUMERATE_NATIVE_ERRORS \
- __WASM_ENUMERATE(CompileError, "WebAssembly.CompileError") \
- __WASM_ENUMERATE(LinkError, "WebAssembly.LinkError") \
- __WASM_ENUMERATE(RuntimeError, "WebAssembly.RuntimeError")
-
-// https://webassembly.github.io/spec/js-api/#error-objects
-// Errors of these types are Error objects whose prototype is the error type's prototype object in their realm. The
-// types only create such errors, for VM::throw_completion<CompileError>(...) and the like.
-#define __WASM_ENUMERATE(ClassName, FullClassName) \
- struct WEB_API ClassName { \
- static GC::Ref<JS::Error> create(JS::Realm&); \
- static GC::Ref<JS::Error> create(JS::Realm&, Utf16String message); \
- static GC::Ref<JS::Error> create(JS::Realm&, StringView message); \
- };
-WASM_ENUMERATE_NATIVE_ERRORS
-#undef __WASM_ENUMERATE
+// https://webassembly.github.io/esm-integration/js-api/index.html#parse-a-webassembly-module
+// The result is a WebAssembly Module Record: a host module whose abstract methods are those of WebAssembly modules.
+JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ReadonlyBytes, JS::Realm&, StringView filename, GC::Ptr<GC::Cell> host_defined);
}
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.idl b/Libraries/LibWeb/WebAssembly/WebAssembly.idl
index 01bba00de8c..bdbb7b3cabb 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.idl
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.idl
@@ -11,7 +11,7 @@ dictionary WebAssemblyCompileOptions {
// https://webassembly.github.io/spec/js-api/#webassembly-namespace
// https://webassembly.github.io/spec/web-api/index.html#streaming-modules
-[Exposed=*, WithInitializer]
+[Exposed=*, WithInitializer, ImplementedIn=Rust]
namespace WebAssembly {
// FIXME: Streaming APIs are supposed to be only exposed to Window, Worker
@@ -22,9 +22,11 @@ namespace WebAssembly {
[NeedsCallerRealm] Promise<Module> compileStreaming(Promise<Response> source, optional WebAssemblyCompileOptions options = {});
// FIXME: Bytes should be an AllowSharedBufferSource;
- [NeedsCallerRealm] Promise<WebAssemblyInstantiatedSource> instantiate(BufferSource bytes, optional object importObject, optional WebAssemblyCompileOptions options = {});
+ [NeedsCallerRealm, ImplementedAs=instantiate_bytes] Promise<WebAssemblyInstantiatedSource> instantiate(BufferSource bytes, optional object importObject, optional WebAssemblyCompileOptions options = {});
[NeedsCallerRealm] Promise<WebAssemblyInstantiatedSource> instantiateStreaming(Promise<Response> source, optional object importObject, optional WebAssemblyCompileOptions options = {});
// INTEROP: A Module is instantiated even with a third argument, which other implementations ignore. Overload
// resolution would pick the BufferSource overload for three arguments, and throw a TypeError.
- [NeedsCallerRealm] Promise<Instance> instantiate(Module moduleObject, optional object importObject, optional any ignored);
+ [NeedsCallerRealm, ImplementedAs=instantiate_module] Promise<Instance> instantiate(Module moduleObject, optional object importObject, optional any ignored);
+
+ readonly attribute Tag JSTag;
};
diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
deleted file mode 100644
index 43d672aefd1..00000000000
--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (c) 2025, Glenn Skrzypczak <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/ConservativeVector.h>
-#include <LibGC/Heap.h>
-#include <LibJS/HostClassBuilder.h>
-#include <LibJS/Runtime/ModuleEnvironment.h>
-#include <LibJS/Runtime/ModuleRequest.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Global.h>
-#include <LibWeb/WebAssembly/Instance.h>
-#include <LibWeb/WebAssembly/Memory.h>
-#include <LibWeb/WebAssembly/Module.h>
-#include <LibWeb/WebAssembly/Table.h>
-#include <LibWeb/WebAssembly/Tag.h>
-#include <LibWeb/WebAssembly/WebAssembly.h>
-#include <LibWeb/WebAssembly/WebAssemblyModule.h>
-
-namespace Web::WebAssembly {
-
-namespace {
-
-// The fields that a WebAssembly Module Record has besides those of a Cyclic Module Record.
-class WebAssemblyModuleHostData final : public GC::Cell {
- GC_CELL(WebAssemblyModuleHostData, GC::Cell);
- GC_DECLARE_ALLOCATOR(WebAssemblyModuleHostData);
-
-public:
- using JSValueConversionIsForbidden = void;
-
- GC::Ptr<Instance> instance() const { return m_instance; }
- void set_instance(GC::Ref<Instance> instance) { m_instance = instance; }
-
- GC::Ref<WebAssembly::Module> module_source() const { return m_module_source; }
-
- void set_module_record(GC::Ref<JS::HostModule> module_record) { m_module_record = module_record; }
-
- Vector<Utf16FlyString> export_name_list();
-
-private:
- explicit WebAssemblyModuleHostData(WebAssembly::Module& module_source)
- : m_module_source(module_source)
- {
- }
-
- virtual void visit_edges(Visitor& visitor) override
- {
- Base::visit_edges(visitor);
- visitor.visit(m_instance);
- visitor.visit(m_module_source);
- visitor.visit(m_module_record);
- }
-
- GC::Ptr<Instance> m_instance; // [[Instance]]
- GC::Ref<WebAssembly::Module> m_module_source; // [[ModuleSource]]
- GC::Ptr<JS::HostModule> m_module_record; // [[ModuleRecord]]
-
- Optional<Vector<Utf16FlyString>> m_cached_export_name_list;
-};
-
-GC_DEFINE_ALLOCATOR(WebAssemblyModuleHostData);
-
-struct WebAssemblyModuleTraits {
- static Vector<Utf16FlyString> get_exported_names(JS::HostModule&);
- static JS::ResolvedBinding resolve_export(JS::HostModule&, Utf16FlyString const& export_name);
- static JS::ThrowCompletionOr<void> initialize_environment(JS::HostModule&);
- static JS::ThrowCompletionOr<void> execute_module(JS::HostModule&, GC::Ptr<JS::PromiseCapability>);
-};
-
-constexpr JSHostModuleHooks webassembly_module_hooks = JS::make_host_module_hooks<WebAssemblyModuleTraits>();
-constexpr JSHostClass webassembly_module_host_class = JS::make_host_class(JS_HOST_CLASS_MODULE, "WebAssemblyModule"sv, nullptr, &webassembly_module_hooks, nullptr, 0);
-
-bool is_webassembly_module_record(JS::Module const& module)
-{
- return JS::is_host_instance_of(module, webassembly_module_host_class);
-}
-
-WebAssemblyModuleHostData& host_data_of_webassembly_module_record(JS::Module const& module)
-{
- auto* host_data = JS::host_data_if<WebAssemblyModuleHostData>(module);
- VERIFY(host_data);
- return *host_data;
-}
-
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#parse-a-webassembly-module
-JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ByteBuffer bytes, JS::Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined)
-{
- auto& vm = realm.vm();
-
- // 1. Let stableBytes be a copy of the bytes held by the buffer bytes.
- auto stable_bytes = MUST(ByteBuffer::copy(bytes));
-
- // 2. Compile the WebAssembly module stableBytes and store the result as module.
- // 3. If module is error, throw a CompileError exception.
- // NOTE: When integrating with the JS String Builtins proposal, builtinSetNames should be passed in the following
- // step as « "js-string" » and importedStringModule as null.
- auto module = TRY(Detail::compile_a_webassembly_module(realm, stable_bytes));
-
- // 4. Construct a WebAssembly module object from module and bytes, and let module be the result.
- auto module_object = GC::Heap::the().allocate<WebAssembly::Module>(module, move(bytes), Vector<Utf16String> {}, OptionalNone {});
-
- // 5. Let requestedModules be a set.
- HashTable<ByteString> requested_modules;
-
- // 6. For each (moduleName, name, type) in module_imports(module.[[Module]]),
- auto& compiled_module = *module_object->compiled_module()->module;
- for (size_t index = 0; index < compiled_module.import_count(); ++index) {
- auto entry = compiled_module.import(index);
-
- // 1. If moduleName starts with the prefix "wasm-js:",
- if (entry.module.starts_with("wasm-js:"sv)) {
- // 1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import with invalid module name"sv);
- }
-
- // 2. If name starts with the prefix "wasm:" or "wasm-js:",
- if (entry.name.starts_with("wasm:"sv) || entry.name.starts_with("wasm-js:"sv)) {
- // 1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import with invalid name"sv);
- }
-
- // NOTE: The following step only applies when integrating with the JS String Builtins proposal.
- // FIXME: 3. If Find a builtin with (moduleName, name, type) and builtins module.[[BuiltinSets]] is not null,
- // then continue.
-
- // 4. Append moduleName to requestedModules.
- requested_modules.set(entry.module);
- }
-
- // 7. For each (name, type) in module_exports(module.[[Module]])
- for (size_t index = 0; index < compiled_module.export_count(); ++index) {
- auto entry = compiled_module.module_export(index);
-
- // 1. If name starts with the prefix "wasm:" or "wasm-js:",
- if (entry.name.starts_with("wasm:"sv) || entry.name.starts_with("wasm-js:"sv)) {
- // 1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Export with invalid name"sv);
- }
- }
-
- // 8. Let moduleRecord be { [[Instance]]: ~empty~, [[Realm]]: realm, [[Environment]]: ~empty~,
- // [[Namespace]]: ~empty~, [[ModuleSource]]: module, [[HostDefined]]: hostDefined,
- // [[Status]]: "new", [[EvaluationError]]: undefined, [[DFSIndex]]: undefined,
- // [[DFSAncestorIndex]]: undefined, [[RequestedModules]]: requestedModules,
- // [[LoadedModules]]: « », [[CycleRoot]]: ~empty~, [[HasTLA]]: false,
- // [[AsyncEvaluation]]: false, [[TopLevelCapability]]: ~empty~ [[AsyncParentModules]]: « »,
- // [[PendingAsyncDependencies]]: ~empty~, }.
- AK::Vector<JS::ModuleRequest> module_requests;
- for (auto const& module_name : requested_modules) {
- module_requests.append(JS::ModuleRequest { Utf16FlyString::from_utf8(module_name), {} });
- }
- auto host_data = realm.heap().allocate<WebAssemblyModuleHostData>(module_object);
- auto module_record = JS::HostModule::create(realm, webassembly_module_host_class, filename, move(module_requests), host_defined, host_data);
-
- // 9. Set module.[[ModuleRecord]] to moduleRecord.
- host_data->set_module_record(module_record);
-
- // 10. Return moduleRecord.
- return module_record;
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#export-name-list
-Vector<Utf16FlyString> WebAssemblyModuleHostData::export_name_list()
-{
- // AD-HOC: Return cached export name list if available
- if (m_cached_export_name_list.has_value())
- return m_cached_export_name_list.value();
-
- // 1. Let module be record’s [[ModuleSource]] internal slot.
- auto module = m_module_source;
-
- // 2. Let exports be an empty list.
- Vector<Utf16FlyString> exports;
-
- // 3. For each(name, type) in module_exports(module.[[Module]])
- auto& compiled_module = *module->compiled_module()->module;
- for (size_t index = 0; index < compiled_module.export_count(); ++index) {
- // 1. Append name to the end of exports.
- exports.append(Utf16FlyString::from_utf8(compiled_module.module_export(index).name));
- }
-
- // AD-HOC: Cache exports
- m_cached_export_name_list = exports;
-
- // 4. Return exports.
- return exports;
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#get-exported-names
-Vector<Utf16FlyString> WebAssemblyModuleTraits::get_exported_names(JS::HostModule& record)
-{
- // 1. Let record be this WebAssembly Module Record.
- // 2. Return the export name list of record.
- return host_data_of_webassembly_module_record(record).export_name_list();
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#resolve-export
-JS::ResolvedBinding WebAssemblyModuleTraits::resolve_export(JS::HostModule& record, Utf16FlyString const& export_name)
-{
- // 1. Let record be this WebAssembly Module Record.
- // 2. If the export name list of record contains exportName, return { [[Module]]: record, [[BindingName]]: exportName }.
- if (host_data_of_webassembly_module_record(record).export_name_list().contains_slow(export_name)) {
- return JS::ResolvedBinding { JS::ResolvedBinding::Type::BindingName, &record, export_name };
- }
-
- // 3. Otherwise, return null.
- return JS::ResolvedBinding::null();
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#module-declaration-environment-setup
-JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::initialize_environment(JS::HostModule& record)
-{
- auto& vm = record.vm();
-
- // 1. Let record be this WebAssembly Module Record.
- // 2. Let env be NewModuleEnvironment(null).
- auto env = JS::new_module_environment(nullptr);
-
- // 3. Set record.[[Environment]] to env.
- record.set_environment(env);
-
- // 4. For each name in the export name list of record,
- for (auto const& name : host_data_of_webassembly_module_record(record).export_name_list()) {
- // 1. Perform !env.CreateImmutableBinding(name, true).
- MUST(env->create_immutable_binding(vm, name, true));
- }
-
- return {};
-}
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#module-execution
-JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModule& record, GC::Ptr<JS::PromiseCapability> capability)
-{
- auto& vm = record.vm();
-
- // 1. Assert: promiseCapability was not provided.
- VERIFY(!capability);
-
- // 2. Let record be this WebAssembly Module Record.
- auto& record_host_data = host_data_of_webassembly_module_record(record);
- auto& realm = record.realm();
-
- // 3. Let module be record.[[ModuleSource]].[[Module]].
- auto& module = *record_host_data.module_source()->compiled_module()->module;
- auto& store = Detail::WebAssemblyCache::the().store();
-
- // 4. Let imports be « ».
- // NB: The host functions and globals made for the imports are referenced from here only until the instance
- // holds them, and converting values runs user code (valueOf) that may collect garbage.
- GC::ConservativeVector<Wasm::Runtime::Extern> imports;
- size_t imported_function_count = 0;
-
- // 5. For each (importedModuleName, name, importtype) in module_imports(module),
- for (size_t import_index = 0; import_index < module.import_count(); ++import_index) {
- auto entry = module.import(import_index);
-
- // NOTE: The following step only applies when integrating with the JS String Builtins proposal.
- // FIXME: 1. If Find a builtin with (importedModuleName, name) and builtins module.[[BuiltinSets]] is not null, then continue.
-
- // 2. Let importedModule be GetImportedModule(record, importedModuleName).
- auto imported_module = record.get_imported_module(JS::ModuleRequest { Utf16FlyString::from_utf8(entry.module) });
-
- // 3. Let resolution be importedModule.ResolveExport(name).
- auto resolution = imported_module->resolve_export(vm, Utf16FlyString::from_utf8(entry.name));
-
- // 4. Assert: resolution is a ResolvedBinding Record, as validated during environment initialization.
- VERIFY(resolution.is_valid());
-
- // 5. Let resolvedModule be resolution.\[[Module]].
- auto resolved_module = resolution.module;
-
- // 6. Let resolvedName be resolution.[[BindingName]].
- auto resolved_name = resolution.export_name;
-
- // 7. If resolvedModule is a WebAssembly Module Record,
- if (is_webassembly_module_record(*resolved_module)) {
- auto& resolved_module_host_data = host_data_of_webassembly_module_record(*resolved_module);
-
- // 1. If resolvedModule.[[Instance]] is ~empty~, throw a {LinkError} exception.
- if (!resolved_module_host_data.instance()) {
- return vm.throw_completion<LinkError>("Module has not been instantiated"sv);
- }
-
- // 2. Assert: resolvedModule.[[Instance]] is a WebAssembly Instance object.
- // 3. Assert: resolvedModule.[[ModuleSource]] is a WebAssembly Module object.
- // 4. Let module be resolvedModule.[[ModuleSource]].[[Module]].
- auto& resolved_instance = *resolved_module_host_data.instance();
-
- // 5. Let externval be instance_export(resolvedModule.[[Instance]], resolvedName).
- // https://webassembly.github.io/spec/core/appendix/embedding.html#embed-instance-export
- auto resolved_name_utf8 = resolved_name.view().to_utf8_but_should_be_ported_to_utf16();
- auto externval = store.find_export(resolved_instance.instance_address(), resolved_name_utf8.bytes_as_string_view());
-
- // 6. Assert: externval is not error.
- VERIFY(externval.has_value());
-
- // 7. Assert: module_exports(module) contains an element (resolvedName, type).
- // 8. Let externtype be the value of type for the element (resolvedName, type) in module_exports(module).
- // 9. If importtype is not an extern subtype of externtype, throw a LinkError exception.
- // NB: Instantiation checks the type of every import, and throws that LinkError.
-
- // 10. Append externval to imports.
- imports.append(*externval);
- }
-
- // 8. Otherwise,
- else {
- // 1. Let env be resolvedModule.[[Environment]].
- auto env = resolved_module->environment();
-
- // 2. Let v be ?env.GetBindingValue(resolvedName, true).
- auto v = TRY(env->get_binding_value(vm, resolved_name, true));
-
- switch (entry.type.kind) {
- // 3. If importtype is of the form func functype,
- case Wasm::Runtime::ExternKind::Function: {
- // 1. If IsCallable(v) is false, throw a LinkError exception.
- if (!v.is_function())
- return vm.throw_completion<LinkError>(JS::ErrorType::NotAFunction, v);
- auto& function = v.as_function();
-
- Wasm::Runtime::Entity funcaddr = nullptr;
- // 2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
- if (auto exported_address = Detail::exported_function_address(function); exported_address.has_value()) {
- // 1. Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.
- funcaddr = *exported_address;
- }
- // 3. Otherwise,
- else {
- // 1. Create a host function from v and functype, and let funcaddr be the result.
- // 2. Let index be the number of external functions in imports, defining the index of the host function funcaddr.
- funcaddr = Detail::create_host_function(vm, function, Detail::function_type_in_store(module, entry.type.type_index), imported_function_count);
- }
-
- // 4. Let externfunc be the external value func funcaddr.
- // 5. Append externfunc to imports.
- imports.append({ Wasm::Runtime::ExternKind::Function, funcaddr });
- break;
- }
-
- // 4. If importtype is of the form global mut valtype,
- case Wasm::Runtime::ExternKind::Global: {
- auto valtype = store.canonical_value_type(module, entry.type.value_type);
- auto is_mutable = entry.type.is_mutable;
-
- // 1. Let store be the surrounding agent’s associated store.
- // 2. If v implements Global,
- Wasm::Runtime::Entity globaladdr = nullptr;
- if (auto* global = Bindings::global_from_value(v)) {
- // 1. Let globaladdr be v.[[Global]].
- globaladdr = global->address();
-
- // 2. Let targetmut valuetype be global_type(store, globaladdr).
- bool target_is_mutable = false;
- (void)store.global_type(globaladdr, target_is_mutable);
-
- // 3. If mut is const and targetmut is var, throw a LinkError exception.
- if (!is_mutable && target_is_mutable) {
- return vm.throw_completion<LinkError>("Mutable globals are not supported for immutable imports"sv);
- }
- }
-
- // 3. Otherwise,
- else {
- // AD-HOC: If valtype is i64 and v is a Number, throw a LinkError exception.
- if (valtype.kind == Wasm::Runtime::ValueKind::I64 && v.is_number()) {
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number to a BigInteger"sv);
- }
-
- // AD-HOC: If valtype is not i64 and v is a BigInt, throw a LinkError exception.
- if (valtype.kind != Wasm::Runtime::ValueKind::I64 && v.is_bigint()) {
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a BigInteger to a Number"sv);
- }
-
- // 1. If valtype is v128, throw a LinkError exception.
- if (valtype.kind == Wasm::Runtime::ValueKind::V128) {
- return vm.throw_completion<LinkError>("V128 is not supported as a global value type"sv);
- }
-
- // 2. If mut is var, throw a LinkError exception.
- if (is_mutable) {
- return vm.throw_completion<LinkError>("Variable global value types are not supported"sv);
- }
-
- // 3. Let value be ?ToWebAssemblyValue(v, valtype).
- auto value = TRY(Detail::to_webassembly_value(vm, v, valtype));
-
- // 4. Let(store, globaladdr) be global_alloc(store, mut valtype, value).
- // 5. Set the surrounding agent’s associated store to store.
- globaladdr = store.allocate_global(valtype, is_mutable, value);
- }
-
- // 4. Let externglobal be global globaladdr.
- // 5. Append externglobal to imports.
- imports.append({ Wasm::Runtime::ExternKind::Global, globaladdr });
- break;
- }
-
- // 5. If importtype is of the form mem memtype,
- case Wasm::Runtime::ExternKind::Memory: {
- // 1. If v does not implement Memory, throw a LinkError exception.
- auto* memory = Bindings::memory_from_value(v);
- if (!memory) {
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Memory for a memory import"sv);
- }
-
- // 2. Let externmem be the external value mem v.[[Memory]].
- // 3. Append externmem to imports.
- imports.append({ Wasm::Runtime::ExternKind::Memory, memory->address() });
- break;
- }
-
- // 6. If importtype is of the form table tabletype,
- case Wasm::Runtime::ExternKind::Table: {
- // 1. If v does not implement Table, throw a LinkError exception.
- auto* table = Bindings::table_from_value(v);
- if (!table) {
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Table for a table import"sv);
- }
-
- // 2. Let tableaddr be v.[[Table]].
- // 3. Let externtable be the external value table tableaddr.
- // 4. Append externtable to imports.
- imports.append({ Wasm::Runtime::ExternKind::Table, table->address() });
- break;
- }
-
- // 7. If importtype is of the form tag attribute functype,
- case Wasm::Runtime::ExternKind::Tag: {
- // 1. Assert: attribute is exception.
- // 2. If v does not implement Tag, throw a LinkError exception.
- auto* tag = Bindings::tag_from_value(v);
- if (!tag)
- return vm.throw_completion<LinkError>("Expected an instance of WebAssembly.Tag for a tag import"sv);
-
- // 3. Let tagaddr be v.[[Address]].
- // 4. Let externtag be the external value tag tagaddr.
- // 5. Append externtag to imports.
- imports.append({ Wasm::Runtime::ExternKind::Tag, tag->address() });
- break;
- }
- }
- }
-
- if (entry.type.kind == Wasm::Runtime::ExternKind::Function)
- ++imported_function_count;
- }
-
- // 6. Instantiate the core of a WebAssembly module module with imports, and let instance be the result.
- auto instance_address = TRY(Detail::instantiate_core_module(vm, module, imports));
-
- // 7. Set record.[[Instance]] to instance.
- auto instance = Instance::create(realm, instance_address);
- record_host_data.set_instance(instance);
-
- // 8. For each (name, externtype) of module_exports(module),
- for (auto const& entry : store.instance_exports(instance_address)) {
- // 1. If externtype is of the form global mut globaltype,
- if (entry.value.kind == Wasm::Runtime::ExternKind::Global) {
- // 1. Assert: externval is of the form global globaladdr.
- // 2. Let global globaladdr be externval.
- // 3. Let global_value be global_read(store, globaladdr).
- auto globaladdr = entry.value.entity.ptr();
- bool is_mutable = false;
- auto type = store.global_type(globaladdr, is_mutable);
-
- // 4. If globaltype is not v128,
- if (type.kind != Wasm::Runtime::ValueKind::V128) {
- // NOTE: The condition above leaves unsupported JS values as uninitialized in TDZ and therefore as a
- // reference error on access. When integrating with shared globals, they may be excluded here
- // similarly to v128 above.
-
- // 1. Perform !record.[[Environment]].InitializeBinding(name, ToJSValue(global_value)).
- auto value = TRY(Detail::to_js_value(vm, store.global_get(globaladdr), type));
- MUST(record.environment()->initialize_binding(vm, Utf16FlyString::from_utf8(entry.name), value, JS::Environment::InitializeBindingHint::Normal));
-
- // FIXME: 2. If mut is var, then associate all future mutations of globaladdr with the ECMA-262 binding record
- // for name in record.[[Environment]], such that record.[[Environment]].GetBindingValue(resolution.[[BindingName]], true)
- // always returns ToJSValue(global_read(store, globaladdr)) for the current surrounding agent’s associated store store.
- }
- }
-
- // 2. Otherwise,
- else {
- // 1. Perform !record.[[Environment]].InitializeBinding(name, !Get(instance.[[Exports]], name)).
- auto name = Utf16FlyString::from_utf8(entry.name);
- MUST(Bindings::initialize_webassembly_export_binding(realm, *record.environment(), name, instance));
- }
- }
-
- // NOTE: The linking semantics here for Wasm to Wasm modules are identical to the WebAssembly JS API semantics as if
- // passing the the exports object as the imports object in instantiation. When linking Wasm module imports to
- // JS module exports, the JS API semantics are exactly followed as well. It is only in the case of importing
- // Wasm from JS that WebAssembly.Global unwrapping is observable on the WebAssembly Module Record Environment
- // Record.
-
- return {};
-}
-
-}
diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.h b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.h
deleted file mode 100644
index 7f1d65d1a70..00000000000
--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (c) 2025, Glenn Skrzypczak <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/ByteBuffer.h>
-#include <LibJS/Runtime/Completion.h>
-#include <LibJS/Runtime/HostModule.h>
-
-namespace Web::WebAssembly {
-
-// https://webassembly.github.io/esm-integration/js-api/index.html#parse-a-webassembly-module
-// The result is a WebAssembly Module Record: a host module whose abstract methods are those of WebAssembly modules.
-JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ByteBuffer bytes, JS::Realm&, StringView filename = {}, GC::Ptr<GC::Cell> host_defined = nullptr);
-
-}
diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.py
index 8f12b295503..ffa1411227d 100644
--- a/Meta/Generators/libweb_bindings/glue_headers.py
+++ b/Meta/Generators/libweb_bindings/glue_headers.py
@@ -18,7 +18,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_n
"EventTiming": "LibWeb/EventTiming/BindingsGlue.h",
"IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h",
"TrustedTypes": "LibWeb/TrustedTypes/BindingsGlue.h",
- "WebAssembly": "LibWeb/WebAssembly/BindingsGlue.h",
"WebAudio": "LibWeb/WebAudio/BindingsGlue.h",
}
if module in module_headers:
diff --git a/Meta/Generators/libweb_bindings/intrinsics.py b/Meta/Generators/libweb_bindings/intrinsics.py
index 73f3478b644..af870cf3e69 100644
--- a/Meta/Generators/libweb_bindings/intrinsics.py
+++ b/Meta/Generators/libweb_bindings/intrinsics.py
@@ -752,7 +752,6 @@ def write_wrapper_factory_implementation(out: TextIO, interface_sets: InterfaceS
#include <LibWeb/DOM/BindingsGlue.h>
#include <LibWeb/Fetch/BindingsGlue.h>
#include <LibWeb/HTML/BindingsGlue.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/Wrappable.h>
"""
diff --git a/Meta/Linters/check_libjs_includes.py b/Meta/Linters/check_libjs_includes.py
index d75758be619..6db6b409140 100755
--- a/Meta/Linters/check_libjs_includes.py
+++ b/Meta/Linters/check_libjs_includes.py
@@ -42,7 +42,6 @@ ALLOWED_HEADERS = {
"LibJS/Runtime/DeclarativeEnvironment.h",
"LibJS/Runtime/Environment.h",
"LibJS/Runtime/Error.h",
- "LibJS/Runtime/ErrorConstructor.h",
"LibJS/Runtime/ErrorData.h",
"LibJS/Runtime/ErrorTypes.h",
"LibJS/Runtime/ExternalMemory.h",
@@ -61,7 +60,6 @@ ALLOWED_HEADERS = {
"LibJS/Runtime/JSONObject.h",
"LibJS/Runtime/Map.h",
"LibJS/Runtime/MapIterator.h",
- "LibJS/Runtime/ModuleEnvironment.h",
"LibJS/Runtime/ModuleRequest.h",
"LibJS/Runtime/NativeFunction.h",
"LibJS/Runtime/NumberObject.h",
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index f2bb1afb450..7b0bc527dbc 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -72,9 +72,10 @@ ALLOWED_REALM_MENTIONS = {
"Streams": (5, 14, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),
"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),
"WebAssembly": (
- 15,
- 89,
- "WebAssembly constructors/exports instantiate JS objects/functions in spec-selected realms",
+ 2,
+ 8,
+ "the C++ glue of the Rust WebAssembly JS API creates errors and module records in a given realm, and reads "
+ "the agent cluster of one",
),
"WebAudio": (
8,
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 3d22f9f973e..98e9da85b77 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -53,9 +53,10 @@ IN_ONE_LIBRARY = {
"a dependency of libweb_bindings_rust alone, whose archive LibWeb's library links",
),
"libwasm_engine": (
- {"libwasm_jit"},
- "a dev-dependency of libwasm_jit alone, whose tests run compiled code against it; the engine is the one Rust "
- "archive of LibWasm's library (Libraries/LibWasm/CMakeLists.txt)",
+ {"libwasm_jit", "libweb_bindings_rust"},
+ "a dev-dependency of libwasm_jit, whose tests run compiled code against it, and a dependency of "
+ "libweb_bindings_rust, whose archive LibWeb's library links; LibWasm's library builds the other copy, with the "
+ "C ABI, for the tools, and no process uses both (Libraries/LibWasm/CMakeLists.txt)",
),
}
diff --git a/Services/WebContent/CMakeLists.txt b/Services/WebContent/CMakeLists.txt
index d8980a57962..f3b98190f61 100644
--- a/Services/WebContent/CMakeLists.txt
+++ b/Services/WebContent/CMakeLists.txt
@@ -32,7 +32,7 @@ target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${CMAKE_CU
target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD_SOURCE_DIR}>)
target_include_directories(webcontentservice PUBLIC $<BUILD_INTERFACE:${LADYBIRD_SOURCE_DIR}/Services/>)
-target_link_libraries(webcontentservice PUBLIC LibCompositing LibCore LibCrypto LibDevTools LibFileSystem LibGfx LibHTTP LibIPC LibJS LibMain LibAudio LibMedia LibWasm LibWeb LibRequests LibImageDecoderClient LibMediaClient LibGC)
+target_link_libraries(webcontentservice PUBLIC LibCompositing LibCore LibCrypto LibDevTools LibFileSystem LibGfx LibHTTP LibIPC LibJS LibMain LibAudio LibMedia LibWeb LibRequests LibImageDecoderClient LibMediaClient LibGC)
target_link_libraries(webcontentservice PRIVATE OpenSSL::Crypto OpenSSL::SSL)
target_compile_options(webcontentservice PRIVATE $<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:-Wexit-time-destructors>)
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index bf6659dc922..cf68573bd85 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -83,7 +83,7 @@ target_link_libraries(TestFetchURL PRIVATE LibURL)
target_link_libraries(TestImageData PRIVATE LibGC LibJS)
target_link_libraries(TestWebIDLBuffers PRIVATE LibGC LibJS)
target_link_libraries(TestStructuredSerializeCorpus PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
-target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC LibWasm)
+target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeFormat PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeHardening PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC)
target_link_libraries(TestStructuredSerializeSharedArrayBuffer PRIVATE LibGC LibJS LibIPC)
diff --git a/Tests/LibWeb/TestWrapperWorld.cpp b/Tests/LibWeb/TestWrapperWorld.cpp
index 05293bef74c..8f5eb982671 100644
--- a/Tests/LibWeb/TestWrapperWorld.cpp
+++ b/Tests/LibWeb/TestWrapperWorld.cpp
@@ -30,14 +30,13 @@
#include <LibWeb/HTML/HTMLDocument.h>
#include <LibWeb/HTML/LocalTraversableNavigable.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/Page/Page.h>
#include <LibWeb/Platform/FontPlugin.h>
#include <LibWeb/Platform/Timer.h>
#include <LibWeb/ResizeObserver/ResizeObserver.h>
-#include <LibWeb/WebAssembly/BindingsGlue.h>
-#include <LibWeb/WebAssembly/Instance.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
namespace {
@@ -1048,7 +1047,7 @@ TEST_CASE(relevant_global_main_world_wrapper_ignores_preferred_realm)
s_main_thread_vm_was_initialized_by_an_earlier_wrapper_test = true;
}
-TEST_CASE(wasm_instance_exports_are_not_shared_with_another_world)
+TEST_CASE(wasm_instance_exports_belong_to_the_realm_of_the_instance)
{
ensure_font_plugin_installed();
@@ -1068,15 +1067,21 @@ TEST_CASE(wasm_instance_exports_are_not_shared_with_another_world)
auto& extension_realm = *extension_execution_context->realm;
install_test_host_defined(extension_realm, Web::Bindings::WrapperWorld::Type::Extension, window_realm);
- static constexpr u8 empty_module_bytes[] = { 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00 };
- auto bytes = JS::ArrayBuffer::create(window_realm, MUST(ByteBuffer::copy(empty_module_bytes, sizeof(empty_module_bytes))));
- auto& module_constructor = Web::Bindings::ensure_web_constructor<Web::Bindings::ModulePrototype>(window_realm, "WebAssembly.Module"_utf16_fly_string);
- auto module_wrapper = MUST(JS::construct(vm, module_constructor, bytes.ptr()));
- auto instance = MUST(Web::Bindings::construct_instance(window_realm, *Web::Bindings::module_from_value(module_wrapper.ptr()), nullptr));
+ // An Instance made in the window realm, whose exports object belongs to that realm.
+ GC::Ptr<JS::Object> instance_wrapper;
+ {
+ Web::HTML::TemporaryExecutionContext execution_context { window_realm };
+ static constexpr u8 empty_module_bytes[] = { 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00 };
+ auto bytes = JS::ArrayBuffer::create(window_realm, MUST(ByteBuffer::copy(empty_module_bytes, sizeof(empty_module_bytes))));
+ auto& web_assembly = MUST(window_realm.global_object().get("WebAssembly"_utf16_fly_string)).as_object();
+ auto module = MUST(JS::construct(vm, MUST(web_assembly.get("Module"_utf16_fly_string)).as_function(), bytes.ptr()));
+ instance_wrapper = MUST(JS::construct(vm, MUST(web_assembly.get("Instance"_utf16_fly_string)).as_function(), module.ptr()));
+ }
- auto exports = Web::Bindings::exports(window_realm, instance);
- EXPECT(&exports->shape().realm() == &window_realm);
- EXPECT_DEATH("Reading a WebAssembly instance's exports from another world", Web::Bindings::exports(extension_realm, instance));
+ // Read through the window realm's wrapper while the extension realm is the current realm.
+ EXPECT(vm.current_realm() == &extension_realm);
+ auto exports = MUST(instance_wrapper->get("exports"_utf16_fly_string));
+ EXPECT(&exports.as_object().shape().realm() == &window_realm);
vm.pop_execution_context();
vm.pop_execution_context();
diff --git a/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt b/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt
index 6249bbe2b63..b144e766663 100644
--- a/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt
+++ b/Tests/LibWeb/Text/expected/namespace-objects-default-property-attributes.txt
@@ -338,6 +338,9 @@ s enumerable: true
s value before: function s() { [native code] }
s value after: replaced
== WebAssembly property descriptors
+JSTag writable: undefined
+JSTag configurable: true
+JSTag enumerable: true
validate writable: true
validate configurable: true
validate enumerable: true
@@ -378,9 +381,6 @@ RuntimeError configurable: true
RuntimeError enumerable: false
RuntimeError value before: function RuntimeError() { [native code] }
RuntimeError value after: replaced
-JSTag writable: undefined
-JSTag configurable: true
-JSTag enumerable: true
Exception writable: true
Exception configurable: true
Exception enumerable: false
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/constructor/multi-value.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/constructor/multi-value.any.txt
index 9c644e90f83..9b5f63ee45f 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/constructor/multi-value.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/constructor/multi-value.any.txt
@@ -2,8 +2,7 @@ Harness status: OK
Found 3 tests
-2 Pass
-1 Fail
+3 Pass
Pass multiple return values from wasm to js
Pass multiple return values inside wasm
-Fail multiple return values from js to wasm
\ No newline at end of file
+Pass multiple return values from js to wasm
\ No newline at end of file