Skip to content

Truly independent web browser

LibWeb: Implement the WebAssembly JS string builtins

Andreas Kling7337339fa998
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index bfb0d4e363a..dbb40f80c5c 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -984,6 +984,7 @@ set(SOURCES
WebLocks/LockManager.cpp
WebLocks/LockRequest.cpp
WebLocks/NavigatorLocks.cpp
+ WebAssembly/Builtins.cpp
WebAssembly/Exception.cpp
WebAssembly/Global.cpp
WebAssembly/Instance.cpp
diff --git a/Libraries/LibWeb/WebAssembly/Builtins.cpp b/Libraries/LibWeb/WebAssembly/Builtins.cpp
new file mode 100644
index 00000000000..f35efea1378
--- /dev/null
+++ b/Libraries/LibWeb/WebAssembly/Builtins.cpp
@@ -0,0 +1,725 @@
+/*
+ * 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
new file mode 100644
index 00000000000..3697785142f
--- /dev/null
+++ b/Libraries/LibWeb/WebAssembly/Builtins.h
@@ -0,0 +1,28 @@
+/*
+ * 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/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cpp
index 17bd032d449..45cfc3dbe5b 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.cpp
+++ b/Libraries/LibWeb/WebAssembly/Instance.cpp
@@ -30,9 +30,24 @@ namespace Web::WebAssembly {
GC_DEFINE_ALLOCATOR(Instance);
-WebIDL::ExceptionOr<GC::Ref<Instance>> Instance::create(JS::Realm& realm, Module& module, GC::Ptr<JS::Object> import_object)
+// 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)
{
- auto instance = TRY(Detail::instantiate_module(realm.vm(), *module.compiled_module()->module, 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);
}
diff --git a/Libraries/LibWeb/WebAssembly/Module.cpp b/Libraries/LibWeb/WebAssembly/Module.cpp
index 240ae1468e7..86efed8bba6 100644
--- a/Libraries/LibWeb/WebAssembly/Module.cpp
+++ b/Libraries/LibWeb/WebAssembly/Module.cpp
@@ -11,8 +11,10 @@
#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>
@@ -44,10 +46,12 @@ GC::Ref<Module> Module::create()
return GC::Heap::the().allocate<Module>();
}
-WebIDL::ExceptionOr<GC::Ref<Module>> Module::create(JS::Realm& realm, WebIDL::BufferSource bytes)
+// 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);
@@ -55,48 +59,86 @@ WebIDL::ExceptionOr<GC::Ref<Module>> Module::create(JS::Realm& realm, WebIDL::Bu
}
auto stable_bytes = stable_bytes_or_error.release_value();
- auto compiled_module = TRY(Detail::compile_a_webassembly_module(realm, stable_bytes));
- return GC::Heap::the().allocate<Module>(move(compiled_module), move(stable_bytes));
+ // 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)
+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/threads/js-api/index.html#dom-module-imports
+// 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]].
- // 2. Let imports be « ».
+ 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;
- // 3. For each (moduleName, name, type) of module_imports(module),
- auto& module = *module_object->m_compiled_module->module;
+ // 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);
- // 3.1. Let kind be the string value of the extern type type.
+
+ // 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;
}
- // 3.2. Let obj be «[ "module" → moduleName, "name" → name, "kind" → kind ]».
+ // 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),
};
- // 3.3. Append obj to imports.
+ // 5. Append obj to imports.
import_objects.append(move(descriptor));
}
- // 4. Return imports.
+ // 6. Return imports.
return import_objects;
}
diff --git a/Libraries/LibWeb/WebAssembly/Module.h b/Libraries/LibWeb/WebAssembly/Module.h
index caefd23d000..20a6d602ef4 100644
--- a/Libraries/LibWeb/WebAssembly/Module.h
+++ b/Libraries/LibWeb/WebAssembly/Module.h
@@ -27,23 +27,27 @@ class 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);
+ 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);
+ 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 a0015112e8b..b59d242b084 100644
--- a/Libraries/LibWeb/WebAssembly/Module.idl
+++ b/Libraries/LibWeb/WebAssembly/Module.idl
@@ -20,8 +20,7 @@ dictionary ModuleImportDescriptor {
[LegacyNamespace=WebAssembly, Exposed=*, Serializable]
interface Module {
// FIXME: Bytes should be an AllowSharedBufferSource;
- // FIXME: Constructor is missing the WebAssemblyCompileOptions parameter.
- constructor(BufferSource bytes);
+ constructor(BufferSource bytes, optional WebAssemblyCompileOptions options = {});
static sequence<ModuleExportDescriptor> exports(Module moduleObject);
static sequence<ModuleImportDescriptor> imports(Module moduleObject);
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
index 05e11f291a8..0c63176901e 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
@@ -31,6 +31,7 @@
#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/ContentSecurityPolicy/BlockingAlgorithms.h>
@@ -40,6 +41,7 @@
#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>
@@ -55,10 +57,10 @@
namespace Web::WebAssembly {
-static GC::Ref<WebIDL::Promise> asynchronously_compile_webassembly_module(JS::Realm&, ByteBuffer, HTML::Task::Source = HTML::Task::Source::Unspecified);
+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>);
+static GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm&, GC::Ref<WebIDL::Promise>, Bindings::WebAssemblyCompileOptions const&);
namespace Detail {
@@ -180,7 +182,7 @@ void initialize(JS::Object& self, JS::Realm& realm)
}
// https://webassembly.github.io/spec/js-api/#dom-webassembly-validate
-bool validate(JS::Realm& realm, WebIDL::BufferSource bytes)
+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);
@@ -197,12 +199,23 @@ bool validate(JS::Realm& realm, WebIDL::BufferSource bytes)
if (module.is_error())
return false;
- // 4. Return true.
+ // 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)
+WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile(JS::Realm& realm, WebIDL::BufferSource bytes, Bindings::WebAssemblyCompileOptions const& options)
{
auto& vm = realm.vm();
@@ -213,20 +226,21 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile(JS::Realm& realm, WebIDL::
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 and return the result.
- return asynchronously_compile_webassembly_module(realm, stable_bytes.release_value());
+ // 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)
+WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> compile_streaming(JS::Realm& realm, GC::Ref<WebIDL::Promise> source, Bindings::WebAssemblyCompileOptions const& options)
{
- // The compileStreaming(source) method, when invoked, returns the result of compiling a potential WebAssembly response with source.
- return compile_potential_webassembly_response(realm, source);
+ // 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)
+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();
@@ -240,27 +254,28 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate(JS::Realm& realm, WebI
// 2. Perform HostEnsureCanCompileWasmBytes()
TRY(Detail::host_ensure_can_compile_wasm_bytes(realm));
- // 3. Asynchronously compile a WebAssembly module from stableBytes and let promiseOfModule be the result.
- auto promise_of_module = asynchronously_compile_webassembly_module(realm, stable_bytes.release_value());
+ // 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)
+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)
+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) method, when invoked, performs the following steps:
+ // 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.
- auto promise_of_module = compile_potential_webassembly_response(realm, source);
+ // 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);
@@ -584,7 +599,7 @@ Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const&
}
// 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)
+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();
@@ -593,16 +608,37 @@ JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_im
if (import_count != 0 && !import_object)
return vm.throw_completion<JS::TypeError>("ImportObject must be provided when module has imports"_utf16);
- // FIXME: 2. Let builtinOrStringImports be the ordered map «[ ]».
- // FIXME: 3. For each builtinSetName of builtinSetNames,
- // 1. Let builtinSetQualifiedName be builtinSetName prefixed with "wasm:"
- // 2. Assert: builtinOrStringImports does not contain builtinSetQualifiedName
- // 3. If builtinSetName does not refer to a builtin set, then continue.
- // 4. Let exportsObject be the result of instantiate a builtin set with builtinSetName
- // 5. Set builtinOrStringImports[builtinSetQualifiedName] to exportsObject
- // FIXME: 4. If importedStringModule is not null,
- // 1. Let exportsObject be the result of instantiate imported strings with module and importedStringModule
- // 2. Set builtinOrStringImports[importedStringModule] to exportsObject
+ // 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
@@ -616,13 +652,26 @@ JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_im
auto import = module.import(import_index);
dbgln_if(LIBWEB_WASM_DEBUG, "Trying to resolve {}::{}", import.module, import.name);
- // FIXME: 6.1. If builtinOrStringImports[moduleName] exists,
- // 1. Let o be builtinOrStringImports[moduleName].
- // 2. If o is not an Object or if ? HasProperty(o, componentName) is false,
- // 1. Set o to ? Get(importObject, moduleName).
+ 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,
- // 6.2.1. Let o be ? Get(importObject, moduleName).
- auto value = TRY(import_object->get(Utf16FlyString::from_utf8(import.module)));
+ 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())
@@ -630,7 +679,7 @@ JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_im
auto const& object = value.as_object();
// 6.4. Let v be ? Get(o, componentName).
- auto import_ = TRY(object.get(Utf16FlyString::from_utf8(import.name)));
+ auto import_ = TRY(object.get(component_name));
switch (import.type.kind) {
// 6.5. If externtype is of the form func functype,
@@ -744,9 +793,9 @@ JS::ThrowCompletionOr<GC::ConservativeVector<Wasm::Runtime::Extern>> read_the_im
return imports;
}
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm::Runtime::Module const& module, GC::Ptr<JS::Object> import_object)
+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));
+ auto imports = TRY(read_the_imports(vm, module, import_object, builtin_set_names, imported_string_module));
return instantiate_core_module(vm, module, imports);
}
@@ -1228,31 +1277,46 @@ JS::ThrowCompletionOr<void> host_ensure_can_compile_wasm_bytes(JS::Realm& realm)
}
// 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, HTML::Task::Source task_source)
+GC::Ref<WebIDL::Promise> asynchronously_compile_webassembly_module(JS::Realm& realm, ByteBuffer bytes, Bindings::WebAssemblyCompileOptions const& options, HTML::Task::Source task_source)
{
// 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, task_source]() mutable {
+ 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 to perform the following steps. If taskSource was provided, queue the task on that task source.
- HTML::queue_a_task(task_source, nullptr, nullptr, GC::create_function(GC::Heap::the(), [&realm, bytes = move(bytes), promise, module_or_error = move(module_or_error)]() mutable {
+ // 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.
+ // 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. Otherwise,
+ // 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 and bytes, and let moduleObject be the result.
- auto module_object = GC::Heap::the().allocate<Module>(module_or_error.release_value(), move(bytes));
+ // 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);
@@ -1273,13 +1337,16 @@ GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm
// 2. Let module be moduleObject.[[Module]].
auto module = module_object->compiled_module();
- // FIXME: 3. Let builtinSetNames be moduleObject.[[BuiltinSets]].
- // FIXME: 4. Let importedStringModule be moduleObject.[[ImportedStringModule]].
+ // 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);
+ 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;
@@ -1374,7 +1441,7 @@ GC::Ref<WebIDL::Promise> instantiate_promise_of_module(JS::Realm& realm, GC::Ref
}
// 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)
+GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm& realm, GC::Ref<WebIDL::Promise> source, Bindings::WebAssemblyCompileOptions const& options)
{
auto& vm = realm.vm();
@@ -1388,7 +1455,7 @@ GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm& realm
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](JS::Value unwrapped_source) -> WebIDL::ExceptionOr<JS::Value> {
+ 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.
@@ -1433,7 +1500,7 @@ GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm& realm
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](JS::Value body_array_buffer) -> WebIDL::ExceptionOr<JS::Value> {
+ 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());
@@ -1443,8 +1510,9 @@ GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm& realm
return JS::js_undefined();
}
- // 2. Asynchronously compile the WebAssembly module stableBytes using the networking task source and resolve returnValue with the result.
- auto result = asynchronously_compile_webassembly_module(HTML::relevant_realm(*return_value->promise()), stable_bytes.release_value(), HTML::Task::Source::Networking);
+ // 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());
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h
index f02cacee099..9008cb06b43 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h
@@ -23,6 +23,7 @@
#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>
@@ -34,13 +35,13 @@ class Tag;
WEB_API void initialize(JS::Object&, JS::Realm&);
-WEB_API bool validate(JS::Realm&, WebIDL::BufferSource bytes);
-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 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&);
-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<Module> module_object, 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 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 {
@@ -122,8 +123,8 @@ 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);
-JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM&, Wasm::Runtime::Module const&, GC::Ptr<JS::Object> import_object);
+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);
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.idl b/Libraries/LibWeb/WebAssembly/WebAssembly.idl
index 555c4353ad2..01bba00de8c 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.idl
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.idl
@@ -3,6 +3,12 @@ dictionary WebAssemblyInstantiatedSource {
required Instance instance;
};
+// https://webassembly.github.io/spec/js-api/#dictdef-webassemblycompileoptions
+dictionary WebAssemblyCompileOptions {
+ USVString? importedStringConstants = null;
+ sequence<USVString> builtins = [];
+};
+
// https://webassembly.github.io/spec/js-api/#webassembly-namespace
// https://webassembly.github.io/spec/web-api/index.html#streaming-modules
[Exposed=*, WithInitializer]
@@ -10,13 +16,15 @@ namespace WebAssembly {
// FIXME: Streaming APIs are supposed to be only exposed to Window, Worker
// FIXME: Bytes should be an AllowSharedBufferSource;
- [NeedsCallerRealm] boolean validate(BufferSource bytes);
+ [NeedsCallerRealm] boolean validate(BufferSource bytes, optional WebAssemblyCompileOptions options = {});
// FIXME: Bytes should be an AllowSharedBufferSource;
- [NeedsCallerRealm] Promise<Module> compile(BufferSource bytes);
- [NeedsCallerRealm] Promise<Module> compileStreaming(Promise<Response> source);
+ [NeedsCallerRealm] Promise<Module> compile(BufferSource bytes, optional WebAssemblyCompileOptions options = {});
+ [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);
- [NeedsCallerRealm] Promise<WebAssemblyInstantiatedSource> instantiateStreaming(Promise<Response> source, optional object importObject);
- [NeedsCallerRealm] Promise<Instance> instantiate(Module moduleObject, optional object importObject);
+ [NeedsCallerRealm] 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);
};
diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
index 90599ce4832..43d672aefd1 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
@@ -103,7 +103,7 @@ JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ByteBu
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));
+ 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;
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.txt
index 6055c864758..f99549aad4d 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.txt
@@ -1,3 +1,10 @@
-Harness status: Error
+Harness status: OK
-Found 0 tests
+Found 5 tests
+
+5 Pass
+Pass basic
+Pass basic 1
+Pass basic 2
+Pass basic 3
+Pass basic 4
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.worker.txt
index 6055c864758..f99549aad4d 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.worker.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/basic.any.worker.txt
@@ -1,3 +1,10 @@
-Harness status: Error
+Harness status: OK
-Found 0 tests
+Found 5 tests
+
+5 Pass
+Pass basic
+Pass basic 1
+Pass basic 2
+Pass basic 3
+Pass basic 4
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.txt
index eb056b1bbb0..466e9ee2662 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.txt
@@ -2,44 +2,44 @@ Harness status: OK
Found 40 tests
-40 Fail
-Fail constants
-Fail constants 1
-Fail constants 2
-Fail constants 3
-Fail constants 4
-Fail constants 5
-Fail constants 6
-Fail constants 7
-Fail constants 8
-Fail constants 9
-Fail constants 10
-Fail constants 11
-Fail constants 12
-Fail constants 13
-Fail constants 14
-Fail constants 15
-Fail constants 16
-Fail constants 17
-Fail constants 18
-Fail constants 19
-Fail constants 20
-Fail constants 21
-Fail constants 22
-Fail constants 23
-Fail constants 24
-Fail constants 25
-Fail constants 26
-Fail constants 27
-Fail constants 28
-Fail constants 29
-Fail constants 30
-Fail constants 31
-Fail constants 32
-Fail constants 33
-Fail constants 34
-Fail constants 35
-Fail constants 36
-Fail constants 37
-Fail constants 38
-Fail constants 39
\ No newline at end of file
+40 Pass
+Pass constants
+Pass constants 1
+Pass constants 2
+Pass constants 3
+Pass constants 4
+Pass constants 5
+Pass constants 6
+Pass constants 7
+Pass constants 8
+Pass constants 9
+Pass constants 10
+Pass constants 11
+Pass constants 12
+Pass constants 13
+Pass constants 14
+Pass constants 15
+Pass constants 16
+Pass constants 17
+Pass constants 18
+Pass constants 19
+Pass constants 20
+Pass constants 21
+Pass constants 22
+Pass constants 23
+Pass constants 24
+Pass constants 25
+Pass constants 26
+Pass constants 27
+Pass constants 28
+Pass constants 29
+Pass constants 30
+Pass constants 31
+Pass constants 32
+Pass constants 33
+Pass constants 34
+Pass constants 35
+Pass constants 36
+Pass constants 37
+Pass constants 38
+Pass constants 39
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.worker.txt
index eb056b1bbb0..466e9ee2662 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.worker.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/constants.any.worker.txt
@@ -2,44 +2,44 @@ Harness status: OK
Found 40 tests
-40 Fail
-Fail constants
-Fail constants 1
-Fail constants 2
-Fail constants 3
-Fail constants 4
-Fail constants 5
-Fail constants 6
-Fail constants 7
-Fail constants 8
-Fail constants 9
-Fail constants 10
-Fail constants 11
-Fail constants 12
-Fail constants 13
-Fail constants 14
-Fail constants 15
-Fail constants 16
-Fail constants 17
-Fail constants 18
-Fail constants 19
-Fail constants 20
-Fail constants 21
-Fail constants 22
-Fail constants 23
-Fail constants 24
-Fail constants 25
-Fail constants 26
-Fail constants 27
-Fail constants 28
-Fail constants 29
-Fail constants 30
-Fail constants 31
-Fail constants 32
-Fail constants 33
-Fail constants 34
-Fail constants 35
-Fail constants 36
-Fail constants 37
-Fail constants 38
-Fail constants 39
\ No newline at end of file
+40 Pass
+Pass constants
+Pass constants 1
+Pass constants 2
+Pass constants 3
+Pass constants 4
+Pass constants 5
+Pass constants 6
+Pass constants 7
+Pass constants 8
+Pass constants 9
+Pass constants 10
+Pass constants 11
+Pass constants 12
+Pass constants 13
+Pass constants 14
+Pass constants 15
+Pass constants 16
+Pass constants 17
+Pass constants 18
+Pass constants 19
+Pass constants 20
+Pass constants 21
+Pass constants 22
+Pass constants 23
+Pass constants 24
+Pass constants 25
+Pass constants 26
+Pass constants 27
+Pass constants 28
+Pass constants 29
+Pass constants 30
+Pass constants 31
+Pass constants 32
+Pass constants 33
+Pass constants 34
+Pass constants 35
+Pass constants 36
+Pass constants 37
+Pass constants 38
+Pass constants 39
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.txt
index 2950b038f38..564c51192c2 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail imports
\ No newline at end of file
+1 Pass
+Pass imports
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.worker.txt
index 2950b038f38..564c51192c2 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.worker.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/jsapi/js-string/imports.any.worker.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Fail
-Fail imports
\ No newline at end of file
+1 Pass
+Pass imports
\ No newline at end of file