Skip to content

Truly independent web browser

LibWasm+LibWeb: Run WebAssembly on the Rust engine

Andreas Kling86608764020c
diff --git a/Libraries/LibWasm/Engine/build.rs b/Libraries/LibWasm/Engine/build.rs
index 08756165d03..4f2a4bf8f25 100644
--- a/Libraries/LibWasm/Engine/build.rs
+++ b/Libraries/LibWasm/Engine/build.rs
@@ -31,11 +31,13 @@ fn main() {
println!("cargo::rustc-check-cfg=cfg(wasm_interpreter)");
println!("cargo:rerun-if-changed=cbindgen.toml");
println!("cargo:rerun-if-changed=src/capi.rs");
+ println!("cargo:rerun-if-changed=src/runtime/heap.rs");
// The bindings only cover the C ABI, so they are generated from that file alone.
let bindings = cbindgen::Builder::new()
.with_config(cbindgen::Config::from_file(manifest_directory.join("cbindgen.toml")).expect("read cbindgen.toml"))
.with_src(manifest_directory.join("src/capi.rs"))
+ .with_src(manifest_directory.join("src/runtime/heap.rs"))
.generate()
.expect("generate the C ABI header");
bindings.write_to_file(output_directory.join("RustFFI.h"));
diff --git a/Libraries/LibWasm/Engine/src/abi.rs b/Libraries/LibWasm/Engine/src/abi.rs
index 0d8b3fcf819..5248a3cb90b 100644
--- a/Libraries/LibWasm/Engine/src/abi.rs
+++ b/Libraries/LibWasm/Engine/src/abi.rs
@@ -176,8 +176,11 @@ pub struct ExecutionContext {
}
/// What the interpreter knows about a type at runtime: how to check subtyping against it, and how objects of it are
-/// laid out. A GC object starts with the address of its type's Rtt; an array continues with its length, then its
-/// elements, and a struct with its fields.
+/// laid out. Rtts live in cells of their own, after the cell header (see heap.rs).
+///
+/// A GC object is a cell that starts with the address of its type's Rtt, followed by the cell header LibGC owns, the
+/// address of its data (OBJECT_DATA_OFFSET), and an array's length (OBJECT_LENGTH_OFFSET). The data is a struct's
+/// fields or an array's elements, inline at OBJECT_INLINE_DATA_OFFSET if they fit there and outside the heap otherwise.
#[repr(C)]
pub struct Rtt {
pub kind: u32,
@@ -185,11 +188,11 @@ pub struct Rtt {
pub depth: u32,
/// The identities of this type's supertypes, from the root down, and of this type last: `depth + 1` of them.
pub display: *const u32,
- /// For structs, the byte offset of each field from the start of the object.
+ /// For structs, the byte offset of each field from the start of the data.
pub field_offsets: *const u32,
/// The STORAGE_* kind of each field of a struct, or of the elements of an array.
pub field_kinds: *const u8,
- /// For structs, the size of an object; for arrays, the size of an element.
+ /// For structs, the size of the data; for arrays, the size of an element.
pub size: u32,
pub field_count: u32,
}
@@ -199,17 +202,21 @@ pub const RTT_KIND_STRUCT: u32 = 1;
pub const RTT_KIND_ARRAY: u32 = 2;
/// How a struct field or array element is stored: one 8-byte word, with packed and 32-bit values zero-extended
-/// in it, or 16 bytes for a v128.
+/// in it, or 16 bytes for a v128. References the collector follows (those of the any, extern, and exn hierarchies)
+/// have a kind of their own.
pub const STORAGE_64: u8 = 0;
pub const STORAGE_I8: u8 = 1;
pub const STORAGE_I16: u8 = 2;
pub const STORAGE_V128: u8 = 3;
pub const STORAGE_32: u8 = 4;
+/// A reference in the any, extern, or exn hierarchy, which the collector follows.
+pub const STORAGE_REFERENCE: u8 = 5;
+/// A function reference, which the collector follows to its function. Stored like STORAGE_64.
+pub const STORAGE_FUNCTION_REFERENCE: u8 = 6;
-/// Where an array's elements start.
-pub const ARRAY_ELEMENTS_OFFSET: usize = 16;
-/// Where a struct's fields start.
-pub const STRUCT_FIELDS_OFFSET: usize = 8;
+pub const OBJECT_DATA_OFFSET: usize = 16;
+pub const OBJECT_LENGTH_OFFSET: usize = 24;
+pub const OBJECT_INLINE_DATA_OFFSET: usize = 32;
/// What the runtime enters the interpreter with, and what it gets back.
#[repr(C)]
@@ -312,8 +319,10 @@ pub fn layout_constants() -> String {
constant("STORAGE_I16", STORAGE_I16 as usize);
constant("STORAGE_V128", STORAGE_V128 as usize);
constant("STORAGE_32", STORAGE_32 as usize);
- constant("ARRAY_ELEMENTS_OFFSET", ARRAY_ELEMENTS_OFFSET);
- constant("STRUCT_FIELDS_OFFSET", STRUCT_FIELDS_OFFSET);
+ constant("STORAGE_REFERENCE", STORAGE_REFERENCE as usize);
+ constant("STORAGE_FUNCTION_REFERENCE", STORAGE_FUNCTION_REFERENCE as usize);
+ constant("OBJECT_DATA_OFFSET", OBJECT_DATA_OFFSET);
+ constant("OBJECT_LENGTH_OFFSET", OBJECT_LENGTH_OFFSET);
constant("CONTEXT_ARGUMENT_1", offset_of!(ExecutionContext, arguments) + 8);
constant("CONTEXT_ARGUMENT_2", offset_of!(ExecutionContext, arguments) + 16);
constant("CONTEXT_ARGUMENT_3", offset_of!(ExecutionContext, arguments) + 24);
diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rs
index ea1051ccda5..687581dc986 100644
--- a/Libraries/LibWasm/Engine/src/capi.rs
+++ b/Libraries/LibWasm/Engine/src/capi.rs
@@ -11,11 +11,11 @@
//! belongs to one thread. Addresses index the store's functions, tables, memories, globals, and instances.
use crate::module::{ExternalKind, ImportDescription, Module};
-use crate::runtime::{
- ExternValue, FunctionAddress, GlobalAddress, InstanceAddress, InstantiationError, MemoryAddress, Store,
- TableAddress, TagAddress, Trap, Value,
-};
+use crate::runtime::entity::{Entity, Handle};
+use crate::runtime::heap::{GcInterface, Visitor};
+use crate::runtime::{ExternValue, FunctionKind, HostFunction, InstantiationError, MemoryAddress, Store, Trap, Value};
use crate::types::{AddressType, FuncType, GlobalType, HeapType, Limits, MemoryType, RefType, TableType, ValType};
+use core::ffi::c_void;
use std::rc::Rc;
use std::sync::Arc;
@@ -256,28 +256,29 @@ impl WasmExternKind {
#[derive(Debug, Clone, Copy)]
pub struct WasmExtern {
pub kind: WasmExternKind,
- pub address: u32,
+ /// The entity's cell.
+ pub entity: *mut c_void,
}
impl WasmExtern {
fn of(value: ExternValue) -> Self {
- let (kind, address) = match value {
- ExternValue::Function(address) => (WasmExternKind::Function, address.0),
- ExternValue::Table(address) => (WasmExternKind::Table, address.0),
- ExternValue::Memory(address) => (WasmExternKind::Memory, address.0),
- ExternValue::Global(address) => (WasmExternKind::Global, address.0),
- ExternValue::Tag(address) => (WasmExternKind::Tag, address.0),
+ let (kind, entity) = match value {
+ ExternValue::Function(address) => (WasmExternKind::Function, address.cell().cast()),
+ ExternValue::Table(address) => (WasmExternKind::Table, address.cell().cast()),
+ ExternValue::Memory(address) => (WasmExternKind::Memory, address.cell().cast()),
+ ExternValue::Global(address) => (WasmExternKind::Global, address.cell().cast()),
+ ExternValue::Tag(address) => (WasmExternKind::Tag, address.cell().cast()),
};
- Self { kind, address }
+ Self { kind, entity }
}
fn to_extern_value(self) -> ExternValue {
match self.kind {
- WasmExternKind::Function => ExternValue::Function(FunctionAddress(self.address)),
- WasmExternKind::Table => ExternValue::Table(TableAddress(self.address)),
- WasmExternKind::Memory => ExternValue::Memory(MemoryAddress(self.address)),
- WasmExternKind::Global => ExternValue::Global(GlobalAddress(self.address)),
- WasmExternKind::Tag => ExternValue::Tag(TagAddress(self.address)),
+ WasmExternKind::Function => ExternValue::Function(entity(self.entity)),
+ WasmExternKind::Table => ExternValue::Table(entity(self.entity)),
+ WasmExternKind::Memory => ExternValue::Memory(entity(self.entity)),
+ WasmExternKind::Global => ExternValue::Global(entity(self.entity)),
+ WasmExternKind::Tag => ExternValue::Tag(entity(self.entity)),
}
}
}
@@ -523,10 +524,14 @@ pub unsafe extern "C" fn wasm_module_function_type_values(
unsafe { write_function_type(function, parameters, results) };
}
+/// Write the parameter and result types of `function`; a null `results` skips the results.
unsafe fn write_function_type(function: &FuncType, parameters: *mut WasmValueType, results: *mut WasmValueType) {
for (index, &ty) in function.params.iter().enumerate() {
unsafe { *parameters.add(index) = WasmValueType::of(ty) };
}
+ if results.is_null() {
+ return;
+ }
for (index, &ty) in function.results.iter().enumerate() {
unsafe { *results.add(index) = WasmValueType::of(ty) };
}
@@ -537,10 +542,20 @@ unsafe fn write_function_type(function: &FuncType, parameters: *mut WasmValueTyp
/// A store, which belongs to the thread that created it.
pub struct WasmStore(Store);
-/// Create a store for the current thread.
+/// Create a store for the current thread, whose entities, GC objects, and memories live in the LibGC heap and
+/// primitive storage of `interface`. The store keeps no entity alive: its embedder visits or roots the cells of those
+/// it uses (see `WasmExtern`).
+///
+/// # Safety
+///
+/// `interface` must hold the functions of LibGC's C interface and a heap of the current thread, which outlives the
+/// store.
#[unsafe(no_mangle)]
-pub extern "C" fn wasm_store_create() -> *mut WasmStore {
- Box::into_raw(Box::new(WasmStore(Store::new())))
+pub unsafe extern "C" fn wasm_store_create(interface: *const GcInterface) -> *mut WasmStore {
+ let interface = unsafe { *interface };
+ let store = Box::into_raw(Box::new(WasmStore(Store::with_heap(Some(interface)))));
+ unsafe { (*store).0.attach_to_heap() };
+ store
}
/// # Safety
@@ -551,6 +566,11 @@ pub unsafe extern "C" fn wasm_store_destroy(store: *mut WasmStore) {
unsafe { drop(Box::from_raw(store)) };
}
+/// The entity of a cell an embedder passed in. Panics if the cell is not a live entity of the kind.
+fn entity<T: Entity>(cell: *mut c_void) -> Handle<T> {
+ unsafe { Handle::from_cell(cell) }.expect("the embedder passes a live entity of the right kind")
+}
+
fn store_of<'a>(store: *mut WasmStore) -> &'a mut Store {
unsafe { &mut (*store).0 }
}
@@ -563,10 +583,38 @@ pub enum WasmStatus {
LinkError,
/// Execution trapped.
Trap,
+ /// An exception was thrown and not caught.
+ Exception,
+ /// Execution ran out of stack.
+ StackExhausted,
+}
+
+impl WasmStatus {
+ /// The status of a trap, with what the embedder needs to know of it in `error` and `exception`.
+ fn of_trap(trap: &Trap, error: *mut WasmString, exception: *mut u64) -> Self {
+ match trap {
+ Trap::UncaughtException(reference) => {
+ if !exception.is_null() {
+ unsafe { *exception = *reference };
+ }
+ write_string(error, &trap.message());
+ Self::Exception
+ }
+ Trap::StackExhausted => {
+ write_string(error, &trap.message());
+ Self::StackExhausted
+ }
+ _ => {
+ write_string(error, &trap.message());
+ Self::Trap
+ }
+ }
+ }
}
/// A function the embedder implements. It reads the arguments and writes the results, in the order of the function
-/// type, and returns false with a message in `error` to trap.
+/// type, and returns `Ok`. It traps by returning `Trap` with a message in `error`, and throws an exception by
+/// returning `Exception` with the exception's reference in `exception`.
pub type WasmHostCallback = unsafe extern "C" fn(
user_data: *mut std::ffi::c_void,
store: *mut WasmStore,
@@ -575,15 +623,23 @@ pub type WasmHostCallback = unsafe extern "C" fn(
results: *mut WasmValue,
result_count: usize,
error: *mut WasmString,
-) -> bool;
+ exception: *mut u64,
+) -> WasmStatus;
-/// Releases the user data of a host function when the store is destroyed.
+/// Visits the cells the user data of a host function refers to, with a LibGC visitor.
+pub type WasmVisitCallback = unsafe extern "C" fn(user_data: *mut std::ffi::c_void, visitor: *mut std::ffi::c_void);
+
+/// Releases the user data of a host function when its function goes away.
pub type WasmReleaseCallback = unsafe extern "C" fn(user_data: *mut std::ffi::c_void);
struct HostFunctionData {
callback: WasmHostCallback,
- user_data: *mut std::ffi::c_void,
+ visit: WasmVisitCallback,
release: WasmReleaseCallback,
+ user_data: *mut std::ffi::c_void,
+ /// The store the function belongs to, which its calls get.
+ store: *mut WasmStore,
+ result_count: usize,
}
impl Drop for HostFunctionData {
@@ -592,7 +648,56 @@ impl Drop for HostFunctionData {
}
}
-/// Add a host function of the given type to the store, and return its address.
+impl HostFunction for HostFunctionData {
+ fn call(&self, _: &mut Store, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ let arguments: Vec<WasmValue> = arguments.iter().map(|&value| WasmValue::of(value)).collect();
+ let mut results = vec![
+ WasmValue {
+ kind: WasmValueKind::I32,
+ low: 0,
+ high: 0,
+ };
+ self.result_count
+ ];
+ let mut error = WasmString {
+ data: std::ptr::null_mut(),
+ length: 0,
+ };
+ let mut exception = 0u64;
+ let status = unsafe {
+ (self.callback)(
+ self.user_data,
+ self.store,
+ arguments.as_ptr(),
+ arguments.len(),
+ results.as_mut_ptr(),
+ results.len(),
+ &raw mut error,
+ &raw mut exception,
+ )
+ };
+ let message = if error.data.is_null() {
+ String::new()
+ } else {
+ let bytes = unsafe { ak::slice_from_raw_parts(error.data, error.length) };
+ let message = String::from_utf8_lossy(bytes).into_owned();
+ unsafe { wasm_string_release(error) };
+ message
+ };
+ match status {
+ WasmStatus::Ok => Ok(results.into_iter().map(WasmValue::to_value).collect()),
+ WasmStatus::Exception => Err(Trap::UncaughtException(exception)),
+ _ => Err(Trap::Host(message)),
+ }
+ }
+
+ fn visit_edges(&self, visitor: &Visitor) {
+ unsafe { (self.visit)(self.user_data, visitor.raw()) };
+ }
+}
+
+/// Add a host function of the given type to the store, and return its cell. The function visits what its user data
+/// refers to with `visit`, and releases the user data with `release` when it goes away.
///
/// # Safety
///
@@ -605,9 +710,10 @@ pub unsafe extern "C" fn wasm_store_allocate_host_function(
results: *const WasmValueType,
result_count: usize,
callback: WasmHostCallback,
- user_data: *mut std::ffi::c_void,
+ visit: WasmVisitCallback,
release: WasmReleaseCallback,
-) -> u32 {
+ user_data: *mut std::ffi::c_void,
+) -> *mut c_void {
let to_types = |types: *const WasmValueType, count: usize| -> Vec<ValType> {
unsafe { ak::slice_from_raw_parts(types, count) }
.iter()
@@ -618,56 +724,15 @@ pub unsafe extern "C" fn wasm_store_allocate_host_function(
params: to_types(parameters, parameter_count),
results: to_types(results, result_count),
};
- let wasm_store = store;
let data = Rc::new(HostFunctionData {
callback,
- user_data,
+ visit,
release,
+ user_data,
+ store,
+ result_count: ty.results.len(),
});
- let result_count = ty.results.len();
- let address = store_of(store).allocate_host_function(
- ty,
- // The callback gets the store it runs in, which is this one.
- Rc::new(move |_: &mut Store, arguments: &[Value]| {
- let arguments: Vec<WasmValue> = arguments.iter().map(|&value| WasmValue::of(value)).collect();
- let mut results = vec![
- WasmValue {
- kind: WasmValueKind::I32,
- low: 0,
- high: 0,
- };
- result_count
- ];
- let mut error = WasmString {
- data: std::ptr::null_mut(),
- length: 0,
- };
- let succeeded = unsafe {
- (data.callback)(
- data.user_data,
- wasm_store,
- arguments.as_ptr(),
- arguments.len(),
- results.as_mut_ptr(),
- results.len(),
- &raw mut error,
- )
- };
- if !succeeded {
- let message = if error.data.is_null() {
- String::new()
- } else {
- let bytes = unsafe { ak::slice_from_raw_parts(error.data, error.length) };
- let message = String::from_utf8_lossy(bytes).into_owned();
- unsafe { wasm_string_release(error) };
- message
- };
- return Err(Trap::Host(message));
- }
- Ok(results.into_iter().map(WasmValue::to_value).collect())
- }),
- );
- address.0
+ store_of(store).allocate_host_function(ty, data).cell().cast()
}
/// Add a memory to the store. Returns false if it cannot be allocated.
@@ -679,41 +744,44 @@ pub unsafe extern "C" fn wasm_store_allocate_host_function(
pub unsafe extern "C" fn wasm_store_allocate_memory(
store: *mut WasmStore,
limits: WasmLimits,
- address: *mut u32,
+ address: *mut *mut c_void,
) -> bool {
let Some(allocated) = store_of(store).allocate_memory(MemoryType {
limits: limits.to_limits(),
}) else {
return false;
};
- unsafe { *address = allocated.0 };
+ unsafe { *address = allocated.cell().cast() };
true
}
-/// Add a table to the store, with every element set to `initial`.
+/// Add a table to the store, with every element set to `initial`. Returns false if it would be too large.
///
/// # Safety
///
-/// `store` must be a live store.
+/// `store` must be a live store, and `address` writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_allocate_table(
store: *mut WasmStore,
element: WasmValueType,
limits: WasmLimits,
initial: u64,
-) -> u32 {
+ address: *mut *mut c_void,
+) -> bool {
let ValType::Ref(element) = element.to_value_type() else {
panic!("table elements are references");
};
- store_of(store)
- .allocate_table(
- TableType {
- element,
- limits: limits.to_limits(),
- },
- initial,
- )
- .0
+ let Some(allocated) = store_of(store).allocate_table(
+ TableType {
+ element,
+ limits: limits.to_limits(),
+ },
+ initial,
+ ) else {
+ return false;
+ };
+ unsafe { *address = allocated.cell().cast() };
+ true
}
/// Add a global to the store.
@@ -727,7 +795,7 @@ pub unsafe extern "C" fn wasm_store_allocate_global(
ty: WasmValueType,
mutable: bool,
value: WasmValue,
-) -> u32 {
+) -> *mut c_void {
store_of(store)
.allocate_global(
GlobalType {
@@ -736,7 +804,8 @@ pub unsafe extern "C" fn wasm_store_allocate_global(
},
value.to_value(),
)
- .0
+ .cell()
+ .cast()
}
/// Instantiate `module` with `imports`, one for each of its imports in order. On success, writes the instance's
@@ -745,15 +814,16 @@ pub unsafe extern "C" fn wasm_store_allocate_global(
/// # Safety
///
/// `store` and `module` must be live, `imports` must hold `import_count` externs, and the out parameters must be
-/// writable (`error` may be null).
+/// writable (`error` and `exception` may be null).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_instantiate(
store: *mut WasmStore,
module: *const WasmModule,
imports: *const WasmExtern,
import_count: usize,
- instance: *mut u32,
+ instance: *mut *mut c_void,
error: *mut WasmString,
+ exception: *mut u64,
) -> WasmStatus {
let mut values = Vec::with_capacity(import_count);
for import in unsafe { ak::slice_from_raw_parts(imports, import_count) } {
@@ -762,17 +832,14 @@ pub unsafe extern "C" fn wasm_store_instantiate(
let module = unsafe { (*module).0.clone() };
match store_of(store).instantiate(module, &values) {
Ok(address) => {
- unsafe { *instance = address.0 };
+ unsafe { *instance = address.cell().cast() };
WasmStatus::Ok
}
Err(InstantiationError::Link(message)) => {
write_string(error, &message);
WasmStatus::LinkError
}
- Err(InstantiationError::Trap(trap)) => {
- write_string(error, &trap.message());
- WasmStatus::Trap
- }
+ Err(InstantiationError::Trap(trap)) => WasmStatus::of_trap(&trap, error, exception),
}
}
@@ -782,8 +849,8 @@ pub unsafe extern "C" fn wasm_store_instantiate(
///
/// `store` must be a live store with an instance at `instance`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_instance_export_count(store: *mut WasmStore, instance: u32) -> usize {
- store_of(store).instance(InstanceAddress(instance)).module.exports.len()
+pub unsafe extern "C" fn wasm_store_instance_export_count(store: *mut WasmStore, instance: *mut c_void) -> usize {
+ store_of(store).instance(entity(instance)).module.exports.len()
}
/// The name and value of an instance's export, in the module's order.
@@ -795,12 +862,12 @@ pub unsafe extern "C" fn wasm_store_instance_export_count(store: *mut WasmStore,
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_instance_export(
store: *mut WasmStore,
- instance: u32,
+ instance: *mut c_void,
index: usize,
name: *mut WasmStringView,
value: *mut WasmExtern,
) -> bool {
- let instance = store_of(store).instance(InstanceAddress(instance));
+ let instance = store_of(store).instance(entity(instance));
let export = &instance.module.exports[index];
unsafe { *name = WasmStringView::of(&export.name) };
let Some(extern_value) = instance.export(&export.name) else {
@@ -819,7 +886,7 @@ pub unsafe extern "C" fn wasm_store_instance_export(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_instance_find_export(
store: *mut WasmStore,
- instance: u32,
+ instance: *mut c_void,
name: *const u8,
length: usize,
value: *mut WasmExtern,
@@ -828,7 +895,7 @@ pub unsafe extern "C" fn wasm_store_instance_find_export(
let Ok(name) = std::str::from_utf8(name) else {
return false;
};
- let Some(extern_value) = store_of(store).instance(InstanceAddress(instance)).export(name) else {
+ let Some(extern_value) = store_of(store).instance(entity(instance)).export(name) else {
return false;
};
unsafe { *value = WasmExtern::of(extern_value) };
@@ -843,11 +910,11 @@ pub unsafe extern "C" fn wasm_store_instance_find_export(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_function_type(
store: *mut WasmStore,
- function: u32,
+ function: *mut c_void,
parameter_count: *mut usize,
result_count: *mut usize,
) {
- let ty = &store_of(store).function(FunctionAddress(function)).ty;
+ let ty = &store_of(store).function(entity(function)).ty;
unsafe {
*parameter_count = ty.params.len();
*result_count = ty.results.len();
@@ -863,11 +930,11 @@ pub unsafe extern "C" fn wasm_store_function_type(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_function_type_values(
store: *mut WasmStore,
- function: u32,
+ function: *mut c_void,
parameters: *mut WasmValueType,
results: *mut WasmValueType,
) {
- let ty = &store_of(store).function(FunctionAddress(function)).ty;
+ let ty = &store_of(store).function(entity(function)).ty;
unsafe { write_function_type(ty, parameters, results) };
}
@@ -876,32 +943,30 @@ pub unsafe extern "C" fn wasm_store_function_type_values(
/// # Safety
///
/// `store` must be a live store with a function at `function`, `arguments` must hold one value for each parameter,
-/// `results` must have room for one value for each result, and `error` must be null or writable.
+/// `results` must have room for one value for each result, and `error` and `exception` must be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_invoke(
store: *mut WasmStore,
- function: u32,
+ function: *mut c_void,
arguments: *const WasmValue,
argument_count: usize,
results: *mut WasmValue,
result_count: usize,
error: *mut WasmString,
+ exception: *mut u64,
) -> WasmStatus {
let arguments: Vec<Value> = unsafe { ak::slice_from_raw_parts(arguments, argument_count) }
.iter()
.map(|value| value.to_value())
.collect();
- match store_of(store).invoke(FunctionAddress(function), &arguments) {
+ match store_of(store).invoke(entity(function), &arguments) {
Ok(values) => {
for (index, value) in values.into_iter().take(result_count).enumerate() {
unsafe { *results.add(index) = WasmValue::of(value) };
}
WasmStatus::Ok
}
- Err(trap) => {
- write_string(error, &trap.message());
- WasmStatus::Trap
- }
+ Err(trap) => WasmStatus::of_trap(&trap, error, exception),
}
}
@@ -911,8 +976,8 @@ pub unsafe extern "C" fn wasm_store_invoke(
///
/// `store` must be a live store with a function at `function`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_function_reference(store: *mut WasmStore, function: u32) -> u64 {
- store_of(store).function_reference(FunctionAddress(function))
+pub unsafe extern "C" fn wasm_store_function_reference(store: *mut WasmStore, function: *mut c_void) -> u64 {
+ store_of(store).function_reference(entity(function))
}
/// The function a function reference refers to. Returns false for null.
@@ -924,12 +989,12 @@ pub unsafe extern "C" fn wasm_store_function_reference(store: *mut WasmStore, fu
pub unsafe extern "C" fn wasm_store_function_from_reference(
store: *mut WasmStore,
reference: u64,
- function: *mut u32,
+ function: *mut *mut c_void,
) -> bool {
let Some(address) = store_of(store).function_from_reference(reference) else {
return false;
};
- unsafe { *function = address.0 };
+ unsafe { *function = address.cell().cast() };
true
}
@@ -939,8 +1004,12 @@ pub unsafe extern "C" fn wasm_store_function_from_reference(
///
/// `store` must be a live store with a memory at `memory`, and `size` writable.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_memory_data(store: *mut WasmStore, memory: u32, size: *mut usize) -> *mut u8 {
- let memory = store_of(store).memory_mut(MemoryAddress(memory));
+pub unsafe extern "C" fn wasm_store_memory_data(
+ store: *mut WasmStore,
+ memory: *mut c_void,
+ size: *mut usize,
+) -> *mut u8 {
+ let memory = store_of(store).memory_mut(entity(memory));
unsafe { *size = memory.size() };
memory.bytes_mut().as_mut_ptr()
}
@@ -951,9 +1020,9 @@ pub unsafe extern "C" fn wasm_store_memory_data(store: *mut WasmStore, memory: u
///
/// `store` must be a live store with a memory at `memory`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_memory_grow(store: *mut WasmStore, memory: u32, delta: u64) -> i64 {
+pub unsafe extern "C" fn wasm_store_memory_grow(store: *mut WasmStore, memory: *mut c_void, delta: u64) -> i64 {
store_of(store)
- .memory_mut(MemoryAddress(memory))
+ .memory_mut(entity(memory))
.grow(delta)
.map_or(-1, |previous| previous as i64)
}
@@ -964,16 +1033,16 @@ pub unsafe extern "C" fn wasm_store_memory_grow(store: *mut WasmStore, memory: u
///
/// `store` must be a live store with a memory at `memory`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_memory_limits(store: *mut WasmStore, memory: u32) -> WasmLimits {
- WasmLimits::of(&store_of(store).memory(MemoryAddress(memory)).ty.limits)
+pub unsafe extern "C" fn wasm_store_memory_limits(store: *mut WasmStore, memory: *mut c_void) -> WasmLimits {
+ WasmLimits::of(&store_of(store).memory(entity(memory)).ty.limits)
}
/// # Safety
///
/// `store` must be a live store with a table at `table`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_table_size(store: *mut WasmStore, table: u32) -> u64 {
- store_of(store).table(TableAddress(table)).elements.len() as u64
+pub unsafe extern "C" fn wasm_store_table_size(store: *mut WasmStore, table: *mut c_void) -> u64 {
+ store_of(store).table(entity(table)).elements.len() as u64
}
/// The element type and limits a table was created with.
@@ -984,11 +1053,11 @@ pub unsafe extern "C" fn wasm_store_table_size(store: *mut WasmStore, table: u32
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_table_type(
store: *mut WasmStore,
- table: u32,
+ table: *mut c_void,
element: *mut WasmValueType,
limits: *mut WasmLimits,
) {
- let table = store_of(store).table(TableAddress(table));
+ let table = store_of(store).table(entity(table));
unsafe {
*element = WasmValueType::of(ValType::Ref(table.ty.element));
*limits = WasmLimits::of(&table.ty.limits);
@@ -1001,8 +1070,13 @@ pub unsafe extern "C" fn wasm_store_table_type(
///
/// `store` must be a live store with a table at `table`, and `value` writable.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_table_get(store: *mut WasmStore, table: u32, index: u64, value: *mut u64) -> bool {
- let Some(&element) = store_of(store).table(TableAddress(table)).elements.get(index as usize) else {
+pub unsafe extern "C" fn wasm_store_table_get(
+ store: *mut WasmStore,
+ table: *mut c_void,
+ index: u64,
+ value: *mut u64,
+) -> bool {
+ let Some(&element) = store_of(store).table(entity(table)).elements.get(index as usize) else {
return false;
};
unsafe { *value = element };
@@ -1015,9 +1089,14 @@ pub unsafe extern "C" fn wasm_store_table_get(store: *mut WasmStore, table: u32,
///
/// `store` must be a live store with a table at `table`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_table_set(store: *mut WasmStore, table: u32, index: u64, value: u64) -> bool {
+pub unsafe extern "C" fn wasm_store_table_set(
+ store: *mut WasmStore,
+ table: *mut c_void,
+ index: u64,
+ value: u64,
+) -> bool {
let Some(element) = store_of(store)
- .table_mut(TableAddress(table))
+ .table_mut(entity(table))
.elements
.get_mut(index as usize)
else {
@@ -1033,9 +1112,14 @@ pub unsafe extern "C" fn wasm_store_table_set(store: *mut WasmStore, table: u32,
///
/// `store` must be a live store with a table at `table`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_table_grow(store: *mut WasmStore, table: u32, delta: u64, initial: u64) -> i64 {
+pub unsafe extern "C" fn wasm_store_table_grow(
+ store: *mut WasmStore,
+ table: *mut c_void,
+ delta: u64,
+ initial: u64,
+) -> i64 {
store_of(store)
- .table_mut(TableAddress(table))
+ .table_mut(entity(table))
.grow(delta, initial)
.map_or(-1, |previous| previous as i64)
}
@@ -1048,10 +1132,10 @@ pub unsafe extern "C" fn wasm_store_table_grow(store: *mut WasmStore, table: u32
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_global_type(
store: *mut WasmStore,
- global: u32,
+ global: *mut c_void,
mutable: *mut bool,
) -> WasmValueType {
- let ty = store_of(store).global(GlobalAddress(global)).ty;
+ let ty = store_of(store).global(entity(global)).ty;
unsafe { *mutable = ty.mutable };
WasmValueType::of(ty.value)
}
@@ -1060,14 +1144,312 @@ pub unsafe extern "C" fn wasm_store_global_type(
///
/// `store` must be a live store with a global at `global`.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_global_get(store: *mut WasmStore, global: u32) -> WasmValue {
- WasmValue::of(store_of(store).global(GlobalAddress(global)).get())
+pub unsafe extern "C" fn wasm_store_global_get(store: *mut WasmStore, global: *mut c_void) -> WasmValue {
+ WasmValue::of(store_of(store).global(entity(global)).get())
}
/// # Safety
///
/// `store` must be a live store with a global at `global`, and `value` must have the global's type.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn wasm_store_global_set(store: *mut WasmStore, global: u32, value: WasmValue) {
- store_of(store).global_mut(GlobalAddress(global)).set(value.to_value());
+pub unsafe extern "C" fn wasm_store_global_set(store: *mut WasmStore, global: *mut c_void, value: WasmValue) {
+ store_of(store).global_mut(entity(global)).set(value.to_value());
+}
+
+// Custom sections.
+
+/// The number of custom sections of a module.
+///
+/// # Safety
+///
+/// `module` must be a live module.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_custom_section_count(module: *const WasmModule) -> usize {
+ module_of(module).custom_sections.len()
+}
+
+/// The name and contents of a module's custom section, in the order of the binary.
+///
+/// # Safety
+///
+/// `module` must be a live module with a custom section at `index`, and the out parameters must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_module_custom_section(
+ module: *const WasmModule,
+ index: usize,
+ name: *mut WasmStringView,
+ contents: *mut WasmStringView,
+) {
+ let module = module_of(module);
+ let section = &module.custom_sections[index];
+ let bytes = &module.bytes[section.contents.start as usize..section.contents.end as usize];
+ unsafe {
+ *name = WasmStringView::of(&section.name);
+ *contents = WasmStringView {
+ data: bytes.as_ptr(),
+ length: bytes.len(),
+ };
+ }
+}
+
+// Tags and exceptions.
+
+/// Add a tag for exceptions that carry values of the given types, and return its address.
+///
+/// # Safety
+///
+/// `store` must be a live store, and `parameters` must hold `parameter_count` types.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_tag(
+ store: *mut WasmStore,
+ parameters: *const WasmValueType,
+ parameter_count: usize,
+) -> *mut c_void {
+ let params = unsafe { ak::slice_from_raw_parts(parameters, parameter_count) }
+ .iter()
+ .map(|ty| ty.to_value_type())
+ .collect();
+ store_of(store)
+ .allocate_tag(FuncType {
+ params,
+ results: Vec::new(),
+ })
+ .cell()
+ .cast()
+}
+
+/// The number of values an exception with the tag carries.
+///
+/// # Safety
+///
+/// `store` must be a live store with a tag at `tag`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_tag_parameter_count(store: *mut WasmStore, tag: *mut c_void) -> usize {
+ store_of(store).tag(entity(tag)).ty.params.len()
+}
+
+/// The types of the values an exception with the tag carries.
+///
+/// # Safety
+///
+/// `store` must be a live store with a tag at `tag`, and `parameters` must have room for its parameter count.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_tag_parameters(
+ store: *mut WasmStore,
+ tag: *mut c_void,
+ parameters: *mut WasmValueType,
+) {
+ let ty = &store_of(store).tag(entity(tag)).ty;
+ unsafe { write_function_type(ty, parameters, std::ptr::null_mut()) };
+}
+
+/// Create an exception with the tag, carrying `values`, and return its reference. The exception is a cell of the
+/// store's heap, which keeps it while something refers to it.
+///
+/// # Safety
+///
+/// `store` must be a live store with a tag at `tag`, and `values` must hold one value of each of its parameter types.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_allocate_exception(
+ store: *mut WasmStore,
+ tag: *mut c_void,
+ values: *const WasmValue,
+ value_count: usize,
+) -> u64 {
+ let values: Vec<Value> = unsafe { ak::slice_from_raw_parts(values, value_count) }
+ .iter()
+ .map(|value| value.to_value())
+ .collect();
+ store_of(store).allocate_exception_with_values(entity(tag), &values)
+}
+
+/// The tag of an exception.
+///
+/// # Safety
+///
+/// `store` must be a live store, and `exception` a reference to one of its exceptions.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_exception_tag(store: *mut WasmStore, exception: u64) -> *mut c_void {
+ store_of(store).exception(exception).tag.cell().cast()
+}
+
+/// The values an exception carries.
+///
+/// # Safety
+///
+/// `store` must be a live store, `exception` a reference to one of its exceptions, and `values` must have room for
+/// the parameter count of its tag.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_exception_values(store: *mut WasmStore, exception: u64, values: *mut WasmValue) {
+ for (index, value) in store_of(store).exception_values(exception).into_iter().enumerate() {
+ unsafe { *values.add(index) = WasmValue::of(value) };
+ }
+}
+
+// Functions, memories.
+
+/// The index of a WebAssembly function in the function index space of the module that defines it. Returns false for a
+/// host function.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`, and `index` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_function_index(
+ store: *mut WasmStore,
+ function: *mut c_void,
+ index: *mut u32,
+) -> bool {
+ let FunctionKind::Wasm {
+ index: function_index, ..
+ } = store_of(store).function(entity(function)).kind
+ else {
+ return false;
+ };
+ unsafe { *index = function_index };
+ true
+}
+
+/// The handle of the LibGC primitive storage a memory lives in, or zero if the store has no heap.
+///
+/// # Safety
+///
+/// `store` must be a live store with a memory at `memory`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_memory_primitive_storage_handle(store: *mut WasmStore, memory: *mut c_void) -> u64 {
+ store_of(store).memory(entity(memory)).primitive_storage_handle()
+}
+
+/// Called with a memory's address after `memory.grow` grows it.
+pub type WasmMemoryGrowCallback = unsafe extern "C" fn(user_data: *mut std::ffi::c_void, memory: *mut c_void);
+
+/// Have `callback` run with `user_data` after each `memory.grow` that grows a memory of the store, but not after
+/// `wasm_store_memory_grow()`.
+///
+/// # Safety
+///
+/// `store` must be a live store, and `user_data` must stay valid until the callback is cleared or the store is
+/// destroyed.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_set_memory_grow_callback(
+ store: *mut WasmStore,
+ callback: WasmMemoryGrowCallback,
+ user_data: *mut std::ffi::c_void,
+) {
+ store_of(store).memory_grow_callback = Some(Rc::new(move |memory: MemoryAddress| unsafe {
+ callback(user_data, memory.cell().cast());
+ }));
+}
+
+/// Remove the callback `wasm_store_set_memory_grow_callback()` set.
+///
+/// # Safety
+///
+/// `store` must be a live store.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_clear_memory_grow_callback(store: *mut WasmStore) {
+ store_of(store).memory_grow_callback = None;
+}
+
+// WASI.
+
+/// The state of a WASI command, whose functions a store gets with `wasm_wasi_allocate_function()`.
+pub struct WasmWasi(Rc<crate::wasi::Wasi>);
+
+fn strings_of(strings: *const WasmStringView, count: usize) -> Vec<String> {
+ if count == 0 {
+ return Vec::new();
+ }
+ unsafe { ak::slice_from_raw_parts(strings, count) }
+ .iter()
+ .map(|string| {
+ String::from_utf8_lossy(unsafe { ak::slice_from_raw_parts(string.data, string.length) }).into_owned()
+ })
+ .collect()
+}
+
+/// Create the state of a WASI command with its arguments, its environment (as `NAME=value` strings), and the host
+/// directories it sees at the guest paths of the same index.
+///
+/// # Safety
+///
+/// Each array must hold its count of strings.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_wasi_create(
+ arguments: *const WasmStringView,
+ argument_count: usize,
+ environment: *const WasmStringView,
+ environment_count: usize,
+ host_paths: *const WasmStringView,
+ guest_paths: *const WasmStringView,
+ preopen_count: usize,
+) -> *mut WasmWasi {
+ let preopens = strings_of(host_paths, preopen_count)
+ .into_iter()
+ .zip(strings_of(guest_paths, preopen_count))
+ .map(|(host, guest)| crate::wasi::Preopen::new(host, guest))
+ .collect();
+ let wasi = crate::wasi::Wasi::new(
+ strings_of(arguments, argument_count),
+ strings_of(environment, environment_count),
+ preopens,
+ );
+ Box::into_raw(Box::new(WasmWasi(Rc::new(wasi))))
+}
+
+/// # Safety
+///
+/// `wasi` must come from `wasm_wasi_create()`. The functions made from it keep what they need.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_wasi_destroy(wasi: *mut WasmWasi) {
+ unsafe { drop(Box::from_raw(wasi)) };
+}
+
+/// Add the WASI function `name` (of `wasi_snapshot_preview1`) to the store, and write its cell to `function`.
+/// Returns false if there is no such function.
+///
+/// # Safety
+///
+/// `store` and `wasi` must be live, `name` must hold `length` bytes, and `function` must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_wasi_allocate_function(
+ store: *mut WasmStore,
+ wasi: *mut WasmWasi,
+ name: *const u8,
+ length: usize,
+ function: *mut *mut c_void,
+) -> bool {
+ let Ok(name) = std::str::from_utf8(unsafe { ak::slice_from_raw_parts(name, length) }) else {
+ return false;
+ };
+ let Some(address) = unsafe { &(*wasi).0 }.allocate_function(store_of(store), name) else {
+ return false;
+ };
+ unsafe { *function = address.cell().cast() };
+ true
+}
+
+/// Have the WASI functions work on `memory`, which is usually the memory the command exports. The memory must live
+/// while they run, as the command's instance makes it.
+///
+/// # Safety
+///
+/// `wasi` must be live, and `memory` a memory's cell.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_wasi_set_memory(wasi: *mut WasmWasi, memory: *mut c_void) {
+ unsafe { &(*wasi).0 }.set_memory(entity(memory));
+}
+
+/// Whether the command called proc_exit, and with which code.
+///
+/// # Safety
+///
+/// `wasi` must be live, and `code` writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_wasi_exit_code(wasi: *mut WasmWasi, code: *mut i32) -> bool {
+ let Some(exit_code) = unsafe { &(*wasi).0 }.exit_code() else {
+ return false;
+ };
+ unsafe { *code = exit_code };
+ true
}
diff --git a/Libraries/LibWasm/Engine/src/lib.rs b/Libraries/LibWasm/Engine/src/lib.rs
index 004ce2f0628..e1cbb1a7819 100644
--- a/Libraries/LibWasm/Engine/src/lib.rs
+++ b/Libraries/LibWasm/Engine/src/lib.rs
@@ -30,6 +30,7 @@ pub mod reader;
pub mod runtime;
pub mod types;
pub mod validator;
+pub mod wasi;
pub use error::{Error, Result};
pub use module::Module;
diff --git a/Libraries/LibWasm/Engine/src/module.rs b/Libraries/LibWasm/Engine/src/module.rs
index bf0fea400b8..7207a73d2d6 100644
--- a/Libraries/LibWasm/Engine/src/module.rs
+++ b/Libraries/LibWasm/Engine/src/module.rs
@@ -126,6 +126,13 @@ pub struct RecursionGroup {
pub count: u32,
}
+/// A custom section: its name and the range of its contents.
+#[derive(Debug, Clone)]
+pub struct CustomSection {
+ pub name: String,
+ pub contents: ByteRange,
+}
+
#[derive(Debug, Default)]
pub struct Module {
pub bytes: Box<[u8]>,
@@ -144,6 +151,7 @@ pub struct Module {
pub data_count: Option<u32>,
pub code: Vec<FunctionBody>,
pub data: Vec<Data>,
+ pub custom_sections: Vec<CustomSection>,
// Index spaces, imports first.
pub imported_function_count: u32,
diff --git a/Libraries/LibWasm/Engine/src/parser.rs b/Libraries/LibWasm/Engine/src/parser.rs
index dcbb83117b4..2eed6160533 100644
--- a/Libraries/LibWasm/Engine/src/parser.rs
+++ b/Libraries/LibWasm/Engine/src/parser.rs
@@ -8,6 +8,7 @@
//! byte ranges, which validation decodes as it checks them.
use crate::error::{Error, Result};
+use crate::module::CustomSection;
use crate::module::{
ConstantExpression, Data, DataMode, Element, ElementItems, ElementMode, Export, ExternalKind, FunctionBody, Global,
Import, ImportDescription, Module, RecursionGroup, Table,
@@ -88,7 +89,11 @@ pub fn parse(bytes: &[u8]) -> Result<Module> {
}
match id {
SECTION_CUSTOM => {
- section.read_name()?;
+ let name = section.read_name()?.to_string();
+ module.custom_sections.push(CustomSection {
+ name,
+ contents: section.position() as u32..section.end() as u32,
+ });
continue;
}
SECTION_TYPE => parse_type_section(&mut section, &mut module)?,
diff --git a/Libraries/LibWasm/Engine/src/quickening.rs b/Libraries/LibWasm/Engine/src/quickening.rs
index 954a8995287..1f67f4f45e1 100644
--- a/Libraries/LibWasm/Engine/src/quickening.rs
+++ b/Libraries/LibWasm/Engine/src/quickening.rs
@@ -13,28 +13,39 @@
//!
//! - The prefix 0xFF, followed by a one-byte sub-opcode, for instructions with an immediate byte to spare.
//! - Single-byte opcodes from 0xF4 to 0xFA, for instructions with none (0xF0 to 0xF3 are the runtime's entry and exit
-//! pseudo-instructions).
+//! pseudo-instructions), and from 0xE0 to 0xEC for constants.
//!
//! The rules:
//!
-//! 1. A core load or store (opcodes 0x28 to 0x3E) that cannot use the guard pages of memory 0, because it accesses
-//! another memory or memory 0 is a memory64, becomes an explicitly bounds-checked access:
+//! 1. A core load or store (opcodes 0x28 to 0x3E) whose memory argument is not exactly a one-byte alignment followed by
+//! the offset, for memory 0 as a memory32, becomes an explicitly bounds-checked access. That is every access that
+//! cannot use the guard pages of memory 0, because it accesses another memory or memory 0 is a memory64, and also
+//! every access whose alignment is encoded in more than one byte or that names memory 0 with an explicit memory
+//! index, so that the plain handlers can rely on the layout `op align offset`:
//!
//! `op align [memory] offset` becomes `0xFF sub [memory] offset 0x01*`, where sub is the original opcode, plus 0x40
//! if a memory index follows. The memory index and offset keep their original encodings. The alignment, which only
//! matters to validation, is dropped; if it took more than one byte, `nop` instructions (0x01) fill the bytes it
//! leaves over, after the access.
//!
-//! A SIMD load or store (0xFD followed by sub-opcode 0x00 to 0x0B or 0x54 to 0x5D) on such a memory works the same
-//! way, with its own sub-opcode: 0x80 plus the position of its SIMD sub-opcode in `SIMD_ACCESSES`, plus 0x20 if a
+//! A SIMD load or store (0xFD followed by sub-opcode 0x00 to 0x0B or 0x54 to 0x5D) with such a memory argument works
+//! the same way, with its own sub-opcode: 0x80 plus the position of its SIMD sub-opcode in `SIMD_ACCESSES`, plus 0x20 if a
//! memory index follows. A lane index, if the instruction has one, comes after the offset, and `nop` instructions
//! fill what the SIMD sub-opcode and alignment leave over.
//!
//! 2. An instruction whose operand or local type is v128, where the plain form assumes a single 8-byte slot, becomes
//! its v128 form with the same immediates (see `V128_FORMS`).
//!
+//! 3. An `i32.const` or `i64.const` whose immediate takes n > 1 bytes becomes a fixed-width form, so that executing it
+//! takes a load instead of a decoding loop: `I32_CONST_FIXED + n - 2` (n up to 5) or `I64_CONST_FIXED + n - 2` (n
+//! up to 10), followed by the value in n little-endian bytes, which hold it since a LEB128 integer of n bytes has
+//! at most 7n bits. The value is sign-extended from those 8n bits, except that an i32 of 5 bytes and an i64 of 9 or
+//! 10 bytes keep their value in the first 4 or 8 bytes, followed by zeros. Since a function body ends with `end`,
+//! reading the byte after a 3-byte value stays inside the code.
+//!
//! Executing code may assume these rules have been applied: plain loads and stores access memory 0, which is a
-//! memory32 with guard pages, and the plain forms of the instructions in rule 2 never see v128 values.
+//! memory32 with guard pages, their alignment takes one byte and no memory index follows it, and the plain forms of
+//! the instructions in rule 2 never see v128 values.
pub const QUICK_PREFIX: u8 = 0xff;
@@ -51,6 +62,28 @@ pub const SIMD_ACCESSES: [u32; 22] = [
0x5b, 0x5c, 0x5d,
];
+/// The fixed-width form of an `i32.const` with a 2-byte immediate; those for 3 to 5 bytes follow (rule 3).
+pub const I32_CONST_FIXED: u8 = 0xe0;
+/// The fixed-width form of an `i64.const` with a 2-byte immediate; those for 3 to 10 bytes follow (rule 3).
+pub const I64_CONST_FIXED: u8 = 0xe4;
+
+/// The rewrite of rule 3 for a constant at `position` whose immediate of `length` bytes has the value `value`, or
+/// None if the immediate takes one byte.
+pub fn fixed_constant(position: usize, length: usize, value: i64, is_i64: bool) -> Option<Rewrite> {
+ if length < 2 {
+ return None;
+ }
+ let opcode = if is_i64 { I64_CONST_FIXED } else { I32_CONST_FIXED } + (length - 2) as u8;
+ let mut bytes = vec![opcode];
+ let stored = if is_i64 { length.min(8) } else { length.min(4) };
+ bytes.extend_from_slice(&value.to_le_bytes()[..stored]);
+ bytes.resize(1 + length, 0);
+ Some(Rewrite {
+ position: position as u32,
+ bytes,
+ })
+}
+
pub const LOCAL_GET_V128: u8 = 0xf4;
pub const LOCAL_SET_V128: u8 = 0xf5;
pub const LOCAL_TEE_V128: u8 = 0xf6;
diff --git a/Libraries/LibWasm/Engine/src/runtime/entity.rs b/Libraries/LibWasm/Engine/src/runtime/entity.rs
new file mode 100644
index 00000000000..f9315573152
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/entity.rs
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The entities of the runtime: functions, tables, memories, globals, tags, and instances. Each is a cell of the heap,
+//! with the entity right after the cell header, and lives while something refers to it: an embedder's cell, another
+//! entity (an instance refers to everything it defines and imports, a function to its instance), or an interpreter
+//! frame, whose function pointer the conservative scan of the stack finds. The store refers to none of them.
+//!
+//! The first word of an entity's cell says what it is, so that a handle an embedder passes in can be checked.
+
+use super::heap::{CELL_HEADER_SIZE, CellType, Heap, Visitor};
+use super::memory::MemoryInstance;
+use super::{FunctionInstance, FunctionKind, GlobalInstance, Instance, TableInstance, TagInstance};
+use core::ffi::c_void;
+use core::ptr::NonNull;
+
+pub const ENTITY_FUNCTION: usize = 0;
+pub const ENTITY_TABLE: usize = 1;
+pub const ENTITY_MEMORY: usize = 2;
+pub const ENTITY_GLOBAL: usize = 3;
+pub const ENTITY_TAG: usize = 4;
+pub const ENTITY_INSTANCE: usize = 5;
+pub const ENTITY_KIND_COUNT: usize = 6;
+
+pub const ENTITY_NAMES: [&str; ENTITY_KIND_COUNT] = [
+ "WebAssembly function",
+ "WebAssembly table",
+ "WebAssembly memory",
+ "WebAssembly global",
+ "WebAssembly tag",
+ "WebAssembly instance",
+];
+
+/// What the first word of an entity's cell holds, besides its kind.
+const ENTITY_MAGIC: u64 = 0x5741_534d_0000_0000;
+
+pub trait Entity: Sized {
+ const KIND: usize;
+
+ /// Visit the cells the entity refers to.
+ fn visit_edges(&self, visitor: &Visitor);
+}
+
+/// An entity, as the address of the entity in its cell. Function references and tag identities are the handles of
+/// their functions and tags, and the interpreter's views of instances, tables, memories, and globals are the first
+/// fields of theirs, so the interpreter's pointers are handles too.
+pub struct Handle<T>(NonNull<T>);
+
+impl<T> Clone for Handle<T> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<T> Copy for Handle<T> {}
+
+impl<T> PartialEq for Handle<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0
+ }
+}
+
+impl<T> Eq for Handle<T> {}
+
+impl<T> core::hash::Hash for Handle<T> {
+ fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
+ self.0.hash(state);
+ }
+}
+
+impl<T> core::fmt::Debug for Handle<T> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(formatter, "{:p}", self.0)
+ }
+}
+
+impl<T: Entity> Handle<T> {
+ /// # Safety
+ ///
+ /// `pointer` must be the address of a live entity of this kind.
+ pub unsafe fn from_ptr(pointer: *const T) -> Self {
+ Self(NonNull::new(pointer.cast_mut()).expect("an entity is never null"))
+ }
+
+ /// The entity of a cell, if the cell is an entity of this kind.
+ ///
+ /// # Safety
+ ///
+ /// `cell` must be a live cell of the runtime.
+ pub unsafe fn from_cell(cell: *mut c_void) -> Option<Self> {
+ if cell.is_null() || unsafe { cell.cast::<u64>().read() } != ENTITY_MAGIC | T::KIND as u64 {
+ return None;
+ }
+ Some(Self(unsafe {
+ NonNull::new_unchecked(cell.cast::<u8>().add(CELL_HEADER_SIZE).cast())
+ }))
+ }
+
+ pub fn as_ptr(self) -> *mut T {
+ self.0.as_ptr()
+ }
+
+ pub fn cell(self) -> *mut u8 {
+ self.0.as_ptr().cast::<u8>().wrapping_sub(CELL_HEADER_SIZE)
+ }
+
+ /// # Safety
+ ///
+ /// The entity must be alive for `'a`, and not be mutated meanwhile.
+ pub unsafe fn get<'a>(self) -> &'a T {
+ unsafe { self.0.as_ref() }
+ }
+
+ /// # Safety
+ ///
+ /// The entity must be alive for `'a`, and not be accessed otherwise meanwhile.
+ pub unsafe fn get_mut<'a>(mut self) -> &'a mut T {
+ unsafe { self.0.as_mut() }
+ }
+}
+
+/// The size of the cell of an entity kind.
+pub fn entity_cell_size(kind: usize) -> usize {
+ let size = match kind {
+ ENTITY_FUNCTION => size_of::<FunctionInstance>(),
+ ENTITY_TABLE => size_of::<TableInstance>(),
+ ENTITY_MEMORY => size_of::<MemoryInstance>(),
+ ENTITY_GLOBAL => size_of::<GlobalInstance>(),
+ ENTITY_TAG => size_of::<TagInstance>(),
+ ENTITY_INSTANCE => size_of::<Instance>(),
+ _ => unreachable!("there are {ENTITY_KIND_COUNT} entity kinds"),
+ };
+ (CELL_HEADER_SIZE + size).next_multiple_of(16)
+}
+
+/// Make `entity` a cell of `heap`. Garbage is not collected until the entity is in place, but may be right after, so
+/// the caller keeps the handle where the collector looks: on the stack, or in a cell it reaches.
+pub fn allocate<T: Entity>(heap: &Heap, entity: T) -> Handle<T> {
+ const { assert!(align_of::<T>() <= 16, "cells are 16-byte aligned") };
+ heap.defer_gc();
+ let cell = heap.allocate_cell(CellType::Entity(T::KIND));
+ let handle = unsafe {
+ cell.cast::<u64>().write(ENTITY_MAGIC | T::KIND as u64);
+ let pointer = cell.add(CELL_HEADER_SIZE).cast::<T>();
+ pointer.write(entity);
+ Handle::from_ptr(pointer)
+ };
+ heap.undefer_gc();
+ handle
+}
+
+unsafe fn kind_of(cell: *mut c_void) -> usize {
+ let word = unsafe { cell.cast::<u64>().read() };
+ debug_assert_eq!(word & !0xffff, ENTITY_MAGIC);
+ (word & 0xffff) as usize
+}
+
+/// # Safety
+///
+/// Only LibGC calls this, with a live entity's cell.
+pub unsafe extern "C" fn entity_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
+ unsafe fn visit<T: Entity>(cell: *mut c_void, visitor: *mut c_void) {
+ let handle = unsafe { Handle::<T>::from_cell(cell) }.expect("the cell is an entity of its kind");
+ unsafe { handle.get() }.visit_edges(&Visitor::new(visitor));
+ }
+ unsafe {
+ match kind_of(cell) {
+ ENTITY_FUNCTION => visit::<FunctionInstance>(cell, visitor),
+ ENTITY_TABLE => visit::<TableInstance>(cell, visitor),
+ ENTITY_MEMORY => visit::<MemoryInstance>(cell, visitor),
+ ENTITY_GLOBAL => visit::<GlobalInstance>(cell, visitor),
+ ENTITY_TAG => visit::<TagInstance>(cell, visitor),
+ ENTITY_INSTANCE => visit::<Instance>(cell, visitor),
+ _ => unreachable!("there are {ENTITY_KIND_COUNT} entity kinds"),
+ }
+ }
+}
+
+/// Drop the entity of a cell, which is going away.
+///
+/// # Safety
+///
+/// `cell` must be an entity's cell, which nothing uses afterwards.
+pub unsafe extern "C" fn destroy_entity(cell: *mut u8) {
+ unsafe fn destroy<T: Entity>(cell: *mut u8) {
+ let handle = unsafe { Handle::<T>::from_cell(cell.cast()) }.expect("the cell is an entity of its kind");
+ unsafe {
+ core::ptr::drop_in_place(handle.as_ptr());
+ // A dead cell is no entity, so a stale handle to it is rejected.
+ cell.cast::<u64>().write(0);
+ }
+ }
+ unsafe {
+ match kind_of(cell.cast()) {
+ ENTITY_FUNCTION => destroy::<FunctionInstance>(cell),
+ ENTITY_TABLE => destroy::<TableInstance>(cell),
+ ENTITY_MEMORY => destroy::<MemoryInstance>(cell),
+ ENTITY_GLOBAL => destroy::<GlobalInstance>(cell),
+ ENTITY_TAG => destroy::<TagInstance>(cell),
+ ENTITY_INSTANCE => destroy::<Instance>(cell),
+ _ => unreachable!("there are {ENTITY_KIND_COUNT} entity kinds"),
+ }
+ }
+}
+
+/// # Safety
+///
+/// Only LibGC calls this, with an entity's cell that is going away.
+pub unsafe extern "C" fn entity_destroy(cell: *mut c_void) {
+ unsafe { destroy_entity(cell.cast()) };
+}
+
+impl Entity for FunctionInstance {
+ const KIND: usize = ENTITY_FUNCTION;
+
+ fn visit_edges(&self, visitor: &Visitor) {
+ match &self.kind {
+ FunctionKind::Wasm { instance, .. } => visitor.visit_cell(instance.cell()),
+ FunctionKind::Host(host) => host.visit_edges(visitor),
+ }
+ }
+}
+
+impl Entity for TableInstance {
+ const KIND: usize = ENTITY_TABLE;
+
+ fn visit_edges(&self, visitor: &Visitor) {
+ for &element in &self.elements {
+ visitor.visit_value(element, self.trace);
+ }
+ }
+}
+
+impl Entity for MemoryInstance {
+ const KIND: usize = ENTITY_MEMORY;
+
+ fn visit_edges(&self, _: &Visitor) {}
+}
+
+impl Entity for GlobalInstance {
+ const KIND: usize = ENTITY_GLOBAL;
+
+ fn visit_edges(&self, visitor: &Visitor) {
+ visitor.visit_value(self.value[0], self.trace);
+ }
+}
+
+impl Entity for TagInstance {
+ const KIND: usize = ENTITY_TAG;
+
+ fn visit_edges(&self, _: &Visitor) {}
+}
+
+impl Entity for Instance {
+ const KIND: usize = ENTITY_INSTANCE;
+
+ fn visit_edges(&self, visitor: &Visitor) {
+ for function in &self.functions {
+ visitor.visit_cell(function.cell());
+ }
+ for table in &self.tables {
+ visitor.visit_cell(table.cell());
+ }
+ for memory in &self.memories {
+ visitor.visit_cell(memory.cell());
+ }
+ for global in &self.globals {
+ visitor.visit_cell(global.cell());
+ }
+ for tag in &self.tags {
+ visitor.visit_cell(tag.cell());
+ }
+ for (segment, &trace) in self.element_storage.iter().zip(&self.element_traces) {
+ for &value in segment {
+ visitor.visit_value(value, trace);
+ }
+ }
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rs
index aadb19709d9..ab94f82efda 100644
--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs
@@ -4,34 +4,95 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! GC objects: their runtime types, layout, and allocation (see `Rtt` in abi.rs for the layout).
+//! GC objects, exceptions, and runtime types, as cells of the heap (see heap.rs), and how the collector traces them.
//!
//! References in the any hierarchy are encoded so that their kind shows in their low bits: zero is null, an i31 has
//! bit 0 set (its value is in the bits above), a host value converted from an externref has bits 1:0 equal to 0b10,
-//! and GC objects are 8-byte aligned addresses. Converting between externref and anyref keeps the bits.
+//! and GC objects and exceptions are the addresses of their cells. Converting between externref and anyref keeps the
+//! bits. An embedder's host values should be the addresses of its cells with bit 1 set, so that the collector keeps
+//! them alive; other host values are never followed.
-use super::{Store, Value};
+use super::heap::{
+ CELL_HEADER_SIZE, CellFunctions, CellType, Heap, TRACE_FUNCTION, TRACE_NONE, TRACE_REFERENCE, Visitor,
+ object_size_class,
+};
+use super::{Store, TagAddress, Value};
use crate::abi::{
- ARRAY_ELEMENTS_OFFSET, RTT_KIND_ARRAY, RTT_KIND_FUNCTION, RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_I8,
- STORAGE_I16, STORAGE_V128, STRUCT_FIELDS_OFFSET,
+ OBJECT_DATA_OFFSET, OBJECT_INLINE_DATA_OFFSET, OBJECT_LENGTH_OFFSET, RTT_KIND_ARRAY, RTT_KIND_FUNCTION,
+ RTT_KIND_STRUCT, Rtt, STORAGE_32, STORAGE_64, STORAGE_FUNCTION_REFERENCE, STORAGE_I8, STORAGE_I16,
+ STORAGE_REFERENCE, STORAGE_V128,
};
-use crate::types::{CompositeType, StorageType, ValType};
+use crate::types::{CompositeType, HeapType, StorageType, SubType, ValType};
+use core::ffi::c_void;
+
+pub const EXCEPTION_CELL_SIZE: usize = 48;
+const EXCEPTION_TAG_OFFSET: usize = 16;
+const EXCEPTION_PAYLOAD_OFFSET: usize = 24;
+const EXCEPTION_LENGTH_OFFSET: usize = 32;
+const EXCEPTION_KINDS_OFFSET: usize = 40;
+const STORE_ROOT_STORE_OFFSET: usize = 16;
+
+/// The largest data an object can have.
+const MAX_OBJECT_DATA_SIZE: u64 = 1 << 31;
+
+pub static CELL_FUNCTIONS: CellFunctions = CellFunctions {
+ object_visit_edges,
+ object_destroy,
+ object_external_memory_size,
+ rtt_visit_edges,
+ rtt_destroy,
+ exception_visit_edges,
+ exception_destroy,
+ store_root_visit_edges,
+ store_root_destroy,
+ entity_visit_edges: super::entity::entity_visit_edges,
+ entity_destroy: super::entity::entity_destroy,
+};
+
+unsafe fn read<T: Copy>(cell: *const c_void, offset: usize) -> T {
+ unsafe { cell.cast::<u8>().add(offset).cast::<T>().read() }
+}
-/// An Rtt and the arrays it points at.
-pub struct RttStorage {
- pub rtt: Rtt,
- display: Box<[u32]>,
- _field_offsets: Box<[u32]>,
- _field_kinds: Box<[u8]>,
+unsafe fn write<T>(cell: *mut u8, offset: usize, value: T) {
+ unsafe { cell.add(offset).cast::<T>().write(value) };
}
-pub fn storage_kind(storage: StorageType) -> u8 {
+/// How the collector follows values of `ty` (TRACE_*). Concrete heap types are identities of `types`.
+pub fn trace_of(ty: ValType, types: &[SubType]) -> u8 {
+ let ValType::Ref(reference) = ty else {
+ return TRACE_NONE;
+ };
+ match reference.heap {
+ HeapType::Func | HeapType::NoFunc => TRACE_FUNCTION,
+ HeapType::Concrete(identity) => match types.get(identity as usize).map(|ty| &ty.composite) {
+ Some(CompositeType::Func(_)) => TRACE_FUNCTION,
+ Some(_) => TRACE_REFERENCE,
+ None => panic!("concrete heap types are identities of the store"),
+ },
+ _ => TRACE_REFERENCE,
+ }
+}
+
+pub fn storage_kind(storage: StorageType, types: &[SubType]) -> u8 {
match storage {
StorageType::I8 => STORAGE_I8,
StorageType::I16 => STORAGE_I16,
StorageType::Val(ValType::V128) => STORAGE_V128,
StorageType::Val(ValType::I32 | ValType::F32) => STORAGE_32,
- StorageType::Val(_) => STORAGE_64,
+ StorageType::Val(value) => match trace_of(value, types) {
+ TRACE_REFERENCE => STORAGE_REFERENCE,
+ TRACE_FUNCTION => STORAGE_FUNCTION_REFERENCE,
+ _ => STORAGE_64,
+ },
+ }
+}
+
+/// How the collector follows a field of storage `kind`.
+fn trace_of_storage(kind: u8) -> u8 {
+ match kind {
+ STORAGE_REFERENCE => TRACE_REFERENCE,
+ STORAGE_FUNCTION_REFERENCE => TRACE_FUNCTION,
+ _ => TRACE_NONE,
}
}
@@ -39,82 +100,295 @@ fn storage_size(kind: u8) -> u32 {
if kind == STORAGE_V128 { 16 } else { 8 }
}
-impl RttStorage {
- /// The runtime type of the store type `identity`, whose supertypes have runtime types already.
- pub fn new(store: &Store, identity: u32) -> Box<Self> {
- let sub_type = &store.types[identity as usize];
- let mut display = match sub_type.supertypes.first() {
- Some(&supertype) => store.rtts[supertype as usize].display.to_vec(),
- None => Vec::new(),
+fn leak<T>(values: Vec<T>) -> *const T {
+ Box::leak(values.into_boxed_slice()).as_ptr()
+}
+
+unsafe fn free<T>(pointer: *const T, length: usize) {
+ if length != 0 {
+ unsafe {
+ drop(Box::from_raw(core::ptr::slice_from_raw_parts_mut(
+ pointer.cast_mut(),
+ length,
+ )));
+ };
+ }
+}
+
+/// The Rtt of a cell that holds one.
+fn rtt_of_cell(cell: *mut u8) -> *mut Rtt {
+ cell.wrapping_add(CELL_HEADER_SIZE).cast()
+}
+
+fn cell_of_rtt(rtt: *const Rtt) -> *mut u8 {
+ rtt.cast::<u8>().cast_mut().wrapping_sub(CELL_HEADER_SIZE)
+}
+
+/// Allocate the runtime type of the store type `identity`, whose supertypes have runtime types already.
+pub fn allocate_rtt(store: &Store, identity: u32) -> *const Rtt {
+ let sub_type = &store.types[identity as usize];
+ let mut display = match sub_type.supertypes.first() {
+ Some(&supertype) => {
+ let parent = store.rtt(supertype);
+ unsafe { ak::slice_from_raw_parts(parent.display, parent.depth as usize + 1) }.to_vec()
+ }
+ None => Vec::new(),
+ };
+ display.push(identity);
+ let (kind, field_kinds, field_offsets, size) = match &sub_type.composite {
+ CompositeType::Func(_) => (RTT_KIND_FUNCTION, Vec::new(), Vec::new(), 0),
+ CompositeType::Struct(fields) => {
+ let kinds: Vec<u8> = fields
+ .iter()
+ .map(|field| storage_kind(field.storage, &store.types))
+ .collect();
+ let mut offsets = Vec::with_capacity(kinds.len());
+ let mut offset = 0;
+ for &kind in &kinds {
+ offsets.push(offset);
+ offset += storage_size(kind);
+ }
+ (RTT_KIND_STRUCT, kinds, offsets, offset)
+ }
+ CompositeType::Array(element) => {
+ let kind = storage_kind(element.storage, &store.types);
+ (RTT_KIND_ARRAY, vec![kind], Vec::new(), storage_size(kind))
+ }
+ };
+ let depth = display.len() as u32 - 1;
+ let field_count = field_offsets.len() as u32;
+ let kind_count = field_kinds.len();
+ let cell = store.heap.allocate_cell(CellType::Rtt);
+ let rtt = rtt_of_cell(cell);
+ unsafe {
+ rtt.write(Rtt {
+ kind,
+ depth,
+ display: leak(display),
+ field_offsets: leak(field_offsets),
+ field_kinds: leak(field_kinds),
+ size,
+ field_count: kind_count as u32,
+ });
+ // The count of offsets and kinds differs for arrays, which have one kind and no offsets.
+ debug_assert!(field_count as usize <= kind_count);
+ }
+ rtt
+}
+
+unsafe extern "C" fn rtt_visit_edges(_: *mut c_void, _: *mut c_void) {}
+
+unsafe extern "C" fn rtt_destroy(cell: *mut c_void) {
+ unsafe {
+ let rtt = &*rtt_of_cell(cell.cast());
+ free(rtt.display, rtt.depth as usize + 1);
+ let kind_count = if rtt.kind == RTT_KIND_ARRAY {
+ 1
+ } else {
+ rtt.field_count as usize
};
- display.push(identity);
- let (kind, field_kinds, field_offsets, size) = match &sub_type.composite {
- CompositeType::Func(_) => (RTT_KIND_FUNCTION, Vec::new(), Vec::new(), 0),
- CompositeType::Struct(fields) => {
- let kinds: Vec<u8> = fields.iter().map(|field| storage_kind(field.storage)).collect();
- let mut offsets = Vec::with_capacity(kinds.len());
- let mut offset = STRUCT_FIELDS_OFFSET as u32;
- for &kind in &kinds {
- offsets.push(offset);
- offset += storage_size(kind);
+ free(rtt.field_kinds, kind_count);
+ let offset_count = if rtt.kind == RTT_KIND_STRUCT {
+ rtt.field_count as usize
+ } else {
+ 0
+ };
+ free(rtt.field_offsets, offset_count);
+ }
+}
+
+/// Allocate a zeroed object of the type `rtt` with `data_size` bytes of data and, for an array, `length` elements.
+/// Returns zero if the data is too large.
+pub fn allocate_object(heap: &Heap, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
+ if data_size > MAX_OBJECT_DATA_SIZE {
+ return 0;
+ }
+ let (cell, data) = match object_size_class(data_size as usize) {
+ Some(class) => {
+ let cell = heap.allocate_cell(CellType::Object(class));
+ (cell, unsafe { cell.add(OBJECT_INLINE_DATA_OFFSET) })
+ }
+ None => {
+ // The data lives outside the heap, after a word that holds the number of words after it. It counts towards
+ // the next collection before the cell is allocated, which may collect.
+ let words = data_size.div_ceil(8) as usize;
+ heap.did_allocate_external_memory((words + 1) * 8);
+ let block = Box::leak(vec![0u64; words + 1].into_boxed_slice());
+ block[0] = words as u64;
+ let data = unsafe { block.as_mut_ptr().add(1) }.cast::<u8>();
+ (heap.allocate_cell(CellType::Object(0)), data)
+ }
+ };
+ unsafe {
+ write(cell, 0, rtt as u64);
+ write(cell, OBJECT_DATA_OFFSET, data as u64);
+ write(cell, OBJECT_LENGTH_OFFSET, length);
+ }
+ cell as u64
+}
+
+/// The out-of-line data of an object and its size in words, if it has some.
+unsafe fn out_of_line_data(cell: *const c_void) -> Option<(*mut u64, usize)> {
+ unsafe {
+ let data: *mut u64 = read(cell, OBJECT_DATA_OFFSET);
+ if data.cast::<u8>().cast_const() == cell.cast::<u8>().add(OBJECT_INLINE_DATA_OFFSET) {
+ return None;
+ }
+ let block = data.sub(1);
+ Some((block, *block as usize + 1))
+ }
+}
+
+unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
+ let visitor = Visitor::new(visitor);
+ unsafe {
+ let rtt: *const Rtt = read(cell, 0);
+ visitor.visit_cell(cell_of_rtt(rtt));
+ let rtt = &*rtt;
+ let data: *const u8 = read(cell, OBJECT_DATA_OFFSET);
+ if rtt.kind == RTT_KIND_STRUCT {
+ for index in 0..rtt.field_count as usize {
+ let trace = trace_of_storage(*rtt.field_kinds.add(index));
+ if trace != TRACE_NONE {
+ let field = data.add(*rtt.field_offsets.add(index) as usize).cast::<u64>().read();
+ visitor.visit_value(field, trace);
}
- (RTT_KIND_STRUCT, kinds, offsets, offset)
}
- CompositeType::Array(element) => {
- let kind = storage_kind(element.storage);
- (RTT_KIND_ARRAY, vec![kind], Vec::new(), storage_size(kind))
+ } else {
+ let trace = trace_of_storage(*rtt.field_kinds);
+ if trace != TRACE_NONE {
+ let length: u64 = read(cell, OBJECT_LENGTH_OFFSET);
+ for index in 0..length as usize {
+ visitor.visit_value(data.cast::<u64>().add(index).read(), trace);
+ }
}
- };
- let display = display.into_boxed_slice();
- let field_offsets = field_offsets.into_boxed_slice();
- let field_kinds = field_kinds.into_boxed_slice();
- Box::new(Self {
- rtt: Rtt {
- kind,
- depth: display.len() as u32 - 1,
- display: display.as_ptr(),
- field_offsets: field_offsets.as_ptr(),
- field_kinds: field_kinds.as_ptr(),
- size,
- field_count: field_offsets.len() as u32,
+ }
+ }
+}
+
+unsafe extern "C" fn object_destroy(cell: *mut c_void) {
+ unsafe {
+ if let Some((block, words)) = out_of_line_data(cell) {
+ free(block, words);
+ }
+ }
+}
+
+unsafe extern "C" fn object_external_memory_size(cell: *const c_void) -> usize {
+ unsafe { out_of_line_data(cell).map_or(0, |(_, words)| words * 8) }
+}
+
+/// An exception: a tag and the values thrown with it, in operand stack order (the last value in the lowest slot).
+pub struct Exception {
+ pub tag: TagAddress,
+ pub payload: &'static [u64],
+}
+
+/// Allocate an exception with the tag `tag` and the slots of `payload`, which the collector follows as `traces` says
+/// (TRACE_*).
+pub fn allocate_exception(heap: &Heap, tag: TagAddress, payload: &[u64], traces: &[u8]) -> u64 {
+ let cell = heap.allocate_cell(CellType::Exception);
+ let kinds: Vec<u8> = traces.to_vec();
+ unsafe {
+ write(cell, EXCEPTION_TAG_OFFSET, tag.as_ptr() as u64);
+ write(cell, EXCEPTION_PAYLOAD_OFFSET, leak(payload.to_vec()) as u64);
+ write(cell, EXCEPTION_LENGTH_OFFSET, payload.len() as u64);
+ write(cell, EXCEPTION_KINDS_OFFSET, leak(kinds) as u64);
+ }
+ cell as u64
+}
+
+/// The exception an exception reference refers to.
+pub fn exception(reference: u64) -> Exception {
+ let cell = reference as *const c_void;
+ unsafe {
+ let tag: u64 = read(cell, EXCEPTION_TAG_OFFSET);
+ let payload: *const u64 = read(cell, EXCEPTION_PAYLOAD_OFFSET);
+ let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);
+ Exception {
+ tag: TagAddress::from_ptr(tag as *const super::TagInstance),
+ payload: if length == 0 {
+ &[]
+ } else {
+ ak::slice_from_raw_parts(payload, length as usize)
},
- display,
- _field_offsets: field_offsets,
- _field_kinds: field_kinds,
- })
+ }
+ }
+}
+
+unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
+ let visitor = Visitor::new(visitor);
+ unsafe {
+ let payload: *const u64 = read(cell, EXCEPTION_PAYLOAD_OFFSET);
+ let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);
+ let kinds: *const u8 = read(cell, EXCEPTION_KINDS_OFFSET);
+ let tag: *const super::TagInstance = read(cell, EXCEPTION_TAG_OFFSET);
+ visitor.visit_cell(TagAddress::from_ptr(tag).cell());
+ for index in 0..length as usize {
+ visitor.visit_value(*payload.add(index), *kinds.add(index));
+ }
+ }
+}
+
+unsafe extern "C" fn exception_destroy(cell: *mut c_void) {
+ unsafe {
+ let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);
+ free(read::<*const u64>(cell, EXCEPTION_PAYLOAD_OFFSET), length as usize);
+ free(read::<*const u8>(cell, EXCEPTION_KINDS_OFFSET), length as usize);
+ }
+}
+
+/// Allocate the cell through which the collector reaches what a store refers to.
+pub(crate) fn allocate_store_root(heap: &Heap, store: *const Store) -> *mut u8 {
+ let cell = heap.allocate_cell(CellType::StoreRoot);
+ unsafe { write(cell, STORE_ROOT_STORE_OFFSET, store as u64) };
+ cell
+}
+
+/// Detach a store's root cell from the store, which is going away, so that the collector no longer reaches it.
+pub(crate) fn detach_store_root(cell: *mut u8) {
+ unsafe { write(cell, STORE_ROOT_STORE_OFFSET, 0u64) };
+}
+
+unsafe extern "C" fn store_root_destroy(cell: *mut c_void) {
+ unsafe {
+ let store: *mut Store = read(cell, STORE_ROOT_STORE_OFFSET);
+ if let Some(store) = store.as_mut() {
+ store.root_cell = std::ptr::null_mut();
+ }
}
}
-/// The largest object the runtime allocates.
-const MAX_OBJECT_SIZE: u64 = 1 << 31;
+unsafe extern "C" fn store_root_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
+ unsafe {
+ let store: *const Store = read(cell, STORE_ROOT_STORE_OFFSET);
+ if let Some(store) = store.as_ref() {
+ store.trace(&Visitor::new(visitor));
+ }
+ }
+}
impl Store {
pub fn rtt(&self, identity: u32) -> &Rtt {
- &self.rtts[identity as usize].rtt
+ unsafe { &*self.rtt_pointers[identity as usize] }
}
- /// Allocate a zeroed object of `size` bytes whose type is `rtt`, or return zero if it is too large.
- pub fn allocate_object(&mut self, rtt: *const Rtt, size: u64) -> u64 {
- if size > MAX_OBJECT_SIZE {
- return 0;
- }
- let mut words = vec![0u64; size.div_ceil(8) as usize].into_boxed_slice();
- words[0] = rtt as u64;
- let object = words.as_mut_ptr() as u64;
- self.objects.push(words);
- object
+ /// Allocate a zeroed object of `data_size` bytes whose type is `rtt`, or return zero if it is too large.
+ pub fn allocate_object(&mut self, rtt: *const Rtt, data_size: u64, length: u64) -> u64 {
+ allocate_object(&self.heap, rtt, data_size, length)
}
/// Allocate a struct of the type `identity` with the given field values.
pub fn allocate_struct(&mut self, identity: u32, fields: &[Value]) -> u64 {
let rtt: *const Rtt = self.rtt(identity);
let size = u64::from(unsafe { (*rtt).size });
- let object = self.allocate_object(rtt, size);
+ let object = self.allocate_object(rtt, size, 0);
+ let data = unsafe { read::<*mut u8>(object as *const c_void, OBJECT_DATA_OFFSET) };
for (index, value) in fields.iter().enumerate() {
unsafe {
let offset = *(*rtt).field_offsets.add(index);
let kind = *(*rtt).field_kinds.add(index);
- store_field(object + u64::from(offset), kind, *value);
+ store_field(data.add(offset as usize), kind, *value);
}
}
object
@@ -124,26 +398,45 @@ impl Store {
pub fn allocate_array(&mut self, identity: u32, values: &[Value]) -> u64 {
let rtt: *const Rtt = self.rtt(identity);
let (element_size, kind) = unsafe { (u64::from((*rtt).size), *(*rtt).field_kinds) };
- let size = ARRAY_ELEMENTS_OFFSET as u64 + values.len() as u64 * element_size;
- let object = self.allocate_object(rtt, size);
+ let object = self.allocate_object(rtt, values.len() as u64 * element_size, values.len() as u64);
if object == 0 {
return 0;
}
- unsafe {
- *((object + 8) as *mut u64) = values.len() as u64;
- for (index, value) in values.iter().enumerate() {
- store_field(
- object + ARRAY_ELEMENTS_OFFSET as u64 + index as u64 * element_size,
- kind,
- *value,
- );
- }
+ let data = unsafe { read::<*mut u8>(object as *const c_void, OBJECT_DATA_OFFSET) };
+ for (index, value) in values.iter().enumerate() {
+ unsafe { store_field(data.add(index * element_size as usize), kind, *value) };
}
object
}
+
+ /// Make an exception with `tag` and the values of `payload` (in operand stack order), and return its reference.
+ pub fn allocate_exception(&mut self, tag: TagAddress, payload: &[u64]) -> u64 {
+ let mut traces = Vec::with_capacity(payload.len());
+ // The slots are in operand stack order, the last parameter first.
+ for &param in self.tag(tag).ty.params.iter().rev() {
+ traces.push(trace_of(param, &self.types));
+ traces.extend(std::iter::repeat_n(TRACE_NONE, param.slot_count() as usize - 1));
+ }
+ allocate_exception(&self.heap, tag, payload, &traces)
+ }
+
+ /// The exception an exception reference refers to.
+ pub fn exception(&self, reference: u64) -> Exception {
+ exception(reference)
+ }
+
+ /// Visit what the store keeps: its runtime types, and the exception of a trap that is on its way out.
+ pub fn trace(&self, visitor: &Visitor) {
+ for &rtt in &self.rtt_pointers {
+ visitor.visit_cell(cell_of_rtt(rtt));
+ }
+ if let Some(super::Trap::UncaughtException(exception)) = &self.pending_trap {
+ visitor.visit_cell(*exception as *mut u8);
+ }
+ }
}
-unsafe fn store_field(address: u64, kind: u8, value: Value) {
+unsafe fn store_field(address: *mut u8, kind: u8, value: Value) {
let mut slots = Vec::with_capacity(2);
value.push_slots(&mut slots);
let mask = match kind {
@@ -152,9 +445,9 @@ unsafe fn store_field(address: u64, kind: u8, value: Value) {
_ => u64::MAX,
};
unsafe {
- *(address as *mut u64) = slots[0] & mask;
+ address.cast::<u64>().write(slots[0] & mask);
if kind == STORAGE_V128 {
- *((address + 8) as *mut u64) = slots[1];
+ address.cast::<u64>().add(1).write(slots[1]);
}
}
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rs
new file mode 100644
index 00000000000..7a89168f033
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs
@@ -0,0 +1,456 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Where the runtime's garbage-collected objects and linear memories live: in the embedder's LibGC heap and primitive
+//! storage, reached through the functions of Libraries/LibGC/CAPI.h that the embedder hands over in a `GcInterface`,
+//! or, for a store without one (as in this crate's tests), in plain allocations that are never freed and mappings of
+//! their own.
+//!
+//! Cells start with a word that belongs to the runtime and a word that holds LibGC's mark, state, and kind. GC objects
+//! (see gc.rs) are cells; so are runtime types, exceptions, and the cell that roots a store. The embedder's thread
+//! stack, which holds the interpreter's frames, is scanned conservatively, and LibGC recognizes pointers into a cell,
+//! so references with tags in their low bits keep their cells alive there too.
+
+use core::ffi::{c_char, c_void};
+use std::sync::OnceLock;
+
+/// Mirrors GCCellTypeInfo.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct CellTypeInfo {
+ pub cell_size: u32,
+ pub alignment: u32,
+ pub kind: u8,
+ pub visit_edges: unsafe extern "C" fn(cell: *mut c_void, visitor: *mut c_void),
+ pub finalize: Option<unsafe extern "C" fn(cell: *mut c_void)>,
+ pub destroy: Option<unsafe extern "C" fn(cell: *mut c_void)>,
+ pub external_memory_size: Option<unsafe extern "C" fn(cell: *const c_void) -> usize>,
+ pub class_name: Option<unsafe extern "C" fn(cell: *const c_void, length: *mut usize) -> *const c_char>,
+}
+
+/// Mirrors GCLayout.
+#[derive(Default, Clone, Copy)]
+#[repr(C)]
+pub struct GcLayout {
+ pub cell_mark_offset: u32,
+ pub cell_state_offset: u32,
+ pub cell_kind_offset: u32,
+ pub min_cell_size: u32,
+ pub max_cell_size: u32,
+ pub max_cell_alignment: u32,
+ pub cell_type_info_size: u32,
+ pub weak_impl_pointer_offset: u32,
+ pub free_cell_next_offset: u32,
+ pub free_cell_link_mask: u32,
+ pub local_cursor_offset: u32,
+ pub local_end_offset: u32,
+ pub local_cell_size_offset: u32,
+ pub heap_allocated_bytes_since_last_gc_offset: u32,
+ pub heap_gc_bytes_threshold_offset: u32,
+ pub heap_total_allocated_bytes_offset: u32,
+ pub heap_region_offset_mask: u64,
+ pub primitive_storage_cage_offset_mask: u64,
+}
+
+/// Mirrors GCPrimitiveStorageLayout.
+#[derive(Default, Clone, Copy)]
+#[repr(C)]
+pub struct PrimitiveStorageLayout {
+ pub offset: usize,
+ pub size: usize,
+ pub capacity: usize,
+}
+
+/// The functions of LibGC's C interface the runtime uses, and the heap to use them with. An embedder fills it in with
+/// the functions of Libraries/LibGC/CAPI.h of the same names.
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct GcInterface {
+ pub heap: *mut c_void,
+ pub gc_get_layout: unsafe extern "C" fn(layout: *mut GcLayout),
+ pub gc_allocator_create:
+ unsafe extern "C" fn(type_info: *const CellTypeInfo, name: *const c_char, name_length: usize) -> *mut c_void,
+ pub gc_heap_allocate_cell:
+ unsafe extern "C" fn(heap: *mut c_void, allocator: *mut c_void, must_mark: *mut bool) -> *mut c_void,
+ pub gc_heap_defer_gc: unsafe extern "C" fn(heap: *mut c_void),
+ pub gc_heap_undefer_gc: unsafe extern "C" fn(heap: *mut c_void),
+ pub gc_heap_collect_garbage: unsafe extern "C" fn(heap: *mut c_void, collection_type: i32, print_report: bool),
+ pub gc_heap_did_allocate_external_memory: unsafe extern "C" fn(heap: *mut c_void, size: usize),
+ pub gc_root_create: unsafe extern "C" fn(cell: *mut c_void) -> *mut c_void,
+ pub gc_root_destroy: unsafe extern "C" fn(root: *mut c_void),
+ pub gc_visitor_visit_cell: unsafe extern "C" fn(visitor: *mut c_void, cell: *mut c_void),
+ pub gc_visitor_visit_possible_values: unsafe extern "C" fn(visitor: *mut c_void, data: *const u8, size: usize),
+ pub gc_primitive_storage_reserve: unsafe extern "C" fn(
+ size: usize,
+ capacity: usize,
+ zero_fill: bool,
+ guard_size: usize,
+ out_handle: *mut u64,
+ out_layout: *mut PrimitiveStorageLayout,
+ ) -> bool,
+ pub gc_primitive_storage_resize: unsafe extern "C" fn(
+ handle: u64,
+ new_size: usize,
+ zero_fill: bool,
+ out_layout: *mut PrimitiveStorageLayout,
+ ) -> bool,
+ pub gc_primitive_storage_free: unsafe extern "C" fn(handle: u64),
+ pub gc_primitive_storage_data: unsafe extern "C" fn(handle: u64) -> *mut u8,
+}
+
+/// The size of the words every cell starts with: one of the runtime's and one of LibGC's.
+pub const CELL_HEADER_SIZE: usize = 16;
+
+const CELL_STATE_LIVE: u8 = 0;
+const CELL_KIND_OTHER: u8 = 0;
+
+/// The cell types of the runtime, in the order of their allocators.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum CellType {
+ /// A GC object whose inline data has the size of the given size class.
+ Object(usize),
+ Rtt,
+ Exception,
+ StoreRoot,
+ /// A function, table, memory, global, tag, or instance (see entity.rs), by its ENTITY_* kind.
+ Entity(usize),
+}
+
+/// The sizes of the data a GC object can keep inline. Larger data is allocated outside of the heap.
+pub const OBJECT_DATA_SIZE_CLASSES: [usize; 17] = [
+ 0, 16, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096,
+];
+
+/// The size class of objects with `size` bytes of data, or None if the data does not fit inline.
+pub fn object_size_class(size: usize) -> Option<usize> {
+ OBJECT_DATA_SIZE_CLASSES.iter().position(|&class| class >= size)
+}
+
+/// What every cell type needs from the rest of the runtime.
+pub struct CellFunctions {
+ pub object_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ pub object_destroy: unsafe extern "C" fn(*mut c_void),
+ pub object_external_memory_size: unsafe extern "C" fn(*const c_void) -> usize,
+ pub rtt_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ pub rtt_destroy: unsafe extern "C" fn(*mut c_void),
+ pub exception_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ pub exception_destroy: unsafe extern "C" fn(*mut c_void),
+ pub store_root_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ pub store_root_destroy: unsafe extern "C" fn(*mut c_void),
+ pub entity_visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ pub entity_destroy: unsafe extern "C" fn(*mut c_void),
+}
+
+/// The allocators of the runtime's cell types, which LibGC requires to outlive every heap, so there is one set of
+/// them for the process, made with the first interface.
+struct Allocators {
+ objects: Vec<*mut c_void>,
+ rtt: *mut c_void,
+ exception: *mut c_void,
+ store_root: *mut c_void,
+ entities: Vec<*mut c_void>,
+}
+
+// The allocators are only handles, which LibGC only uses from the thread of the heap it allocates from.
+unsafe impl Send for Allocators {}
+unsafe impl Sync for Allocators {}
+
+static ALLOCATORS: OnceLock<Allocators> = OnceLock::new();
+
+/// The functions of the first interface, which every heap's cells are visited with: they are the same functions of
+/// LibGC whichever heap a store uses.
+struct Functions(GcInterface);
+
+// Only the function pointers are used, never the heap.
+unsafe impl Send for Functions {}
+unsafe impl Sync for Functions {}
+
+static FUNCTIONS: OnceLock<Functions> = OnceLock::new();
+
+unsafe extern "C" fn class_name(_: *const c_void, length: *mut usize) -> *const c_char {
+ const NAME: &str = "WebAssembly cell";
+ unsafe { length.write(NAME.len()) };
+ NAME.as_ptr().cast()
+}
+
+fn type_info(
+ cell_size: usize,
+ visit_edges: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ destroy: Option<unsafe extern "C" fn(*mut c_void)>,
+ external_memory_size: Option<unsafe extern "C" fn(*const c_void) -> usize>,
+) -> &'static CellTypeInfo {
+ Box::leak(Box::new(CellTypeInfo {
+ cell_size: cell_size as u32,
+ alignment: 16,
+ kind: CELL_KIND_OTHER,
+ visit_edges,
+ finalize: None,
+ destroy,
+ external_memory_size,
+ class_name: Some(class_name),
+ }))
+}
+
+impl Allocators {
+ fn new(interface: &GcInterface, functions: &CellFunctions) -> Self {
+ let create = |info: &'static CellTypeInfo, name: &'static str| unsafe {
+ (interface.gc_allocator_create)(info, name.as_ptr().cast(), name.len())
+ };
+ let objects = OBJECT_DATA_SIZE_CLASSES
+ .iter()
+ .map(|&data_size| {
+ create(
+ type_info(
+ crate::abi::OBJECT_INLINE_DATA_OFFSET + data_size,
+ functions.object_visit_edges,
+ Some(functions.object_destroy),
+ Some(functions.object_external_memory_size),
+ ),
+ "WebAssembly object",
+ )
+ })
+ .collect();
+ Self {
+ objects,
+ rtt: create(
+ type_info(
+ CELL_HEADER_SIZE + size_of::<crate::abi::Rtt>().next_multiple_of(16),
+ functions.rtt_visit_edges,
+ Some(functions.rtt_destroy),
+ None,
+ ),
+ "WebAssembly runtime type",
+ ),
+ exception: create(
+ type_info(
+ super::gc::EXCEPTION_CELL_SIZE,
+ functions.exception_visit_edges,
+ Some(functions.exception_destroy),
+ None,
+ ),
+ "WebAssembly exception",
+ ),
+ store_root: create(
+ type_info(
+ 32,
+ functions.store_root_visit_edges,
+ Some(functions.store_root_destroy),
+ None,
+ ),
+ "WebAssembly store",
+ ),
+ entities: (0..super::entity::ENTITY_KIND_COUNT)
+ .map(|kind| {
+ create(
+ type_info(
+ cell_size(CellType::Entity(kind)),
+ functions.entity_visit_edges,
+ Some(functions.entity_destroy),
+ None,
+ ),
+ super::entity::ENTITY_NAMES[kind],
+ )
+ })
+ .collect(),
+ }
+ }
+
+ fn of(&self, cell_type: CellType) -> *mut c_void {
+ match cell_type {
+ CellType::Object(class) => self.objects[class],
+ CellType::Rtt => self.rtt,
+ CellType::Exception => self.exception,
+ CellType::StoreRoot => self.store_root,
+ CellType::Entity(kind) => self.entities[kind],
+ }
+ }
+}
+
+/// The size of a cell of a type.
+pub fn cell_size(cell_type: CellType) -> usize {
+ match cell_type {
+ CellType::Object(class) => crate::abi::OBJECT_INLINE_DATA_OFFSET + OBJECT_DATA_SIZE_CLASSES[class],
+ CellType::Rtt => CELL_HEADER_SIZE + size_of::<crate::abi::Rtt>().next_multiple_of(16),
+ CellType::Exception => super::gc::EXCEPTION_CELL_SIZE,
+ CellType::StoreRoot => 32,
+ CellType::Entity(kind) => super::entity::entity_cell_size(kind),
+ }
+}
+
+/// A LibGC heap.
+pub struct GcHeap {
+ pub interface: GcInterface,
+ layout: GcLayout,
+ allocators: &'static Allocators,
+}
+
+pub enum Heap {
+ /// Cells are plain allocations, which the store's entities are freed with, and memories are mappings of their own.
+ Standalone(core::cell::RefCell<Vec<*mut u8>>),
+ Gc(Box<GcHeap>),
+}
+
+impl Heap {
+ pub fn new(interface: Option<GcInterface>, functions: &CellFunctions) -> Self {
+ let Some(interface) = interface else {
+ return Self::Standalone(core::cell::RefCell::new(Vec::new()));
+ };
+ let mut layout = GcLayout::default();
+ unsafe { (interface.gc_get_layout)(&raw mut layout) };
+ assert!(
+ layout.cell_mark_offset as usize >= 8 && (layout.cell_kind_offset as usize) < CELL_HEADER_SIZE,
+ "LibGC keeps its cell header in the second word"
+ );
+ let allocators = ALLOCATORS.get_or_init(|| Allocators::new(&interface, functions));
+ FUNCTIONS.get_or_init(|| Functions(interface));
+ Self::Gc(Box::new(GcHeap {
+ interface,
+ layout,
+ allocators,
+ }))
+ }
+
+ pub fn gc(&self) -> Option<&GcHeap> {
+ match self {
+ Self::Standalone(_) => None,
+ Self::Gc(heap) => Some(heap),
+ }
+ }
+
+ /// Allocate a zero-filled cell. Garbage may be collected first, so every reference the caller holds outside of
+ /// the stack and the cells the store reaches must be in a deferred section.
+ pub fn allocate_cell(&self, cell_type: CellType) -> *mut u8 {
+ let size = cell_size(cell_type);
+ match self {
+ Self::Standalone(entities) => {
+ // NB: Standalone stores never free their cells, but drop their entities when they go away.
+ let words = vec![0u128; size.div_ceil(16)].into_boxed_slice();
+ let cell: *mut u8 = Box::leak(words).as_mut_ptr().cast();
+ if matches!(cell_type, CellType::Entity(_)) {
+ entities.borrow_mut().push(cell);
+ }
+ cell
+ }
+ Self::Gc(heap) => unsafe {
+ let mut must_mark = false;
+ let cell: *mut u8 = (heap.interface.gc_heap_allocate_cell)(
+ heap.interface.heap,
+ heap.allocators.of(cell_type),
+ &raw mut must_mark,
+ )
+ .cast();
+ assert!(!cell.is_null(), "LibGC allocates the cell");
+ core::ptr::write_bytes(cell, 0, size);
+ *cell.add(heap.layout.cell_mark_offset as usize) = u8::from(must_mark);
+ *cell.add(heap.layout.cell_state_offset as usize) = CELL_STATE_LIVE;
+ *cell.add(heap.layout.cell_kind_offset as usize) = CELL_KIND_OTHER;
+ cell
+ },
+ }
+ }
+
+ /// Drop the entities of a standalone heap, whose store is going away.
+ pub(crate) fn drop_standalone_entities(&self) {
+ if let Self::Standalone(entities) = self {
+ for cell in entities.take() {
+ unsafe { super::entity::destroy_entity(cell) };
+ }
+ }
+ }
+
+ /// Count memory a cell owns outside of the heap towards the next collection.
+ pub fn did_allocate_external_memory(&self, size: usize) {
+ if let Self::Gc(heap) = self {
+ unsafe { (heap.interface.gc_heap_did_allocate_external_memory)(heap.interface.heap, size) };
+ }
+ }
+
+ /// Stop collecting garbage until the matching undefer_gc(), for code that keeps references where the collector
+ /// does not look.
+ pub fn defer_gc(&self) {
+ if let Self::Gc(heap) = self {
+ unsafe { (heap.interface.gc_heap_defer_gc)(heap.interface.heap) };
+ }
+ }
+
+ pub fn undefer_gc(&self) {
+ if let Self::Gc(heap) = self {
+ unsafe { (heap.interface.gc_heap_undefer_gc)(heap.interface.heap) };
+ }
+ }
+}
+
+impl GcHeap {
+ /// Keep the cell alive until the root is destroyed.
+ pub(crate) fn root(&self, cell: *mut u8) -> *mut c_void {
+ unsafe { (self.interface.gc_root_create)(cell.cast()) }
+ }
+
+ pub(crate) fn unroot(&self, root: *mut c_void) {
+ unsafe { (self.interface.gc_root_destroy)(root) };
+ }
+}
+
+/// How the collector follows a value: not at all, as a reference in the any, extern, or exn hierarchy, or as a
+/// function reference, which points into its function's cell.
+pub const TRACE_NONE: u8 = 0;
+pub const TRACE_REFERENCE: u8 = 1;
+pub const TRACE_FUNCTION: u8 = 2;
+
+/// A visitor LibGC passes to the cells' visit_edges, with the functions to visit cells with.
+pub struct Visitor {
+ raw: *mut c_void,
+ interface: *const GcInterface,
+}
+
+impl Visitor {
+ /// The visitor LibGC passed to a cell's visit_edges. Only cells of a LibGC heap are visited, so there is an
+ /// interface by then.
+ pub fn new(raw: *mut c_void) -> Self {
+ let functions = FUNCTIONS.get().expect("cells are only visited once a heap exists");
+ Self {
+ raw,
+ interface: &raw const functions.0,
+ }
+ }
+
+ /// The LibGC visitor itself, for an embedder to visit its cells with.
+ pub fn raw(&self) -> *mut c_void {
+ self.raw
+ }
+
+ pub(crate) fn visit_cell(&self, cell: *mut u8) {
+ unsafe { ((*self.interface).gc_visitor_visit_cell)(self.raw, cell.cast()) };
+ }
+
+ /// Visit a value of a type whose TRACE_* kind is `trace`.
+ pub fn visit_value(&self, value: u64, trace: u8) {
+ match trace {
+ TRACE_REFERENCE => self.visit_reference(value),
+ TRACE_FUNCTION if value != 0 => self.visit_cell((value as *mut u8).wrapping_sub(CELL_HEADER_SIZE)),
+ _ => {}
+ }
+ }
+
+ /// Visit a reference in the any, extern, or exn hierarchy, whose kind is in its low bits (see gc.rs).
+ pub fn visit_reference(&self, reference: u64) {
+ if reference == 0 || reference & 1 != 0 {
+ return;
+ }
+ if reference & 3 == 2 {
+ // An embedder's host value, which LibGC only follows if it points into a cell.
+ unsafe {
+ ((*self.interface).gc_visitor_visit_possible_values)(
+ self.raw,
+ (&raw const reference).cast(),
+ size_of::<u64>(),
+ );
+ }
+ return;
+ }
+ self.visit_cell(reference as *mut u8);
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
index e6433ada6f4..1ac257842c6 100644
--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs
@@ -7,7 +7,7 @@
//! The runtime services the interpreter calls for what needs the runtime: growing memories and tables, and calling
//! host functions. Each takes the execution context, whose `arguments` hold the operands.
-use super::{FunctionInstance, FunctionKind, Store, Trap, Value};
+use super::{FunctionInstance, FunctionKind, MemoryAddress, Store, TableAddress, Trap, Value};
use crate::abi::{
ExecutionContext, FRAME_FUNCTION, FRAME_HEADER_SIZE, FRAME_INSTANCE, FRAME_RETURN_IP, FRAME_SAVED_FP, MemoryData,
TableData,
@@ -30,12 +30,15 @@ pub unsafe extern "C" fn wasm_runtime_memory_grow(context: *mut ExecutionContext
let data = (*context).arguments[0] as *const MemoryData;
let delta = (*context).arguments[1];
let store = store_of(context);
- store
- .memories
- .iter_mut()
- .find(|memory| std::ptr::eq(&raw const *memory.data, data))
- .and_then(|memory| memory.grow(delta))
- .unwrap_or(u64::MAX)
+ // The data is at the memory's handle.
+ let memory = MemoryAddress::from_ptr(data.cast());
+ let Some(previous) = store.memory_mut(memory).grow(delta) else {
+ return u64::MAX;
+ };
+ if let Some(callback) = store.memory_grow_callback.clone() {
+ callback(memory);
+ }
+ previous
}
}
@@ -52,11 +55,10 @@ pub unsafe extern "C" fn wasm_runtime_table_grow(context: *mut ExecutionContext)
let delta = (*context).arguments[1];
let initial = (*context).arguments[2];
let store = store_of(context);
+ // The data is at the table's handle.
store
- .tables
- .iter_mut()
- .find(|table| std::ptr::eq(&raw const *table.data, data))
- .and_then(|table| table.grow(delta, initial))
+ .table_mut(TableAddress::from_ptr(data.cast()))
+ .grow(delta, initial)
.unwrap_or(u64::MAX)
}
}
@@ -90,7 +92,7 @@ pub unsafe extern "C" fn wasm_runtime_call_host(context: *mut ExecutionContext)
slot -= ty.slot_count() as usize;
arguments.push(Value::from_slots(ty, &slots[slot..]));
}
- let results = match callback(store, &arguments) {
+ let results = match callback.call(store, &arguments) {
Ok(results) => results,
Err(Trap::UncaughtException(exception)) => {
// The exception continues in the caller, as if the call instruction had thrown it.
@@ -117,8 +119,8 @@ pub unsafe extern "C" fn wasm_runtime_call_host(context: *mut ExecutionContext)
}
}
-/// Allocate a zeroed GC object of `arguments[1]` bytes whose runtime type is `arguments[0]`. Returns zero if it is
-/// too large.
+/// Allocate a GC object whose runtime type is `arguments[0]`, with `arguments[1]` bytes of zeroed data and, for an
+/// array, `arguments[2]` elements. Returns zero if it is too large.
///
/// # Safety
///
@@ -129,7 +131,8 @@ pub unsafe extern "C" fn wasm_runtime_allocate(context: *mut ExecutionContext) -
let store = store_of(context);
let rtt = (*context).arguments[0] as *const crate::abi::Rtt;
let size = (*context).arguments[1];
- let object = store.allocate_object(rtt, size);
+ let length = (*context).arguments[2];
+ let object = store.allocate_object(rtt, size, length);
if object == 0 {
store.pending_trap = Some(Trap::Host("out of memory".to_string()));
}
@@ -157,8 +160,8 @@ pub unsafe extern "C" fn wasm_runtime_throw(context: *mut ExecutionContext) -> u
let tag = store.tag_from_identity((*context).arguments[0]);
let slot_count: u32 = store.tag(tag).ty.params.iter().map(|param| param.slot_count()).sum();
let top = (*context).arguments[1] as *const u64;
- let payload: Box<[u64]> = ak::slice_from_raw_parts(top, slot_count as usize).into();
- exception = store.allocate_exception(tag, payload);
+ let payload = ak::slice_from_raw_parts(top, slot_count as usize).to_vec();
+ exception = store.allocate_exception(tag, &payload);
}
if unwind(context, store, exception, frame, pc) {
return 1;
@@ -206,7 +209,7 @@ unsafe fn unwind(context: *mut ExecutionContext, store: &Store, exception: u64,
continue;
}
let payload: &[u64] = match clause.kind {
- CatchKind::Catch | CatchKind::CatchRef => &store.exception(exception).payload,
+ CatchKind::Catch | CatchKind::CatchRef => store.exception(exception).payload,
CatchKind::CatchAll | CatchKind::CatchAllRef => &[],
};
let pushes_reference = matches!(clause.kind, CatchKind::CatchRef | CatchKind::CatchAllRef);
diff --git a/Libraries/LibWasm/Engine/src/runtime/memory.rs b/Libraries/LibWasm/Engine/src/runtime/memory.rs
index ce9fa118ab5..01e57d3ebf4 100644
--- a/Libraries/LibWasm/Engine/src/runtime/memory.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/memory.rs
@@ -6,11 +6,12 @@
//! Linear memories. A memory reserves the address range its accesses can form up front and only commits what it has
//! grown to, so that its base never moves and accesses past its end fault into the guard region instead of needing a
-//! bounds check.
+//! bounds check. A store with a LibGC heap keeps its memories in LibGC's primitive storage, inside the cage that
+//! array buffers live in, so that buffers can view them; other stores map their own.
+use super::ranges::RangeSet;
use crate::abi::MemoryData;
use crate::types::{AddressType, MemoryType};
-use std::sync::Mutex;
pub const PAGE_SIZE: u64 = 64 * 1024;
const MEMORY32_MAX_PAGES: u64 = 1 << 16;
@@ -24,26 +25,31 @@ const MEMORY64_MAX_PAGES: u64 = 1 << 18;
pub const GUARDED_RESERVATION_SIZE: u64 = 2 * (MEMORY32_MAX_PAGES * PAGE_SIZE) + PAGE_SIZE;
/// The address ranges all memories reserve, for the fault handler to recognize accesses that ran off a memory.
-static RESERVATIONS: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static RESERVATIONS: RangeSet = RangeSet::new();
+/// Whether `address` is in the reservation of a memory. Async-signal-safe, for the fault handler.
pub fn is_in_any_reservation(address: usize) -> bool {
- // The fault handler cannot block, so a contended lock means the fault is not ours to handle.
- let Ok(reservations) = RESERVATIONS.try_lock() else {
- return false;
- };
- reservations
- .iter()
- .any(|&(start, length)| address >= start && address - start < length)
+ RESERVATIONS.contains(address)
}
+/// A memory. The interpreter sees its data, which is its first field and so at its handle.
+#[repr(C)]
pub struct MemoryInstance {
- /// What the interpreter reads. Boxed, so that its address stays put for the instances that refer to it.
- pub data: Box<MemoryData>,
+ pub data: MemoryData,
pub ty: MemoryType,
reservation: *mut u8,
reservation_size: usize,
pages: u64,
maximum_pages: u64,
+ backing: Backing,
+}
+
+enum Backing {
+ Mapping,
+ PrimitiveStorage {
+ handle: u64,
+ interface: super::heap::GcInterface,
+ },
}
// The reservation is only accessed through the memory that owns it.
@@ -111,42 +117,70 @@ mod platform {
}
impl MemoryInstance {
- pub fn new(ty: MemoryType) -> Option<Self> {
- let (maximum_pages, reservation_size) = match ty.limits.address_type {
- AddressType::I32 => (
- ty.limits.max.unwrap_or(MEMORY32_MAX_PAGES).min(MEMORY32_MAX_PAGES),
- GUARDED_RESERVATION_SIZE as usize,
- ),
+ pub fn new(ty: MemoryType, heap: &super::heap::Heap) -> Option<Self> {
+ let (maximum_pages, capacity, guard_size) = match ty.limits.address_type {
+ AddressType::I32 => {
+ let maximum_pages = ty.limits.max.unwrap_or(MEMORY32_MAX_PAGES).min(MEMORY32_MAX_PAGES);
+ let capacity = maximum_pages * PAGE_SIZE;
+ (maximum_pages, capacity, GUARDED_RESERVATION_SIZE - capacity)
+ }
AddressType::I64 => {
let maximum_pages = ty.limits.max.unwrap_or(MEMORY64_MAX_PAGES).min(MEMORY64_MAX_PAGES);
// A memory that cannot grow still reserves a page, so that its base is a valid address.
- (maximum_pages, (maximum_pages.max(1) * PAGE_SIZE) as usize)
+ (maximum_pages, maximum_pages.max(1) * PAGE_SIZE, 0)
}
};
if ty.limits.min > maximum_pages {
return None;
}
- let reservation = unsafe { platform::reserve(reservation_size) };
- if reservation.is_null() {
- return None;
- }
- RESERVATIONS
- .lock()
- .expect("the reservation list is never poisoned")
- .push((reservation as usize, reservation_size));
+ let reservation_size = (capacity + guard_size) as usize;
+ let (reservation, backing) = match heap.gc() {
+ Some(gc) => {
+ let interface = gc.interface;
+ let mut handle = 0;
+ let mut layout = super::heap::PrimitiveStorageLayout::default();
+ let reserved = unsafe {
+ (interface.gc_primitive_storage_reserve)(
+ 0,
+ capacity as usize,
+ true,
+ guard_size as usize,
+ &raw mut handle,
+ &raw mut layout,
+ )
+ };
+ if !reserved {
+ return None;
+ }
+ let data = unsafe { (interface.gc_primitive_storage_data)(handle) };
+ (data, Backing::PrimitiveStorage { handle, interface })
+ }
+ None => {
+ let reservation = unsafe { platform::reserve(reservation_size) };
+ if reservation.is_null() {
+ return None;
+ }
+ (reservation, Backing::Mapping)
+ }
+ };
let mut memory = Self {
- data: Box::new(MemoryData {
+ data: MemoryData {
base: reservation,
size: 0,
address64: u64::from(ty.limits.address_type == AddressType::I64),
shared: u64::from(ty.limits.shared),
- }),
+ },
ty,
reservation,
reservation_size,
pages: 0,
maximum_pages,
+ backing,
};
+ // NB: Dropping the memory releases the reservation if anything fails from here on.
+ if !RESERVATIONS.add(reservation as usize, reservation_size) {
+ return None;
+ }
memory.grow(ty.limits.min)?;
Some(memory)
}
@@ -159,6 +193,14 @@ impl MemoryInstance {
(self.pages * PAGE_SIZE) as usize
}
+ /// The handle of the primitive storage the memory lives in, or zero if it is a plain mapping.
+ pub fn primitive_storage_handle(&self) -> u64 {
+ match &self.backing {
+ Backing::Mapping => 0,
+ Backing::PrimitiveStorage { handle, .. } => *handle,
+ }
+ }
+
pub fn maximum_pages(&self) -> u64 {
self.maximum_pages
}
@@ -171,9 +213,23 @@ impl MemoryInstance {
return None;
}
if delta != 0 {
- let start = unsafe { self.reservation.add(self.size()) };
- if !unsafe { platform::commit(start, (delta * PAGE_SIZE) as usize) } {
- return None;
+ match &self.backing {
+ Backing::Mapping => {
+ let start = unsafe { self.reservation.add(self.size()) };
+ if !unsafe { platform::commit(start, (delta * PAGE_SIZE) as usize) } {
+ return None;
+ }
+ }
+ Backing::PrimitiveStorage { handle, interface } => {
+ // Within the capacity, the storage stays where it is.
+ let new_size = (new_pages * PAGE_SIZE) as usize;
+ let resized = unsafe {
+ (interface.gc_primitive_storage_resize)(*handle, new_size, true, core::ptr::null_mut())
+ };
+ if !resized {
+ return None;
+ }
+ }
}
}
self.pages = new_pages;
@@ -192,11 +248,12 @@ impl MemoryInstance {
impl Drop for MemoryInstance {
fn drop(&mut self) {
- let start = self.reservation as usize;
- RESERVATIONS
- .lock()
- .expect("the reservation list is never poisoned")
- .retain(|&(reservation, _)| reservation != start);
- unsafe { platform::release(self.reservation, self.reservation_size) };
+ RESERVATIONS.remove(self.reservation as usize);
+ match &self.backing {
+ Backing::Mapping => unsafe { platform::release(self.reservation, self.reservation_size) },
+ Backing::PrimitiveStorage { handle, interface } => unsafe {
+ (interface.gc_primitive_storage_free)(*handle);
+ },
+ }
}
}
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index 3358eb9a763..0d4e112e780 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -4,14 +4,17 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The runtime: the store of functions, memories, tables, and globals that instances share, instantiation, and
-//! calling into the interpreter.
+//! The runtime: the store, which holds what the entities of a thread share (types, runtime types, the interpreter's
+//! context), the entities themselves (see entity.rs), instantiation, and calling into the interpreter.
pub mod constant;
+pub mod entity;
pub mod gc;
+pub mod heap;
pub mod helpers;
pub mod interpreter;
pub mod memory;
+pub mod ranges;
use crate::abi::{
EntryRecord, ExecutionContext, FRAME_HEADER_SIZE, FUNCTION_KIND_HOST, FUNCTION_KIND_WASM,
@@ -143,18 +146,12 @@ impl Trap {
}
}
-macro_rules! define_address {
- ($name:ident) => {
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
- pub struct $name(pub u32);
- };
-}
-define_address!(FunctionAddress);
-define_address!(TableAddress);
-define_address!(MemoryAddress);
-define_address!(GlobalAddress);
-define_address!(InstanceAddress);
-define_address!(TagAddress);
+pub type FunctionAddress = entity::Handle<FunctionInstance>;
+pub type TableAddress = entity::Handle<TableInstance>;
+pub type MemoryAddress = entity::Handle<MemoryInstance>;
+pub type GlobalAddress = entity::Handle<GlobalInstance>;
+pub type InstanceAddress = entity::Handle<Instance>;
+pub type TagAddress = entity::Handle<TagInstance>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExternValue {
@@ -167,21 +164,27 @@ pub enum ExternValue {
/// A tag, which exceptions are thrown with. Its address is its identity.
pub struct TagInstance {
- pub address: TagAddress,
/// The types of the values an exception with this tag carries.
pub ty: FuncType,
pub type_identity: u32,
}
-/// An exception: a tag and the values thrown with it, in operand stack order (the last value in the lowest slot).
-/// An exception reference is the address of its ExceptionInstance.
-pub struct ExceptionInstance {
- pub tag: TagAddress,
- pub payload: Box<[u64]>,
+/// A function the embedder implements.
+pub trait HostFunction {
+ /// Get the arguments and return the results, in the function type's order.
+ fn call(&self, store: &mut Store, arguments: &[Value]) -> Result<Vec<Value>, Trap>;
+
+ /// Visit the cells the function refers to, which its function keeps alive.
+ fn visit_edges(&self, _visitor: &heap::Visitor) {}
+}
+
+impl<F: Fn(&mut Store, &[Value]) -> Result<Vec<Value>, Trap>> HostFunction for F {
+ fn call(&self, store: &mut Store, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ self(store, arguments)
+ }
}
-/// A function the embedder implements. It gets the arguments and returns the results, in the function type's order.
-pub type HostCallback = Rc<dyn Fn(&mut Store, &[Value]) -> Result<Vec<Value>, Trap>>;
+pub type HostCallback = Rc<dyn HostFunction>;
pub enum FunctionKind {
Wasm {
@@ -193,32 +196,40 @@ pub enum FunctionKind {
}
/// A function. The interpreter sees its header, which is its first field, so that a function reference, which points
-/// at the header, also points at the function.
+/// at the header, is the function's handle.
#[repr(C)]
pub struct FunctionInstance {
pub header: FunctionHeader,
- pub address: FunctionAddress,
pub ty: FuncType,
/// What `header.vector_storage` points at.
pub vector_storage: Box<[u32]>,
pub kind: FunctionKind,
}
+/// A table. The interpreter sees its data, which is its first field and so at its handle.
+#[repr(C)]
pub struct TableInstance {
- pub data: Box<TableData>,
+ pub data: TableData,
pub ty: TableType,
pub elements: Vec<u64>,
+ /// How the collector follows the elements (TRACE_*).
+ pub trace: u8,
}
impl TableInstance {
- fn new(ty: TableType, initial: u64) -> Self {
+ fn new(ty: TableType, initial: u64, trace: u8) -> Self {
let mut elements = vec![initial; ty.limits.min as usize];
- let data = Box::new(TableData {
+ let data = TableData {
elements: elements.as_mut_ptr(),
size: elements.len() as u64,
address64: u64::from(ty.limits.address_type == crate::types::AddressType::I64),
- });
- Self { data, ty, elements }
+ };
+ Self {
+ data,
+ ty,
+ elements,
+ trace,
+ }
}
fn sync(&mut self) {
@@ -242,11 +253,14 @@ impl TableInstance {
/// The largest number of elements a table may grow to.
const MAX_TABLE_SIZE: u64 = 10_000_000;
+/// A global. The interpreter sees its value's slots, which are its first field and so at its handle.
#[repr(C, align(16))]
pub struct GlobalInstance {
/// The value's slots: one, or two for v128.
pub value: [u64; 2],
pub ty: GlobalType,
+ /// How the collector follows the value (TRACE_*).
+ pub trace: u8,
}
impl GlobalInstance {
@@ -261,9 +275,10 @@ impl GlobalInstance {
}
}
-/// An instance. The interpreter sees its `data`.
+/// An instance. The interpreter sees its data, which is its first field and so at its handle.
+#[repr(C)]
pub struct Instance {
- pub data: Box<InstanceData>,
+ pub data: InstanceData,
pub module: Arc<Module>,
pub functions: Vec<FunctionAddress>,
pub tables: Vec<TableAddress>,
@@ -274,6 +289,8 @@ pub struct Instance {
pub type_identities: Vec<u32>,
/// The references of each passive element segment. The interpreter sees them through `element_segments`.
pub element_storage: Vec<Vec<u64>>,
+ /// How the collector follows the references of each element segment (TRACE_*).
+ pub element_traces: Vec<u8>,
/// Each element segment, empty once dropped or used by instantiation.
pub element_segments: Vec<Segment>,
/// Each data segment, empty once dropped or used by instantiation.
@@ -300,22 +317,18 @@ pub enum InstantiationError {
/// The bytes of stack a call into WebAssembly leaves free for the runtime functions it calls.
const STACK_RESERVE: usize = 256 * 1024;
+/// What the entities of a thread share. Its heap holds the entities, which the store does not refer to: they live
+/// while their embedder, other entities, or running code refer to them, and belong to the store that made them.
pub struct Store {
context: Box<ExecutionContext>,
- pub functions: Vec<Box<FunctionInstance>>,
- pub tables: Vec<Box<TableInstance>>,
- pub memories: Vec<Box<MemoryInstance>>,
- pub globals: Vec<Box<GlobalInstance>>,
- pub instances: Vec<Box<Instance>>,
- pub tags: Vec<Box<TagInstance>>,
- /// The runtime type of each type identity, and the addresses the interpreter sees them by.
- #[allow(clippy::vec_box)] // The interpreter holds the addresses of the Rtts, which must not move.
- rtts: Vec<Box<gc::RttStorage>>,
+ /// Where entities, GC objects, exceptions, runtime types, and memories live.
+ pub heap: heap::Heap,
+ /// The cell through which the heap traces the runtime types, which the store keeps for as long as it lives.
+ pub(crate) root_cell: *mut u8,
+ /// The root that keeps `root_cell` alive.
+ root: Option<*mut core::ffi::c_void>,
+ /// The runtime type of each type identity, in the cells the heap keeps them in.
rtt_pointers: Vec<*const crate::abi::Rtt>,
- // FIXME: Collect objects nothing refers to anymore.
- objects: Vec<Box<[u64]>>,
- // FIXME: Collect exceptions nothing refers to anymore.
- pub exceptions: Vec<Box<ExceptionInstance>>,
canonicalizer: TypeCanonicalizer,
/// The type of each store-wide type identity, with its type indices replaced by identities, so that types of
/// different modules can be compared.
@@ -324,6 +337,8 @@ pub struct Store {
identities: Vec<u32>,
/// A trap a runtime function reported, which the interpreter only knows as TRAP_RUNTIME.
pending_trap: Option<Trap>,
+ /// What runs after `memory.grow` grows a memory.
+ pub memory_grow_callback: Option<Rc<dyn Fn(MemoryAddress)>>,
}
impl Default for Store {
@@ -332,8 +347,27 @@ impl Default for Store {
}
}
+impl Drop for Store {
+ fn drop(&mut self) {
+ if !self.root_cell.is_null() {
+ gc::detach_store_root(self.root_cell);
+ }
+ if let (Some(root), Some(heap)) = (self.root.take(), self.heap.gc()) {
+ heap.unroot(root);
+ }
+ self.heap.drop_standalone_entities();
+ }
+}
+
impl Store {
+ /// A store whose GC objects and memories are plain allocations that are never freed.
pub fn new() -> Self {
+ Self::with_heap(None)
+ }
+
+ /// A store whose entities and GC objects live in the heap of `interface`, and whose memories live in its
+ /// primitive storage. The store must stay where it is once `attach_to_heap()` gives it a root cell.
+ pub fn with_heap(interface: Option<heap::GcInterface>) -> Self {
interpreter::check_cpu_features();
interpreter::install_fault_handler();
Self {
@@ -345,53 +379,60 @@ impl Store {
arguments: [0; 6],
rtts: std::ptr::null(),
}),
- functions: Vec::new(),
- tables: Vec::new(),
- memories: Vec::new(),
- globals: Vec::new(),
- instances: Vec::new(),
canonicalizer: TypeCanonicalizer::new(),
types: Vec::new(),
identities: Vec::new(),
pending_trap: None,
- tags: Vec::new(),
- exceptions: Vec::new(),
- rtts: Vec::new(),
+ heap: heap::Heap::new(interface, &gc::CELL_FUNCTIONS),
+ root_cell: std::ptr::null_mut(),
+ root: None,
rtt_pointers: Vec::new(),
- objects: Vec::new(),
+ memory_grow_callback: None,
}
}
+ /// Have the heap keep the runtime types for as long as the store lives. The store must not move after this.
+ pub fn attach_to_heap(&mut self) {
+ let Some(heap) = self.heap.gc() else {
+ return;
+ };
+ self.root_cell = gc::allocate_store_root(&self.heap, self);
+ self.root = Some(heap.root(self.root_cell));
+ }
+
+ // NB: The accessors below trust that the entity lives, which its embedder, or the instance it belongs to,
+ // guarantees while it uses it.
+
pub fn function(&self, address: FunctionAddress) -> &FunctionInstance {
- &self.functions[address.0 as usize]
+ unsafe { address.get() }
}
pub fn memory(&self, address: MemoryAddress) -> &MemoryInstance {
- &self.memories[address.0 as usize]
+ unsafe { address.get() }
}
pub fn memory_mut(&mut self, address: MemoryAddress) -> &mut MemoryInstance {
- &mut self.memories[address.0 as usize]
+ unsafe { address.get_mut() }
}
pub fn table(&self, address: TableAddress) -> &TableInstance {
- &self.tables[address.0 as usize]
+ unsafe { address.get() }
}
pub fn table_mut(&mut self, address: TableAddress) -> &mut TableInstance {
- &mut self.tables[address.0 as usize]
+ unsafe { address.get_mut() }
}
pub fn global(&self, address: GlobalAddress) -> &GlobalInstance {
- &self.globals[address.0 as usize]
+ unsafe { address.get() }
}
pub fn global_mut(&mut self, address: GlobalAddress) -> &mut GlobalInstance {
- &mut self.globals[address.0 as usize]
+ unsafe { address.get_mut() }
}
pub fn instance(&self, address: InstanceAddress) -> &Instance {
- &self.instances[address.0 as usize]
+ unsafe { address.get() }
}
/// The store-wide identity of a function type that is not part of a recursion group.
@@ -417,13 +458,15 @@ impl Store {
{
return;
}
+ let first = self.types.len() as u32;
for sub_type in group {
- let identity = self.types.len() as u32;
- self.identities.push(identity);
+ self.identities.push(self.types.len() as u32);
self.types.push(sub_type.clone());
- let rtt = gc::RttStorage::new(self, identity);
- self.rtt_pointers.push(&raw const rtt.rtt);
- self.rtts.push(rtt);
+ }
+ // Types of a group refer to each other, so they all have to be there before their runtime types are made.
+ for identity in first..self.types.len() as u32 {
+ let rtt = gc::allocate_rtt(self, identity);
+ self.rtt_pointers.push(rtt);
}
self.context.rtts = self.rtt_pointers.as_ptr();
}
@@ -437,51 +480,57 @@ impl Store {
}
pub fn allocate_host_function(&mut self, ty: FuncType, callback: HostCallback) -> FunctionAddress {
- let address = FunctionAddress(self.functions.len() as u32);
let type_identity = self.identity_of_function_type(&ty);
- let mut function = Box::new(FunctionInstance {
- header: FunctionHeader {
- code: std::ptr::null(),
- code_end: std::ptr::null(),
- side_table: std::ptr::null(),
- instance: std::ptr::null(),
- kind: FUNCTION_KIND_HOST,
- param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
- result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
- local_count: 0,
- locals_size: 0,
- reserved: 0,
- frame_size: 0,
- type_identity,
- host: std::ptr::null(),
- vector_storage: std::ptr::null(),
+ let function = entity::allocate(
+ &self.heap,
+ FunctionInstance {
+ header: FunctionHeader {
+ code: std::ptr::null(),
+ code_end: std::ptr::null(),
+ side_table: std::ptr::null(),
+ instance: std::ptr::null(),
+ kind: FUNCTION_KIND_HOST,
+ param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
+ result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
+ local_count: 0,
+ locals_size: 0,
+ reserved: 0,
+ frame_size: 0,
+ type_identity,
+ host: std::ptr::null(),
+ vector_storage: std::ptr::null(),
+ },
+ ty,
+ vector_storage: Box::new([]),
+ kind: FunctionKind::Host(callback),
},
- address,
- ty,
- vector_storage: Box::new([]),
- kind: FunctionKind::Host(callback),
- });
- function.header.host = (&raw const *function).cast();
- self.functions.push(function);
- address
+ );
+ unsafe { function.get_mut() }.header.host = function.as_ptr().cast_const().cast();
+ function
}
pub fn allocate_memory(&mut self, ty: crate::types::MemoryType) -> Option<MemoryAddress> {
- let memory = MemoryInstance::new(ty)?;
- self.memories.push(Box::new(memory));
- Some(MemoryAddress(self.memories.len() as u32 - 1))
+ let memory = MemoryInstance::new(ty, &self.heap)?;
+ Some(entity::allocate(&self.heap, memory))
}
- pub fn allocate_table(&mut self, ty: TableType, initial: u64) -> TableAddress {
- self.tables.push(Box::new(TableInstance::new(ty, initial)));
- TableAddress(self.tables.len() as u32 - 1)
+ /// Add a table of `ty.limits.min` elements set to `initial`. Returns None if it would be too large.
+ pub fn allocate_table(&mut self, ty: TableType, initial: u64) -> Option<TableAddress> {
+ if ty.limits.min > MAX_TABLE_SIZE {
+ return None;
+ }
+ let trace = gc::trace_of(ValType::Ref(ty.element), &self.types);
+ Some(entity::allocate(&self.heap, TableInstance::new(ty, initial, trace)))
}
pub fn allocate_global(&mut self, ty: GlobalType, value: Value) -> GlobalAddress {
- let mut global = Box::new(GlobalInstance { value: [0; 2], ty });
+ let mut global = GlobalInstance {
+ value: [0; 2],
+ ty,
+ trace: gc::trace_of(ty.value, &self.types),
+ };
global.set(value);
- self.globals.push(global);
- GlobalAddress(self.globals.len() as u32 - 1)
+ entity::allocate(&self.heap, global)
}
pub fn instantiate(
@@ -489,6 +538,23 @@ impl Store {
module: Arc<Module>,
imports: &[ExternValue],
) -> Result<InstanceAddress, InstantiationError> {
+ // Instantiation keeps references in places the collector does not look, like the values of constant
+ // expressions on their way into globals and segments. The start function runs once they are in place.
+ self.heap.defer_gc();
+ let instance = self.instantiate_without_starting(module, imports);
+ self.heap.undefer_gc();
+ let (instance, start) = instance?;
+ if let Some(start) = start {
+ self.invoke(start, &[]).map_err(InstantiationError::Trap)?;
+ }
+ Ok(instance)
+ }
+
+ fn instantiate_without_starting(
+ &mut self,
+ module: Arc<Module>,
+ imports: &[ExternValue],
+ ) -> Result<(InstanceAddress, Option<FunctionAddress>), InstantiationError> {
let link_error = |message: &str| Err(InstantiationError::Link(message.to_string()));
if imports.len() != module.imports.len() {
return link_error("wrong number of imports");
@@ -578,46 +644,50 @@ impl Store {
}
// The instance is allocated before its contents, so that its functions can point at its data.
- let instance_address = InstanceAddress(self.instances.len() as u32);
- let mut instance = Box::new(Instance {
- data: Box::new(InstanceData {
- memory0_base: std::ptr::null_mut(),
- memories: std::ptr::null(),
- globals: std::ptr::null(),
- functions: std::ptr::null(),
- tables: std::ptr::null(),
- type_identities: std::ptr::null(),
- data_segments: std::ptr::null(),
- element_segments: std::ptr::null(),
- tags: std::ptr::null(),
- function_count: 0,
- memory_count: 0,
- }),
- module: module.clone(),
- functions: Vec::new(),
- tables: Vec::new(),
- memories: Vec::new(),
- globals: Vec::new(),
- exports: HashMap::new(),
- type_identities,
- element_storage: Vec::new(),
- element_segments: Vec::new(),
- data_segments: module
- .data
- .iter()
- .map(|data| Segment {
- contents: module.bytes.as_ptr().wrapping_add(data.bytes.start as usize),
- length: u64::from(data.bytes.end - data.bytes.start),
- })
- .collect(),
- function_headers: Vec::new(),
- global_slots: Vec::new(),
- tags: Vec::new(),
- tag_identities: Vec::new(),
- table_datas: Vec::new(),
- memory_datas: Vec::new(),
- });
- let instance_data: *const InstanceData = &raw const *instance.data;
+ let instance_address = entity::allocate(
+ &self.heap,
+ Instance {
+ data: InstanceData {
+ memory0_base: std::ptr::null_mut(),
+ memories: std::ptr::null(),
+ globals: std::ptr::null(),
+ functions: std::ptr::null(),
+ tables: std::ptr::null(),
+ type_identities: std::ptr::null(),
+ data_segments: std::ptr::null(),
+ element_segments: std::ptr::null(),
+ tags: std::ptr::null(),
+ function_count: 0,
+ memory_count: 0,
+ },
+ module: module.clone(),
+ functions: Vec::new(),
+ tables: Vec::new(),
+ memories: Vec::new(),
+ globals: Vec::new(),
+ exports: HashMap::new(),
+ type_identities,
+ element_storage: Vec::new(),
+ element_traces: Vec::new(),
+ element_segments: Vec::new(),
+ data_segments: module
+ .data
+ .iter()
+ .map(|data| Segment {
+ contents: module.bytes.as_ptr().wrapping_add(data.bytes.start as usize),
+ length: u64::from(data.bytes.end - data.bytes.start),
+ })
+ .collect(),
+ function_headers: Vec::new(),
+ global_slots: Vec::new(),
+ tags: Vec::new(),
+ tag_identities: Vec::new(),
+ table_datas: Vec::new(),
+ memory_datas: Vec::new(),
+ },
+ );
+ let instance = unsafe { instance_address.get_mut() };
+ let instance_data: *const InstanceData = instance_address.as_ptr().cast_const().cast();
for (offset, &type_index) in module.functions.iter().enumerate() {
let info = &module.function_infos[offset];
@@ -652,51 +722,47 @@ impl Store {
let vector_storage = vector_storage.into_boxed_slice();
let frame_size =
(FRAME_HEADER_SIZE as u32 + info.max_stack_slots * 8 + SPILL_AREA_SIZE as u32).next_multiple_of(16);
- let address = FunctionAddress(self.functions.len() as u32);
let code = module.bytes.as_ptr().wrapping_add(body.code.start as usize);
let code_end = module.bytes.as_ptr().wrapping_add(body.code.end as usize - 1);
- self.functions.push(Box::new(FunctionInstance {
- header: FunctionHeader {
- code,
- code_end,
- side_table: info.side_table.as_ptr().cast(),
- instance: instance_data,
- kind: if has_v128_locals {
- FUNCTION_KIND_WASM_VECTOR
- } else {
- FUNCTION_KIND_WASM
+ let address = entity::allocate(
+ &self.heap,
+ FunctionInstance {
+ header: FunctionHeader {
+ code,
+ code_end,
+ side_table: info.side_table.as_ptr().cast(),
+ instance: instance_data,
+ kind: if has_v128_locals {
+ FUNCTION_KIND_WASM_VECTOR
+ } else {
+ FUNCTION_KIND_WASM
+ },
+ param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
+ result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
+ local_count,
+ locals_size,
+ reserved: 0,
+ frame_size,
+ type_identity: instance.type_identities[type_index as usize],
+ host: std::ptr::null(),
+ vector_storage: if has_v128_locals {
+ vector_storage.as_ptr()
+ } else {
+ std::ptr::null()
+ },
},
- param_slots: ty.params.iter().map(|param| param.slot_count()).sum(),
- result_slots: ty.results.iter().map(|result| result.slot_count()).sum(),
- local_count,
- locals_size,
- reserved: 0,
- frame_size,
- type_identity: instance.type_identities[type_index as usize],
- host: std::ptr::null(),
- vector_storage: if has_v128_locals {
- vector_storage.as_ptr()
- } else {
- std::ptr::null()
+ ty,
+ vector_storage,
+ kind: FunctionKind::Wasm {
+ module: module.clone(),
+ index: module.imported_function_count + offset as u32,
+ instance: instance_address,
},
},
- address,
- ty,
- vector_storage,
- kind: FunctionKind::Wasm {
- module: module.clone(),
- index: module.imported_function_count + offset as u32,
- instance: instance_address,
- },
- }));
+ );
functions.push(address);
}
instance.functions = functions;
- instance.function_headers = instance
- .functions
- .iter()
- .map(|address| &raw const self.function(*address).header)
- .collect();
for memory in &module.memories {
let address = self
@@ -747,7 +813,10 @@ impl Store {
let ValType::Ref(element) = canonical(ValType::Ref(table.ty.element)) else {
unreachable!("table elements are references");
};
- tables.push(self.allocate_table(TableType { element, ..table.ty }, initial));
+ let address = self
+ .allocate_table(TableType { element, ..table.ty }, initial)
+ .ok_or_else(|| InstantiationError::Link("cannot allocate table".to_string()))?;
+ tables.push(address);
}
instance.tables = tables;
for tag in &module.tags {
@@ -759,7 +828,7 @@ impl Store {
tags.push(self.allocate_tag_with_identity(ty, type_identity));
}
instance.tags = tags;
- self.refresh_instance_data(&mut instance);
+ refresh_instance_data(instance);
for export in &module.exports {
let value = match export.kind {
@@ -803,6 +872,14 @@ impl Store {
element_values.push(values);
}
instance.element_storage = element_values;
+ instance.element_traces = module
+ .elements
+ .iter()
+ .map(|element| {
+ let ty = ValType::Ref(element.ty).map_type_indices(&|index| instance.type_identities[index as usize]);
+ gc::trace_of(ty, &self.types)
+ })
+ .collect();
instance.element_segments = instance
.element_storage
.iter()
@@ -818,14 +895,13 @@ impl Store {
.collect();
instance.data.element_segments = instance.element_segments.as_ptr();
instance.data.data_segments = instance.data_segments.as_ptr();
- self.instances.push(instance);
- let instance_index = instance_address.0 as usize;
for (index, element) in module.elements.iter().enumerate() {
if let ElementMode::Active { table, offset } = &element.mode {
- let offset = self.evaluate_offset(instance_index, &module, offset)?;
- let table_address = self.instances[instance_index].tables[*table as usize];
- let values = std::mem::take(&mut self.instances[instance_index].element_storage[index]);
+ let offset = self.evaluate_offset(instance_address, &module, offset)?;
+ let instance = unsafe { instance_address.get_mut() };
+ let table_address = instance.tables[*table as usize];
+ let values = std::mem::take(&mut instance.element_storage[index]);
let table = self.table_mut(table_address);
let end = offset.checked_add(values.len() as u64);
if end.is_none_or(|end| end > table.elements.len() as u64) {
@@ -837,8 +913,8 @@ impl Store {
for (index, data) in module.data.iter().enumerate() {
if let DataMode::Active { memory, offset } = &data.mode {
- let offset = self.evaluate_offset(instance_index, &module, offset)?;
- let memory_address = self.instances[instance_index].memories[*memory as usize];
+ let offset = self.evaluate_offset(instance_address, &module, offset)?;
+ let memory_address = self.instance(instance_address).memories[*memory as usize];
let bytes = module.bytes_of(&data.bytes);
let memory = self.memory_mut(memory_address);
let end = offset.checked_add(bytes.len() as u64);
@@ -846,24 +922,23 @@ impl Store {
return Err(InstantiationError::Trap(Trap::MemoryOutOfBounds));
}
memory.bytes_mut()[offset as usize..offset as usize + bytes.len()].copy_from_slice(bytes);
- self.instances[instance_index].data_segments[index].length = 0;
+ unsafe { instance_address.get_mut() }.data_segments[index].length = 0;
}
}
- if let Some(start) = module.start {
- let function = self.instances[instance_index].functions[start as usize];
- self.invoke(function, &[]).map_err(InstantiationError::Trap)?;
- }
- Ok(instance_address)
+ let start = module
+ .start
+ .map(|start| self.instance(instance_address).functions[start as usize]);
+ Ok((instance_address, start))
}
fn evaluate_offset(
&mut self,
- instance_index: usize,
+ instance: InstanceAddress,
module: &Module,
expression: &crate::module::ConstantExpression,
) -> Result<u64, InstantiationError> {
- let instance = &self.instances[instance_index];
+ let instance = unsafe { instance.get() };
let (globals, functions, type_identities) = (
instance.globals.clone(),
instance.functions.clone(),
@@ -878,50 +953,8 @@ impl Store {
}
}
- /// Point the instance's interpreter-visible data at its current contents.
- fn refresh_instance_data(&self, instance: &mut Instance) {
- instance.function_headers = instance
- .functions
- .iter()
- .map(|address| &raw const self.function(*address).header)
- .collect();
- instance.global_slots = instance
- .globals
- .iter()
- .map(|address| self.globals[address.0 as usize].value.as_ptr().cast_mut())
- .collect();
- instance.table_datas = instance
- .tables
- .iter()
- .map(|address| (&raw const *self.tables[address.0 as usize].data).cast_mut())
- .collect();
- instance.memory_datas = instance
- .memories
- .iter()
- .map(|address| (&raw const *self.memories[address.0 as usize].data).cast_mut())
- .collect();
- let data = &mut instance.data;
- data.functions = instance.function_headers.as_ptr();
- data.function_count = instance.function_headers.len() as u32;
- data.globals = instance.global_slots.as_ptr();
- data.tables = instance.table_datas.as_ptr();
- data.memories = instance.memory_datas.as_ptr();
- data.memory_count = instance.memory_datas.len() as u32;
- data.memory0_base = instance
- .memories
- .first()
- .map_or(std::ptr::null_mut(), |address| self.memory(*address).data.base);
- data.type_identities = instance.type_identities.as_ptr();
- instance.tag_identities = instance
- .tags
- .iter()
- .map(|address| (&raw const *self.tags[address.0 as usize]) as u64)
- .collect();
- instance.data.tags = instance.tag_identities.as_ptr();
- }
-
pub fn tag(&self, address: TagAddress) -> &TagInstance {
- &self.tags[address.0 as usize]
+ unsafe { address.get() }
}
/// Add a tag for exceptions that carry values of the parameter types of `ty`.
@@ -931,44 +964,47 @@ impl Store {
}
fn allocate_tag_with_identity(&mut self, ty: FuncType, type_identity: u32) -> TagAddress {
- let address = TagAddress(self.tags.len() as u32);
- self.tags.push(Box::new(TagInstance {
- address,
- ty,
- type_identity,
- }));
- address
+ entity::allocate(&self.heap, TagInstance { ty, type_identity })
}
- /// The tag of an exception reference's identity.
- pub fn tag_from_identity(&self, identity: u64) -> TagAddress {
- unsafe { (*(identity as *const TagInstance)).address }
+ /// Allocate an exception with the tag `tag` that carries `values`, one for each parameter of the tag's type.
+ pub fn allocate_exception_with_values(&mut self, tag: TagAddress, values: &[Value]) -> u64 {
+ // An exception's slots are in operand stack order, the last value first.
+ let mut payload = Vec::new();
+ for value in values.iter().rev() {
+ value.push_slots(&mut payload);
+ }
+ self.allocate_exception(tag, &payload)
}
- /// Make an exception with `tag` and the values of `payload`, and return its reference.
- pub fn allocate_exception(&mut self, tag: TagAddress, payload: Box<[u64]>) -> u64 {
- let exception = Box::new(ExceptionInstance { tag, payload });
- let reference = (&raw const *exception) as u64;
- self.exceptions.push(exception);
- reference
+ /// The values an exception carries, one for each parameter of its tag's type.
+ pub fn exception_values(&self, reference: u64) -> Vec<Value> {
+ let exception = self.exception(reference);
+ let params = &self.tag(exception.tag).ty.params;
+ let mut values = Vec::with_capacity(params.len());
+ let mut slot = exception.payload.len();
+ for &param in params {
+ slot -= param.slot_count() as usize;
+ values.push(Value::from_slots(param, &exception.payload[slot..]));
+ }
+ values
}
- /// The exception an exception reference refers to.
- pub fn exception(&self, reference: u64) -> &ExceptionInstance {
- unsafe { &*(reference as *const ExceptionInstance) }
+ /// The tag of a tag identity, which is the tag's handle.
+ pub fn tag_from_identity(&self, identity: u64) -> TagAddress {
+ unsafe { TagAddress::from_ptr(identity as *const TagInstance) }
}
pub fn function_reference(&self, address: FunctionAddress) -> u64 {
- (&raw const self.function(address).header) as u64
+ address.as_ptr() as u64
}
- /// The function a non-null function reference refers to.
+ /// The function a function reference refers to, which is the function's handle.
pub fn function_from_reference(&self, reference: u64) -> Option<FunctionAddress> {
if reference == 0 {
return None;
}
- let function = unsafe { &*(reference as *const FunctionInstance) };
- Some(function.address)
+ Some(unsafe { FunctionAddress::from_ptr(reference as *const FunctionInstance) })
}
pub fn invoke(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
@@ -1014,14 +1050,45 @@ impl Store {
}
fn call_host(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
- let FunctionKind::Host(callback) = &self.functions[address.0 as usize].kind else {
+ let FunctionKind::Host(callback) = &self.function(address).kind else {
unreachable!("only host functions are called through call_host")
};
let callback = callback.clone();
- callback(self, arguments)
+ callback.call(self, arguments)
}
}
+/// Point the instance's interpreter-visible data at its current contents. The interpreter's view of each entity is at
+/// its handle.
+fn refresh_instance_data(instance: &mut Instance) {
+ instance.function_headers = instance
+ .functions
+ .iter()
+ .map(|address| address.as_ptr().cast_const().cast::<FunctionHeader>())
+ .collect();
+ instance.global_slots = instance.globals.iter().map(|address| address.as_ptr().cast()).collect();
+ instance.table_datas = instance.tables.iter().map(|address| address.as_ptr().cast()).collect();
+ instance.memory_datas = instance
+ .memories
+ .iter()
+ .map(|address| address.as_ptr().cast())
+ .collect();
+ let data = &mut instance.data;
+ data.functions = instance.function_headers.as_ptr();
+ data.function_count = instance.function_headers.len() as u32;
+ data.globals = instance.global_slots.as_ptr();
+ data.tables = instance.table_datas.as_ptr();
+ data.memories = instance.memory_datas.as_ptr();
+ data.memory_count = instance.memory_datas.len() as u32;
+ data.memory0_base = instance
+ .memories
+ .first()
+ .map_or(std::ptr::null_mut(), |address| unsafe { address.get() }.data.base);
+ data.type_identities = instance.type_identities.as_ptr();
+ instance.tag_identities = instance.tags.iter().map(|address| address.as_ptr() as u64).collect();
+ instance.data.tags = instance.tag_identities.as_ptr();
+}
+
fn limits_match(current: u64, current_max: Option<u64>, expected: &crate::types::Limits) -> bool {
if current < expected.min {
return false;
diff --git a/Libraries/LibWasm/Engine/src/runtime/ranges.rs b/Libraries/LibWasm/Engine/src/runtime/ranges.rs
new file mode 100644
index 00000000000..399034a35f4
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/runtime/ranges.rs
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Sets of address ranges that the fault handler looks addresses up in: the reservations of memories, and later the
+//! code of compiled functions. A lookup takes no lock and touches only a fixed static array, so it is async-signal-safe
+//! and cannot be blocked by a thread that is adding or removing a range. Adding and removing take a lock among
+//! themselves.
+//!
+//! Each slot is a seqlock: its writer makes the sequence odd, writes the range, and makes the sequence even again. A
+//! lookup that sees an odd sequence, or a sequence that changed while it read the range, skips the slot. That is safe
+//! because a range is only added before anything accesses it and removed after nothing can, so no fault that the
+//! handler must recognize lands in a range that is changing.
+
+use std::sync::Mutex;
+use std::sync::atomic::{AtomicUsize, Ordering, fence};
+
+/// The most ranges a set holds.
+pub const CAPACITY: usize = 4096;
+
+struct Slot {
+ sequence: AtomicUsize,
+ start: AtomicUsize,
+ end: AtomicUsize,
+}
+
+pub struct RangeSet {
+ slots: [Slot; CAPACITY],
+ /// Serializes the writers.
+ lock: Mutex<()>,
+}
+
+impl RangeSet {
+ pub const fn new() -> Self {
+ Self {
+ slots: [const {
+ Slot {
+ sequence: AtomicUsize::new(0),
+ start: AtomicUsize::new(0),
+ end: AtomicUsize::new(0),
+ }
+ }; CAPACITY],
+ lock: Mutex::new(()),
+ }
+ }
+
+ fn write(slot: &Slot, start: usize, end: usize) {
+ let sequence = slot.sequence.load(Ordering::Relaxed);
+ slot.sequence.store(sequence.wrapping_add(1), Ordering::Relaxed);
+ fence(Ordering::Release);
+ slot.start.store(start, Ordering::Relaxed);
+ slot.end.store(end, Ordering::Relaxed);
+ slot.sequence.store(sequence.wrapping_add(2), Ordering::Release);
+ }
+
+ /// Add the range [start, start + length). Returns false if the set is full.
+ pub fn add(&self, start: usize, length: usize) -> bool {
+ assert!(start != 0 && length != 0, "ranges are not empty and not at null");
+ let _guard = self.lock.lock().expect("the range lock is never poisoned");
+ let Some(slot) = self.slots.iter().find(|slot| slot.end.load(Ordering::Relaxed) == 0) else {
+ return false;
+ };
+ Self::write(slot, start, start + length);
+ true
+ }
+
+ /// Remove the range that starts at `start`.
+ pub fn remove(&self, start: usize) {
+ let _guard = self.lock.lock().expect("the range lock is never poisoned");
+ if let Some(slot) = self
+ .slots
+ .iter()
+ .find(|slot| slot.end.load(Ordering::Relaxed) != 0 && slot.start.load(Ordering::Relaxed) == start)
+ {
+ Self::write(slot, 0, 0);
+ }
+ }
+
+ /// Whether `address` is in one of the ranges. Async-signal-safe.
+ pub fn contains(&self, address: usize) -> bool {
+ self.slots.iter().any(|slot| {
+ let before = slot.sequence.load(Ordering::Acquire);
+ if before & 1 != 0 {
+ return false;
+ }
+ let start = slot.start.load(Ordering::Relaxed);
+ let end = slot.end.load(Ordering::Relaxed);
+ fence(Ordering::Acquire);
+ let after = slot.sequence.load(Ordering::Relaxed);
+ before == after && start <= address && address < end
+ })
+ }
+}
+
+impl Default for RangeSet {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::RangeSet;
+
+ #[test]
+ fn adds_finds_and_removes_ranges() {
+ let set = RangeSet::new();
+ assert!(set.add(0x1000, 0x100));
+ assert!(set.add(0x4000, 0x10));
+ assert!(set.contains(0x1000) && set.contains(0x10ff) && set.contains(0x400f));
+ assert!(!set.contains(0x1100) && !set.contains(0xfff) && !set.contains(0x4010));
+ set.remove(0x1000);
+ assert!(!set.contains(0x1000) && set.contains(0x4000));
+ }
+}
diff --git a/Libraries/LibWasm/Engine/src/validator.rs b/Libraries/LibWasm/Engine/src/validator.rs
index 046cb85ef38..80366dd4f9d 100644
--- a/Libraries/LibWasm/Engine/src/validator.rs
+++ b/Libraries/LibWasm/Engine/src/validator.rs
@@ -645,7 +645,11 @@ impl FunctionValidator<'_> {
let opcode = self.module.bytes[self.instruction_start as usize];
let is_core_access = (crate::opcode::I32_LOAD..=crate::opcode::I64_STORE32).contains(&opcode);
self.checked_access = None;
- if memory != 0 || address_type == AddressType::I64 {
+ // The plain handlers only decode `align offset` with a one-byte alignment, for memory 0 as a memory32 (see
+ // rule 1 in quickening.rs). Every other encoding, even of the same access, becomes a checked access.
+ let is_plain =
+ memory_bytes.is_none() && alignment_end - alignment_start == 1 && address_type == AddressType::I32;
+ if !is_plain {
if is_core_access {
self.rewrites.push(crate::quickening::checked_access(
&self.module.bytes,
@@ -1081,13 +1085,23 @@ impl FunctionValidator<'_> {
let address_type = self.memory_address_type(reader.read_u32()?)?;
self.unary(address_type.value_type(), address_type.value_type())?;
}
- opcode::I32_CONST => {
- reader.read_i32()?;
- self.push_value(I32);
- }
- opcode::I64_CONST => {
- reader.read_i64()?;
- self.push_value(I64);
+ opcode::I32_CONST | opcode::I64_CONST => {
+ let start = reader.position();
+ let is_i64 = opcode == opcode::I64_CONST;
+ let value = if is_i64 {
+ reader.read_i64()?
+ } else {
+ i64::from(reader.read_i32()?)
+ };
+ if let Some(rewrite) = crate::quickening::fixed_constant(
+ self.instruction_start as usize,
+ reader.position() - start,
+ value,
+ is_i64,
+ ) {
+ self.rewrites.push(rewrite);
+ }
+ self.push_value(if is_i64 { I64 } else { I32 });
}
opcode::F32_CONST => {
reader.read_bytes(4)?;
diff --git a/Libraries/LibWasm/Engine/src/wasi.rs b/Libraries/LibWasm/Engine/src/wasi.rs
new file mode 100644
index 00000000000..9c8bbd33520
--- /dev/null
+++ b/Libraries/LibWasm/Engine/src/wasi.rs
@@ -0,0 +1,765 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The `wasi_snapshot_preview1` interface, for running WASI commands outside of a browser. Its functions are host
+//! functions of a store, which work on the memory `set_memory()` names, and only exist on Unix hosts.
+
+use crate::runtime::{FunctionAddress, MemoryAddress, Store, Trap, Value};
+use crate::types::{FuncType, ValType};
+use std::cell::{Cell, RefCell};
+use std::collections::HashMap;
+use std::rc::Rc;
+
+/// The name of the module WASI functions are imported from.
+pub const MODULE_NAME: &str = "wasi_snapshot_preview1";
+
+/// A host directory that the guest sees at `guest_path`.
+pub struct Preopen {
+ pub host_path: String,
+ pub guest_path: String,
+ /// The host descriptor of the directory, once something has opened it.
+ host_fd: Cell<Option<i32>>,
+}
+
+impl Preopen {
+ pub fn new(host_path: String, guest_path: String) -> Self {
+ Self {
+ host_path,
+ guest_path,
+ host_fd: Cell::new(None),
+ }
+ }
+}
+
+/// The state of a WASI command: its arguments, environment, descriptors, and how it exited.
+pub struct Wasi {
+ arguments: Vec<String>,
+ environment: Vec<String>,
+ /// The preopened directories, which are the guest's descriptors from 3 up.
+ preopens: Vec<Preopen>,
+ /// The guest descriptors path_open created, and the host descriptors they are.
+ files: RefCell<HashMap<u32, i32>>,
+ next_fd: Cell<u32>,
+ memory: Cell<Option<MemoryAddress>>,
+ exit_code: Cell<Option<i32>>,
+}
+
+/// A WASI errno value.
+type Errno = u16;
+
+const ERRNO_SUCCESS: Errno = 0;
+const ERRNO_BADF: Errno = 8;
+const ERRNO_FAULT: Errno = 21;
+// NB: Only the Unix implementation maps host errors.
+#[cfg_attr(not(unix), allow(dead_code))]
+const ERRNO_INVAL: Errno = 28;
+#[cfg_attr(not(unix), allow(dead_code))]
+const ERRNO_IO: Errno = 29;
+const ERRNO_ISDIR: Errno = 31;
+const ERRNO_NOSYS: Errno = 52;
+
+/// What a guest descriptor refers to.
+enum Descriptor {
+ Host(i32),
+ Preopen(usize),
+}
+
+impl Wasi {
+ pub fn new(arguments: Vec<String>, environment: Vec<String>, preopens: Vec<Preopen>) -> Self {
+ let next_fd = 3 + preopens.len() as u32;
+ Self {
+ arguments,
+ environment,
+ preopens,
+ files: RefCell::new(HashMap::new()),
+ next_fd: Cell::new(next_fd),
+ memory: Cell::new(None),
+ exit_code: Cell::new(None),
+ }
+ }
+
+ /// Have the functions work on `memory`, which is usually the memory the command exports.
+ pub fn set_memory(&self, memory: MemoryAddress) {
+ self.memory.set(Some(memory));
+ }
+
+ /// The code the command passed to proc_exit, if it called it.
+ pub fn exit_code(&self) -> Option<i32> {
+ self.exit_code.get()
+ }
+
+ /// Add the WASI function `name` to `store`. Returns None if there is no such function.
+ pub fn allocate_function(self: &Rc<Self>, store: &mut Store, name: &str) -> Option<FunctionAddress> {
+ let &(_, signature) = FUNCTIONS.iter().find(|(function, _)| *function == name)?;
+ let (parameters, result) = signature.split_once('>').unwrap_or((signature, ""));
+ let to_types = |text: &str| -> Vec<ValType> {
+ text.chars()
+ .map(|character| if character == 'I' { ValType::I64 } else { ValType::I32 })
+ .collect()
+ };
+ let ty = FuncType {
+ params: to_types(parameters),
+ results: to_types(result),
+ };
+ let wasi = self.clone();
+ let name = name.to_string();
+ Some(store.allocate_host_function(
+ ty,
+ Rc::new(move |store: &mut Store, arguments: &[Value]| wasi.call(store, &name, arguments)),
+ ))
+ }
+
+ fn call(&self, store: &mut Store, name: &str, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ let argument = |index: usize| -> u64 {
+ match arguments[index] {
+ Value::I32(value) => u64::from(value as u32),
+ Value::I64(value) => value as u64,
+ _ => 0,
+ }
+ };
+ if name == "proc_exit" {
+ let code = argument(0) as u32 as i32;
+ self.exit_code.set(Some(code));
+ return Err(Trap::Host(format!("exit:{code}")));
+ }
+ let Some(memory) = self.memory.get() else {
+ return Ok(vec![Value::I32(i32::from(ERRNO_FAULT))]);
+ };
+ let mut memory = Memory(store.memory_mut(memory).bytes_mut());
+ let errno = match self.dispatch(&mut memory, name, &argument) {
+ Ok(()) => ERRNO_SUCCESS,
+ Err(errno) => errno,
+ };
+ Ok(vec![Value::I32(i32::from(errno))])
+ }
+
+ fn descriptor(&self, fd: u32) -> Option<Descriptor> {
+ if fd <= 2 {
+ return Some(Descriptor::Host(fd as i32));
+ }
+ let preopen = (fd - 3) as usize;
+ if preopen < self.preopens.len() {
+ return Some(Descriptor::Preopen(preopen));
+ }
+ self.files.borrow().get(&fd).map(|&host_fd| Descriptor::Host(host_fd))
+ }
+
+ fn host_fd(&self, fd: u32) -> Result<i32, Errno> {
+ match self.descriptor(fd) {
+ Some(Descriptor::Host(host_fd)) => Ok(host_fd),
+ Some(Descriptor::Preopen(index)) => self.preopen_fd(index),
+ None => Err(ERRNO_BADF),
+ }
+ }
+
+ /// The host descriptor to resolve paths relative to `fd` from, which is the working directory for a descriptor
+ /// the guest does not have.
+ fn directory_fd(&self, fd: u32) -> Result<i32, Errno> {
+ match self.descriptor(fd) {
+ Some(Descriptor::Host(host_fd)) => Ok(host_fd),
+ Some(Descriptor::Preopen(index)) => self.preopen_fd(index),
+ None => Ok(platform::AT_FDCWD),
+ }
+ }
+
+ fn preopen_fd(&self, index: usize) -> Result<i32, Errno> {
+ let preopen = &self.preopens[index];
+ if let Some(fd) = preopen.host_fd.get() {
+ return Ok(fd);
+ }
+ let fd = platform::open_directory(&preopen.host_path)?;
+ preopen.host_fd.set(Some(fd));
+ Ok(fd)
+ }
+
+ fn dispatch(&self, memory: &mut Memory, name: &str, argument: &dyn Fn(usize) -> u64) -> Result<(), Errno> {
+ let a = |index: usize| argument(index) as u32;
+ match name {
+ "args_get" => write_strings(memory, &self.arguments, a(0), a(1)),
+ "args_sizes_get" => write_string_sizes(memory, &self.arguments, a(0), a(1)),
+ "environ_get" => write_strings(memory, &self.environment, a(0), a(1)),
+ "environ_sizes_get" => write_string_sizes(memory, &self.environment, a(0), a(1)),
+ "clock_res_get" => memory.write_u64(a(1), platform::clock_resolution(a(0))?),
+ "clock_time_get" => memory.write_u64(a(2), platform::clock_time(a(0))?),
+ "fd_close" => match self.descriptor(a(0)) {
+ Some(Descriptor::Host(host_fd)) => {
+ platform::close(host_fd)?;
+ self.files.borrow_mut().remove(&a(0));
+ Ok(())
+ }
+ Some(Descriptor::Preopen(_)) => Err(ERRNO_ISDIR),
+ None => Err(ERRNO_BADF),
+ },
+ "fd_fdstat_get" => {
+ let host_fd = self.host_fd(a(0))?;
+ let (filetype, flags) = platform::fd_status(host_fd)?;
+ memory.write_u8(a(1), filetype)?;
+ memory.write_u16(a(1).wrapping_add(2), flags)?;
+ // FIXME: Implement rights.
+ memory.write_u64(a(1).wrapping_add(8), 0)?;
+ memory.write_u64(a(1).wrapping_add(16), 0)
+ }
+ "fd_filestat_get" => {
+ let host_fd = self.host_fd(a(0))?;
+ write_filestat(memory, a(1), &platform::fstat(host_fd)?)
+ }
+ "fd_prestat_get" => {
+ let Some(Descriptor::Preopen(index)) = self.descriptor(a(0)) else {
+ return Err(ERRNO_BADF);
+ };
+ // The only kind of preopened descriptor is a directory, tag 0.
+ memory.write_u8(a(1), 0)?;
+ memory.write_u32(a(1).wrapping_add(4), self.preopens[index].guest_path.len() as u32)
+ }
+ "fd_prestat_dir_name" => {
+ let Some(Descriptor::Preopen(index)) = self.descriptor(a(0)) else {
+ return Err(ERRNO_BADF);
+ };
+ let name = self.preopens[index].guest_path.as_bytes();
+ let length = (a(2) as usize).min(name.len());
+ memory.slice(a(1), length as u32)?.copy_from_slice(&name[..length]);
+ Ok(())
+ }
+ "fd_read" | "fd_write" => {
+ let Some(Descriptor::Host(host_fd)) = self.descriptor(a(0)) else {
+ return Err(ERRNO_BADF);
+ };
+ let mut total: u32 = 0;
+ for index in 0..a(2) {
+ let iovec = a(1).wrapping_add(index.wrapping_mul(8));
+ let buffer = memory.read_u32(iovec)?;
+ let length = memory.read_u32(iovec.wrapping_add(4))?;
+ let bytes = memory.slice(buffer, length)?;
+ let transferred = if name == "fd_read" {
+ platform::read(host_fd, bytes)?
+ } else {
+ platform::write(host_fd, bytes)?
+ };
+ total = total.wrapping_add(transferred as u32);
+ if transferred < bytes.len() {
+ break;
+ }
+ }
+ memory.write_u32(a(3), total)
+ }
+ "fd_seek" => {
+ let Some(Descriptor::Host(host_fd)) = self.descriptor(a(0)) else {
+ return Err(ERRNO_BADF);
+ };
+ let position = platform::seek(host_fd, argument(1) as i64, a(2))?;
+ memory.write_u64(a(3), position)
+ }
+ "fd_tell" => {
+ let Some(Descriptor::Host(host_fd)) = self.descriptor(a(0)) else {
+ return Err(ERRNO_BADF);
+ };
+ let position = platform::seek(host_fd, 0, platform::WHENCE_CURRENT)?;
+ memory.write_u64(a(1), position)
+ }
+ "path_create_directory" => {
+ let directory = self.directory_fd(a(0))?;
+ platform::create_directory(directory, memory.slice(a(1), a(2))?)
+ }
+ "path_filestat_get" => {
+ let directory = self.directory_fd(a(0))?;
+ let follow_symlinks = a(1) & LOOKUP_SYMLINK_FOLLOW != 0;
+ let status = platform::stat_at(directory, memory.slice(a(2), a(3))?, follow_symlinks)?;
+ write_filestat(memory, a(4), &status)
+ }
+ "path_open" => {
+ let directory = self.directory_fd(a(0))?;
+ let options = OpenOptions {
+ follow_symlinks: a(1) & LOOKUP_SYMLINK_FOLLOW != 0,
+ open_flags: a(4) as u16,
+ rights: argument(5),
+ fd_flags: a(7) as u16,
+ };
+ let host_fd = platform::open_at(directory, memory.slice(a(2), a(3))?, &options)?;
+ let fd = self.next_fd.get();
+ self.next_fd.set(fd + 1);
+ self.files.borrow_mut().insert(fd, host_fd);
+ memory.write_u32(a(8), fd)
+ }
+ "random_get" => platform::fill_with_random(memory.slice(a(0), a(1))?),
+ "sched_yield" => Ok(()),
+ _ => Err(ERRNO_NOSYS),
+ }
+ }
+}
+
+const LOOKUP_SYMLINK_FOLLOW: u32 = 1;
+
+/// How path_open opens a file.
+#[cfg_attr(not(unix), allow(dead_code))]
+struct OpenOptions {
+ follow_symlinks: bool,
+ open_flags: u16,
+ rights: u64,
+ fd_flags: u16,
+}
+
+/// Each function and its type: 'i' is i32 and 'I' is i64, with the result after '>'.
+static FUNCTIONS: &[(&str, &str)] = &[
+ ("args_get", "ii>i"),
+ ("args_sizes_get", "ii>i"),
+ ("environ_get", "ii>i"),
+ ("environ_sizes_get", "ii>i"),
+ ("clock_res_get", "ii>i"),
+ ("clock_time_get", "iIi>i"),
+ ("fd_advise", "iIIi>i"),
+ ("fd_allocate", "iII>i"),
+ ("fd_close", "i>i"),
+ ("fd_datasync", "i>i"),
+ ("fd_fdstat_get", "ii>i"),
+ ("fd_fdstat_set_flags", "ii>i"),
+ ("fd_fdstat_set_rights", "iII>i"),
+ ("fd_filestat_get", "ii>i"),
+ ("fd_filestat_set_size", "iI>i"),
+ ("fd_filestat_set_times", "iIIi>i"),
+ ("fd_pread", "iiiIi>i"),
+ ("fd_prestat_get", "ii>i"),
+ ("fd_prestat_dir_name", "iii>i"),
+ ("fd_pwrite", "iiiIi>i"),
+ ("fd_read", "iiii>i"),
+ ("fd_readdir", "iiiIi>i"),
+ ("fd_renumber", "ii>i"),
+ ("fd_seek", "iIii>i"),
+ ("fd_sync", "i>i"),
+ ("fd_tell", "ii>i"),
+ ("fd_write", "iiii>i"),
+ ("path_create_directory", "iii>i"),
+ ("path_filestat_get", "iiiii>i"),
+ ("path_filestat_set_times", "iiiiIIi>i"),
+ ("path_link", "iiiiiii>i"),
+ ("path_open", "iiiiiIIii>i"),
+ ("path_readlink", "iiiiii>i"),
+ ("path_remove_directory", "iii>i"),
+ ("path_rename", "iiiiii>i"),
+ ("path_symlink", "iiiii>i"),
+ ("path_unlink_file", "iii>i"),
+ ("poll_oneoff", "iiii>i"),
+ ("proc_exit", "i"),
+ ("proc_raise", "i>i"),
+ ("sched_yield", ">i"),
+ ("random_get", "ii>i"),
+ ("sock_accept", "iii>i"),
+ ("sock_recv", "iiiiii>i"),
+ ("sock_send", "iiiii>i"),
+ ("sock_shutdown", "ii>i"),
+];
+
+/// The guest's memory, which every access checks the bounds of.
+struct Memory<'a>(&'a mut [u8]);
+
+impl Memory<'_> {
+ fn slice(&mut self, address: u32, length: u32) -> Result<&mut [u8], Errno> {
+ let start = address as usize;
+ let end = start.checked_add(length as usize).ok_or(ERRNO_FAULT)?;
+ self.0.get_mut(start..end).ok_or(ERRNO_FAULT)
+ }
+
+ fn read_u32(&mut self, address: u32) -> Result<u32, Errno> {
+ let bytes = self.slice(address, 4)?;
+ Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
+ }
+
+ fn write(&mut self, address: u32, bytes: &[u8]) -> Result<(), Errno> {
+ self.slice(address, bytes.len() as u32)?.copy_from_slice(bytes);
+ Ok(())
+ }
+
+ fn write_u8(&mut self, address: u32, value: u8) -> Result<(), Errno> {
+ self.write(address, &[value])
+ }
+
+ fn write_u16(&mut self, address: u32, value: u16) -> Result<(), Errno> {
+ self.write(address, &value.to_le_bytes())
+ }
+
+ fn write_u32(&mut self, address: u32, value: u32) -> Result<(), Errno> {
+ self.write(address, &value.to_le_bytes())
+ }
+
+ fn write_u64(&mut self, address: u32, value: u64) -> Result<(), Errno> {
+ self.write(address, &value.to_le_bytes())
+ }
+}
+
+/// Write the pointers to `strings` at `pointers`, and the strings, each followed by a null byte, at `buffer`.
+fn write_strings(memory: &mut Memory, strings: &[String], pointers: u32, buffer: u32) -> Result<(), Errno> {
+ let mut offset = buffer;
+ for (index, string) in strings.iter().enumerate() {
+ memory.write_u32(pointers.wrapping_add(index as u32 * 4), offset)?;
+ memory.write(offset, string.as_bytes())?;
+ memory.write_u8(offset.wrapping_add(string.len() as u32), 0)?;
+ offset = offset.wrapping_add(string.len() as u32 + 1);
+ }
+ Ok(())
+}
+
+fn write_string_sizes(memory: &mut Memory, strings: &[String], count: u32, size: u32) -> Result<(), Errno> {
+ memory.write_u32(count, strings.len() as u32)?;
+ let total: usize = strings.iter().map(|string| string.len() + 1).sum();
+ memory.write_u32(size, total as u32)
+}
+
+/// What fd_filestat_get and path_filestat_get return.
+pub struct FileStatus {
+ device: u64,
+ inode: u64,
+ filetype: u8,
+ link_count: u64,
+ size: u64,
+ access_time: u64,
+ modification_time: u64,
+ status_change_time: u64,
+}
+
+fn write_filestat(memory: &mut Memory, address: u32, status: &FileStatus) -> Result<(), Errno> {
+ memory.write_u64(address, status.device)?;
+ memory.write_u64(address.wrapping_add(8), status.inode)?;
+ memory.write_u8(address.wrapping_add(16), status.filetype)?;
+ memory.write_u64(address.wrapping_add(24), status.link_count)?;
+ memory.write_u64(address.wrapping_add(32), status.size)?;
+ memory.write_u64(address.wrapping_add(40), status.access_time)?;
+ memory.write_u64(address.wrapping_add(48), status.modification_time)?;
+ memory.write_u64(address.wrapping_add(56), status.status_change_time)
+}
+
+#[cfg(unix)]
+mod platform {
+ use super::{ERRNO_INVAL, ERRNO_IO, Errno, FileStatus, OpenOptions};
+ use std::ffi::CString;
+
+ pub const AT_FDCWD: i32 = libc::AT_FDCWD;
+ pub const WHENCE_CURRENT: u32 = 1;
+
+ const NANOSECONDS_PER_SECOND: u64 = 1_000_000_000;
+
+ fn last_errno() -> Errno {
+ errno_of(std::io::Error::last_os_error().raw_os_error().unwrap_or(0))
+ }
+
+ /// The WASI errno of a host errno.
+ fn errno_of(host: i32) -> Errno {
+ match host {
+ libc::E2BIG => 1,
+ libc::EACCES => 2,
+ libc::EADDRINUSE => 3,
+ libc::EADDRNOTAVAIL => 4,
+ libc::EAFNOSUPPORT => 5,
+ libc::EAGAIN => 6,
+ libc::EALREADY => 7,
+ libc::EBADF => 8,
+ libc::EBUSY => 10,
+ libc::ECHILD => 12,
+ libc::ECONNREFUSED => 14,
+ libc::ECONNRESET => 15,
+ libc::EDEADLK => 16,
+ libc::EDOM => 18,
+ libc::EEXIST => 20,
+ libc::EFAULT => 21,
+ libc::EFBIG => 22,
+ libc::EINTR => 27,
+ libc::EINVAL => 28,
+ libc::EIO => 29,
+ libc::EISDIR => 31,
+ libc::ELOOP => 32,
+ libc::EMFILE => 33,
+ libc::EMLINK => 34,
+ libc::ENAMETOOLONG => 37,
+ libc::ENFILE => 41,
+ libc::ENOBUFS => 42,
+ libc::ENODEV => 43,
+ libc::ENOENT => 44,
+ libc::ENOEXEC => 45,
+ libc::ENOMEM => 48,
+ libc::ENOSPC => 51,
+ libc::ENOSYS => 52,
+ libc::ENOTDIR => 54,
+ libc::ENOTEMPTY => 55,
+ libc::ENOTSUP => 58,
+ libc::ENOTTY => 59,
+ libc::ENXIO => 60,
+ libc::EOVERFLOW => 61,
+ libc::EPERM => 63,
+ libc::EPIPE => 64,
+ libc::ERANGE => 68,
+ libc::EROFS => 69,
+ libc::ESPIPE => 70,
+ libc::ESRCH => 71,
+ libc::ETIMEDOUT => 73,
+ libc::EXDEV => 75,
+ _ => ERRNO_IO,
+ }
+ }
+
+ fn path_of(bytes: &[u8]) -> Result<CString, Errno> {
+ CString::new(bytes).map_err(|_| ERRNO_INVAL)
+ }
+
+ pub fn open_directory(path: &str) -> Result<i32, Errno> {
+ let path = path_of(path.as_bytes())?;
+ let fd = unsafe { libc::open(path.as_ptr(), libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC) };
+ if fd < 0 { Err(last_errno()) } else { Ok(fd) }
+ }
+
+ pub fn open_at(directory: i32, path: &[u8], options: &OpenOptions) -> Result<i32, Errno> {
+ const OFLAGS_CREAT: u16 = 1;
+ const OFLAGS_DIRECTORY: u16 = 2;
+ const OFLAGS_EXCL: u16 = 4;
+ const OFLAGS_TRUNC: u16 = 8;
+ const FDFLAGS_APPEND: u16 = 1;
+ const FDFLAGS_NONBLOCK: u16 = 4;
+ const FDFLAGS_SYNC: u16 = 16;
+ const RIGHTS_FD_READ: u64 = 1 << 1;
+ const RIGHTS_FD_WRITE: u64 = 1 << 6;
+
+ let path = path_of(path)?;
+ let readable = options.rights & RIGHTS_FD_READ != 0;
+ let writable = options.rights & RIGHTS_FD_WRITE != 0;
+ let mut flags = match (readable, writable) {
+ (_, false) => libc::O_RDONLY,
+ (false, true) => libc::O_WRONLY,
+ (true, true) => libc::O_RDWR,
+ };
+ flags |= libc::O_CLOEXEC;
+ if options.open_flags & OFLAGS_DIRECTORY != 0 {
+ flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC;
+ }
+ if options.open_flags & OFLAGS_CREAT != 0 {
+ flags |= libc::O_CREAT;
+ }
+ if options.open_flags & OFLAGS_EXCL != 0 {
+ flags |= libc::O_EXCL;
+ }
+ if options.open_flags & OFLAGS_TRUNC != 0 {
+ flags |= libc::O_TRUNC;
+ }
+ if options.fd_flags & FDFLAGS_APPEND != 0 {
+ flags |= libc::O_APPEND;
+ }
+ if options.fd_flags & FDFLAGS_NONBLOCK != 0 {
+ flags |= libc::O_NONBLOCK;
+ }
+ if options.fd_flags & FDFLAGS_SYNC != 0 {
+ flags |= libc::O_SYNC;
+ }
+ if !options.follow_symlinks {
+ flags |= libc::O_NOFOLLOW;
+ }
+ let fd = unsafe { libc::openat(directory, path.as_ptr(), flags, 0o644 as libc::c_uint) };
+ if fd < 0 { Err(last_errno()) } else { Ok(fd) }
+ }
+
+ pub fn close(fd: i32) -> Result<(), Errno> {
+ if unsafe { libc::close(fd) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(())
+ }
+
+ pub fn read(fd: i32, bytes: &mut [u8]) -> Result<usize, Errno> {
+ let result = unsafe { libc::read(fd, bytes.as_mut_ptr().cast(), bytes.len()) };
+ if result < 0 {
+ Err(last_errno())
+ } else {
+ Ok(result as usize)
+ }
+ }
+
+ pub fn write(fd: i32, bytes: &[u8]) -> Result<usize, Errno> {
+ let result = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };
+ if result < 0 {
+ Err(last_errno())
+ } else {
+ Ok(result as usize)
+ }
+ }
+
+ pub fn seek(fd: i32, offset: i64, whence: u32) -> Result<u64, Errno> {
+ let whence = match whence {
+ 0 => libc::SEEK_SET,
+ 1 => libc::SEEK_CUR,
+ 2 => libc::SEEK_END,
+ _ => return Err(ERRNO_INVAL),
+ };
+ let result = unsafe { libc::lseek(fd, offset as libc::off_t, whence) };
+ if result < 0 {
+ Err(last_errno())
+ } else {
+ Ok(result as u64)
+ }
+ }
+
+ pub fn create_directory(directory: i32, path: &[u8]) -> Result<(), Errno> {
+ let path = path_of(path)?;
+ if unsafe { libc::mkdirat(directory, path.as_ptr(), 0o755) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(())
+ }
+
+ fn filetype_of(mode: libc::mode_t) -> u8 {
+ match mode & libc::S_IFMT {
+ libc::S_IFBLK => 1,
+ libc::S_IFCHR => 2,
+ libc::S_IFDIR => 3,
+ libc::S_IFREG => 4,
+ libc::S_IFSOCK => 6,
+ libc::S_IFLNK => 7,
+ _ => 0,
+ }
+ }
+
+ // NB: The types of stat's fields differ between hosts.
+ #[allow(clippy::unnecessary_cast)]
+ fn status_of(status: &libc::stat) -> FileStatus {
+ let time = |seconds: i64, nanoseconds: i64| -> u64 {
+ (seconds as u64)
+ .wrapping_mul(NANOSECONDS_PER_SECOND)
+ .wrapping_add(nanoseconds as u64)
+ };
+ FileStatus {
+ device: status.st_dev as u64,
+ inode: status.st_ino as u64,
+ filetype: filetype_of(status.st_mode),
+ link_count: status.st_nlink as u64,
+ size: status.st_size as u64,
+ access_time: time(status.st_atime as i64, status.st_atime_nsec as i64),
+ modification_time: time(status.st_mtime as i64, status.st_mtime_nsec as i64),
+ status_change_time: time(status.st_ctime as i64, status.st_ctime_nsec as i64),
+ }
+ }
+
+ pub fn fstat(fd: i32) -> Result<FileStatus, Errno> {
+ let mut status = unsafe { std::mem::zeroed::<libc::stat>() };
+ if unsafe { libc::fstat(fd, &raw mut status) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(status_of(&status))
+ }
+
+ pub fn stat_at(directory: i32, path: &[u8], follow_symlinks: bool) -> Result<FileStatus, Errno> {
+ let path = path_of(path)?;
+ let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
+ let mut status = unsafe { std::mem::zeroed::<libc::stat>() };
+ if unsafe { libc::fstatat(directory, path.as_ptr(), &raw mut status, flags) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(status_of(&status))
+ }
+
+ /// The filetype and fdflags of a descriptor.
+ pub fn fd_status(fd: i32) -> Result<(u8, u16), Errno> {
+ let status = fstat(fd)?;
+ let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
+ if flags < 0 {
+ return Err(last_errno());
+ }
+ let mut fd_flags = 0;
+ if flags & libc::O_APPEND != 0 {
+ fd_flags |= 1;
+ }
+ if flags & libc::O_NONBLOCK != 0 {
+ fd_flags |= 4;
+ }
+ if flags & libc::O_SYNC == libc::O_SYNC {
+ fd_flags |= 16;
+ }
+ Ok((status.filetype, fd_flags))
+ }
+
+ fn clock_of(id: u32) -> Result<libc::clockid_t, Errno> {
+ match id {
+ 0 => Ok(libc::CLOCK_REALTIME),
+ 1 => Ok(libc::CLOCK_MONOTONIC),
+ 2 => Ok(libc::CLOCK_PROCESS_CPUTIME_ID),
+ 3 => Ok(libc::CLOCK_THREAD_CPUTIME_ID),
+ _ => Err(ERRNO_INVAL),
+ }
+ }
+
+ fn nanoseconds_of(time: &libc::timespec) -> u64 {
+ (time.tv_sec as u64)
+ .wrapping_mul(NANOSECONDS_PER_SECOND)
+ .wrapping_add(time.tv_nsec as u64)
+ }
+
+ pub fn clock_time(id: u32) -> Result<u64, Errno> {
+ let mut time = unsafe { std::mem::zeroed::<libc::timespec>() };
+ if unsafe { libc::clock_gettime(clock_of(id)?, &raw mut time) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(nanoseconds_of(&time))
+ }
+
+ pub fn clock_resolution(id: u32) -> Result<u64, Errno> {
+ let mut time = unsafe { std::mem::zeroed::<libc::timespec>() };
+ if unsafe { libc::clock_getres(clock_of(id)?, &raw mut time) } != 0 {
+ return Err(last_errno());
+ }
+ Ok(nanoseconds_of(&time))
+ }
+
+ pub fn fill_with_random(bytes: &mut [u8]) -> Result<(), Errno> {
+ // getentropy() fills at most 256 bytes at a time.
+ for chunk in bytes.chunks_mut(256) {
+ if unsafe { libc::getentropy(chunk.as_mut_ptr().cast(), chunk.len()) } != 0 {
+ return Err(last_errno());
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(not(unix))]
+mod platform {
+ use super::{ERRNO_NOSYS, Errno, FileStatus, OpenOptions};
+
+ pub const AT_FDCWD: i32 = -100;
+ pub const WHENCE_CURRENT: u32 = 1;
+
+ pub fn open_directory(_: &str) -> Result<i32, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn open_at(_: i32, _: &[u8], _: &OpenOptions) -> Result<i32, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn close(_: i32) -> Result<(), Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn read(_: i32, _: &mut [u8]) -> Result<usize, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn write(_: i32, _: &[u8]) -> Result<usize, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn seek(_: i32, _: i64, _: u32) -> Result<u64, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn create_directory(_: i32, _: &[u8]) -> Result<(), Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn fstat(_: i32) -> Result<FileStatus, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn stat_at(_: i32, _: &[u8], _: bool) -> Result<FileStatus, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn fd_status(_: i32) -> Result<(u8, u16), Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn clock_time(_: u32) -> Result<u64, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn clock_resolution(_: u32) -> Result<u64, Errno> {
+ Err(ERRNO_NOSYS)
+ }
+ pub fn fill_with_random(_: &mut [u8]) -> Result<(), Errno> {
+ Err(ERRNO_NOSYS)
+ }
+}
diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rs
index ed50bfcb1b7..94e9caa15a5 100644
--- a/Libraries/LibWasm/Engine/tests/execution.rs
+++ b/Libraries/LibWasm/Engine/tests/execution.rs
@@ -182,7 +182,7 @@ fn catches_exceptions_from_webassembly_and_host_functions() {
let Value::I32(value) = arguments[0] else {
unreachable!();
};
- let exception = store.allocate_exception(tag, Box::new([u64::from((value * 2) as u32)]));
+ let exception = store.allocate_exception(tag, &[u64::from((value * 2) as u32)]);
Err(Trap::UncaughtException(exception))
}),
);
@@ -206,7 +206,7 @@ fn catches_exceptions_from_webassembly_and_host_functions() {
panic!("the exception should leave the interpreter");
};
assert_eq!(store.exception(exception).tag, tag);
- assert_eq!(&*store.exception(exception).payload, &[5]);
+ assert_eq!(store.exception(exception).payload, &[5]);
}
#[test]
@@ -246,3 +246,40 @@ fn waits_on_shared_memory() {
Ok(vec![Value::I32(6)])
);
}
+
+#[test]
+fn traps_on_ranges_that_wrap_around() {
+ let mut store = Store::new();
+ let instance = instantiate(&mut store, "wrapping_ranges.wasm");
+ let wrapping_start = Value::I64(-256);
+ assert_eq!(
+ call(&mut store, instance, "fill", &[wrapping_start, Value::I64(512)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "copy",
+ &[wrapping_start, Value::I64(0), Value::I64(512)]
+ ),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(
+ &mut store,
+ instance,
+ "copy",
+ &[Value::I64(0), wrapping_start, Value::I64(512)]
+ ),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "table_fill", &[Value::I64(-2), Value::I64(4)]),
+ Err(Trap::TableOutOfBounds)
+ );
+ assert_eq!(
+ call(&mut store, instance, "fill", &[Value::I64(16), Value::I64(16)]),
+ Ok(vec![])
+ );
+}
diff --git a/Libraries/LibWasm/Engine/tests/fault_stress.rs b/Libraries/LibWasm/Engine/tests/fault_stress.rs
new file mode 100644
index 00000000000..41a7002faa1
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fault_stress.rs
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#![cfg(all(target_arch = "x86_64", not(windows)))]
+
+//! Out-of-bounds accesses trap while another thread reserves, grows, and releases memories, which changes the set of
+//! reservations the fault handler looks addresses up in.
+
+use libwasm_engine::runtime::{ExternValue, Store, Trap, Value};
+use libwasm_engine::types::{AddressType, Limits, MemoryType};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+#[test]
+fn out_of_bounds_accesses_trap_while_memories_come_and_go() {
+ let stop = Arc::new(AtomicBool::new(false));
+ let churn = {
+ let stop = stop.clone();
+ std::thread::spawn(move || {
+ let mut rounds = 0u64;
+ while !stop.load(Ordering::Relaxed) {
+ let mut store = Store::new();
+ for _ in 0..8 {
+ let memory = store
+ .allocate_memory(MemoryType {
+ limits: Limits {
+ min: 1,
+ max: Some(4),
+ address_type: AddressType::I32,
+ shared: false,
+ },
+ })
+ .expect("the memory is allocated");
+ let _ = store.memory_mut(memory).grow(1);
+ }
+ // Dropping the store releases its memories.
+ drop(store);
+ rounds += 1;
+ }
+ rounds
+ })
+ };
+
+ let bytes =
+ std::fs::read(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/out-of-bounds.wasm"))
+ .unwrap();
+ let module = Arc::new(libwasm_engine::compile(&bytes).unwrap());
+ let mut store = Store::new();
+ let instance = store.instantiate(module, &[]).unwrap();
+ let export = |name: &str| match store.instance(instance).export(name) {
+ Some(ExternValue::Function(function)) => function,
+ _ => panic!("no function export {name}"),
+ };
+ let (load, store_function) = (export("load"), export("store"));
+ for iteration in 0..20_000u32 {
+ let address = 65536 + (iteration % 1024) * 4096;
+ assert_eq!(
+ store.invoke(load, &[Value::I32(address as i32)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ assert_eq!(
+ store.invoke(store_function, &[Value::I32(iteration as i32)]),
+ Err(Trap::MemoryOutOfBounds)
+ );
+ }
+ stop.store(true, Ordering::Relaxed);
+ let rounds = churn.join().unwrap();
+ assert!(rounds > 0);
+}
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wasm b/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wasm
new file mode 100644
index 00000000000..d5f97a55992
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wat b/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wat
new file mode 100644
index 00000000000..ec92fa1db4b
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/out-of-bounds.wat
@@ -0,0 +1,6 @@
+(module
+ (memory 1)
+ (func (export "load") (param i32) (result i32)
+ (i32.load (local.get 0)))
+ (func (export "store") (param i32)
+ (i32.store offset=65536 (local.get 0) (i32.const 1))))
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wasm b/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wasm
new file mode 100644
index 00000000000..fa1b53dba33
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wat b/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wat
new file mode 100644
index 00000000000..67ef56531ef
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/wrapping_ranges.wat
@@ -0,0 +1,10 @@
+(module
+ (memory i64 1)
+ (table i64 4 funcref)
+ (memory $other 1)
+ (func (export "fill") (param i64 i64)
+ (memory.fill (local.get 0) (i32.const 0x55) (local.get 1)))
+ (func (export "copy") (param i64 i64 i64)
+ (memory.copy (local.get 0) (local.get 1) (local.get 2)))
+ (func (export "table_fill") (param i64 i64)
+ (table.fill (local.get 0) (ref.null func) (local.get 1))))
diff --git a/Libraries/LibWasm/Interpreter/interpreter.flap b/Libraries/LibWasm/Interpreter/interpreter.flap
index 8d65ea50958..f1c058b5e45 100644
--- a/Libraries/LibWasm/Interpreter/interpreter.flap
+++ b/Libraries/LibWasm/Interpreter/interpreter.flap
@@ -927,13 +927,14 @@ handler Select() @opcode(0x1b) {
handler SelectTyped() @opcode(0x1c) {
let bytes = immediates();
- let type_byte: u64 = alias(bytes[1]);
+ # The count of types, which is 1, may take more than one byte.
let length = leb_length(bytes);
+ let type_byte: u64 = alias(bytes[length]);
let current: u64 = ip;
let mut type_length: u64 = 1;
if type_byte >= 0x63 @cold {
if type_byte <= 0x64 {
- let heap_bytes: Sequence<u8> = alias(current + 3);
+ let heap_bytes: Sequence<u8> = alias(current + 2 + length);
let heap_length = leb_length(heap_bytes);
type_length = heap_length + 1;
}
@@ -1769,6 +1770,136 @@ handler I64Const() @opcode(0x42) {
advance(length + 1);
}
+# Constants quickened into fixed-width forms (rule 3 in quickening.rs): the value is in the bytes after the opcode,
+# sign-extended from their width.
+
+inline fn sign_extended(value: u64, bits: u64) -> u64 {
+ let width: u64 = 64;
+ let shift = width - bits;
+ let moved = value << shift;
+ let signed = signed64(moved);
+ let extended = signed >> signed64(shift);
+ let result: u64 = alias(extended);
+ result
+}
+
+inline fn push_i32(value: u64) {
+ let narrow = u32(value);
+ let wide: u64 = alias(narrow);
+ push(wide);
+}
+
+# A 5- to 7-byte value: its low 4 bytes, and the rest from 4 bytes that end where it does.
+inline fn fixed_value_over_4(length: u64) -> u64 {
+ let current: u64 = ip;
+ let mut low: u64;
+ load32(low, [current, 1]);
+ let end_word = current + length - 3;
+ let mut high: u64;
+ load32(high, [end_word, 0]);
+ let word: u64 = 8;
+ let unused = (word - length) << 3;
+ let rest = high >> unused;
+ let value = low | (rest << 32);
+ sign_extended(value, length << 3)
+}
+
+handler I32ConstFixed2() @opcode(0xe0) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load16(value, [current, 1]);
+ push_i32(sign_extended(value, 16));
+ advance(3);
+}
+
+handler I32ConstFixed3() @opcode(0xe1) {
+ # The byte after the value belongs to the next instruction, which a function body always has.
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push_i32(sign_extended(value, 24));
+ advance(4);
+}
+
+handler I32ConstFixed4() @opcode(0xe2) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push(value);
+ advance(5);
+}
+
+handler I32ConstFixed5() @opcode(0xe3) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push(value);
+ advance(6);
+}
+
+handler I64ConstFixed2() @opcode(0xe4) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load16(value, [current, 1]);
+ push(sign_extended(value, 16));
+ advance(3);
+}
+
+handler I64ConstFixed3() @opcode(0xe5) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push(sign_extended(value, 24));
+ advance(4);
+}
+
+handler I64ConstFixed4() @opcode(0xe6) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load32(value, [current, 1]);
+ push(sign_extended(value, 32));
+ advance(5);
+}
+
+handler I64ConstFixed5() @opcode(0xe7) {
+ push(fixed_value_over_4(5));
+ advance(6);
+}
+
+handler I64ConstFixed6() @opcode(0xe8) {
+ push(fixed_value_over_4(6));
+ advance(7);
+}
+
+handler I64ConstFixed7() @opcode(0xe9) {
+ push(fixed_value_over_4(7));
+ advance(8);
+}
+
+handler I64ConstFixed8() @opcode(0xea) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load64(value, [current, 1]);
+ push(value);
+ advance(9);
+}
+
+handler I64ConstFixed9() @opcode(0xeb) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load64(value, [current, 1]);
+ push(value);
+ advance(10);
+}
+
+handler I64ConstFixed10() @opcode(0xec) {
+ let current: u64 = ip;
+ let mut value: u64;
+ load64(value, [current, 1]);
+ push(value);
+ advance(11);
+}
+
handler F32Const() @opcode(0x43) {
let current: u64 = ip;
let mut value: u64;
@@ -3177,9 +3308,13 @@ inline fn three_operands() -> (u64, u64, u64) {
(first, second, third)
}
-# Trap unless `count` items from `start` are within `size`.
+# Trap unless `count` items from `start` are within `size`. The operands of memory64 and table64 operations are 64-bit,
+# so the end can wrap around.
inline fn check_range(start: u64, count: u64, size: u64, code: u64) {
let end = start + count;
+ guard end >= start else @cold {
+ trap(code);
+ };
guard end <= size else @cold {
trap(code);
};
@@ -6841,11 +6976,12 @@ inline fn identity_of_type(type_index: u64) -> u64 {
identity
}
-# Allocate a zeroed object of `size` bytes whose type is `rtt`.
-inline fn allocate_object(rtt: u64, size: u64) -> u64 {
+# Allocate an object whose type is `rtt`, with `size` bytes of zeroed data and, for an array, `length` elements.
+inline fn allocate_object(rtt: u64, size: u64, length: u64) -> u64 {
let context_pointer = context();
store64([context_pointer, CONTEXT_ARGUMENTS], rtt);
store64([context_pointer, CONTEXT_ARGUMENT_1], size);
+ store64([context_pointer, CONTEXT_ARGUMENT_2], length);
let object: u64 = call_helper(wasm_runtime_allocate, context_pointer);
guard object != 0 else @cold {
trap(TRAP_RUNTIME);
@@ -7012,10 +7148,16 @@ inline fn non_null(reference: u64) -> u64 {
inline fn array_length(array: u64) -> u64 {
let mut length: u64;
- load64(length, [array, 8]);
+ load64(length, [array, OBJECT_LENGTH_OFFSET]);
length
}
+inline fn object_data(object: u64) -> u64 {
+ let mut data: u64;
+ load64(data, [object, OBJECT_DATA_OFFSET]);
+ data
+}
+
inline fn array_element_kind(array: u64) -> u64 {
let mut rtt: u64;
load64(rtt, [array, 0]);
@@ -7028,6 +7170,9 @@ inline fn array_element_kind(array: u64) -> u64 {
inline fn check_array_range(start: u64, count: u64, length: u64) {
let end = start + count;
+ guard end >= start else @cold {
+ trap(TRAP_ARRAY_OUT_OF_BOUNDS);
+ };
guard end <= length else @cold {
trap(TRAP_ARRAY_OUT_OF_BOUNDS);
};
@@ -7035,7 +7180,8 @@ inline fn check_array_range(start: u64, count: u64, length: u64) {
inline fn element_address(array: u64, index: u64, kind: u64) -> u64 {
let size = storage_size(kind);
- array + ARRAY_ELEMENTS_OFFSET + (index * size)
+ let data = object_data(array);
+ data + (index * size)
}
# The two LEB128 immediates of a GC instruction, and the length of the instruction.
@@ -7059,7 +7205,8 @@ handler StructNew() @opcode(0xfb, 0x0) {
let rtt = rtt_of_type(type_index);
let mut size: u64;
load32(size, [rtt, RTT_SIZE]);
- let object = allocate_object(rtt, size);
+ let object = allocate_object(rtt, size, 0);
+ let data = object_data(object);
let mut field_count: u64;
load32(field_count, [rtt, RTT_FIELD_COUNT]);
let mut offsets_pointer: u64;
@@ -7074,7 +7221,7 @@ handler StructNew() @opcode(0xfb, 0x0) {
index = index - 1;
let offset: u64 = alias(offsets[index]);
let kind: u64 = alias(kinds[index]);
- pop_into_storage(object + offset, kind);
+ pop_into_storage(data + offset, kind);
}
push(object);
advance(length);
@@ -7085,7 +7232,7 @@ handler StructNewDefault() @opcode(0xfb, 0x1) {
let rtt = rtt_of_type(type_index);
let mut size: u64;
load32(size, [rtt, RTT_SIZE]);
- let object = allocate_object(rtt, size);
+ let object = allocate_object(rtt, size, 0);
push(object);
advance(length);
}
@@ -7101,7 +7248,8 @@ inline fn field_of(object: u64, type_index: u64, field_index: u64) -> (u64, u64)
let kinds: Sequence<u8> = alias(kinds_pointer);
let offset: u64 = alias(offsets[field_index]);
let kind: u64 = alias(kinds[field_index]);
- (object + offset, kind)
+ let data = object_data(object);
+ (data + offset, kind)
}
handler StructGet() @opcode(0xfb, 0x2) {
@@ -7152,10 +7300,8 @@ inline fn allocate_array(type_index: u64, count: u64) -> u64 {
let rtt = rtt_of_type(type_index);
let mut element_size: u64;
load32(element_size, [rtt, RTT_SIZE]);
- let size = (count * element_size) + ARRAY_ELEMENTS_OFFSET;
- let array = allocate_object(rtt, size);
- store64([array, 8], count);
- array
+ let size = count * element_size;
+ allocate_object(rtt, size, count)
}
handler ArrayNew() @opcode(0xfb, 0x6) {
@@ -7218,7 +7364,7 @@ handler ArrayNewData() @opcode(0xfb, 0x9) {
let array = allocate_array(type_index, wide_count);
let mut contents: u64;
load64(contents, [segment, SEGMENT_CONTENTS]);
- copy_data_elements(array + ARRAY_ELEMENTS_OFFSET, contents + wide_source, wide_count, kind);
+ copy_data_elements(object_data(array), contents + wide_source, wide_count, kind);
push(array);
advance(length);
}
@@ -7236,7 +7382,7 @@ handler ArrayNewElem() @opcode(0xfb, 0xa) {
let array = allocate_array(type_index, wide_count);
let mut contents: u64;
load64(contents, [segment, SEGMENT_CONTENTS]);
- copy_elements(array + ARRAY_ELEMENTS_OFFSET, contents + (wide_source << 3), wide_count);
+ copy_elements(object_data(array), contents + (wide_source << 3), wide_count);
push(array);
advance(length);
}
@@ -7592,12 +7738,13 @@ handler PrefixFE() @opcode(0xfe) {
# The memory, address of a `size`-byte atomic access, and length of the instruction.
inline fn atomic_access(address_operand: u64, size: u64) -> (u64, u64, u64) {
let [bytes, prefix_length] = prefixed_immediates();
- let flags: u64 = alias(bytes[0]);
- let alignment_length = leb_length(bytes);
+ # The flags may take more than one byte; their bit 6 says a memory index follows.
+ let [flags, alignment_length] = read_leb(bytes);
let start: u64 = alias(bytes);
let mut memory_index: u64 = 0;
let mut index_length: u64 = 0;
- if flags >= 0x40 {
+ let has_memory_index = flags & 0x40;
+ if has_memory_index != 0 {
let index_bytes: Sequence<u8> = alias(start + alignment_length);
let [decoded_index, decoded_length] = read_leb(index_bytes);
memory_index = decoded_index;
diff --git a/Libraries/LibWasm/Runtime/CMakeLists.txt b/Libraries/LibWasm/Runtime/CMakeLists.txt
index 2e377061ca8..35f9d8c36be 100644
--- a/Libraries/LibWasm/Runtime/CMakeLists.txt
+++ b/Libraries/LibWasm/Runtime/CMakeLists.txt
@@ -5,7 +5,7 @@ set(SOURCES
ladybird_lib(LibWasmRuntime wasmruntime EXPLICIT_SYMBOL_EXPORT)
import_rust_crate(MANIFEST_PATH ../Engine/Cargo.toml CRATE_NAME libwasm_engine FEATURES allocator FFI_HEADER RustFFI.h)
-target_link_libraries(LibWasmRuntime PRIVATE libwasm_engine)
+target_link_libraries(LibWasmRuntime PRIVATE libwasm_engine PUBLIC LibGC)
if ((LINUX OR BSD) AND NOT BUILD_SHARED_LIBS)
target_link_options(LibWasmRuntime INTERFACE LINKER:--allow-multiple-definition)
endif()
diff --git a/Libraries/LibWasm/Runtime/Runtime.cpp b/Libraries/LibWasm/Runtime/Runtime.cpp
index 39d7fd7d49b..54e924c434f 100644
--- a/Libraries/LibWasm/Runtime/Runtime.cpp
+++ b/Libraries/LibWasm/Runtime/Runtime.cpp
@@ -4,6 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibGC/CAPI.h>
+#include <LibGC/Heap.h>
#include <LibWasm/Runtime/Runtime.h>
#include <RustFFI.h>
@@ -11,7 +13,6 @@ namespace Wasm::Runtime {
static_assert(sizeof(ValueType) == sizeof(FFI::WasmValueType));
static_assert(sizeof(Value) == sizeof(FFI::WasmValue));
-static_assert(sizeof(Extern) == sizeof(FFI::WasmExtern));
static_assert(sizeof(Limits) == sizeof(FFI::WasmLimits));
static_assert(sizeof(ExternType) == sizeof(FFI::WasmExternType));
@@ -111,9 +112,52 @@ Optional<FunctionType> Module::function_type(u32 type_index) const
});
}
-Store::Store()
- : m_store(FFI::wasm_store_create())
+size_t Module::custom_section_count() const
{
+ return FFI::wasm_module_custom_section_count(m_module);
+}
+
+CustomSection Module::custom_section(size_t index) const
+{
+ FFI::WasmStringView name {};
+ FFI::WasmStringView contents {};
+ FFI::wasm_module_custom_section(m_module, index, &name, &contents);
+ return { from_ffi(name), ReadonlyBytes { contents.data, contents.length } };
+}
+
+template<typename To, typename From>
+static To function_cast(From function)
+{
+ return reinterpret_cast<To>(function);
+}
+
+static FFI::GcInterface gc_interface(GC::Heap& heap)
+{
+ using Interface = FFI::GcInterface;
+ return {
+ .heap = &heap,
+ .gc_get_layout = function_cast<decltype(Interface::gc_get_layout)>(gc_get_layout),
+ .gc_allocator_create = function_cast<decltype(Interface::gc_allocator_create)>(gc_allocator_create),
+ .gc_heap_allocate_cell = function_cast<decltype(Interface::gc_heap_allocate_cell)>(gc_heap_allocate_cell),
+ .gc_heap_defer_gc = function_cast<decltype(Interface::gc_heap_defer_gc)>(gc_heap_defer_gc),
+ .gc_heap_undefer_gc = function_cast<decltype(Interface::gc_heap_undefer_gc)>(gc_heap_undefer_gc),
+ .gc_heap_collect_garbage = function_cast<decltype(Interface::gc_heap_collect_garbage)>(gc_heap_collect_garbage),
+ .gc_heap_did_allocate_external_memory = function_cast<decltype(Interface::gc_heap_did_allocate_external_memory)>(gc_heap_did_allocate_external_memory),
+ .gc_root_create = function_cast<decltype(Interface::gc_root_create)>(gc_root_create),
+ .gc_root_destroy = function_cast<decltype(Interface::gc_root_destroy)>(gc_root_destroy),
+ .gc_visitor_visit_cell = function_cast<decltype(Interface::gc_visitor_visit_cell)>(gc_visitor_visit_cell),
+ .gc_visitor_visit_possible_values = function_cast<decltype(Interface::gc_visitor_visit_possible_values)>(gc_visitor_visit_possible_values),
+ .gc_primitive_storage_reserve = function_cast<decltype(Interface::gc_primitive_storage_reserve)>(gc_primitive_storage_reserve),
+ .gc_primitive_storage_resize = function_cast<decltype(Interface::gc_primitive_storage_resize)>(gc_primitive_storage_resize),
+ .gc_primitive_storage_free = gc_primitive_storage_free,
+ .gc_primitive_storage_data = gc_primitive_storage_data,
+ };
+}
+
+Store::Store(GC::Heap& heap)
+{
+ auto interface = gc_interface(heap);
+ m_store = FFI::wasm_store_create(&interface);
}
Store::~Store()
@@ -121,27 +165,39 @@ Store::~Store()
FFI::wasm_store_destroy(m_store);
}
+static void* to_ffi(Entity entity) { return entity; }
+static Entity entity_from_ffi(void* cell) { return static_cast<GC::ForeignCell*>(cell); }
+
namespace {
struct HostFunctionData {
Store& store;
Store::HostFunction function;
- size_t result_count { 0 };
};
}
-static bool call_host_function(void* user_data, FFI::WasmStore*, FFI::WasmValue const* arguments, size_t argument_count, FFI::WasmValue* results, size_t result_count, FFI::WasmString* error)
+static FFI::WasmStatus call_host_function(void* user_data, FFI::WasmStore*, FFI::WasmValue const* arguments, size_t argument_count, FFI::WasmValue* results, size_t result_count, FFI::WasmString* error, u64* exception)
{
auto& data = *static_cast<HostFunctionData*>(user_data);
ReadonlySpan<Value> argument_span { reinterpret_cast<Value const*>(arguments), argument_count };
Span<Value> result_span { reinterpret_cast<Value*>(results), result_count };
auto result = data.function(data.store, argument_span, result_span);
- if (result.is_error()) {
- *error = make_string(result.error());
- return false;
+ if (!result.is_error())
+ return FFI::WasmStatus::Ok;
+ if (auto thrown = result.error().thrown_exception; thrown.has_value()) {
+ *exception = *thrown;
+ return FFI::WasmStatus::Exception;
}
- return true;
+ *error = make_string(result.error().message);
+ return FFI::WasmStatus::Trap;
+}
+
+static void visit_host_function(void* user_data, void* visitor)
+{
+ // NB: LibGC's C interface passes its Cell::Visitor as the visitor.
+ auto& data = *static_cast<HostFunctionData*>(user_data);
+ static_cast<GC::Cell::Visitor*>(visitor)->visit_possible_values(data.function.raw_capture_range());
}
static void release_host_function(void* user_data)
@@ -149,7 +205,7 @@ static void release_host_function(void* user_data)
delete static_cast<HostFunctionData*>(user_data);
}
-u32 Store::allocate_host_function(FunctionType const& type, HostFunction function)
+Entity Store::allocate_host_function(FunctionType const& type, HostFunction function)
{
Vector<FFI::WasmValueType> parameters;
Vector<FFI::WasmValueType> results;
@@ -157,173 +213,305 @@ u32 Store::allocate_host_function(FunctionType const& type, HostFunction functio
parameters.append(to_ffi(parameter));
for (auto result : type.results)
results.append(to_ffi(result));
- auto* data = new HostFunctionData { *this, move(function), type.results.size() };
- return FFI::wasm_store_allocate_host_function(m_store, parameters.data(), parameters.size(), results.data(), results.size(), call_host_function, data, release_host_function);
+ auto* data = new HostFunctionData { *this, move(function) };
+ return entity_from_ffi(FFI::wasm_store_allocate_host_function(m_store, parameters.data(), parameters.size(), results.data(), results.size(), call_host_function, visit_host_function, release_host_function, data));
}
-Optional<u32> Store::allocate_memory(Limits limits)
+Optional<Entity> Store::allocate_memory(Limits limits)
{
- u32 address = 0;
- if (!FFI::wasm_store_allocate_memory(m_store, to_ffi(limits), &address))
+ void* memory = nullptr;
+ if (!FFI::wasm_store_allocate_memory(m_store, to_ffi(limits), &memory))
return {};
- return address;
+ return entity_from_ffi(memory);
}
-u32 Store::allocate_table(ValueType element, Limits limits, u64 initial)
+Optional<Entity> Store::allocate_table(ValueType element, Limits limits, u64 initial)
{
- return FFI::wasm_store_allocate_table(m_store, to_ffi(element), to_ffi(limits), initial);
+ void* table = nullptr;
+ if (!FFI::wasm_store_allocate_table(m_store, to_ffi(element), to_ffi(limits), initial, &table))
+ return {};
+ return entity_from_ffi(table);
}
-u32 Store::allocate_global(ValueType type, bool is_mutable, Value value)
+Entity Store::allocate_global(ValueType type, bool is_mutable, Value value)
{
- return FFI::wasm_store_allocate_global(m_store, to_ffi(type), is_mutable, to_ffi(value));
+ return entity_from_ffi(FFI::wasm_store_allocate_global(m_store, to_ffi(type), is_mutable, to_ffi(value)));
}
-ErrorOr<u32, Failure> Store::instantiate(Module const& module, ReadonlySpan<Extern> imports)
+static Failure failure_of(FFI::WasmStatus status, FFI::WasmString error, u64 exception)
{
- u32 instance = 0;
- FFI::WasmString error {};
- auto status = FFI::wasm_store_instantiate(m_store, module.handle(), reinterpret_cast<FFI::WasmExtern const*>(imports.data()), imports.size(), &instance, &error);
switch (status) {
- case FFI::WasmStatus::Ok:
- return instance;
case FFI::WasmStatus::LinkError:
- return Failure { FailureKind::LinkError, take_string(error) };
+ return { FailureKind::LinkError, take_string(error) };
case FFI::WasmStatus::Trap:
- return Failure { FailureKind::Trap, take_string(error) };
+ return { FailureKind::Trap, take_string(error) };
+ case FFI::WasmStatus::Exception:
+ return { FailureKind::Exception, take_string(error), exception };
+ case FFI::WasmStatus::StackExhausted:
+ return { FailureKind::StackExhausted, take_string(error) };
+ case FFI::WasmStatus::Ok:
+ break;
}
VERIFY_NOT_REACHED();
}
-Vector<InstanceExport> Store::instance_exports(u32 instance)
+ErrorOr<Entity, Failure> Store::instantiate(Module const& module, ReadonlySpan<Extern> imports)
{
- auto count = FFI::wasm_store_instance_export_count(m_store, instance);
+ static_assert(sizeof(Extern) == sizeof(FFI::WasmExtern));
+ void* instance = nullptr;
+ FFI::WasmString error {};
+ u64 exception = 0;
+ auto status = FFI::wasm_store_instantiate(m_store, module.handle(), reinterpret_cast<FFI::WasmExtern const*>(imports.data()), imports.size(), &instance, &error, &exception);
+ if (status == FFI::WasmStatus::Ok)
+ return entity_from_ffi(instance);
+ return failure_of(status, error, exception);
+}
+
+Vector<InstanceExport> Store::instance_exports(Entity instance)
+{
+ auto count = FFI::wasm_store_instance_export_count(m_store, to_ffi(instance));
Vector<InstanceExport> exports;
exports.ensure_capacity(count);
for (size_t index = 0; index < count; ++index) {
FFI::WasmStringView name {};
FFI::WasmExtern value {};
- if (!FFI::wasm_store_instance_export(m_store, instance, index, &name, &value))
+ if (!FFI::wasm_store_instance_export(m_store, to_ffi(instance), index, &name, &value))
continue;
exports.unchecked_append({ from_ffi(name), bit_cast<Extern>(value) });
}
return exports;
}
-Optional<Extern> Store::find_export(u32 instance, StringView name)
+Optional<Extern> Store::find_export(Entity instance, StringView name)
{
FFI::WasmExtern value {};
- if (!FFI::wasm_store_instance_find_export(m_store, instance, reinterpret_cast<u8 const*>(name.characters_without_null_termination()), name.length(), &value))
+ if (!FFI::wasm_store_instance_find_export(m_store, to_ffi(instance), reinterpret_cast<u8 const*>(name.characters_without_null_termination()), name.length(), &value))
return {};
return bit_cast<Extern>(value);
}
-FunctionType Store::function_type(u32 function)
+FunctionType Store::function_type(Entity function)
{
size_t parameter_count = 0;
size_t result_count = 0;
- FFI::wasm_store_function_type(m_store, function, &parameter_count, &result_count);
+ FFI::wasm_store_function_type(m_store, to_ffi(function), &parameter_count, &result_count);
return make_function_type(parameter_count, result_count, [&](auto* parameters, auto* results) {
- FFI::wasm_store_function_type_values(m_store, function, parameters, results);
+ FFI::wasm_store_function_type_values(m_store, to_ffi(function), parameters, results);
});
}
-ErrorOr<Vector<Value>, ByteString> Store::invoke(u32 function, ReadonlySpan<Value> arguments)
+ErrorOr<Values, Failure> Store::invoke(Entity function, ReadonlySpan<Value> arguments)
{
size_t parameter_count = 0;
size_t result_count = 0;
- FFI::wasm_store_function_type(m_store, function, &parameter_count, &result_count);
- Vector<Value> results;
+ FFI::wasm_store_function_type(m_store, to_ffi(function), &parameter_count, &result_count);
+ Values results;
results.resize(result_count);
FFI::WasmString error {};
- auto status = FFI::wasm_store_invoke(m_store, function, reinterpret_cast<FFI::WasmValue const*>(arguments.data()), arguments.size(), reinterpret_cast<FFI::WasmValue*>(results.data()), results.size(), &error);
+ u64 exception = 0;
+ auto status = FFI::wasm_store_invoke(m_store, to_ffi(function), reinterpret_cast<FFI::WasmValue const*>(arguments.data()), arguments.size(), reinterpret_cast<FFI::WasmValue*>(results.data()), results.size(), &error, &exception);
if (status != FFI::WasmStatus::Ok)
- return take_string(error);
+ return failure_of(status, error, exception);
return results;
}
-u64 Store::function_reference(u32 function)
+u64 Store::function_reference(Entity function)
+{
+ return FFI::wasm_store_function_reference(m_store, to_ffi(function));
+}
+
+Entity Store::function_from_reference(u64 reference)
{
- return FFI::wasm_store_function_reference(m_store, function);
+ void* function = nullptr;
+ VERIFY(FFI::wasm_store_function_from_reference(m_store, reference, &function));
+ return entity_from_ffi(function);
}
-Optional<u32> Store::function_from_reference(u64 reference)
+Optional<u32> Store::function_index(Entity function)
{
- u32 function = 0;
- if (!FFI::wasm_store_function_from_reference(m_store, reference, &function))
+ u32 index = 0;
+ if (!FFI::wasm_store_function_index(m_store, to_ffi(function), &index))
return {};
- return function;
+ return index;
+}
+
+Entity Store::allocate_tag(ReadonlySpan<ValueType> parameters)
+{
+ Vector<FFI::WasmValueType> types;
+ for (auto parameter : parameters)
+ types.append(to_ffi(parameter));
+ return entity_from_ffi(FFI::wasm_store_allocate_tag(m_store, types.data(), types.size()));
+}
+
+Vector<ValueType> Store::tag_parameters(Entity tag)
+{
+ Vector<FFI::WasmValueType> types;
+ types.resize(FFI::wasm_store_tag_parameter_count(m_store, to_ffi(tag)));
+ FFI::wasm_store_tag_parameters(m_store, to_ffi(tag), types.data());
+ Vector<ValueType> parameters;
+ parameters.ensure_capacity(types.size());
+ for (auto type : types)
+ parameters.unchecked_append(from_ffi(type));
+ return parameters;
}
-Bytes Store::memory(u32 memory)
+u64 Store::allocate_exception(Entity tag, ReadonlySpan<Value> values)
+{
+ return FFI::wasm_store_allocate_exception(m_store, to_ffi(tag), reinterpret_cast<FFI::WasmValue const*>(values.data()), values.size());
+}
+
+Entity Store::exception_tag(u64 exception)
+{
+ return entity_from_ffi(FFI::wasm_store_exception_tag(m_store, exception));
+}
+
+Values Store::exception_values(u64 exception)
+{
+ Values values;
+ values.resize(FFI::wasm_store_tag_parameter_count(m_store, to_ffi(exception_tag(exception))));
+ FFI::wasm_store_exception_values(m_store, exception, reinterpret_cast<FFI::WasmValue*>(values.data()));
+ return values;
+}
+
+Bytes Store::memory(Entity memory)
{
size_t size = 0;
- auto* data = FFI::wasm_store_memory_data(m_store, memory, &size);
+ auto* data = FFI::wasm_store_memory_data(m_store, to_ffi(memory), &size);
return { data, size };
}
-i64 Store::grow_memory(u32 memory, u64 delta)
+i64 Store::grow_memory(Entity memory, u64 delta)
{
- return FFI::wasm_store_memory_grow(m_store, memory, delta);
+ return FFI::wasm_store_memory_grow(m_store, to_ffi(memory), delta);
}
-Limits Store::memory_limits(u32 memory)
+Limits Store::memory_limits(Entity memory)
{
- return from_ffi(FFI::wasm_store_memory_limits(m_store, memory));
+ return from_ffi(FFI::wasm_store_memory_limits(m_store, to_ffi(memory)));
}
-u64 Store::table_size(u32 table)
+GC::PrimitiveStorageHandle Store::memory_primitive_storage_handle(Entity memory)
{
- return FFI::wasm_store_table_size(m_store, table);
+ auto handle = FFI::wasm_store_memory_primitive_storage_handle(m_store, to_ffi(memory));
+ return { .index = static_cast<u32>(handle), .generation = static_cast<u32>(handle >> GC_PRIMITIVE_STORAGE_HANDLE_GENERATION_SHIFT) };
}
-ValueType Store::table_element_type(u32 table)
+void Store::set_memory_grow_callback(Function<void(Entity)> callback)
+{
+ m_memory_grow_callback = move(callback);
+ if (!m_memory_grow_callback) {
+ FFI::wasm_store_clear_memory_grow_callback(m_store);
+ return;
+ }
+ FFI::wasm_store_set_memory_grow_callback(
+ m_store, [](void* user_data, void* memory) {
+ static_cast<Store*>(user_data)->m_memory_grow_callback(entity_from_ffi(memory));
+ },
+ this);
+}
+
+u64 Store::table_size(Entity table)
+{
+ return FFI::wasm_store_table_size(m_store, to_ffi(table));
+}
+
+ValueType Store::table_element_type(Entity table)
{
FFI::WasmValueType element {};
FFI::WasmLimits limits {};
- FFI::wasm_store_table_type(m_store, table, &element, &limits);
+ FFI::wasm_store_table_type(m_store, to_ffi(table), &element, &limits);
return from_ffi(element);
}
-Limits Store::table_limits(u32 table)
+Limits Store::table_limits(Entity table)
{
FFI::WasmValueType element {};
FFI::WasmLimits limits {};
- FFI::wasm_store_table_type(m_store, table, &element, &limits);
+ FFI::wasm_store_table_type(m_store, to_ffi(table), &element, &limits);
return from_ffi(limits);
}
-Optional<u64> Store::table_get(u32 table, u64 index)
+Optional<u64> Store::table_get(Entity table, u64 index)
{
u64 value = 0;
- if (!FFI::wasm_store_table_get(m_store, table, index, &value))
+ if (!FFI::wasm_store_table_get(m_store, to_ffi(table), index, &value))
return {};
return value;
}
-bool Store::table_set(u32 table, u64 index, u64 value)
+bool Store::table_set(Entity table, u64 index, u64 value)
+{
+ return FFI::wasm_store_table_set(m_store, to_ffi(table), index, value);
+}
+
+i64 Store::grow_table(Entity table, u64 delta, u64 initial)
{
- return FFI::wasm_store_table_set(m_store, table, index, value);
+ return FFI::wasm_store_table_grow(m_store, to_ffi(table), delta, initial);
}
-i64 Store::grow_table(u32 table, u64 delta, u64 initial)
+ValueType Store::global_type(Entity global, bool& is_mutable)
{
- return FFI::wasm_store_table_grow(m_store, table, delta, initial);
+ return from_ffi(FFI::wasm_store_global_type(m_store, to_ffi(global), &is_mutable));
}
-ValueType Store::global_type(u32 global, bool& is_mutable)
+Value Store::global_get(Entity global)
{
- return from_ffi(FFI::wasm_store_global_type(m_store, global, &is_mutable));
+ return from_ffi(FFI::wasm_store_global_get(m_store, to_ffi(global)));
}
-Value Store::global_get(u32 global)
+void Store::global_set(Entity global, Value value)
{
- return from_ffi(FFI::wasm_store_global_get(m_store, global));
+ FFI::wasm_store_global_set(m_store, to_ffi(global), to_ffi(value));
}
-void Store::global_set(u32 global, Value value)
+static Vector<FFI::WasmStringView> string_views(ReadonlySpan<ByteString> strings)
{
- FFI::wasm_store_global_set(m_store, global, to_ffi(value));
+ Vector<FFI::WasmStringView> views;
+ views.ensure_capacity(strings.size());
+ for (auto const& string : strings)
+ views.unchecked_append({ reinterpret_cast<u8 const*>(string.characters()), string.length() });
+ return views;
+}
+
+Wasi::Wasi(ReadonlySpan<ByteString> arguments, ReadonlySpan<ByteString> environment, ReadonlySpan<Preopen> preopens)
+{
+ Vector<ByteString> host_paths;
+ Vector<ByteString> guest_paths;
+ for (auto const& preopen : preopens) {
+ host_paths.append(preopen.host_path);
+ guest_paths.append(preopen.guest_path);
+ }
+ auto argument_views = string_views(arguments);
+ auto environment_views = string_views(environment);
+ auto host_views = string_views(host_paths);
+ auto guest_views = string_views(guest_paths);
+ m_wasi = FFI::wasm_wasi_create(argument_views.data(), argument_views.size(), environment_views.data(), environment_views.size(), host_views.data(), guest_views.data(), preopens.size());
+}
+
+Wasi::~Wasi()
+{
+ FFI::wasm_wasi_destroy(m_wasi);
+}
+
+Optional<Entity> Wasi::allocate_function(Store& store, StringView name)
+{
+ void* function = nullptr;
+ if (!FFI::wasm_wasi_allocate_function(store.handle(), m_wasi, reinterpret_cast<u8 const*>(name.characters_without_null_termination()), name.length(), &function))
+ return {};
+ return entity_from_ffi(function);
+}
+
+void Wasi::set_memory(Entity memory)
+{
+ FFI::wasm_wasi_set_memory(m_wasi, to_ffi(memory));
+}
+
+Optional<i32> Wasi::exit_code() const
+{
+ i32 code = 0;
+ if (!FFI::wasm_wasi_exit_code(m_wasi, &code))
+ return {};
+ return code;
}
}
diff --git a/Libraries/LibWasm/Runtime/Runtime.h b/Libraries/LibWasm/Runtime/Runtime.h
index cff33a68929..306ee59ba2f 100644
--- a/Libraries/LibWasm/Runtime/Runtime.h
+++ b/Libraries/LibWasm/Runtime/Runtime.h
@@ -16,12 +16,16 @@
#include <AK/Span.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibGC/Forward.h>
+#include <LibGC/PrimitiveStorage.h>
#include <LibWasm/Runtime/Export.h>
namespace Wasm::FFI {
struct WasmModule;
struct WasmStore;
+struct WasmWasi;
}
@@ -103,10 +107,15 @@ enum class ExternKind : u8 {
Tag,
};
-// A function, table, memory, or global of a store, by its address.
+// A function, table, memory, global, tag, or instance: an entity of the store, which is a cell of the store's heap.
+// The store keeps no entity alive: an entity lives while something visits or roots its cell, or while another
+// entity that refers to it lives (an instance refers to what it defines and imports, a function to its instance).
+// Embedders pass the store only entities it made, or the runtime aborts.
+using Entity = GC::ForeignCell*;
+
struct Extern {
ExternKind kind { ExternKind::Function };
- u32 address { 0 };
+ Entity entity { nullptr };
};
struct Limits {
@@ -150,6 +159,14 @@ struct InstanceExport {
Extern value;
};
+struct CustomSection {
+ StringView name;
+ ReadonlyBytes contents;
+};
+
+// Values that may be references to cells, which the garbage collector finds while the vector lives.
+using Values = GC::ConservativeVector<Value, 8>;
+
// A compiled module, which can be shared across threads and instantiated in any store.
class WASMRUNTIME_API Module : public AtomicRefCounted<Module> {
public:
@@ -161,6 +178,8 @@ public:
size_t export_count() const;
ModuleExport module_export(size_t index) const;
Optional<FunctionType> function_type(u32 type_index) const;
+ size_t custom_section_count() const;
+ CustomSection custom_section(size_t index) const;
FFI::WasmModule const* handle() const { return m_module; }
@@ -176,62 +195,132 @@ private:
enum class FailureKind : u8 {
LinkError,
Trap,
+ // An exception was thrown and not caught: `exception` refers to it.
+ Exception,
+ StackExhausted,
};
struct Failure {
FailureKind kind { FailureKind::Trap };
ByteString message;
+ u64 exception { 0 };
+};
+
+// How a host function fails: it traps with a message, or throws an exception, which WebAssembly code can catch.
+struct HostError {
+ HostError(ByteString message)
+ : message(move(message))
+ {
+ }
+
+ static HostError exception(u64 reference)
+ {
+ HostError error { ByteString {} };
+ error.thrown_exception = reference;
+ return error;
+ }
+
+ ByteString message;
+ Optional<u64> thrown_exception;
};
-// Functions, tables, memories, globals, and instances, all of one thread.
+// What the entities of one thread share: their heap, types, and the interpreter's state. One store serves a whole
+// agent.
class WASMRUNTIME_API Store {
AK_MAKE_NONCOPYABLE(Store);
AK_MAKE_NONMOVABLE(Store);
AK_ALLOC_WITH_KMALLOC;
public:
- Store();
+ // Entities and GC objects live in the heap, and memories in LibGC's primitive storage.
+ explicit Store(GC::Heap&);
~Store();
- // A host function writes one result for each result of its type, or returns an error to trap.
- using HostFunction = Function<ErrorOr<void, ByteString>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
-
- u32 allocate_host_function(FunctionType const&, HostFunction);
- Optional<u32> allocate_memory(Limits);
- u32 allocate_table(ValueType element, Limits, u64 initial);
- u32 allocate_global(ValueType, bool is_mutable, Value);
-
- ErrorOr<u32, Failure> instantiate(Module const&, ReadonlySpan<Extern> imports);
- Vector<InstanceExport> instance_exports(u32 instance);
- Optional<Extern> find_export(u32 instance, StringView name);
-
- FunctionType function_type(u32 function);
- ErrorOr<Vector<Value>, ByteString> invoke(u32 function, ReadonlySpan<Value> arguments);
- u64 function_reference(u32 function);
- Optional<u32> function_from_reference(u64 reference);
+ // A host function writes one result for each result of its type, or returns an error to trap or throw. Its
+ // function visits the cells it captures, so it must not capture roots.
+ using HostFunction = Function<ErrorOr<void, HostError>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
+
+ Entity allocate_host_function(FunctionType const&, HostFunction);
+ Optional<Entity> allocate_memory(Limits);
+ Optional<Entity> allocate_table(ValueType element, Limits, u64 initial);
+ Entity allocate_global(ValueType, bool is_mutable, Value);
+
+ // Returns the instance.
+ ErrorOr<Entity, Failure> instantiate(Module const&, ReadonlySpan<Extern> imports);
+ Vector<InstanceExport> instance_exports(Entity instance);
+ Optional<Extern> find_export(Entity instance, StringView name);
+
+ FunctionType function_type(Entity function);
+ ErrorOr<Values, Failure> invoke(Entity function, ReadonlySpan<Value> arguments);
+ u64 function_reference(Entity function);
+ // The function a non-null function reference refers to.
+ Entity function_from_reference(u64 reference);
+ // The index of a WebAssembly function in the function index space of the module that defines it, or nothing for
+ // a host function.
+ Optional<u32> function_index(Entity function);
+
+ Entity allocate_tag(ReadonlySpan<ValueType> parameters);
+ Vector<ValueType> tag_parameters(Entity tag);
+ // An exception is a cell of the heap, which keeps it while something refers to it.
+ u64 allocate_exception(Entity tag, ReadonlySpan<Value> values);
+ Entity exception_tag(u64 exception);
+ Values exception_values(u64 exception);
// The bytes of a memory move when it grows.
- Bytes memory(u32 memory);
+ Bytes memory(Entity memory);
// The previous size in pages, or -1 if the memory cannot grow.
- i64 grow_memory(u32 memory, u64 delta);
- Limits memory_limits(u32 memory);
-
- u64 table_size(u32 table);
- ValueType table_element_type(u32 table);
- Limits table_limits(u32 table);
- Optional<u64> table_get(u32 table, u64 index);
- bool table_set(u32 table, u64 index, u64 value);
+ i64 grow_memory(Entity memory, u64 delta);
+ Limits memory_limits(Entity memory);
+ GC::PrimitiveStorageHandle memory_primitive_storage_handle(Entity memory);
+ // Runs after each memory.grow instruction that grows a memory, but not after grow_memory().
+ void set_memory_grow_callback(Function<void(Entity memory)>);
+
+ u64 table_size(Entity table);
+ ValueType table_element_type(Entity table);
+ Limits table_limits(Entity table);
+ Optional<u64> table_get(Entity table, u64 index);
+ bool table_set(Entity table, u64 index, u64 value);
// The previous size, or -1 if the table cannot grow.
- i64 grow_table(u32 table, u64 delta, u64 initial);
+ i64 grow_table(Entity table, u64 delta, u64 initial);
- ValueType global_type(u32 global, bool& is_mutable);
- Value global_get(u32 global);
- void global_set(u32 global, Value);
+ ValueType global_type(Entity global, bool& is_mutable);
+ Value global_get(Entity global);
+ void global_set(Entity global, Value);
FFI::WasmStore* handle() { return m_store; }
private:
FFI::WasmStore* m_store { nullptr };
+ Function<void(Entity)> m_memory_grow_callback;
+};
+
+// The state of a WASI (wasi_snapshot_preview1) command. Its functions only work on Unix hosts.
+class WASMRUNTIME_API Wasi {
+ AK_MAKE_NONCOPYABLE(Wasi);
+ AK_MAKE_NONMOVABLE(Wasi);
+ AK_ALLOC_WITH_KMALLOC;
+
+public:
+ struct Preopen {
+ ByteString host_path;
+ ByteString guest_path;
+ };
+
+ // The environment is a list of NAME=value strings.
+ Wasi(ReadonlySpan<ByteString> arguments, ReadonlySpan<ByteString> environment, ReadonlySpan<Preopen> preopens);
+ ~Wasi();
+
+ static constexpr StringView module_name = "wasi_snapshot_preview1"sv;
+
+ // Add the WASI function `name` to the store, if there is one.
+ Optional<Entity> allocate_function(Store&, StringView name);
+ // Have the functions work on `memory`, usually the one the command exports.
+ void set_memory(Entity memory);
+ // The code the command passed to proc_exit, if it called it.
+ Optional<i32> exit_code() const;
+
+private:
+ FFI::WasmWasi* m_wasi { nullptr };
};
}
diff --git a/Libraries/LibWasm/Tests/Executor/test-gc-collection.js b/Libraries/LibWasm/Tests/Executor/test-gc-collection.js
new file mode 100644
index 00000000000..218745461ee
--- /dev/null
+++ b/Libraries/LibWasm/Tests/Executor/test-gc-collection.js
@@ -0,0 +1,9 @@
+test("objects, arrays, and exceptions that become garbage are collected", () => {
+ const module = parseWebAssemblyModule(readBinaryWasmFile("Fixtures/Modules/gc-churn.wasm"));
+ const churn = module.getExport("churn");
+ const before = peakResidentMemorySize();
+ // 100000 iterations allocate more than 6 GiB of arrays alone.
+ expect(module.invoke(churn, 100000)).toBe(99999n);
+ const growth = peakResidentMemorySize() - before;
+ expect(growth).toBeLessThan(1024 * 1024 * 1024);
+});
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wasm
new file mode 100644
index 00000000000..5308a58b73d
Binary files /dev/null and b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wasm differ
diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wat
new file mode 100644
index 00000000000..fd752dc53fb
--- /dev/null
+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/gc-churn.wat
@@ -0,0 +1,21 @@
+;; Allocates objects, large arrays, and exceptions that become garbage right away.
+(module
+ (type $node (struct (field (mut i64)) (field (ref null $node))))
+ (type $bytes (array (mut i32)))
+ (tag $thrown (param (ref null $node)))
+ (func (export "churn") (param $count i32) (result i64)
+ (local $index i32)
+ (local $last (ref null $node))
+ (loop $again
+ (local.set $last (struct.new $node (i64.extend_i32_u (local.get $index)) (ref.null $node)))
+ ;; 64 KiB of elements, which live outside the heap.
+ (drop (array.new_default $bytes (i32.const 16384)))
+ (block $caught (result (ref null $node))
+ (try_table (catch $thrown $caught)
+ (throw $thrown (local.get $last)))
+ (unreachable))
+ (drop)
+ (local.set $index (i32.add (local.get $index) (i32.const 1)))
+ (br_if $again (i32.lt_u (local.get $index) (local.get $count))))
+ (struct.get $node 0 (local.get $last)))
+)
diff --git a/Libraries/LibWasm/Tests/differential-fuzz.py b/Libraries/LibWasm/Tests/differential-fuzz.py
new file mode 100644
index 00000000000..b648c42ba05
--- /dev/null
+++ b/Libraries/LibWasm/Tests/differential-fuzz.py
@@ -0,0 +1,319 @@
+#!/usr/bin/env python3
+# Differential fuzzing of the WebAssembly engine against other ones: `wasm-tools smith` generates valid modules, to
+# which this script adds, for each exported function, a probe that calls the function with zero arguments and returns
+# a hash of its results (floats as their bits, references as whether they are null) and of memory 0. Each engine runs
+# each probe; whether it traps and the hash it returns must agree. When the engine under test and the old engine
+# disagree, wabt's interpreter (wasm-interp) decides which one is wrong.
+#
+# differential-fuzz.py --new Build/release/bin/wasm --old /path/to/old/wasm --cases 500 --out /tmp/fuzz
+#
+# Each case that the engine under test gets wrong is kept in the output directory with what the engines returned.
+# Re-run a single case with --seed. Cases are reproducible from their seed.
+
+import argparse
+import concurrent.futures
+import os
+import random
+import re
+import subprocess
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from reencode import DecodeError # noqa: E402
+from reencode import Reader # noqa: E402
+from reencode import unsigned_leb # noqa: E402
+
+SMITH_FEATURES = [
+ "--ensure-termination",
+ "--export-everything",
+ "true",
+ "--canonicalize-nans",
+ "true",
+ "--max-imports",
+ "0",
+ "--min-funcs",
+ "1",
+ "--max-funcs",
+ "8",
+ "--max-memory32-bytes",
+ str(16 * 65536),
+ "--max-memories",
+ "1",
+ "--max-tables",
+ "2",
+ "--max-table-elements",
+ "100",
+ "--max-data-segments",
+ "4",
+ "--simd-enabled",
+ "true",
+ "--bulk-memory-enabled",
+ "true",
+ "--reference-types-enabled",
+ "true",
+ "--multi-value-enabled",
+ "true",
+ "--saturating-float-to-int-enabled",
+ "true",
+ "--sign-extension-ops-enabled",
+ "true",
+ "--tail-call-enabled",
+ "true",
+ "--relaxed-simd-enabled",
+ "false",
+ "--gc-enabled",
+ "false",
+ "--exceptions-enabled",
+ "false",
+ "--threads-enabled",
+ "false",
+ "--memory64-enabled",
+ "false",
+ "--extended-const-enabled",
+ "true",
+ "--allow-start-export",
+ "false",
+]
+
+VALUE_TYPE_ZERO = {
+ 0x7F: bytes([0x41, 0x00]),
+ 0x7E: bytes([0x42, 0x00]),
+ 0x7D: bytes([0x43, 0, 0, 0, 0]),
+ 0x7C: bytes([0x44, 0, 0, 0, 0, 0, 0, 0, 0]),
+ 0x7B: bytes([0xFD, 0x0C]) + bytes(16),
+ 0x70: bytes([0xD0, 0x70]),
+ 0x6F: bytes([0xD0, 0x6F]),
+}
+
+
+def sections_of(data):
+ reader = Reader(data, 8)
+ sections = []
+ while reader.position < reader.end:
+ section_id = reader.byte()
+ size = reader.unsigned(32)
+ sections.append([section_id, bytearray(reader.bytes(size))])
+ return sections
+
+
+def vector_of(contents):
+ reader = Reader(bytes(contents))
+ return reader, reader.unsigned(32)
+
+
+def add_probes(data):
+ """Add, for each exported function, an exported `__probe_<n>` that calls it with zero arguments, drops its
+ results, and returns a hash of memory 0. Returns the new module and the names of the functions probed."""
+ sections = sections_of(data)
+ by_id = {section_id: contents for section_id, contents in sections}
+ if 2 in by_id and vector_of(by_id[2])[1] > 0:
+ raise DecodeError("imports are not probed")
+ types = []
+ reader, count = vector_of(by_id.get(1, b"\0"))
+ for _ in range(count):
+ if reader.byte() != 0x60:
+ raise DecodeError("only function types are probed")
+ parameters = [reader.byte() for _ in range(reader.unsigned(32))]
+ results = [reader.byte() for _ in range(reader.unsigned(32))]
+ if any(t not in VALUE_TYPE_ZERO for t in parameters + results):
+ raise DecodeError("unprobed value type")
+ types.append((parameters, results))
+ reader, count = vector_of(by_id.get(3, b"\0"))
+ functions = [reader.unsigned(32) for _ in range(count)]
+ reader, count = vector_of(by_id.get(7, b"\0"))
+ exports = []
+ for _ in range(count):
+ name = reader.bytes(reader.unsigned(32)).decode()
+ kind = reader.byte()
+ index = reader.unsigned(32)
+ if kind == 0:
+ exports.append((name, index))
+ has_memory = 5 in by_id and vector_of(by_id[5])[1] > 0
+
+ probe_type = len(types)
+ new_types = bytearray(by_id.get(1, b"\0"))
+ reader, count = vector_of(new_types)
+ new_types = bytearray(unsigned_leb(count + 1)) + new_types[reader.position :] + bytes([0x60, 0x00, 0x01, 0x7E])
+
+ # Locals: $i (i32), $hash (i64), $vector (v128).
+ fold = bytes([0x20, 0x01, 0x42, 0x1F, 0x7E, 0x7C, 0x21, 0x01])
+ folds = {
+ 0x7F: bytes([0xAD]) + fold,
+ 0x7E: fold,
+ 0x7D: bytes([0xBC, 0xAD]) + fold,
+ 0x7C: bytes([0xBD]) + fold,
+ 0x7B: bytes([0x21, 0x02, 0x20, 0x02, 0xFD, 0x1D, 0x00]) + fold + bytes([0x20, 0x02, 0xFD, 0x1D, 0x01]) + fold,
+ 0x70: bytes([0xD1, 0xAD]) + fold,
+ 0x6F: bytes([0xD1, 0xAD]) + fold,
+ }
+ bodies = []
+ for _, function_index in exports:
+ parameters, results = types[functions[function_index]]
+ code = bytearray()
+ for parameter in parameters:
+ code += VALUE_TYPE_ZERO[parameter]
+ code += bytes([0x10]) + unsigned_leb(function_index)
+ # The last result is on top.
+ for result in reversed(results):
+ code += folds[result]
+ if has_memory:
+ # block loop
+ # i >= memory.size << 16 -> exit
+ # hash = hash * 31 + i64.load(i); i += 8
+ # end end
+ code += bytes([0x02, 0x40, 0x03, 0x40])
+ code += bytes([0x20, 0x00, 0x3F, 0x00, 0x41, 0x10, 0x74, 0x4F, 0x0D, 0x01])
+ code += bytes([0x20, 0x00, 0x29, 0x03, 0x00]) + fold
+ code += bytes([0x20, 0x00, 0x41, 0x08, 0x6A, 0x21, 0x00, 0x0C, 0x00])
+ code += bytes([0x0B, 0x0B])
+ code += bytes([0x20, 0x01, 0x0B])
+ body = bytes([0x03, 0x01, 0x7F, 0x01, 0x7E, 0x01, 0x7B]) + bytes(code)
+ bodies.append(unsigned_leb(len(body)) + body)
+
+ reader, count = vector_of(by_id.get(3, b"\0"))
+ new_functions = bytearray(unsigned_leb(count + len(exports))) + by_id.get(3, b"\0")[reader.position :]
+ new_functions += unsigned_leb(probe_type) * len(exports)
+ reader, count = vector_of(by_id.get(10, b"\0"))
+ new_code = bytearray(unsigned_leb(count + len(exports))) + by_id.get(10, b"\0")[reader.position :]
+ for body in bodies:
+ new_code += body
+ reader, count = vector_of(by_id.get(7, b"\0"))
+ # Every function gets a plain name as well, since smith's names may not survive a command line.
+ new_exports = bytearray(unsigned_leb(count + 2 * len(exports))) + by_id.get(7, b"\0")[reader.position :]
+ for probe, (_, function_index) in enumerate(exports):
+ name = f"__function_{probe}".encode()
+ new_exports += unsigned_leb(len(name)) + name + bytes([0x00]) + unsigned_leb(function_index)
+ name = f"__probe_{probe}".encode()
+ new_exports += unsigned_leb(len(name)) + name + bytes([0x00]) + unsigned_leb(len(functions) + probe)
+
+ replaced = {1: new_types, 3: new_functions, 7: new_exports, 10: new_code}
+ present = {section_id for section_id, _ in sections}
+ order = [1, 2, 3, 4, 5, 13, 6, 7, 8, 9, 12, 10, 11]
+ out = bytearray(data[:8])
+ for section_id in order:
+ if section_id in replaced:
+ contents = replaced[section_id]
+ elif section_id in present:
+ contents = by_id[section_id]
+ else:
+ continue
+ out += bytes([section_id]) + unsigned_leb(len(contents)) + contents
+ return bytes(out), [name for name, _ in exports]
+
+
+def outcome_of(process):
+ if process.returncode < 0:
+ return f"crash {process.returncode}"
+ output = process.stdout + process.stderr
+ if "trapped" in output or ") => error" in output:
+ return "trap"
+ if "failed" in output.lower() or "error:" in output:
+ return "failed"
+ match = re.search(r"(?: -> |=> i64:)(-?[0-9]+)", output)
+ if not match:
+ return "failed"
+ # Engines print the hash signed or unsigned.
+ return f"returned {int(match[1]) % (1 << 64)}"
+
+
+def run(binary, module, function):
+ try:
+ process = subprocess.run([binary, "-e", function, module], capture_output=True, text=True, timeout=60)
+ except subprocess.TimeoutExpired:
+ return "timeout"
+ return outcome_of(process)
+
+
+def run_wabt(module, function):
+ try:
+ process = subprocess.run(
+ ["wasm-interp", "--enable-all", module, "-r", function], capture_output=True, text=True, timeout=60
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError):
+ return "unavailable"
+ return outcome_of(process)
+
+
+def run_case(seed, arguments):
+ random.seed(seed)
+ entropy = bytes(random.getrandbits(8) for _ in range(arguments.entropy))
+ smith = subprocess.run(
+ [arguments.wasm_tools, "smith", *SMITH_FEATURES, *arguments.smith_argument],
+ input=entropy,
+ capture_output=True,
+ timeout=60,
+ )
+ if smith.returncode != 0:
+ return seed, "skipped", "smith failed"
+ try:
+ module, names = add_probes(smith.stdout)
+ except (DecodeError, IndexError, UnicodeDecodeError) as error:
+ return seed, "skipped", str(error)
+ path = os.path.join(arguments.out, f"case-{seed}.wasm")
+ with open(path, "wb") as file:
+ file.write(module)
+ differences = []
+ verdict = "same"
+ for probe in range(len(names)):
+ function = f"__probe_{probe}"
+ new = run(arguments.new, path, function)
+ old = run(arguments.old, path, function)
+ if new == old:
+ continue
+ wabt = run_wabt(path, function)
+ if old == "failed" and wabt == "failed" and new != "failed":
+ # Neither reference engine can run the module, which is valid (smith only makes valid ones).
+ if verdict == "same":
+ verdict = "references-fail"
+ continue
+ if wabt == new:
+ # The old engine is wrong, or cannot run the module (smith only makes valid ones).
+ if verdict == "same":
+ verdict = "old-wrong"
+ continue
+ verdict = "different"
+ differences.append(f"{function}: new {new!r}, old {old!r}, wabt {wabt!r}")
+ if differences:
+ with open(os.path.join(arguments.out, f"case-{seed}.txt"), "w") as file:
+ file.write("\n".join(differences) + "\n")
+ return seed, "different", "; ".join(differences[:3])
+ os.remove(path)
+ return seed, verdict, f"{len(names)} functions"
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--new", required=True)
+ parser.add_argument("--old", required=True)
+ parser.add_argument("--wasm-tools", default=os.path.expanduser("~/.cargo/bin/wasm-tools"))
+ parser.add_argument("--cases", type=int, default=200)
+ parser.add_argument("--first-seed", type=int, default=0)
+ parser.add_argument("--seed", type=int)
+ parser.add_argument("--entropy", type=int, default=4096)
+ parser.add_argument("--jobs", type=int, default=8)
+ parser.add_argument("--out", required=True)
+ parser.add_argument(
+ "--smith-argument", action="append", default=[], help="More arguments for smith, like --min-uleb-size=5"
+ )
+ arguments = parser.parse_args()
+ os.makedirs(arguments.out, exist_ok=True)
+ seeds = (
+ [arguments.seed]
+ if arguments.seed is not None
+ else range(arguments.first_seed, arguments.first_seed + arguments.cases)
+ )
+ counts = {"same": 0, "different": 0, "skipped": 0, "old-wrong": 0, "references-fail": 0}
+ with concurrent.futures.ThreadPoolExecutor(max_workers=arguments.jobs) as pool:
+ for seed, verdict, detail in pool.map(lambda seed: run_case(seed, arguments), seeds):
+ counts[verdict] += 1
+ if verdict == "different":
+ print(f"seed {seed}: {verdict}: {detail}", flush=True)
+ print(
+ f"{counts['same']} same, {counts['different']} different, {counts['skipped']} skipped, "
+ f"{counts['old-wrong']} where only the old engine is wrong (by wabt), "
+ f"{counts['references-fail']} that neither the old engine nor wabt can run"
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Libraries/LibWasm/Tests/reencode.py b/Libraries/LibWasm/Tests/reencode.py
new file mode 100644
index 00000000000..f9ab0b5136a
--- /dev/null
+++ b/Libraries/LibWasm/Tests/reencode.py
@@ -0,0 +1,477 @@
+#!/usr/bin/env python3
+# Re-encode the function bodies of WebAssembly modules, so that the engine's decoding of immediates can be tested on
+# every encoding the binary format allows, not only the minimal ones that tools emit.
+#
+# reencode.py --mode wide IN OUT Every LEB128 in a function body takes its maximum width: 5 bytes for u32,
+# s32, and s33, 10 for u64 and s64.
+# reencode.py --mode memory-index ... Every memory argument names its memory, including memory 0.
+# reencode.py --tree SOURCE DEST ... Re-encode every .wasm under SOURCE into DEST; other files are linked.
+#
+# Modules this script cannot decode (malformed or invalid ones that the tests expect to be rejected) are copied as
+# they are. Sections and bodies get their sizes fixed up.
+
+import argparse
+import os
+import sys
+
+
+class DecodeError(Exception):
+ pass
+
+
+class Reader:
+ def __init__(self, data, position=0, end=None):
+ self.data = data
+ self.position = position
+ self.end = len(data) if end is None else end
+
+ def byte(self):
+ if self.position >= self.end:
+ raise DecodeError("unexpected end")
+ value = self.data[self.position]
+ self.position += 1
+ return value
+
+ def bytes(self, count):
+ if self.position + count > self.end:
+ raise DecodeError("unexpected end")
+ value = self.data[self.position : self.position + count]
+ self.position += count
+ return value
+
+ def unsigned(self, bits):
+ # Strict, like the binary format: at most ceil(bits / 7) bytes, and the unused bits of the last one are zero.
+ result = 0
+ shift = 0
+ while True:
+ byte = self.byte()
+ result |= (byte & 0x7F) << shift
+ shift += 7
+ if byte & 0x80 == 0:
+ break
+ if shift >= bits:
+ raise DecodeError("integer too long")
+ if result >> bits:
+ raise DecodeError("integer too large")
+ return result
+
+ def signed(self, bits):
+ # Strict, like the binary format: at most ceil(bits / 7) bytes, and the unused bits of the last one extend the
+ # sign.
+ result = 0
+ shift = 0
+ while True:
+ byte = self.byte()
+ result |= (byte & 0x7F) << shift
+ shift += 7
+ if byte & 0x80 == 0:
+ break
+ if shift >= bits:
+ raise DecodeError("integer too long")
+ if shift > bits:
+ unused = shift - bits
+ top = (byte & 0x7F) >> (7 - unused - 1)
+ if top not in (0, (1 << (unused + 1)) - 1):
+ raise DecodeError("integer too large")
+ if result >> (shift - 1):
+ result -= 1 << shift
+ return result
+
+
+def unsigned_leb(value, width=None):
+ out = bytearray()
+ while True:
+ byte = value & 0x7F
+ value >>= 7
+ if value == 0 and width is None:
+ out.append(byte)
+ return bytes(out)
+ out.append(byte | 0x80)
+ if width is not None and len(out) == width - 1:
+ out.append(value & 0x7F)
+ return bytes(out)
+
+
+def signed_leb(value, width=None):
+ out = bytearray()
+ if width is None:
+ while True:
+ byte = value & 0x7F
+ value >>= 7
+ if (value == 0 and byte & 0x40 == 0) or (value == -1 and byte & 0x40):
+ out.append(byte)
+ return bytes(out)
+ out.append(byte | 0x80)
+ for _ in range(width - 1):
+ out.append((value & 0x7F) | 0x80)
+ value >>= 7
+ out.append(value & 0x7F)
+ return bytes(out)
+
+
+# Widths of the maximal encodings.
+U32 = 5
+S32 = 5
+S33 = 5
+U64 = 10
+S64 = 10
+
+
+class Encoder:
+ def __init__(self, mode):
+ self.mode = mode
+ self.out = bytearray()
+
+ def u32(self, value):
+ self.out += unsigned_leb(value, U32 if self.mode == "wide" else None)
+
+ def u64(self, value):
+ self.out += unsigned_leb(value, U64 if self.mode == "wide" else None)
+
+ def s32(self, value):
+ self.out += signed_leb(value, S32 if self.mode == "wide" else None)
+
+ def s33(self, value):
+ self.out += signed_leb(value, S33 if self.mode == "wide" else None)
+
+ def s64(self, value):
+ self.out += signed_leb(value, S64 if self.mode == "wide" else None)
+
+ def raw(self, data):
+ self.out += data
+
+
+def copy_heap_type(reader, encoder):
+ first = reader.data[reader.position]
+ if first & 0x40 and first & 0x80 == 0:
+ # An abstract heap type, which is a byte.
+ encoder.raw(bytes([reader.byte()]))
+ return
+ value = reader.signed(33)
+ if value < 0:
+ raise DecodeError("negative heap type")
+ encoder.s33(value)
+
+
+def copy_value_type(reader, encoder):
+ byte = reader.byte()
+ encoder.raw(bytes([byte]))
+ if byte in (0x63, 0x64):
+ copy_heap_type(reader, encoder)
+
+
+def copy_block_type(reader, encoder):
+ first = reader.data[reader.position]
+ if first == 0x40:
+ encoder.raw(bytes([reader.byte()]))
+ return
+ if first & 0x40 and first & 0x80 == 0:
+ copy_value_type(reader, encoder)
+ return
+ value = reader.signed(33)
+ if value < 0:
+ raise DecodeError("negative block type")
+ encoder.s33(value)
+
+
+def copy_memory_argument(reader, encoder):
+ flags = reader.unsigned(32)
+ has_index = flags & 0x40
+ memory = reader.unsigned(32) if has_index else 0
+ offset = reader.unsigned(64)
+ if encoder.mode == "memory-index":
+ has_index = True
+ encoder.u32(flags | 0x40 if has_index else flags)
+ if has_index:
+ encoder.u32(memory)
+ encoder.u64(offset)
+
+
+# Immediates of the single-byte opcodes. "u" is a u32, "b" a block type, "m" a memory argument, "h" a heap type, "l" a
+# lane index byte, "z" a zero byte, and "v" sixteen bytes.
+PLAIN = {
+ 0x00: "",
+ 0x01: "",
+ 0x02: "b",
+ 0x03: "b",
+ 0x04: "b",
+ 0x05: "",
+ 0x08: "u",
+ 0x0A: "",
+ 0x0B: "",
+ 0x0C: "u",
+ 0x0D: "u",
+ 0x0F: "",
+ 0x10: "u",
+ 0x11: "uu",
+ 0x12: "u",
+ 0x13: "uu",
+ 0x14: "u",
+ 0x15: "u",
+ 0x1A: "",
+ 0x1B: "",
+ 0x20: "u",
+ 0x21: "u",
+ 0x22: "u",
+ 0x23: "u",
+ 0x24: "u",
+ 0x25: "u",
+ 0x26: "u",
+ 0x3F: "u",
+ 0x40: "u",
+ 0xD0: "h",
+ 0xD1: "",
+ 0xD2: "u",
+ 0xD3: "",
+ 0xD4: "",
+ 0xD5: "u",
+ 0xD6: "u",
+}
+for opcode in range(0x28, 0x3F):
+ PLAIN[opcode] = "m"
+for opcode in range(0x45, 0xC5):
+ PLAIN[opcode] = ""
+
+# The 0xFB (GC) sub-opcodes. "c" is br_on_cast's flags byte and two heap types after a label.
+GC = {
+ 0: "u",
+ 1: "u",
+ 2: "uu",
+ 3: "uu",
+ 4: "uu",
+ 5: "uu",
+ 6: "u",
+ 7: "u",
+ 8: "uu",
+ 9: "uu",
+ 10: "uu",
+ 11: "u",
+ 12: "u",
+ 13: "u",
+ 14: "u",
+ 15: "",
+ 16: "u",
+ 17: "uu",
+ 18: "uu",
+ 19: "uu",
+ 20: "h",
+ 21: "h",
+ 22: "h",
+ 23: "h",
+ 24: "c",
+ 25: "c",
+ 26: "",
+ 27: "",
+ 28: "",
+ 29: "",
+ 30: "",
+}
+
+MISC = {
+ 0: "",
+ 1: "",
+ 2: "",
+ 3: "",
+ 4: "",
+ 5: "",
+ 6: "",
+ 7: "",
+ 8: "uu",
+ 9: "u",
+ 10: "uu",
+ 11: "u",
+ 12: "uu",
+ 13: "u",
+ 14: "uu",
+ 15: "u",
+ 16: "u",
+ 17: "u",
+}
+
+
+def simd_immediates(sub):
+ if sub <= 0x0B or sub in (0x5C, 0x5D):
+ return "m"
+ if 0x54 <= sub <= 0x5B:
+ return "ml"
+ if sub == 0x0C:
+ return "v"
+ if sub == 0x0D:
+ return "v"
+ if 0x15 <= sub <= 0x22:
+ return "l"
+ return ""
+
+
+def atomic_immediates(sub):
+ if sub == 0x03:
+ return "z"
+ return "m"
+
+
+def copy_immediates(reader, encoder, kinds):
+ index = 0
+ while index < len(kinds):
+ kind = kinds[index]
+ if kind == "u":
+ encoder.u32(reader.unsigned(32))
+ elif kind == "b":
+ copy_block_type(reader, encoder)
+ elif kind == "m":
+ copy_memory_argument(reader, encoder)
+ elif kind == "h":
+ copy_heap_type(reader, encoder)
+ elif kind == "l" or kind == "z":
+ encoder.raw(bytes([reader.byte()]))
+ elif kind == "v":
+ # A v128 constant or a shuffle's sixteen lanes.
+ encoder.raw(reader.bytes(16))
+ elif kind == "c":
+ encoder.raw(bytes([reader.byte()]))
+ encoder.u32(reader.unsigned(32))
+ copy_heap_type(reader, encoder)
+ copy_heap_type(reader, encoder)
+ else:
+ raise DecodeError(f"unknown immediate kind {kind}")
+ index += 1
+
+
+def copy_instruction(reader, encoder):
+ opcode = reader.byte()
+ encoder.raw(bytes([opcode]))
+ if opcode in PLAIN:
+ copy_immediates(reader, encoder, PLAIN[opcode])
+ return
+ if opcode == 0x0E:
+ count = reader.unsigned(32)
+ encoder.u32(count)
+ for _ in range(count + 1):
+ encoder.u32(reader.unsigned(32))
+ return
+ if opcode == 0x1C:
+ count = reader.unsigned(32)
+ encoder.u32(count)
+ for _ in range(count):
+ copy_value_type(reader, encoder)
+ return
+ if opcode == 0x1F:
+ copy_block_type(reader, encoder)
+ count = reader.unsigned(32)
+ encoder.u32(count)
+ for _ in range(count):
+ kind = reader.byte()
+ encoder.raw(bytes([kind]))
+ if kind < 2:
+ encoder.u32(reader.unsigned(32))
+ encoder.u32(reader.unsigned(32))
+ return
+ if opcode == 0x41:
+ encoder.s32(reader.signed(32))
+ return
+ if opcode == 0x42:
+ encoder.s64(reader.signed(64))
+ return
+ if opcode == 0x43:
+ encoder.raw(reader.bytes(4))
+ return
+ if opcode == 0x44:
+ encoder.raw(reader.bytes(8))
+ return
+ if opcode in (0xFB, 0xFC, 0xFD, 0xFE):
+ sub = reader.unsigned(32)
+ encoder.u32(sub)
+ if opcode == 0xFB:
+ kinds = GC.get(sub)
+ elif opcode == 0xFC:
+ kinds = MISC.get(sub)
+ elif opcode == 0xFD:
+ kinds = simd_immediates(sub)
+ else:
+ kinds = atomic_immediates(sub)
+ if kinds is None:
+ raise DecodeError(f"unknown sub-opcode {opcode:#x} {sub}")
+ copy_immediates(reader, encoder, kinds)
+ return
+ raise DecodeError(f"unknown opcode {opcode:#x}")
+
+
+def reencode_body(body, mode):
+ reader = Reader(body)
+ encoder = Encoder(mode)
+ groups = reader.unsigned(32)
+ encoder.u32(groups)
+ for _ in range(groups):
+ encoder.u32(reader.unsigned(32))
+ copy_value_type(reader, encoder)
+ while reader.position < reader.end:
+ copy_instruction(reader, encoder)
+ return bytes(encoder.out)
+
+
+def reencode_module(data, mode):
+ if data[:8] != b"\0asm\x01\0\0\0":
+ raise DecodeError("not a module")
+ reader = Reader(data, 8)
+ out = bytearray(data[:8])
+ while reader.position < reader.end:
+ section_id = reader.byte()
+ size = reader.unsigned(32)
+ contents = reader.bytes(size)
+ if section_id != 10:
+ out += bytes([section_id]) + unsigned_leb(size) + contents
+ continue
+ section = Reader(contents)
+ count = section.unsigned(32)
+ new_contents = bytearray(unsigned_leb(count))
+ for _ in range(count):
+ body_size = section.unsigned(32)
+ body = reencode_body(section.bytes(body_size), mode)
+ new_contents += unsigned_leb(len(body)) + body
+ if section.position != section.end:
+ raise DecodeError("code section has trailing bytes")
+ out += bytes([10]) + unsigned_leb(len(new_contents)) + new_contents
+ return bytes(out)
+
+
+def reencode_tree(source, destination, mode):
+ rewritten = 0
+ kept = 0
+ for directory, _, files in os.walk(source):
+ relative = os.path.relpath(directory, source)
+ target = os.path.join(destination, relative)
+ os.makedirs(target, exist_ok=True)
+ for name in files:
+ source_path = os.path.join(directory, name)
+ target_path = os.path.join(target, name)
+ if os.path.lexists(target_path):
+ os.remove(target_path)
+ if not name.endswith(".wasm"):
+ os.symlink(os.path.abspath(source_path), target_path)
+ continue
+ data = open(source_path, "rb").read()
+ try:
+ new = reencode_module(data, mode)
+ rewritten += 1
+ except (DecodeError, IndexError):
+ new = data
+ kept += 1
+ open(target_path, "wb").write(new)
+ print(f"{rewritten} modules re-encoded, {kept} kept as they were", file=sys.stderr)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--mode", choices=["wide", "memory-index"], required=True)
+ parser.add_argument("--tree", action="store_true")
+ parser.add_argument("source")
+ parser.add_argument("destination")
+ arguments = parser.parse_args()
+ if arguments.tree:
+ reencode_tree(arguments.source, arguments.destination, arguments.mode)
+ return
+ data = open(arguments.source, "rb").read()
+ open(arguments.destination, "wb").write(reencode_module(data, arguments.mode))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/Libraries/LibWeb/Bindings/HostDefined.cpp b/Libraries/LibWeb/Bindings/HostDefined.cpp
index 3775c102a0e..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/WebAssembly.h>
namespace Web::Bindings {
@@ -32,8 +31,6 @@ void HostDefined::visit_edges(Cell::Visitor& visitor)
visitor.visit(intrinsics);
visitor.visit(wrapper_world);
visitor.visit(principal_realm);
- if (wasm_cache)
- wasm_cache->visit_edges(visitor);
}
}
diff --git a/Libraries/LibWeb/Bindings/HostDefined.h b/Libraries/LibWeb/Bindings/HostDefined.h
index f72c3358b77..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;
- // Created on demand by WebAssembly::Detail::get_cache(). The realm is the only owner that traces it, so the wrapper
- // maps are visited exactly once per collection no matter how many WebAssembly objects are live.
- RefPtr<WebAssembly::Detail::WebAssemblyCache> wasm_cache;
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/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8a34d878912..48e4b7f064b 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -1145,7 +1145,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 LibCompress 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 LibCompress LibCrypto LibHTTP LibGfx LibIPC LibRegex LibSyntax LibTextCodec LibUnicode LibAudio LibMedia LibMediaClient LibWasmRuntime 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/WebAssembly/Global.cpp b/Libraries/LibWeb/WebAssembly/Global.cpp
index c532fbd61a9..cab55c4963b 100644
--- a/Libraries/LibWeb/WebAssembly/Global.cpp
+++ b/Libraries/LibWeb/WebAssembly/Global.cpp
@@ -5,7 +5,6 @@
*/
#include <LibGC/Heap.h>
-#include <LibWasm/Types.h>
#include <LibWeb/Bindings/Global.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
#include <LibWeb/WebAssembly/Global.h>
@@ -16,124 +15,91 @@ namespace Web::WebAssembly {
GC_DEFINE_ALLOCATOR(Global);
// https://webassembly.github.io/spec/js-api/#dom-global-global
-WebIDL::ExceptionOr<GC::Ref<Global>> Global::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, GlobalDescriptor const& descriptor, Wasm::Value value)
+GC::Ref<Global> Global::create(GlobalDescriptor const& descriptor, Wasm::Runtime::Value value)
{
// 1. Let mutable be descriptor["mutable"].
- auto mutable_ = descriptor.mutable_;
-
// 2. Let valuetype be ToValueType(descriptor["value"]).
- auto value_type = descriptor.value;
-
- // 3. If valuetype is v128,
- // 3.1 Throw a TypeError exception.
- if (value_type.kind() == Wasm::ValueType::V128)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "V128 is not supported as a global value type"_utf16 };
+ // 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.
- auto global_type = Wasm::GlobalType { value_type, mutable_ };
-
// 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.
- // 10. Initialize this from globaladdr.
-
- auto address = cache->abstract_machine().store().allocate(global_type, value);
- if (!address.has_value())
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Wasm Global allocation failed"_utf16 };
+ auto global = Detail::WebAssemblyCache::the().store().allocate_global(descriptor.value, descriptor.mutable_, value);
- return Global::create(cache, *address);
+ // 10. Initialize this from globaladdr.
+ return Global::create(global);
}
-GC::Ref<Global> Global::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::GlobalAddress address)
+GC::Ref<Global> Global::create(Wasm::Runtime::Entity global)
{
- auto global = GC::Heap::the().allocate<Global>(cache, address);
-
// https://webassembly.github.io/spec/js-api/#initialize-a-global-object
- auto exists = cache->global_instances().contains(address);
- VERIFY(!exists);
- cache->add_global_instance(address, global);
-
- return global;
+ 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(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::GlobalAddress address)
- : m_cache(move(cache))
- , m_address(address)
+Global::Global(Wasm::Runtime::Entity global)
+ : m_global(global)
{
}
void Global::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
-
- // NOTE: m_cache is already visited by the realm's HostDefined, which owns it.
- visitor.ignore(m_cache);
+ visitor.visit(m_global);
}
-WebIDL::ExceptionOr<Wasm::GlobalType> Global::type() const
+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).
- // 4. If globaltype is of the form mut v128, throw a TypeError.
-
- auto* global_instance = cache().abstract_machine().store().get(address());
- if (!global_instance)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the global instance"_utf16 };
-
- return global_instance->type();
+ bool is_mutable = false;
+ auto value_type = Detail::WebAssemblyCache::the().store().global_type(m_global, is_mutable);
+ return GlobalType { value_type, is_mutable };
}
-WebIDL::ExceptionOr<Wasm::ValueType> Global::value_type() const
+WebIDL::ExceptionOr<Wasm::Runtime::ValueType> Global::value_type() const
{
- auto global_type = TRY(type());
- auto value_type = global_type.type();
- if (value_type.kind() == Wasm::ValueType::V128)
+ // 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 value_type;
+ return global_type.value;
}
-WebIDL::ExceptionOr<Wasm::Value> Global::value() const
+WebIDL::ExceptionOr<Wasm::Runtime::Value> Global::value() const
{
- auto* global_instance = cache().abstract_machine().store().get(address());
- if (!global_instance)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the global instance"_utf16 };
-
(void)TRY(value_type());
// 5. Let value be global_read(store, globaladdr).
// 6. Return value.
- return global_instance->value();
+ return Detail::WebAssemblyCache::the().store().global_get(m_global);
}
// https://webassembly.github.io/spec/js-api/#dom-global-value
-WebIDL::ExceptionOr<void> Global::set_value(Wasm::Value value)
+WebIDL::ExceptionOr<void> Global::set_value(Wasm::Runtime::Value 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_instance = cache().abstract_machine().store().get(address());
- if (!global_instance)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the global instance"_utf16 };
-
- auto mut_value_type = TRY(type());
- if (mut_value_type.type().kind() == Wasm::ValueType::V128)
+ auto global_type = type();
+ if (global_type.value.kind == Wasm::Runtime::ValueKind::V128)
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a V128 global"_utf16 };
-
- if (!mut_value_type.is_mutable())
+ if (!global_type.mutable_)
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a const global"_utf16 };
// 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.
// Note: The store cannot fail, because we checked for mut/val above.
-
- global_instance->set_value(value);
-
+ Detail::WebAssemblyCache::the().store().global_set(m_global, value);
return {};
}
@@ -142,23 +108,25 @@ WebIDL::ExceptionOr<void> Global::set_value(Wasm::Value value)
namespace Web::Bindings {
// https://webassembly.github.io/spec/js-api/#tovaluetype
-static Wasm::ValueType to_value_type(ValueType type)
+static Wasm::Runtime::ValueType to_value_type(ValueType type)
{
+ using Wasm::Runtime::HeapKind;
+ using Wasm::Runtime::ValueKind;
switch (type) {
case ValueType::I32:
- return Wasm::ValueType { Wasm::ValueType::I32 };
+ return Wasm::Runtime::ValueType::scalar(ValueKind::I32);
case ValueType::I64:
- return Wasm::ValueType { Wasm::ValueType::I64 };
+ return Wasm::Runtime::ValueType::scalar(ValueKind::I64);
case ValueType::F32:
- return Wasm::ValueType { Wasm::ValueType::F32 };
+ return Wasm::Runtime::ValueType::scalar(ValueKind::F32);
case ValueType::F64:
- return Wasm::ValueType { Wasm::ValueType::F64 };
+ return Wasm::Runtime::ValueType::scalar(ValueKind::F64);
case ValueType::V128:
- return Wasm::ValueType { Wasm::ValueType::V128 };
+ return Wasm::Runtime::ValueType::scalar(ValueKind::V128);
case ValueType::Anyfunc:
- return Wasm::ValueType { Wasm::ValueType::FunctionReference };
+ return Wasm::Runtime::ValueType::reference(HeapKind::Function);
case ValueType::Externref:
- return Wasm::ValueType { Wasm::ValueType::ExternReference };
+ return Wasm::Runtime::ValueType::reference(HeapKind::Extern);
}
VERIFY_NOT_REACHED();
@@ -174,16 +142,17 @@ static WebAssembly::GlobalDescriptor global_descriptor_from_bindings(GlobalDescr
WebIDL::ExceptionOr<GC::Ref<WebAssembly::Global>> construct_global(JS::Realm& realm, GlobalDescriptor const& descriptor, Optional<JS::Value> value)
{
- auto cache = WebAssembly::Detail::get_cache(realm);
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, global_descriptor.value)
- : TRY(WebAssembly::Detail::to_webassembly_value(realm, *value, global_descriptor.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(move(cache), global_descriptor, wasm_value);
+ return WebAssembly::Global::create(global_descriptor, wasm_value);
}
// https://webassembly.github.io/spec/js-api/#getglobalvalue
@@ -191,7 +160,7 @@ static WebIDL::ExceptionOr<JS::Value> get_global_value(JS::Realm& realm, WebAsse
{
auto value = TRY(global.value());
auto value_type = TRY(global.value_type());
- return WebAssembly::Detail::to_js_value(realm, value, value_type);
+ return TRY(WebAssembly::Detail::to_js_value(realm.vm(), value, value_type));
}
// https://webassembly.github.io/spec/js-api/#dom-global-value
@@ -203,15 +172,15 @@ WebIDL::ExceptionOr<JS::Value> value(JS::Realm& realm, WebAssembly::Global& glob
// 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)
{
- auto global_type = TRY(global.type());
- auto value_type = global_type.type();
- if (value_type.kind() == Wasm::ValueType::V128)
+ 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.is_mutable())
+ if (!global_type.mutable_)
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot set the value of a const global"_utf16 };
- auto value = TRY(WebAssembly::Detail::to_webassembly_value(realm, the_given_value, value_type));
+ auto value = TRY(WebAssembly::Detail::to_webassembly_value(realm.vm(), the_given_value, value_type));
return global.set_value(value);
}
diff --git a/Libraries/LibWeb/WebAssembly/Global.h b/Libraries/LibWeb/WebAssembly/Global.h
index 8a2760566c1..de30771cf5c 100644
--- a/Libraries/LibWeb/WebAssembly/Global.h
+++ b/Libraries/LibWeb/WebAssembly/Global.h
@@ -7,7 +7,6 @@
#pragma once
#include <AK/Optional.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -15,7 +14,12 @@
namespace Web::WebAssembly {
struct GlobalDescriptor {
- Wasm::ValueType value;
+ Wasm::Runtime::ValueType value;
+ bool mutable_ { false };
+};
+
+struct GlobalType {
+ Wasm::Runtime::ValueType value;
bool mutable_ { false };
};
@@ -24,25 +28,22 @@ class Global : public Bindings::GCAllocatedWrappable {
GC_DECLARE_ALLOCATOR(Global);
public:
- static WebIDL::ExceptionOr<GC::Ref<Global>> create(NonnullRefPtr<Detail::WebAssemblyCache>, GlobalDescriptor const&, Wasm::Value);
- static GC::Ref<Global> create(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::GlobalAddress);
+ static GC::Ref<Global> create(GlobalDescriptor const&, Wasm::Runtime::Value);
+ static GC::Ref<Global> create(Wasm::Runtime::Entity global);
- WebIDL::ExceptionOr<Wasm::GlobalType> type() const;
- WebIDL::ExceptionOr<Wasm::Value> value() const;
- WebIDL::ExceptionOr<Wasm::ValueType> value_type() const;
- WebIDL::ExceptionOr<void> set_value(Wasm::Value);
+ 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::GlobalAddress address() const { return m_address; }
- Detail::WebAssemblyCache& cache() { return *m_cache; }
- Detail::WebAssemblyCache& cache() const { return *m_cache; }
+ Wasm::Runtime::Entity address() const { return m_global; }
private:
- Global(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::GlobalAddress);
+ explicit Global(Wasm::Runtime::Entity global);
virtual void visit_edges(Visitor&) override;
- NonnullRefPtr<Detail::WebAssemblyCache> m_cache;
- Wasm::GlobalAddress m_address;
+ Wasm::Runtime::Entity m_global { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cpp
index 66c4dda1942..0f38d7277b7 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.cpp
+++ b/Libraries/LibWeb/WebAssembly/Instance.cpp
@@ -31,54 +31,47 @@ GC_DEFINE_ALLOCATOR(Instance);
WebIDL::ExceptionOr<GC::Ref<Instance>> Instance::create(JS::Realm& realm, Module& module, GC::Ptr<JS::Object> import_object)
{
- auto module_instance = TRY(Detail::instantiate_module(realm, module.compiled_module()->module, import_object));
- return Instance::create(Detail::get_cache(realm), move(module_instance));
+ auto instance = TRY(Detail::instantiate_module(realm.vm(), *module.compiled_module()->module, import_object));
+ return Instance::create(instance);
}
-GC::Ref<Instance> Instance::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, NonnullRefPtr<Wasm::ModuleInstance> module_instance)
+GC::Ref<Instance> Instance::create(Wasm::Runtime::Entity instance)
{
- return GC::Heap::the().allocate<Instance>(move(cache), move(module_instance));
+ return GC::Heap::the().allocate<Instance>(instance);
}
-Instance::Instance(NonnullRefPtr<Detail::WebAssemblyCache> cache, NonnullRefPtr<Wasm::ModuleInstance> module_instance)
- : m_cache(move(cache))
- , m_module_instance(move(module_instance))
+Instance::Instance(Wasm::Runtime::Entity instance)
+ : m_instance(instance)
{
}
-GC::Ref<Global> Instance::global_instance(Wasm::GlobalAddress address)
+GC::Ref<Global> Instance::global_instance(Wasm::Runtime::Entity global)
{
- Optional<GC::Ptr<Global>> object = cache().get_global_instance(address);
- if (!object.has_value())
- object = Global::create(m_cache, address);
- return GC::Ref { **object };
+ if (auto object = Detail::WebAssemblyCache::the().global_object(global))
+ return *object;
+ return Global::create(global);
}
-GC::Ref<Memory> Instance::memory_instance(Wasm::MemoryAddress address)
+GC::Ref<Memory> Instance::memory_instance(Wasm::Runtime::Entity memory)
{
- Optional<GC::Ptr<Memory>> object = cache().get_memory_instance(address);
- if (!object.has_value()) {
- // FIXME: Once LibWasm implements the threads/atomics proposal, the shared-ness should be
- // obtained from the Wasm::MemoryInstance's type.
- object = Memory::create(m_cache, address, Memory::Shared::No);
- }
- return GC::Ref { **object };
+ 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::TableAddress address)
+GC::Ref<Table> Instance::table_instance(Wasm::Runtime::Entity table)
{
- Optional<GC::Ptr<Table>> object = cache().get_table_instance(address);
- if (!object.has_value())
- object = GC::Heap::the().allocate<Table>(m_cache, address);
- return GC::Ref { **object };
+ 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);
-
- // NOTE: m_cache is already visited by the realm's HostDefined, which owns it.
- visitor.ignore(m_cache);
+ visitor.visit(m_instance);
}
}
@@ -127,25 +120,29 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::
auto exports = GC::make_root(JS::Object::create(realm, nullptr));
// https://webassembly.github.io/spec/js-api/#create-an-exports-object
- for (auto& export_ : instance.module_instance()->exports()) {
- auto name = Utf16FlyString::from_utf8(export_.name());
-
- export_.value().visit(
- [&](Wasm::FunctionAddress const& address) {
- auto object = WebAssembly::Detail::create_native_function(realm, address, name, &instance);
- auto object_root = GC::make_root(*object);
- exports->define_direct_property(name, object_root.ptr(), JS::default_attributes);
- },
- [&](Wasm::GlobalAddress const& address) {
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, instance.global_instance(address)), JS::default_attributes);
- },
- [&](Wasm::MemoryAddress const& address) {
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, instance.memory_instance(address)), JS::default_attributes);
- },
- [&](Wasm::TableAddress const& address) {
- exports->define_direct_property(name, table(realm, instance.table_instance(address)), JS::default_attributes);
- },
- [&](Wasm::TagAddress const&) { dbgln("Not yet implemented: tags"); });
+ 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;
+
+ 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:
+ dbgln("Not yet implemented: tags");
+ break;
+ }
}
MUST(exports->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
@@ -154,7 +151,6 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::
GC::Ref<JS::Object const> exports(JS::Realm& realm, GC::Ref<WebAssembly::Instance> instance)
{
- VERIFY(host_defined_of(realm).wasm_cache.ptr() == &instance->cache());
auto& cache = instance_exports_cache_for(instance);
if (cache.exports)
diff --git a/Libraries/LibWeb/WebAssembly/Instance.h b/Libraries/LibWeb/WebAssembly/Instance.h
index 565c43e26f3..170f54ae664 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.h
+++ b/Libraries/LibWeb/WebAssembly/Instance.h
@@ -10,7 +10,6 @@
#include <AK/Optional.h>
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -23,22 +22,19 @@ class Instance : public Bindings::GCAllocatedWrappable {
public:
static WebIDL::ExceptionOr<GC::Ref<Instance>> create(JS::Realm&, Module& module, GC::Ptr<JS::Object> import_object);
- static GC::Ref<Instance> create(NonnullRefPtr<Detail::WebAssemblyCache>, NonnullRefPtr<Wasm::ModuleInstance>);
+ static GC::Ref<Instance> create(Wasm::Runtime::Entity instance);
- Wasm::ModuleInstance const* module_instance() const { return m_module_instance.ptr(); }
- GC::Ref<Global> global_instance(Wasm::GlobalAddress);
- GC::Ref<Memory> memory_instance(Wasm::MemoryAddress);
- GC::Ref<Table> table_instance(Wasm::TableAddress);
- Detail::WebAssemblyCache& cache() { return *m_cache; }
- Detail::WebAssemblyCache& cache() const { return *m_cache; }
+ Wasm::Runtime::Entity instance_address() const { return m_instance; }
+ 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(NonnullRefPtr<Detail::WebAssemblyCache>, NonnullRefPtr<Wasm::ModuleInstance>);
+ explicit Instance(Wasm::Runtime::Entity instance);
virtual void visit_edges(Visitor&) override;
- NonnullRefPtr<Detail::WebAssemblyCache> m_cache;
- NonnullRefPtr<Wasm::ModuleInstance> m_module_instance;
+ Wasm::Runtime::Entity m_instance { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAssembly/Memory.cpp b/Libraries/LibWeb/WebAssembly/Memory.cpp
index 21a1f4cd2b2..2892154c7ab 100644
--- a/Libraries/LibWeb/WebAssembly/Memory.cpp
+++ b/Libraries/LibWeb/WebAssembly/Memory.cpp
@@ -11,7 +11,6 @@
#include <LibJS/Runtime/ArrayBuffer.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWasm/Types.h>
#include <LibWeb/WebAssembly/Memory.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
@@ -57,21 +56,21 @@ static MemoryBufferCache& memory_buffer_cache_for(Memory const& 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* memory_instance = memory.cache().abstract_machine().store().get(memory.address());
- VERIFY(memory_instance);
- auto handle = memory_instance->data().primitive_storage_handle();
+ 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_instance->size() };
+ 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)
{
- auto* memory_instance = memory.cache().abstract_machine().store().get(memory.address());
- VERIFY(memory_instance);
-
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,
@@ -82,7 +81,7 @@ static GC::Ref<JS::ArrayBuffer> create_a_fixed_length_memory_buffer(JS::VM& vm,
// 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_instance->size());
+ VERIFY(array_buffer->byte_length() == memory_size(memory));
// 5. Perform ! SetIntegrityLevel(buffer, "frozen").
MUST(array_buffer->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
@@ -98,11 +97,8 @@ static GC::Ref<JS::ArrayBuffer> create_a_fixed_length_memory_buffer(JS::VM& vm,
// 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)
{
- auto* memory_instance = memory.cache().abstract_machine().store().get(memory.address());
- VERIFY(memory_instance);
-
// 3. If maxsize > (65536 x 65536),
- if (max_size > (65536 * Wasm::Constants::page_size)) {
+ 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);
}
@@ -119,7 +115,7 @@ static JS::ThrowCompletionOr<GC::Ref<JS::ArrayBuffer>> create_a_resizable_memory
// 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_instance->size());
+ VERIFY(buffer->byte_length() == memory_size(memory));
// 5. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
buffer->set_max_byte_length(max_size);
@@ -144,7 +140,7 @@ static JS::ThrowCompletionOr<GC::Ref<JS::ArrayBuffer>> create_a_resizable_memory
// 2. Let length be the length of block.
// 6. Set buffer.[[ArrayBufferByteLength]] to length.
- VERIFY(buffer->byte_length() == memory_instance->size());
+ VERIFY(buffer->byte_length() == memory_size(memory));
// 7. Set buffer.[[ArrayBufferMaxByteLength]] to maxsize.
buffer->set_max_byte_length(max_size);
@@ -251,7 +247,7 @@ static void refresh_buffer_objects(Memory& memory)
refresh_buffer_object(memory, buffer);
}
-WebIDL::ExceptionOr<GC::Ref<Memory>> Memory::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, MemoryDescriptor const& descriptor)
+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.
@@ -265,83 +261,57 @@ WebIDL::ExceptionOr<GC::Ref<Memory>> Memory::create(NonnullRefPtr<Detail::WebAss
if (shared && !descriptor.maximum.has_value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Maximum has to be specified for shared memory."_utf16 };
- Wasm::Limits limits { Wasm::AddressType::I32, descriptor.initial, descriptor.maximum.map([](auto x) -> u64 { return x; }) };
- Wasm::MemoryType memory_type { move(limits) };
+ Wasm::Runtime::Limits limits {
+ .minimum = descriptor.initial,
+ .maximum = descriptor.maximum.value_or(0),
+ .has_maximum = descriptor.maximum.has_value(),
+ .address64 = false,
+ .shared = shared,
+ };
- auto address = cache->abstract_machine().store().allocate(memory_type);
- if (!address.has_value())
+ auto memory = cache().store().allocate_memory(limits);
+ if (!memory.has_value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Wasm Memory allocation failed"_utf16 };
- auto memory_object = Memory::create(cache, *address, shared ? Shared::Yes : Shared::No);
-
- return memory_object;
+ return Memory::create(*memory, shared ? Shared::Yes : Shared::No);
}
-GC::Ref<Memory> Memory::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::MemoryAddress address, Shared shared)
+GC::Ref<Memory> Memory::create(Wasm::Runtime::Entity memory, Shared shared)
{
- auto memory = GC::Heap::the().allocate<Memory>(cache, address, shared);
-
// https://webassembly.github.io/spec/js-api/#initialize-a-memory-object
- auto exists = cache->memory_instances().contains(address);
- VERIFY(!exists);
-
- cache->add_memory_instance(address, memory);
-
- return memory;
+ 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& relevant_global_object, MemoryDescriptor const& descriptor)
+WebIDL::ExceptionOr<GC::Ref<Memory>> Memory::create_for_constructor(JS::Object&, MemoryDescriptor const& descriptor)
{
- auto cache = Detail::get_cache(HTML::relevant_realm(relevant_global_object));
- return Memory::create(move(cache), descriptor);
+ return Memory::create(descriptor);
}
-Memory::Memory(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::MemoryAddress address, Shared shared)
- : m_cache(move(cache))
- , m_address(address)
+Memory::Memory(Wasm::Runtime::Entity memory, Shared shared)
+ : m_memory(memory)
, m_shared(shared)
{
- auto& cache_ref = *m_cache;
- m_cache->abstract_machine().store().get(address)->successful_grow_hook = [&cache_ref, address] {
- refresh_the_memory_buffer(cache_ref, address);
- };
}
void Memory::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
-
- // NOTE: m_cache is already visited by the realm's HostDefined, which owns it.
- visitor.ignore(m_cache);
-}
-
-void Memory::finalize()
-{
- Base::finalize();
-
- // NB: A buffer can keep the cache alive after its realm is gone, so the cache can outlive this Memory. Remove our
- // entry and grow hook before this cell is reused.
- auto entry = m_cache->get_memory_instance(m_address);
- if (!entry.has_value() || entry.value().ptr() != this)
- return;
- m_cache->remove_memory_instance(m_address);
- if (auto* memory = m_cache->abstract_machine().store().get(m_address))
- memory->successful_grow_hook = nullptr;
+ visitor.visit(m_memory);
}
// https://webassembly.github.io/spec/js-api/#dom-memory-grow
WebIDL::ExceptionOr<u32> Memory::grow(u32 delta)
{
- auto* memory = cache().abstract_machine().store().get(address());
- VERIFY(memory);
-
- auto previous_size = memory->size() / Wasm::Constants::page_size;
- if (!memory->grow(delta * Wasm::Constants::page_size, Wasm::MemoryInstance::GrowType::No, Wasm::MemoryInstance::InhibitGrowCallback::Yes))
+ 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(cache(), m_address);
+ refresh_the_memory_buffer(*this);
- return previous_size;
+ return static_cast<u32>(previous_size);
}
// https://webassembly.github.io/threads/js-api/index.html#dom-memory-tofixedlengthbuffer
@@ -378,11 +348,11 @@ WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::to_fixed_length_buffer(JS:
// 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().get_memory_instance(address());
- VERIFY(new_memory.has_value());
+ 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.value());
+ 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);
@@ -406,16 +376,14 @@ WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::to_resizable_buffer(JS::Re
// 3. Let memaddr be this.[[Memory]].
// 4. Let store be the surrounding agent's associated store.
- auto& store = cache().abstract_machine().store();
-
// 5. Let memtype be mem_type(store, memaddr).
- auto mem_type = store.get(address())->type();
+ 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 = mem_type.limits().max().value_or(65536) * Wasm::Constants::page_size;
+ 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));
@@ -445,11 +413,11 @@ WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> Memory::buffer(JS::Realm& realm)
// 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().get_memory_instance(address());
- VERIFY(new_memory.has_value());
+ 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.value());
+ 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);
@@ -480,15 +448,12 @@ bool memory_has_buffer_object(Memory const& memory, JS::ArrayBuffer const& buffe
}
// https://webassembly.github.io/spec/js-api/#refresh-the-memory-buffer
-void refresh_the_memory_buffer(Detail::WebAssemblyCache& cache, Wasm::MemoryAddress address)
+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].
- auto memory = cache.get_memory_instance(address);
- VERIFY(memory.has_value());
-
- refresh_buffer_objects(*memory.value());
+ refresh_buffer_objects(memory);
}
}
diff --git a/Libraries/LibWeb/WebAssembly/Memory.h b/Libraries/LibWeb/WebAssembly/Memory.h
index 34249c565e8..b3b32bb33da 100644
--- a/Libraries/LibWeb/WebAssembly/Memory.h
+++ b/Libraries/LibWeb/WebAssembly/Memory.h
@@ -9,7 +9,6 @@
#include <AK/Optional.h>
#include <LibJS/Forward.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
#include <LibWeb/Bindings/Memory.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
@@ -36,8 +35,8 @@ class Memory : public Bindings::GCAllocatedWrappable {
};
public:
- static WebIDL::ExceptionOr<GC::Ref<Memory>> create(NonnullRefPtr<Detail::WebAssemblyCache>, MemoryDescriptor const&);
- static GC::Ref<Memory> create(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::MemoryAddress, Shared);
+ 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);
@@ -45,23 +44,20 @@ public:
WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> to_resizable_buffer(JS::Realm&);
WebIDL::ExceptionOr<GC::Ref<JS::ArrayBuffer>> buffer(JS::Realm&);
- Wasm::MemoryAddress address() const { return m_address; }
+ Wasm::Runtime::Entity address() const { return m_memory; }
bool is_shared() const { return m_shared == Shared::Yes; }
- Detail::WebAssemblyCache& cache() { return *m_cache; }
- Detail::WebAssemblyCache& cache() const { return *m_cache; }
+ static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }
private:
- Memory(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::MemoryAddress, Shared shared);
+ Memory(Wasm::Runtime::Entity memory, Shared shared);
virtual void visit_edges(Visitor&) override;
- virtual void finalize() override;
- NonnullRefPtr<Detail::WebAssemblyCache> m_cache;
- Wasm::MemoryAddress m_address;
+ Wasm::Runtime::Entity m_memory { nullptr };
Shared m_shared { Shared::No };
};
bool memory_has_buffer_object(Memory const&, JS::ArrayBuffer const&);
-void refresh_the_memory_buffer(Detail::WebAssemblyCache&, Wasm::MemoryAddress);
+void refresh_the_memory_buffer(Memory&);
}
diff --git a/Libraries/LibWeb/WebAssembly/Module.cpp b/Libraries/LibWeb/WebAssembly/Module.cpp
index 6dfed2234db..2e5f2f14b4c 100644
--- a/Libraries/LibWeb/WebAssembly/Module.cpp
+++ b/Libraries/LibWeb/WebAssembly/Module.cpp
@@ -20,6 +20,23 @@ 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>();
@@ -54,33 +71,29 @@ WebIDL::ExceptionOr<Vector<Bindings::ModuleImportDescriptor>> Module::imports(GC
Vector<Bindings::ModuleImportDescriptor> import_objects;
// 3. For each (moduleName, name, type) of module_imports(module),
- auto& imports = module_object->m_compiled_module->module->import_section().imports();
- import_objects.ensure_capacity(imports.size());
- for (auto& import : imports) {
- if (import.description().has<Wasm::TagType>()) {
+ auto& module = *module_object->m_compiled_module->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.
+ auto kind = import_export_kind(import.type.kind);
+ if (!kind.has_value()) {
dbgln("Not yet implemented: importing tags");
continue;
}
- // 3.1. Let kind be the string value of the extern type type.
- auto const kind = import.description().visit(
- [](Wasm::TypeIndex) { return Bindings::ImportExportKind::Function; },
- [](Wasm::TableType) { return Bindings::ImportExportKind::Table; },
- [](Wasm::MemoryType) { return Bindings::ImportExportKind::Memory; },
- [](Wasm::GlobalType) { return Bindings::ImportExportKind::Global; },
- [](Wasm::FunctionType) { return Bindings::ImportExportKind::Function; },
- [](Wasm::TagType) -> Bindings::ImportExportKind { TODO(); });
-
// 3.2. 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()),
+ .kind = *kind,
+ .module = Utf16String::from_utf8(import.module),
+ .name = Utf16String::from_utf8(import.name),
};
// 3.3. Append obj to imports.
import_objects.append(move(descriptor));
}
+
// 4. Return imports.
return import_objects;
}
@@ -93,29 +106,28 @@ WebIDL::ExceptionOr<Vector<Bindings::ModuleExportDescriptor>> Module::exports(GC
Vector<Bindings::ModuleExportDescriptor> export_objects;
// 3. For each (name, type) of module_exports(module),
- auto& exports = module_object->m_compiled_module->module->export_section().entries();
- export_objects.ensure_capacity(exports.size());
- for (auto& entry : exports) {
- if (entry.description().has<Wasm::TagIndex>()) {
+ 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.1. Let kind be the string value of the extern type type.
- auto const kind = entry.description().visit(
- [](Wasm::FunctionIndex) { return Bindings::ImportExportKind::Function; },
- [](Wasm::TableIndex) { return Bindings::ImportExportKind::Table; },
- [](Wasm::MemoryIndex) { return Bindings::ImportExportKind::Memory; },
- [](Wasm::GlobalIndex) { return Bindings::ImportExportKind::Global; },
- [](Wasm::TagIndex) -> Bindings::ImportExportKind { TODO(); });
// 3.2. Let obj be «[ "name" → name, "kind" → kind ]».
Bindings::ModuleExportDescriptor descriptor {
- .kind = kind,
- .name = Utf16String::from_utf8(entry.name()),
+ .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;
}
@@ -124,11 +136,12 @@ WebIDL::ExceptionOr<Vector<ByteBuffer>> Module::custom_sections(GC::Ref<Module>
{
Vector<ByteBuffer> matching_sections;
- auto& custom_sections = module_object->m_compiled_module->module->custom_sections();
- for (auto& section : custom_sections) {
- auto name = Utf16String::from_utf8(section.name());
+ 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())));
+ matching_sections.append(MUST(ByteBuffer::copy(section.contents)));
}
return matching_sections;
diff --git a/Libraries/LibWeb/WebAssembly/Module.h b/Libraries/LibWeb/WebAssembly/Module.h
index 37a7e4c9323..caefd23d000 100644
--- a/Libraries/LibWeb/WebAssembly/Module.h
+++ b/Libraries/LibWeb/WebAssembly/Module.h
@@ -11,7 +11,6 @@
#include <AK/Utf16String.h>
#include <LibGC/Ptr.h>
#include <LibJS/Forward.h>
-#include <LibWasm/Types.h>
#include <LibWeb/Bindings/Module.h>
#include <LibWeb/Bindings/Serializable.h>
#include <LibWeb/Bindings/Wrappable.h>
diff --git a/Libraries/LibWeb/WebAssembly/Table.cpp b/Libraries/LibWeb/WebAssembly/Table.cpp
index 00a491487a3..d39373aefd9 100644
--- a/Libraries/LibWeb/WebAssembly/Table.cpp
+++ b/Libraries/LibWeb/WebAssembly/Table.cpp
@@ -10,7 +10,6 @@
#include <LibGC/Heap.h>
#include <LibJS/Runtime/BigInt.h>
#include <LibJS/Runtime/VM.h>
-#include <LibWasm/Types.h>
#include <LibWeb/Bindings/Table.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
@@ -23,117 +22,104 @@ namespace Web::WebAssembly {
GC_DEFINE_ALLOCATOR(Table);
-WebIDL::ExceptionOr<GC::Ref<Table>> Table::create(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::ValueType element_type, Wasm::AddressType address_type, u64 initial, Optional<u64> maximum, Wasm::Reference reference)
+WebIDL::ExceptionOr<GC::Ref<Table>> Table::create(Wasm::Runtime::ValueType element_type, bool address64, u64 initial, Optional<u64> maximum, u64 reference)
{
- Wasm::Limits limits { address_type, initial, maximum };
- Wasm::TableType table_type { element_type, move(limits) };
-
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 address = cache->abstract_machine().store().allocate(table_type);
- if (!address.has_value())
+ 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 };
- auto& table = *cache->abstract_machine().store().get(*address);
- for (auto& element : table.elements())
- element = reference;
-
// 12. Set the surrounding agent's associated store to store.
// NOTE: The store is updated in-place.
// 13. Initialize this from tableaddr.
- return GC::Heap::the().allocate<Table>(cache, *address);
+ return Table::create(*table);
}
-Table::Table(NonnullRefPtr<Detail::WebAssemblyCache> cache, Wasm::TableAddress address)
- : m_cache(move(cache))
- , m_address(address)
+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.
- auto exists = m_cache->table_instances().contains(m_address);
- VERIFY(!exists);
+ VERIFY(!cache().table_object(table));
// 3. Set table.[[Table]] to tableaddr.
- // NOTE: This is already set by the Table constructor.
+ auto object = GC::Heap::the().allocate<Table>(table);
// 4. Set map[tableaddr] to table.
- m_cache->add_table_instance(m_address, *this);
+ 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);
-
- // NOTE: m_cache is already visited by the realm's HostDefined, which owns it.
- visitor.ignore(m_cache);
+ visitor.visit(m_table);
}
// https://webassembly.github.io/spec/js-api/#dom-table-grow
-WebIDL::ExceptionOr<u64> Table::grow(u64 delta, Wasm::Reference reference)
+WebIDL::ExceptionOr<u64> Table::grow(u64 delta, u64 reference)
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table to grow"_utf16 };
-
// 3. Let initialSize be table_size(store, tableaddr).
- auto initial_size = table->elements().size();
-
- if (!table->grow(delta, reference))
+ // 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 initial_size;
+ return static_cast<u64>(initial_size);
}
// https://webassembly.github.io/spec/js-api/#dom-table-get
-WebIDL::ExceptionOr<Wasm::Reference> Table::get(u64 index) const
+WebIDL::ExceptionOr<u64> Table::get(u64 index) const
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table"_utf16 };
-
// 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
- auto element_type = table->type().element_type();
-
// 4. If elementtype matches exnref, throw a TypeError exception.
- if (element_type.kind() == Wasm::ValueType::ExceptionReference)
+ 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.
- if (table->elements().size() <= index)
+ 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 table->elements()[index];
+ return *result;
}
// https://webassembly.github.io/spec/js-api/#dom-table-set
-WebIDL::ExceptionOr<void> Table::set(u64 index, Wasm::Reference reference)
+WebIDL::ExceptionOr<void> Table::set(u64 index, u64 reference)
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table"_utf16 };
-
// 3. Let (addrtype, limits, elementtype) be table_type(store, tableaddr).
- auto element_type = table->type().element_type();
-
// 4. If elementtype matches exnref, throw a TypeError exception.
- if (element_type.kind() == Wasm::ValueType::ExceptionReference)
+ 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 };
- if (table->elements().size() <= index)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Table element index out of range"_utf16 };
-
// 8. Let store be table_write(store, tableaddr, index64, ref).
// 9. If store is error, throw a RangeError exception.
- table->elements()[index] = reference;
+ 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.
@@ -141,65 +127,40 @@ WebIDL::ExceptionOr<void> Table::set(u64 index, Wasm::Reference reference)
}
// https://webassembly.github.io/spec/js-api/#dom-table-length
-WebIDL::ExceptionOr<u64> Table::length() const
+u64 Table::length() const
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table"_utf16 };
-
- return table->elements().size();
+ return cache().store().table_size(address());
}
-WebIDL::ExceptionOr<Wasm::AddressType> Table::address_type() const
+bool Table::is_address64() const
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table"_utf16 };
-
- return table->type().limits().address_type();
+ return cache().store().table_limits(address()).address64;
}
-WebIDL::ExceptionOr<Wasm::ValueType> Table::element_type() const
+Wasm::Runtime::ValueType Table::element_type() const
{
- auto* table = cache().abstract_machine().store().get(address());
- if (!table)
- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Could not find the memory table"_utf16 };
-
- return table->type().element_type();
+ return cache().store().table_element_type(address());
}
}
namespace Web::Bindings {
-static Wasm::ValueType table_kind_to_value_type(TableKind kind)
+static Wasm::Runtime::ValueType table_kind_to_value_type(TableKind kind)
{
switch (kind) {
case TableKind::Externref:
- return Wasm::ValueType { Wasm::ValueType::ExternReference };
+ return Wasm::Runtime::ValueType::reference(Wasm::Runtime::HeapKind::Extern);
case TableKind::Anyfunc:
- return Wasm::ValueType { Wasm::ValueType::FunctionReference };
+ return Wasm::Runtime::ValueType::reference(Wasm::Runtime::HeapKind::Function);
}
-
- VERIFY_NOT_REACHED();
-}
-
-static Wasm::AddressType address_type_from_bindings(AddressType address_type)
-{
- switch (address_type) {
- case AddressType::I32:
- return Wasm::AddressType::I32;
- case AddressType::I64:
- return Wasm::AddressType::I64;
- }
-
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, Wasm::AddressType address_type)
+static WebIDL::ExceptionOr<u64> address_value_to_u64(JS::VM& vm, JS::Value value, bool address64)
{
- if (address_type == Wasm::AddressType::I64) {
+ if (address64) {
// 1. If addrtype is i64, then:
// 1.1. Let n be ? ToBigInt(value).
auto bigint = TRY(value.to_bigint(vm));
@@ -207,7 +168,6 @@ static WebIDL::ExceptionOr<u64> address_value_to_u64(JS::VM& vm, JS::Value value
// 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())
@@ -226,9 +186,9 @@ static WebIDL::ExceptionOr<u64> address_value_to_u64(JS::VM& vm, JS::Value value
return n;
}
-static JS::Value table_limit_to_js_value(JS::VM& vm, u64 value, Wasm::AddressType address_type)
+static JS::Value table_limit_to_js_value(JS::VM& vm, u64 value, bool address64)
{
- if (address_type == Wasm::AddressType::I64)
+ if (address64)
return JS::BigInt::create(vm, ::Crypto::SignedBigInteger { ::Crypto::UnsignedBigInteger { value } });
return JS::Value { static_cast<u32>(value) };
}
@@ -244,22 +204,21 @@ WebIDL::ExceptionOr<GC::Ref<WebAssembly::Table>> construct_table(JS::Realm& real
// 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 address_type = address_type_from_bindings(descriptor.address.value_or(AddressType::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, address_type));
+ 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(), address_type)) }
+ ? 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(realm, element_type)
- : TRY(WebAssembly::Detail::to_webassembly_value(realm, *value, element_type));
+ ? WebAssembly::Detail::default_webassembly_value(vm, element_type)
+ : TRY(WebAssembly::Detail::to_webassembly_value(vm, *value, element_type));
- auto cache = WebAssembly::Detail::get_cache(realm);
- return WebAssembly::Table::create(move(cache), element_type, address_type, initial, maximum, reference_value.to<Wasm::Reference>());
+ return WebAssembly::Table::create(element_type, address64, initial, maximum, reference_value.reference_bits());
}
JS::Value table(JS::Realm& realm, GC::Ref<WebAssembly::Table> table)
@@ -267,51 +226,44 @@ JS::Value table(JS::Realm& realm, GC::Ref<WebAssembly::Table> table)
return wrap(host_defined_wrapper_world(realm), realm, table);
}
-static WebIDL::ExceptionOr<Wasm::Reference> value_to_table_reference(JS::Realm& realm, WebAssembly::Table& table, Optional<JS::Value> value)
+static WebIDL::ExceptionOr<u64> value_to_table_reference(JS::Realm& realm, WebAssembly::Table& table, Optional<JS::Value> value)
{
- auto element_type = TRY(table.element_type());
+ auto element_type = table.element_type();
auto reference_value = !value.has_value()
- ? WebAssembly::Detail::default_webassembly_value(realm, element_type)
- : TRY(WebAssembly::Detail::to_webassembly_value(realm, *value, element_type));
-
- return reference_value.to<Wasm::Reference>();
+ ? 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 address_type = TRY(table.address_type());
- auto delta = TRY(address_value_to_u64(vm, delta_value, address_type));
+ 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, address_type);
+ 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 address_type = TRY(table.address_type());
- auto index = TRY(address_value_to_u64(vm, index_value, address_type));
+ auto index = TRY(address_value_to_u64(vm, index_value, table.is_address64()));
auto reference = TRY(table.get(index));
- auto element_type = TRY(table.element_type());
- auto wasm_value = Wasm::Value { reference };
- return WebAssembly::Detail::to_js_value(realm, wasm_value, element_type);
+ 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 address_type = TRY(table.address_type());
- auto index = TRY(address_value_to_u64(vm, index_value, address_type));
+ 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)
{
- auto address_type = TRY(table.address_type());
- auto length = TRY(table.length());
- return table_limit_to_js_value(realm.vm(), length, address_type);
+ 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
index 90aebf43f35..398941ba333 100644
--- a/Libraries/LibWeb/WebAssembly/Table.h
+++ b/Libraries/LibWeb/WebAssembly/Table.h
@@ -9,7 +9,6 @@
#include <AK/Optional.h>
#include <LibGC/Ptr.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/WebAssembly/WebAssembly.h>
#include <LibWeb/WebIDL/ExceptionOr.h>
@@ -21,28 +20,26 @@ class Table : public Bindings::GCAllocatedWrappable {
GC_DECLARE_ALLOCATOR(Table);
public:
- static WebIDL::ExceptionOr<GC::Ref<Table>> create(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::ValueType, Wasm::AddressType, u64 initial, Optional<u64> maximum, Wasm::Reference);
+ // 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, Wasm::Reference);
+ 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;
- WebIDL::ExceptionOr<Wasm::Reference> get(u64 index) const;
- WebIDL::ExceptionOr<void> set(u64 index, Wasm::Reference);
-
- WebIDL::ExceptionOr<u64> length() const;
- WebIDL::ExceptionOr<Wasm::AddressType> address_type() const;
- WebIDL::ExceptionOr<Wasm::ValueType> element_type() const;
-
- Wasm::TableAddress address() const { return m_address; }
- Detail::WebAssemblyCache& cache() { return *m_cache; }
- Detail::WebAssemblyCache& cache() const { return *m_cache; }
+ Wasm::Runtime::Entity address() const { return m_table; }
+ static Detail::WebAssemblyCache& cache() { return Detail::WebAssemblyCache::the(); }
private:
- Table(NonnullRefPtr<Detail::WebAssemblyCache>, Wasm::TableAddress);
+ explicit Table(Wasm::Runtime::Entity table);
virtual void visit_edges(Visitor&) override;
- NonnullRefPtr<Detail::WebAssemblyCache> m_cache;
- Wasm::TableAddress m_address;
+ Wasm::Runtime::Entity m_table { nullptr };
};
}
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
index fa9721674c8..3ff6aa5f555 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
@@ -11,10 +11,9 @@
#include <AK/ScopeGuard.h>
#include <AK/StringBuilder.h>
#include <AK/Utf16String.h>
-#include <LibCore/EventLoop.h>
-#include <LibCrypto/Hash/SHA2.h>
+#include <LibCrypto/BigInt/SignedBigInteger.h>
+#include <LibGC/DeferGC.h>
#include <LibGC/Heap.h>
-#include <LibHTTP/Cache/Utilities.h>
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayBuffer.h>
@@ -27,10 +26,6 @@
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/ValueInlines.h>
-#include <LibRequests/RequestClient.h>
-#include <LibThreading/ThreadPool.h>
-#include <LibURL/Parser.h>
-#include <LibWasm/AbstractMachine/Validator.h>
#include <LibWeb/Bindings/HostDefined.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
@@ -38,12 +33,10 @@
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
-#include <LibWeb/Fetch/Infrastructure/NetworkPartitionKey.h>
#include <LibWeb/Fetch/Infrastructure/URL.h>
#include <LibWeb/Fetch/Response.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
-#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
#include <LibWeb/WebAssembly/Global.h>
@@ -66,46 +59,75 @@ static GC::Ref<WebIDL::Promise> compile_potential_webassembly_response(JS::Realm
namespace Detail {
-// HostResizeArrayBuffer and HostGrowSharedArrayBuffer have to find the WebAssembly.Memory that owns a given buffer,
-// which the spec phrases as a scan over every Memory object cache. This registry exists only to serve those scans: it
-// owns nothing and takes no part in garbage collection.
-static Vector<WebAssemblyCache*>& live_caches()
+using WasmValue = Wasm::Runtime::Value;
+using WasmValueType = Wasm::Runtime::ValueType;
+using Wasm::Runtime::HeapKind;
+using Wasm::Runtime::ValueKind;
+
+template<typename T>
+GC::Ptr<T> WebAssemblyCache::ObjectCache<T>::get(Entity entity) const
{
- static NeverDestroyed<Vector<WebAssemblyCache*>> caches;
- return *caches;
+ auto entry = m_objects.get(entity);
+ if (!entry.has_value())
+ return nullptr;
+ return entry->ptr();
}
-WebAssemblyCache::WebAssemblyCache()
+template<typename T>
+void WebAssemblyCache::ObjectCache<T>::set(Entity entity, T& object)
{
- live_caches().append(this);
+ // NB: Stale entries go once there are as many of them as live ones.
+ if (m_objects.size() >= 2 * m_live_after_pruning + 16) {
+ m_objects.remove_all_matching([](auto&, auto& weak) { return !weak; });
+ m_live_after_pruning = m_objects.size();
+ }
+ m_objects.set(entity, object);
}
-WebAssemblyCache::~WebAssemblyCache()
+template<typename T>
+void WebAssemblyCache::ObjectCache<T>::for_each(Function<void(T&)> const& callback) const
{
- live_caches().remove_first_matching([this](auto* cache) { return cache == this; });
+ for (auto& entry : m_objects) {
+ if (entry.value)
+ callback(*entry.value);
+ }
}
-NonnullRefPtr<WebAssemblyCache> get_cache(JS::Realm& realm)
+GC::Ptr<JS::NativeFunction> WebAssemblyCache::function_object(Entity function) const { return m_function_objects.get(function); }
+void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object) { m_function_objects.set(function, object); }
+GC::Ptr<Global> WebAssemblyCache::global_object(Entity global) const { return m_global_objects.get(global); }
+void WebAssemblyCache::set_global_object(Entity global, Global& object) { m_global_objects.set(global, object); }
+GC::Ptr<Memory> WebAssemblyCache::memory_object(Entity memory) const { return m_memory_objects.get(memory); }
+void WebAssemblyCache::set_memory_object(Entity memory, Memory& object) { m_memory_objects.set(memory, object); }
+GC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return m_table_objects.get(table); }
+void WebAssemblyCache::set_table_object(Entity table, Table& object) { m_table_objects.set(table, object); }
+void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const { m_memory_objects.for_each(callback); }
+
+WebAssemblyCache::~WebAssemblyCache() = default;
+
+WebAssemblyCache& WebAssemblyCache::the()
{
- auto& host_defined = Bindings::host_defined_of(realm);
- if (!host_defined.wasm_cache)
- host_defined.wasm_cache = make_ref_counted<WebAssemblyCache>();
- return *host_defined.wasm_cache;
+ // 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;
}
-void WebAssemblyCache::visit_edges(JS::Cell::Visitor& visitor)
+WebAssemblyCache::WebAssemblyCache(GC::Heap& heap)
+ : m_store(make<Wasm::Runtime::Store>(heap))
{
- visitor.visit(m_function_instances);
- visitor.visit(m_imported_objects);
- visitor.visit(m_extern_values);
- visitor.visit(m_inverse_extern_values);
- visitor.visit(m_global_instances);
- visitor.visit(m_memory_instances);
- visitor.visit(m_table_instances);
- m_abstract_machine.visit_external_resources({ .visit_trap = [&visitor](Wasm::ExternallyManagedTrap const& trap) {
- auto& completion = trap.unsafe_external_object_as<JS::Completion>();
- visitor.visit(completion.value());
- } });
+ Array<WasmValueType, 1> js_tag_parameters { WasmValueType::reference(HeapKind::Extern) };
+ m_js_tag = m_store->allocate_tag(js_tag_parameters);
+ m_js_tag_root = GC::Root<GC::ForeignCell> { m_js_tag };
+
+ // 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);
+ });
}
}
@@ -140,18 +162,11 @@ bool validate(JS::Realm& realm, WebIDL::BufferSource bytes)
}
// 2. Compile stableBytes as a WebAssembly module and store the results as module.
- // NOTE: We inline only the validation here to avoid the full compilation cost for just `validate()`.
- auto stable_bytes_buffer = stable_bytes.release_value();
- FixedMemoryStream stream { stable_bytes_buffer.bytes() };
- auto module_or_error = Wasm::Module::parse(stream);
+ (void)realm;
+ auto module = Wasm::Runtime::Module::compile(stable_bytes.value());
// 3. If module is error, return false.
- if (module_or_error.is_error())
- return false;
-
- auto cache = Detail::get_cache(realm);
- auto validation_result = cache->abstract_machine().validate(module_or_error.value(), {}, Wasm::CompileToNative::No);
- if (validation_result.is_error())
+ if (module.is_error())
return false;
// 4. Return true.
@@ -225,249 +240,334 @@ WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::Realm& r
namespace Detail {
-#define TRY_OR_RETURN_TRAP(...) \
- ({ \
- /* Ignore -Wshadow to allow nesting the macro. */ \
- AK_IGNORE_DIAGNOSTIC("-Wshadow", \
- auto&& _temporary_result = (__VA_ARGS__)); \
- static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
- "Do not return a reference from a fallible expression"); \
- if (_temporary_result.is_error()) [[unlikely]] \
- return Wasm::Trap::from_external_object(_temporary_result.release_error()); \
- _temporary_result.release_value(); \
- })
-
-#define TRY_OR_RETURN_OOM_TRAP(vm, ...) \
- ({ \
- /* Ignore -Wshadow to allow nesting the macro. */ \
- AK_IGNORE_DIAGNOSTIC("-Wshadow", \
- auto&& _temporary_result = (__VA_ARGS__)); \
- if (_temporary_result.is_error()) { \
- VERIFY(_temporary_result.error().code() == ENOMEM); \
- return Wasm::Trap::from_external_object((vm).throw_completion<JS::InternalError>((vm).error_message(::JS::VM::ErrorMessage::OutOfMemory))); \
- } \
- static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
- "Do not return a reference from a fallible expression"); \
- _temporary_result.release_value(); \
- })
-
-Wasm::HostFunction create_host_function(JS::Realm& realm, JS::FunctionObject& function, Wasm::FunctionType const& type, size_t function_index)
+// 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;
+
+namespace {
+
+// 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);
+
+}
+
+static u64 host_reference_of(JS::VM& vm, JS::Value value)
{
- return Wasm::HostFunction {
- // NOTE: `type` isn't a GC-backed reference, so copy it in instead.
- [&realm, &function, type = type](auto&, auto arguments) -> Wasm::Result {
- auto& vm = realm.vm();
- GC::RootVector<JS::Value, Wasm::ArgumentsStaticSize> argument_values;
- size_t index = 0;
- for (auto& entry : arguments) {
- argument_values.append(to_js_value(realm, entry, type.parameters()[index]));
- ++index;
- }
+ GC::Cell const* cell = nullptr;
+ if (value.is_cell())
+ cell = &value.as_cell();
+ else
+ cell = vm.heap().allocate<ExternValueBox>(value).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();
+}
- auto result = TRY_OR_RETURN_TRAP(JS::call(vm, function, JS::js_undefined(), argument_values.span()));
- if (type.results().is_empty())
- return Wasm::Result { Vector<Wasm::Value, Wasm::ResultsStaticSize> {} };
+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;
+}
- if (type.results().size() == 1)
- return Wasm::Result { Vector<Wasm::Value, Wasm::ResultsStaticSize> { TRY_OR_RETURN_TRAP(to_webassembly_value(realm, result, type.results().first())) } };
+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;
+}
- auto method = TRY_OR_RETURN_TRAP(result.get_method(vm, vm.names.iterator));
- if (!method)
- return Wasm::Trap::from_external_object(vm.throw_completion<JS::TypeError>(JS::ErrorType::NotIterable, result.to_utf16_string_without_side_effects()));
+// 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)
+{
- auto values = TRY_OR_RETURN_TRAP(JS::iterator_to_list(vm, TRY_OR_RETURN_TRAP(JS::get_iterator_from_method(vm, result, *method))));
+ // 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.
- if (values.size() != type.results().size())
- return Wasm::Trap::from_external_object(vm.throw_completion<JS::TypeError>(Utf16String::formatted("Invalid number of return values for multi-value wasm return of {} objects", type.results().size())));
+ // 4. Let jsArguments be « ».
+ GC::RootVector<JS::Value> js_arguments;
- Vector<Wasm::Value, Wasm::ResultsStaticSize> wasm_values;
- TRY_OR_RETURN_OOM_TRAP(vm, wasm_values.try_ensure_capacity(values.size()));
+ // 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])));
- size_t i = 0;
- for (auto& value : values)
- wasm_values.append(TRY_OR_RETURN_TRAP(to_webassembly_value(realm, value, type.results()[i++])));
+ // 6. Let ret be ? Call(func, undefined, jsArguments).
+ auto ret = TRY(JS::call(vm, function, JS::js_undefined(), js_arguments.span()));
- return Wasm::Result { move(wasm_values) };
- },
- type,
- ByteString::number(function_index),
- };
+ // 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 {};
}
-JS::ThrowCompletionOr<NonnullRefPtr<Wasm::ModuleInstance>> instantiate_module(JS::Realm& realm, Wasm::Module const& module, GC::Ptr<JS::Object> import_object)
+// 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& vm = realm.vm();
- Wasm::Linker linker { module };
- auto cache = get_cache(realm);
+ 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 address = cache.store().allocate_host_function(type, [&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/#run-a-host-function
+ // If the steps threw an exception v, throw a WebAssembly exception with the JavaScript tag and payload v, which
+ // WebAssembly code can catch, and which is v again once it leaves WebAssembly.
+ auto value = result.error_value();
+ Array<WasmValue, 1> payload { WasmValue::from_reference(value.is_null() ? 0 : host_reference_of(vm, value)) };
+ return Wasm::Runtime::HostError::exception(store.allocate_exception(WebAssemblyCache::the().js_tag(), payload));
+ });
+
+ cache.set_host_function_index(address, function_index);
+ return address;
+}
+
+JS::ThrowCompletionOr<Wasm::Runtime::Entity> instantiate_module(JS::VM& vm, Wasm::Runtime::Module const& module, GC::Ptr<JS::Object> import_object)
+{
+ auto& store = WebAssemblyCache::the().store();
+
// https://webassembly.github.io/spec/js-api/index.html#read-the-imports
// 1. If module.imports is not empty, and importObject is undefined, throw a TypeError exception.
- if (!module.import_section().imports().is_empty() && !import_object) {
+ 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 imports be « ».
- HashMap<Wasm::Linker::Name, Wasm::ExternValue> resolved_imports;
+ Vector<Wasm::Runtime::Extern> imports;
+ imports.ensure_capacity(import_count);
size_t imported_function_count = 0;
- if (import_object) {
- dbgln_if(LIBWEB_WASM_DEBUG, "Trying to resolve stuff because import object was specified");
-
- // 3. For each (moduleName, componentName, externtype) of module_imports(module),
- for (auto const& import : module.import_section().imports()) {
- Wasm::Linker::Name import_name { import.module(), import.name(), import.description() };
- dbgln_if(LIBWEB_WASM_DEBUG, "Trying to resolve {}::{}", import_name.module, import_name.name);
-
- // 3.1. Let o be ? Get(importObject, moduleName).
- auto value = TRY(import_object->get(Utf16FlyString::from_utf8(import_name.module)));
-
- // 3.2. 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_name.module)));
- auto const& object = value.as_object();
-
- // 3.3. Let v be ? Get(o, componentName).
- auto import_ = TRY(object.get(Utf16FlyString::from_utf8(import_name.name)));
-
- TRY(import_name.type.visit(
- // 3.4. If externtype is of the form func functype,
- [&](Wasm::TypeIndex index) -> JS::ThrowCompletionOr<void> {
- dbgln_if(LIBWEB_WASM_DEBUG, "Trying to resolve a function {}::{}, type index {}", import_name.module, import_name.name, index.value());
- auto& type = module.type_section().types()[index.value()];
-
- // 3.4.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.name)));
- auto& function = import_.as_function();
- auto& function_type = type.function();
-
- // 3.4.2. If v has a [[FunctionAddress]] internal slot, and therefore is an Exported Function,
- Optional<Wasm::FunctionAddress> address;
- if (auto exported_address = exported_function_address(function); exported_address.has_value()) {
- // 3.4.2.1. Let funcaddr be the value of v’s [[FunctionAddress]] internal slot.
- address = exported_address;
- }
- // 3.4.3. Otherwise,
- else {
- cache->add_imported_object(function);
-
- // 3.4.3.1. Create a host function from v and functype, and let funcaddr be the result.
- // 3.4.3.2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.
- auto host_function = create_host_function(realm, function, function_type, imported_function_count);
- address = cache->abstract_machine().store().allocate(move(host_function));
- }
-
- dbgln_if(LIBWEB_WASM_DEBUG, "Resolved to {}", address->value());
- // FIXME: LinkError instead.
- VERIFY(address.has_value());
-
- // 3.4.4. Let externfunc be the external value func funcaddr.
- // 3.4.5. Append externfunc to imports.
- resolved_imports.set(import_name, Wasm::ExternValue { Wasm::FunctionAddress { *address } });
- ++imported_function_count;
- return {};
- },
- // 3.5. If externtype is of the form global mut valtype,
- [&](Wasm::GlobalType const& type) -> JS::ThrowCompletionOr<void> {
- Optional<Wasm::GlobalAddress> address;
- // 3.5.1. If v is a Number or v is a BigInt,
- if (import_.is_number() || import_.is_bigint()) {
- // 3.5.1.1. If valtype is i64 and v is a Number,
- if (import_.is_number() && type.type().kind() == Wasm::ValueType::I64) {
- // 3.5.1.1.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number to a BigInteger"sv);
- }
- // 3.5.1.2. If valtype is not i64 and v is a BigInt,
- if (import_.is_bigint() && type.type().kind() != Wasm::ValueType::I64) {
- // 3.5.1.2.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a BigInteger to a Number"sv);
- }
- // 3.5.1.3. If valtype is v128,
- if (type.type().kind() == Wasm::ValueType::V128) {
- // 3.5.1.3.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number or BigInt to a V128"sv);
- }
- // 3.5.1.4. Let value be ToWebAssemblyValue(v, valtype).
- auto cast_value = TRY(to_webassembly_value(realm, import_, type.type()));
- // 3.5.1.5. Let store be the surrounding agent's associated store.
- // 3.5.1.6. Let (store, globaladdr) be global_alloc(store, const valtype, value).
- // 3.5.1.7. Set the surrounding agent's associated store to store.
- address = cache->abstract_machine().store().allocate({ type.type(), false }, cast_value);
- }
- // 3.5.2. Otherwise, if v implements Global,
- else if (import_.is_object()) {
- auto* global = Bindings::global_from_value(import_);
- if (!global)
- return vm.throw_completion<LinkError>("Invalid value for global type"sv);
-
- // 3.5.2.1. Let globaladdr be v.[[Global]].
- address = global->address();
- }
- // 3.5.3. Otherwise,
- else {
- // 3.5.3.1. Throw a LinkError exception.
- return vm.throw_completion<LinkError>("Invalid value for global type"sv);
- }
-
- // 3.5.4. Let externglobal be global globaladdr.
- // 3.5.5. Append externglobal to imports.
- resolved_imports.set(import_name, Wasm::ExternValue { *address });
- return {};
- },
- // 3.6. If externtype is of the form mem memtype,
- [&](Wasm::MemoryType const&) -> JS::ThrowCompletionOr<void> {
- // 3.6.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);
- // 3.6.2. Let externmem be the external value mem v.[[Memory]].
- auto address = memory->address();
- // 3.6.3. Append externmem to imports.
- resolved_imports.set(import_name, Wasm::ExternValue { address });
- return {};
- },
- // 3.7. If externtype is of the form table tabletype,
- [&](Wasm::TableType const&) -> JS::ThrowCompletionOr<void> {
- // 3.7.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);
- // 3.7.2. Let tableaddr be v.[[Table]].
- // 3.7.3. Let externtable be the external value table tableaddr.
- auto address = table->address();
- // 3.7.4. Append externtable to imports.
- resolved_imports.set(import_name, Wasm::ExternValue { address });
- return {};
- },
- [&](auto const&) -> JS::ThrowCompletionOr<void> {
- // (noop)
- return {};
- }));
- }
- }
- // (inlined) 4. Return imports.
- linker.link(resolved_imports);
- auto link_result = linker.finish();
- if (link_result.is_error()) {
- StringBuilder builder;
- builder.append("Missing "sv);
- builder.join(' ', link_result.error().missing_imports);
- return vm.throw_completion<LinkError>(MUST(builder.to_string()));
- }
+ // 3. 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);
+
+ // 3.1. Let o be ? Get(importObject, moduleName).
+ auto value = TRY(import_object->get(Utf16FlyString::from_utf8(import.module)));
+
+ // 3.2. 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();
+
+ // 3.3. Let v be ? Get(o, componentName).
+ auto import_ = TRY(object.get(Utf16FlyString::from_utf8(import.name)));
+
+ switch (import.type.kind) {
+ // 3.4. If externtype is of the form func functype,
+ case Wasm::Runtime::ExternKind::Function: {
+ // 3.4.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;
+ // 3.4.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()) {
+ // 3.4.2.1. Let funcaddr be the value of v's [[FunctionAddress]] internal slot.
+ address = *exported_address;
+ }
+ // 3.4.3. Otherwise,
+ else {
+ // 3.4.3.1. Create a host function from v and functype, and let funcaddr be the result.
+ // 3.4.3.2. Let index be the number of external functions in imports. This value index is known as the index of the host function funcaddr.
+ auto function_type = module.function_type(import.type.type_index);
+ VERIFY(function_type.has_value());
+ address = create_host_function(vm, function, function_type.release_value(), imported_function_count);
+ }
- // https://webassembly.github.io/spec/js-api/index.html#instantiate-the-core-of-a-webassembly-module
- auto instance_result = cache->abstract_machine().instantiate(module, link_result.release_value());
- if (instance_result.is_error()) {
- auto instantiation_error = instance_result.release_error();
- switch (instantiation_error.source) {
- case Wasm::InstantiationErrorSource::Linking:
- return vm.throw_completion<LinkError>(instantiation_error.error);
- case Wasm::InstantiationErrorSource::StartFunction:
- return vm.throw_completion<RuntimeError>(instantiation_error.error);
+ // 3.4.4. Let externfunc be the external value func funcaddr.
+ // 3.4.5. Append externfunc to imports.
+ imports.unchecked_append({ Wasm::Runtime::ExternKind::Function, address });
+ ++imported_function_count;
+ break;
+ }
+ // 3.5. If externtype is of the form global mut valtype,
+ case Wasm::Runtime::ExternKind::Global: {
+ auto value_type = import.type.value_type;
+ Wasm::Runtime::Entity address = nullptr;
+ // 3.5.1. If v is a Number or v is a BigInt,
+ if (import_.is_number() || import_.is_bigint()) {
+ // 3.5.1.1. If valtype is i64 and v is a Number,
+ if (import_.is_number() && value_type.kind == ValueKind::I64) {
+ // 3.5.1.1.1. Throw a LinkError exception.
+ return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number to a BigInteger"sv);
+ }
+ // 3.5.1.2. If valtype is not i64 and v is a BigInt,
+ if (import_.is_bigint() && value_type.kind != ValueKind::I64) {
+ // 3.5.1.2.1. Throw a LinkError exception.
+ return vm.throw_completion<LinkError>("Import resolution attempted to cast a BigInteger to a Number"sv);
+ }
+ // 3.5.1.3. If valtype is v128,
+ if (value_type.kind == ValueKind::V128) {
+ // 3.5.1.3.1. Throw a LinkError exception.
+ return vm.throw_completion<LinkError>("Import resolution attempted to cast a Number or BigInt to a V128"sv);
+ }
+ // 3.5.1.4. Let value be ToWebAssemblyValue(v, valtype).
+ auto cast_value = TRY(to_webassembly_value(vm, import_, value_type));
+ // 3.5.1.5. Let store be the surrounding agent's associated store.
+ // 3.5.1.6. Let (store, globaladdr) be global_alloc(store, const valtype, value).
+ // 3.5.1.7. Set the surrounding agent's associated store to store.
+ address = store.allocate_global(value_type, false, cast_value);
+ }
+ // 3.5.2. Otherwise, if v implements Global,
+ else if (auto* global = import_.is_object() ? Bindings::global_from_value(import_) : nullptr) {
+ // 3.5.2.1. Let globaladdr be v.[[Global]].
+ address = global->address();
+ }
+ // 3.5.3. Otherwise,
+ else {
+ // 3.5.3.1. Throw a LinkError exception.
+ return vm.throw_completion<LinkError>("Invalid value for global type"sv);
+ }
+
+ // 3.5.4. Let externglobal be global globaladdr.
+ // 3.5.5. Append externglobal to imports.
+ imports.unchecked_append({ Wasm::Runtime::ExternKind::Global, address });
+ break;
+ }
+ // 3.6. If externtype is of the form mem memtype,
+ case Wasm::Runtime::ExternKind::Memory: {
+ // 3.6.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);
+
+ // 3.6.2. Let externmem be the external value mem v.[[Memory]].
+ // 3.6.3. Append externmem to imports.
+ imports.unchecked_append({ Wasm::Runtime::ExternKind::Memory, memory->address() });
+ break;
+ }
+ // 3.7. If externtype is of the form table tabletype,
+ case Wasm::Runtime::ExternKind::Table: {
+ // 3.7.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);
+
+ // 3.7.2. Let tableaddr be v.[[Table]].
+ // 3.7.3. Let externtable be the external value table tableaddr.
+ // 3.7.4. Append externtable to imports.
+ imports.unchecked_append({ Wasm::Runtime::ExternKind::Table, table->address() });
+ break;
+ }
+ // FIXME: 3.8. If externtype is of the form tag attribute functype, which needs WebAssembly.Tag.
+ case Wasm::Runtime::ExternKind::Tag:
+ return vm.throw_completion<LinkError>("Tag imports are not supported"sv);
}
- VERIFY_NOT_REACHED();
}
- return instance_result.release_value();
+ // 4. Return imports.
+ return instantiate_core_module(vm, module, imports);
+}
+
+// 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)
+{
+ // 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();
}
// https://webassembly.github.io/spec/js-api/#compile-a-webassembly-module
@@ -477,83 +577,10 @@ JS::ThrowCompletionOr<NonnullRefPtr<CompiledWebAssemblyModule>> compile_a_webass
auto& vm = realm.vm();
TRY(host_ensure_can_compile_wasm_bytes(realm));
- Wasm::ModuleStats stats;
- stats.input_size_bytes = data.size();
-
- auto parse_start = MonotonicTime::now();
- FixedMemoryStream stream { data };
- auto module_result = Wasm::Module::parse(stream);
- stats.parse_time = MonotonicTime::now() - parse_start;
- if (module_result.is_error()) {
- return vm.throw_completion<CompileError>(Wasm::parse_error_to_byte_string(module_result.error()));
- }
-
- auto cache = get_cache(realm);
- auto validate_start = MonotonicTime::now();
- auto validation_result = cache->abstract_machine().validate(module_result.value(), {}, Wasm::CompileToNative::No);
- stats.validate_time = MonotonicTime::now() - validate_start;
-
- if (validation_result.is_error())
- return vm.throw_completion<CompileError>(validation_result.error().error_string);
-
- // Content-keyed disk cache: hash the wasm bytes, slot into the HTTP side-data shelf under a synthetic wasm-cache://<hex> URL
- // NB: The entry lives in the cache partition of this realm, so one site cannot hand compiled code to another.
- Optional<Wasm::CompileCacheConfig> wasm_cache_config;
- auto network_isolation_key = Fetch::Infrastructure::determine_the_network_partition_key(HTML::principal_realm_settings_object(realm));
- if (network_isolation_key.has_value() && network_isolation_key->disk_cache_partition().has_value() && ResourceLoader::is_initialized() && ResourceLoader::the().request_client()) {
- auto digest = ::Crypto::Hash::SHA256::hash(data);
- __builtin_memcpy(stats.wasm_hash.data(), digest.bytes().data(), 32);
-
- StringBuilder hex_builder;
- for (auto byte : digest.bytes())
- hex_builder.appendff("{:02x}", byte);
- auto synthetic_url = URL::Parser::basic_parse(ByteString::formatted("wasm-cache://{}", hex_builder.to_byte_string()));
- if (synthetic_url.has_value()) {
- auto method = "GET"_string.to_byte_string();
-
- Wasm::CompileCacheConfig config;
- __builtin_memcpy(config.wasm_hash.data(), digest.bytes().data(), 32);
-
- auto cache_entry_result = ResourceLoader::the().request_client()->create_synthetic_cache_entry(network_isolation_key, *synthetic_url, method);
- if (!cache_entry_result.is_error() && cache_entry_result.value()) {
- auto retrieve_result = ResourceLoader::the().request_client()->retrieve_cache_associated_data(
- network_isolation_key, *synthetic_url, method, OptionalNone {}, 0u,
- HTTP::CacheEntryAssociatedData::WebAssemblyCompiledCode);
- if (!retrieve_result.is_error()) {
- if (auto buf = retrieve_result.release_value(); buf.has_value()) {
- // Copy into an owned buffer: compilation may run on another thread long after the AnonymousBuffer here goes away.
- if (auto copy = ByteBuffer::copy(buf->bytes()); !copy.is_error())
- config.existing_blob = copy.release_value();
- }
- }
-
- config.on_compiled = [network_isolation_key, url = *synthetic_url, method = move(method), event_loop_weak = Core::EventLoop::current_weak()](ByteBuffer blob) mutable {
- auto origin = event_loop_weak->take();
- if (!origin)
- return;
- origin->deferred_invoke([network_isolation_key = move(network_isolation_key), url = move(url), method = move(method), blob = move(blob)]() mutable {
- if (!ResourceLoader::is_initialized() || !ResourceLoader::the().request_client())
- return;
- (void)ResourceLoader::the().request_client()->store_cache_associated_data(
- network_isolation_key, url, method, OptionalNone {}, 0u,
- HTTP::CacheEntryAssociatedData::WebAssemblyCompiledCode, blob.bytes());
- });
- };
- }
-
- wasm_cache_config = move(config);
- }
- }
-
- auto compiled_module = make_ref_counted<CompiledWebAssemblyModule>(module_result.release_value());
- cache->add_compiled_module(compiled_module);
- if (wasm_cache_config.has_value())
- compiled_module->module->set_cranelift_cache_config(wasm_cache_config.release_value());
- compiled_module->module->set_compile_stats(move(stats));
- Threading::ThreadPool::the().submit([module = NonnullRefPtr { compiled_module->module }] {
- Wasm::start_cranelift_compilation(*module);
- });
- return compiled_module;
+ 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());
}
// https://webassembly.github.io/spec/js-api/#HostResizeArrayBuffer
@@ -564,18 +591,14 @@ JS::ThrowCompletionOr<JS::HandledByHost> host_resize_array_buffer(JS::VM& vm, JS
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;
- for (auto* cache : live_caches()) {
- auto const& map = cache->memory_instances();
-
- for (auto const& entry : map) {
- // 1. If SameValue(mem.[[BufferObject]], buffer) is true,
- if (memory_has_buffer_object(*entry.value, buffer)) {
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(!memory);
- memory = entry.value;
- }
+ 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);
@@ -584,19 +607,19 @@ JS::ThrowCompletionOr<JS::HandledByHost> host_resize_array_buffer(JS::VM& vm, JS
// that removes finalized Memory objects from the caches we iterate.
// 1. Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
- VERIFY(buffer.byte_length() % Wasm::Constants::page_size == 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 % Wasm::Constants::page_size != 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 / Wasm::Constants::page_size;
+ 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.
@@ -622,18 +645,14 @@ JS::ThrowCompletionOr<JS::HandledByHost> host_grow_shared_array_buffer(JS::VM& v
// 3. For each memaddr → mem in all Memory object caches,
GC::Ptr<Memory> memory;
- for (auto* cache : live_caches()) {
- auto const& map = cache->memory_instances();
-
- for (auto const& entry : map) {
- // 1. If SameValue(mem.[[BufferObject]], buffer) is true,
- if (memory_has_buffer_object(*entry.value, buffer)) {
- // 2. Assert: buffer is the [[BufferObject]] of exactly one value in map.
- VERIFY(!memory);
- memory = entry.value;
- }
+ 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);
@@ -642,19 +661,19 @@ JS::ThrowCompletionOr<JS::HandledByHost> host_grow_shared_array_buffer(JS::VM& v
// that removes finalized Memory objects from the caches we iterate.
// 1. Assert: buffer.[[ArrayBufferByteLength]] modulo 65536 is 0.
- VERIFY(buffer.byte_length() % Wasm::Constants::page_size == 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 % Wasm::Constants::page_size != 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 / Wasm::Constants::page_size;
+ 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.
@@ -695,7 +714,7 @@ public:
using Behavior = AK::Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)>;
- Wasm::FunctionAddress function_address() const { return m_function_address; }
+ Wasm::Runtime::Entity function_address() const { return m_function; }
JS::ThrowCompletionOr<JS::Value> call(JS::VM& vm) const
{
@@ -704,9 +723,9 @@ public:
}
private:
- ExportedFunctionHostData(Behavior behavior, Wasm::FunctionAddress function_address)
+ ExportedFunctionHostData(Behavior behavior, Wasm::Runtime::Entity function)
: m_behavior(move(behavior))
- , m_function_address(function_address)
+ , m_function(function)
{
}
@@ -714,10 +733,12 @@ private:
{
Base::visit_edges(visitor);
visitor.visit_possible_values(m_behavior.raw_capture_range());
+ visitor.visit(m_function);
}
Behavior m_behavior;
- Wasm::FunctionAddress m_function_address;
+ // The function, which an Exported Function keeps alive.
+ Wasm::Runtime::Entity m_function { nullptr };
};
GC_DEFINE_ALLOCATOR(ExportedFunctionHostData);
@@ -736,13 +757,13 @@ constexpr JSHostClass exported_function_host_class = JS::make_host_class(JS_HOST
}
-GC::Ref<JS::HostFunction> create_exported_function(JS::Realm& realm, Utf16FlyString name, size_t length, Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> behavior, Wasm::FunctionAddress function_address)
+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)
{
- auto host_data = realm.heap().allocate<ExportedFunctionHostData>(move(behavior), function_address);
+ 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);
}
-Optional<Wasm::FunctionAddress> exported_function_address(JS::FunctionObject const& function)
+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();
@@ -750,256 +771,223 @@ Optional<Wasm::FunctionAddress> exported_function_address(JS::FunctionObject con
}
// https://www.w3.org/TR/wasm-js-api-2/#name-of-the-webassembly-function
-Utf16FlyString name_of_webassembly_function(Wasm::Store& store, Wasm::FunctionAddress function_address)
+Utf16FlyString name_of_webassembly_function(Wasm::Runtime::Entity function)
{
- // 1. Let store be the surrounding agent’s associated store.
-
+ // 1. Let store be the surrounding agent's associated store.
// 2. Let funcinst be store.funcs[funcaddr].
- auto* function_instance = store.get(function_address);
- VERIFY(function_instance);
-
- auto index = function_instance->visit(
- // 3. If funcinst is of the form {type functype, hostcode hostfunc},
- [&](Wasm::HostFunction const& host_function) {
- // 1. Assert: hostfunc is a JavaScript object and IsCallable(hostfunc) is true.
- // 2. Let index be the index of the host function funcaddr.
- auto index = host_function.name().to_number<size_t>(TrimWhitespace::No);
- VERIFY(index.has_value());
- return *index;
- },
- // 4. Otherwise,
- [&](Wasm::WasmFunction const& wasm_function) {
- // 1. Let moduleinst be funcinst.module.
- auto const& module_instance = wasm_function.module();
-
- // 2. Assert: funcaddr is contained in moduleinst.funcaddrs.
- // 3. Let index be the index of moduleinst.funcaddrs where funcaddr is found.
- auto index = module_instance.functions().find_first_index(function_address);
- VERIFY(index.has_value());
- return *index;
- });
+ // 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).map([](u32 index) -> size_t { return index; });
+ if (!index.has_value())
+ index = cache.host_function_index(function);
+ VERIFY(index.has_value());
// 5. Return ! ToString(index).
- auto name = Utf16String::number(index);
+ auto name = Utf16String::number(*index);
return Utf16FlyString::from_utf16(name.utf16_view());
}
-GC::Ptr<JS::NativeFunction> create_native_function(JS::Realm& realm, Wasm::FunctionAddress address, Utf16FlyString, GC::Ptr<Instance> instance)
+// 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)
{
- auto cache = get_cache(realm);
- if (auto entry = cache->get_function_instance(address); entry.has_value())
- return *entry;
+ auto& cache = WebAssemblyCache::the();
+ if (auto object = cache.function_object(function))
+ return *object;
- auto& store = cache->abstract_machine().store();
- auto type = store.get(address)->visit([&](auto const& value) { return value.type(); });
- auto length = type.parameters().size();
+ auto type = cache.store().function_type(function);
+ auto length = type.parameters.size();
- auto function = create_exported_function(
+ auto object = create_exported_function(
realm,
- name_of_webassembly_function(store, address),
+ name_of_webassembly_function(function),
length,
- [address, type = move(type), instance, realm = GC::Ref(realm)](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
- (void)instance;
- Vector<Wasm::Value, Wasm::ArgumentsStaticSize> values;
- values.ensure_capacity(type.parameters().size());
-
- // Grab as many values as needed and convert them.
- size_t index = 0;
- for (auto& type : type.parameters())
- values.append(TRY(to_webassembly_value(realm, vm.argument(index++), type)));
-
- auto cache = get_cache(realm);
- auto result = cache->abstract_machine().invoke(address, move(values));
- // FIXME: Use the convoluted mapping of errors defined in the spec.
- if (result.is_trap()) {
- if (auto ptr = result.trap().data.get_pointer<Wasm::ExternallyManagedTrap>())
- return ptr->unsafe_external_object_as<JS::Completion>();
- auto trap = result.trap().format();
- // 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.
- if (trap.ends_with(Wasm::Constants::stack_exhaustion_message))
- return vm.throw_completion<JS::InternalError>(JS::ErrorType::CallStackSizeExceeded);
- return vm.throw_completion<RuntimeError>(Utf16String::formatted("Wasm execution trapped (WIP): {}", trap));
- }
-
- if (result.values().is_empty())
+ [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 (result.values().size() == 1)
- return to_js_value(realm, result.values().first(), type.results().first());
+ if (values.size() == 1)
+ return to_js_value(vm, values.first(), type.results.first());
- // Put result values into a JS::Array in reverse order.
GC::RootVector<JS::Value> js_result_values;
- js_result_values.ensure_capacity(result.values().size());
-
- for (size_t i = result.values().size(); i > 0; i--) {
- // Safety: ensure_capacity is called just before this.
- js_result_values.unchecked_append(to_js_value(realm, result.values().at(i - 1), type.results().at(i - 1)));
- }
-
- return JS::Value(JS::Array::create_from(realm, 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));
},
- address);
+ function);
- cache->add_function_instance(address, function);
- return function;
+ cache.set_function_object(function, object);
+ return object;
}
-JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::Realm& realm, JS::Value value, Wasm::ValueType const& type)
+// https://webassembly.github.io/spec/js-api/#towebassemblyvalue
+static JS::ThrowCompletionOr<u64> to_webassembly_reference(JS::VM& vm, JS::Value value, WasmValueType type)
{
- auto& vm = realm.vm();
- switch (type.kind()) {
- case Wasm::ValueType::I64: {
- auto bigint = TRY(value.to_bigint(vm));
- return Wasm::Value { bigint->big_integer().to_i64() };
- }
- case Wasm::ValueType::I32: {
- auto _i32 = TRY(value.to_i32(vm));
- return Wasm::Value { static_cast<i32>(_i32) };
+ if (value.is_null()) {
+ if (!type.nullable)
+ return vm.throw_completion<JS::TypeError>("Cannot convert null to a non-nullable reference"_utf16);
+ return 0;
}
- case Wasm::ValueType::F64: {
- auto number = TRY(value.to_double(vm));
- return Wasm::Value { static_cast<double>(number) };
- }
- case Wasm::ValueType::F32: {
- auto number = TRY(value.to_double(vm));
- return Wasm::Value { static_cast<float>(number) };
- }
- case Wasm::ValueType::FunctionReference: {
- if (value.is_null())
- return Wasm::Value(Wasm::ValueType { Wasm::ValueType::Kind::FunctionReference });
+ switch (type.heap) {
+ case HeapKind::Function: {
if (value.is_function()) {
- auto& function = value.as_function();
- auto cache = get_cache(realm);
- for (auto& entry : cache->function_instances()) {
- if (entry.value == GC::Ref { function })
- return Wasm::Value { Wasm::Reference { Wasm::Reference::Func { entry.key, cache->abstract_machine().store().get_module_for(entry.key) } } };
- }
+ if (auto address = exported_function_address(value.as_function()); address.has_value())
+ return WebAssemblyCache::the().store().function_reference(*address);
}
-
return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Exported function");
}
- case Wasm::ValueType::ExternReference: {
- if (value.is_null())
- return Wasm::Value(Wasm::ValueType { Wasm::ValueType::Kind::ExternReference });
- auto cache = get_cache(realm);
- if (auto entry = cache->inverse_extern_values().get(value); entry.has_value())
- return Wasm::Value { Wasm::Reference { Wasm::Reference::Extern { *entry } } };
- Wasm::ExternAddress extern_addr = cache->extern_values().size();
- cache->add_extern_value(extern_addr, value);
- return Wasm::Value { Wasm::Reference { Wasm::Reference::Extern { extern_addr } } };
- }
- case Wasm::ValueType::ExceptionReference:
- return Wasm::Value(Wasm::ValueType { Wasm::ValueType::Kind::ExceptionReference });
- case Wasm::ValueType::V128:
- return vm.throw_completion<JS::TypeError>("Cannot convert a vector value to a javascript value"_utf16);
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- return vm.throw_completion<JS::TypeError>("Cannot convert a packed value to a javascript value"_utf16);
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::NoExceptionReference:
- case Wasm::ValueType::TypeUseReference:
+ case HeapKind::Extern:
+ return host_reference_of(vm, value);
+ case HeapKind::Any:
+ // FIXME: Unwrap WebAssembly GC objects once they can reach JavaScript.
+ if (auto reference = i31_reference_of(value); reference.has_value())
+ return *reference;
+ // NB: Converting an externref to anyref keeps its bits.
+ return host_reference_of(vm, value);
+ case HeapKind::Eq:
+ case HeapKind::I31:
+ if (auto reference = i31_reference_of(value); reference.has_value())
+ return *reference;
+ return vm.throw_completion<JS::TypeError>("Cannot convert the value to an i31 reference"_utf16);
+ case HeapKind::Exception:
+ case HeapKind::NoException:
+ return vm.throw_completion<JS::TypeError>("Cannot convert a JavaScript value to an exception reference"_utf16);
+ 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::Struct:
+ case HeapKind::Array:
+ case HeapKind::Concrete:
// FIXME: Implement the conversions for the wasm-gc reference hierarchy
- // (https://webassembly.github.io/spec/js-api/#tojsvalue).
+ // (https://webassembly.github.io/spec/js-api/#towebassemblyvalue).
return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);
}
-
VERIFY_NOT_REACHED();
}
-Wasm::Value default_webassembly_value(JS::Realm& realm, Wasm::ValueType type)
+// https://webassembly.github.io/spec/js-api/#towebassemblyvalue
+JS::ThrowCompletionOr<WasmValue> to_webassembly_value(JS::VM& vm, JS::Value value, WasmValueType type)
{
- switch (type.kind()) {
- case Wasm::ValueType::I32:
- case Wasm::ValueType::I64:
- case Wasm::ValueType::F32:
- case Wasm::ValueType::F64:
- case Wasm::ValueType::V128:
- case Wasm::ValueType::FunctionReference:
- return Wasm::Value(type);
- case Wasm::ValueType::ExternReference:
- return MUST(to_webassembly_value(realm, JS::js_undefined(), type));
- case Wasm::ValueType::ExceptionReference:
- return Wasm::Value(type);
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::NoExceptionReference:
- case Wasm::ValueType::TypeUseReference:
- return Wasm::Value(type);
+
+ 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::Value to_js_value(JS::Realm& realm, Wasm::Value& wasm_value, Wasm::ValueType type)
+JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM& vm, WasmValue wasm_value, WasmValueType type)
{
- switch (type.kind()) {
- case Wasm::ValueType::I64:
- return JS::BigInt::create(realm.vm(), ::Crypto::SignedBigInteger { wasm_value.to<i64>() });
- case Wasm::ValueType::I32:
- return JS::Value(wasm_value.to<i32>());
- case Wasm::ValueType::F64:
- return JS::Value(wasm_value.to<double>());
- case Wasm::ValueType::F32:
- return JS::Value(static_cast<double>(wasm_value.to<float>()));
- case Wasm::ValueType::FunctionReference: {
- auto ref_ = wasm_value.to<Wasm::Reference>();
- if (ref_.ref().has<Wasm::Reference::Null>())
- return JS::js_null();
- auto address = ref_.ref().get<Wasm::Reference::Func>().address;
- auto cache = get_cache(realm);
- auto* function = cache->abstract_machine().store().get(address);
- auto name = function->visit(
- [&](Wasm::WasmFunction& wasm_function) {
- auto index = *wasm_function.module().functions().find_first_index(address);
- return ByteString::formatted("func{}", index);
- },
- [](Wasm::HostFunction& host_function) {
- return host_function.name();
- });
- return create_native_function(realm, address, Utf16FlyString::from_utf8(name));
+
+ 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();
+ if (reference == 0)
+ return JS::js_null();
+
+ if (type.heap == HeapKind::Function)
+ return create_native_function(*vm.current_realm(), WebAssemblyCache::the().store().function_from_reference(reference));
+ if (type.heap == HeapKind::Concrete) {
+ // FIXME: Convert references of concrete types, which needs the module the type belongs to.
+ return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);
}
- case Wasm::ValueType::ExternReference: {
- auto ref_ = wasm_value.to<Wasm::Reference>();
- if (ref_.ref().has<Wasm::Reference::Null>())
- return JS::js_null();
- auto address = ref_.ref().get<Wasm::Reference::Extern>().address;
- auto cache = get_cache(realm);
- auto value = cache->get_extern_value(address);
- return value.release_value();
+
+ if (reference & I31_REFERENCE_BIT)
+ return JS::Value(value_of_i31_reference(reference));
+ if ((reference & REFERENCE_TAG_MASK) == HOST_REFERENCE_TAG)
+ return value_of_host_reference(reference);
+
+ // FIXME: Implement the conversions for the wasm-gc reference hierarchy
+ // (https://webassembly.github.io/spec/js-api/#tojsvalue).
+ return vm.throw_completion<JS::TypeError>("Unsupported heap reference"_utf16);
+}
+
+// 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))));
+ }
+ // FIXME: Throw a WebAssembly.Exception once it exists.
+ return vm.throw_completion<RuntimeError>(Utf16String::formatted("Wasm execution trapped (WIP): {}", failure.message));
}
- case Wasm::ValueType::V128:
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- case Wasm::ValueType::ExceptionReference:
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::NoExceptionReference:
- case Wasm::ValueType::TypeUseReference:
- VERIFY_NOT_REACHED();
+ 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();
}
@@ -1073,7 +1061,7 @@ GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm
// 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_module(realm, module->module, import_object);
+ auto result = Detail::instantiate_module(realm.vm(), *module->module, import_object);
if (result.is_error()) {
WebIDL::reject_promise(promise, result.error_value());
return;
@@ -1083,7 +1071,7 @@ GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm
// 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(Detail::get_cache(realm), move(instance));
+ auto instance_object = Instance::create(instance);
// 4. Resolve promise with instanceObject.
Bindings::resolve_webassembly_instance_promise(realm, promise, instance_object);
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h
index 7112fe313d6..ada4d6a15d4 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h
@@ -9,17 +9,19 @@
#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/Root.h>
+#include <LibGC/Weak.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/AbstractMachine/AbstractMachine.h>
+#include <LibWasm/Runtime/Runtime.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
#include <LibWeb/WebIDL/Buffers.h>
@@ -38,85 +40,98 @@ WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::
namespace Detail {
-Wasm::HostFunction create_host_function(JS::Realm&, JS::FunctionObject& function, Wasm::FunctionType const& type, size_t function_index);
-
struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule> {
- explicit CompiledWebAssemblyModule(NonnullRefPtr<Wasm::Module> module)
+ explicit CompiledWebAssemblyModule(NonnullRefPtr<Wasm::Runtime::Module> module)
: module(move(module))
{
}
- NonnullRefPtr<Wasm::Module> module;
+ NonnullRefPtr<Wasm::Runtime::Module> module;
};
-class WebAssemblyCache : public RefCounted<WebAssemblyCache> {
+// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, and Table object caches.
+// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. The
+// caches only map entities to their objects for as long as both live.
+class WebAssemblyCache {
+ AK_MAKE_NONCOPYABLE(WebAssemblyCache);
+ AK_MAKE_NONMOVABLE(WebAssemblyCache);
+
public:
- WebAssemblyCache();
- ~WebAssemblyCache();
+ using Entity = Wasm::Runtime::Entity;
- void visit_edges(JS::Cell::Visitor&);
+ // The cache of the current thread's agent.
+ static WebAssemblyCache& the();
- void add_compiled_module(NonnullRefPtr<CompiledWebAssemblyModule> module) { m_compiled_modules.append(module); }
- void add_function_instance(Wasm::FunctionAddress address, GC::Ptr<JS::NativeFunction> function) { m_function_instances.set(address, function); }
- void add_imported_object(GC::Ptr<JS::Object> object) { m_imported_objects.set(object); }
- void add_extern_value(Wasm::ExternAddress address, JS::Value value)
- {
- if (auto entry = m_extern_values.get(address); entry.has_value())
- m_inverse_extern_values.remove(entry.value());
- m_extern_values.set(address, value);
- m_inverse_extern_values.set(value, address);
- }
- void add_global_instance(Wasm::GlobalAddress address, GC::Ptr<WebAssembly::Global> global) { m_global_instances.set(address, global); }
- void add_memory_instance(Wasm::MemoryAddress address, GC::Ptr<WebAssembly::Memory> memory) { m_memory_instances.set(address, memory); }
- void remove_memory_instance(Wasm::MemoryAddress address) { m_memory_instances.remove(address); }
- void add_table_instance(Wasm::TableAddress address, GC::Ptr<WebAssembly::Table> table) { m_table_instances.set(address, table); }
-
- Optional<GC::Ptr<JS::NativeFunction>> get_function_instance(Wasm::FunctionAddress address) { return m_function_instances.get(address); }
- Optional<JS::Value> get_extern_value(Wasm::ExternAddress address) { return m_extern_values.get(address); }
- Optional<GC::Ptr<WebAssembly::Global>> get_global_instance(Wasm::GlobalAddress address) { return m_global_instances.get(address); }
- Optional<GC::Ptr<WebAssembly::Memory>> get_memory_instance(Wasm::MemoryAddress address) { return m_memory_instances.get(address); }
- Optional<GC::Ptr<WebAssembly::Table>> get_table_instance(Wasm::TableAddress address) { return m_table_instances.get(address); }
-
- HashMap<Wasm::FunctionAddress, GC::Ptr<JS::NativeFunction>> const& function_instances() const { return m_function_instances; }
- HashMap<Wasm::ExternAddress, JS::Value> const& extern_values() const { return m_extern_values; }
- HashMap<JS::Value, Wasm::ExternAddress> const& inverse_extern_values() const { return m_inverse_extern_values; }
- HashMap<Wasm::GlobalAddress, GC::Ptr<WebAssembly::Global>> const& global_instances() const { return m_global_instances; }
- HashMap<Wasm::MemoryAddress, GC::Ptr<WebAssembly::Memory>> const& memory_instances() const { return m_memory_instances; }
- HashMap<Wasm::TableAddress, GC::Ptr<WebAssembly::Table>> const& table_instances() const { return m_table_instances; }
- HashTable<GC::Ptr<JS::Object>> const& imported_objects() const { return m_imported_objects; }
- Wasm::AbstractMachine& abstract_machine() { return m_abstract_machine; }
+ 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; }
+
+ 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&);
+ void for_each_memory_object(Function<void(WebAssembly::Memory&)> const&) const;
+
+ // The index of a host function: how many functions were imported before it.
+ void set_host_function_index(Entity function, size_t index) { m_host_function_indices.set(function, index); }
+ Optional<size_t> host_function_index(Entity function) const { return m_host_function_indices.get(function); }
private:
- HashMap<Wasm::FunctionAddress, GC::Ptr<JS::NativeFunction>> m_function_instances;
- HashMap<Wasm::ExternAddress, JS::Value> m_extern_values;
- HashMap<JS::Value, Wasm::ExternAddress> m_inverse_extern_values;
- HashMap<Wasm::GlobalAddress, GC::Ptr<WebAssembly::Global>> m_global_instances;
- HashMap<Wasm::MemoryAddress, GC::Ptr<WebAssembly::Memory>> m_memory_instances;
- HashMap<Wasm::TableAddress, GC::Ptr<WebAssembly::Table>> m_table_instances;
- Vector<NonnullRefPtr<CompiledWebAssemblyModule>> m_compiled_modules;
- HashTable<GC::Ptr<JS::Object>> m_imported_objects;
- Wasm::AbstractMachine m_abstract_machine;
+ explicit WebAssemblyCache(GC::Heap&);
+ ~WebAssemblyCache();
+
+ // Objects by entity. An entry whose object is gone is stale: its entity may be gone too, and its address reused.
+ template<typename T>
+ class ObjectCache {
+ public:
+ GC::Ptr<T> get(Entity) const;
+ void set(Entity, T&);
+ void for_each(Function<void(T&)> const&) const;
+
+ private:
+ HashMap<Entity, GC::Weak<T>> m_objects;
+ size_t m_live_after_pruning { 0 };
+ };
+
+ NonnullOwnPtr<Wasm::Runtime::Store> m_store;
+ Entity m_js_tag { nullptr };
+ GC::Root<GC::ForeignCell> m_js_tag_root;
+ ObjectCache<JS::NativeFunction> m_function_objects;
+ ObjectCache<WebAssembly::Global> m_global_objects;
+ ObjectCache<WebAssembly::Memory> m_memory_objects;
+ ObjectCache<WebAssembly::Table> m_table_objects;
+ // NB: An entry outlives its function, but every host function sets its own, so a live one's entry is right.
+ HashMap<Entity, size_t> m_host_function_indices;
};
// 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::FunctionAddress);
+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::FunctionAddress> exported_function_address(JS::FunctionObject const&);
-
-NonnullRefPtr<WebAssemblyCache> get_cache(JS::Realm&);
+Optional<Wasm::Runtime::Entity> exported_function_address(JS::FunctionObject const&);
-JS::ThrowCompletionOr<NonnullRefPtr<Wasm::ModuleInstance>> instantiate_module(JS::Realm&, Wasm::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<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::Store&, Wasm::FunctionAddress);
-GC::Ptr<JS::NativeFunction> create_native_function(JS::Realm&, Wasm::FunctionAddress address, Utf16FlyString name, GC::Ptr<Instance> instance = nullptr);
-JS::ThrowCompletionOr<Wasm::Value> to_webassembly_value(JS::Realm&, JS::Value value, Wasm::ValueType const& type);
-Wasm::Value default_webassembly_value(JS::Realm&, Wasm::ValueType type);
-JS::Value to_js_value(JS::Realm&, Wasm::Value& wasm_value, Wasm::ValueType type);
+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 \
diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
index 7a05d472f8b..ce372ad0189 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
@@ -8,8 +8,6 @@
#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/ModuleEnvironment.h>
#include <LibJS/Runtime/ModuleRequest.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/Validator.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
#include <LibWeb/WebAssembly/Global.h>
@@ -109,16 +107,18 @@ JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ByteBu
HashTable<ByteString> requested_modules;
// 6. For each (moduleName, name, type) in module_imports(module.[[Module]]),
- auto const& imports = module_object->compiled_module()->module->import_section().imports();
- for (auto const& entry : imports) {
+ 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)) {
+ 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)) {
+ 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);
}
@@ -128,14 +128,15 @@ JS::ThrowCompletionOr<GC::Ref<JS::HostModule>> parse_a_webassembly_module(ByteBu
// then continue.
// 4. Append moduleName to requestedModules.
- requested_modules.set(entry.module());
+ requested_modules.set(entry.module);
}
// 7. For each (name, type) in module_exports(module.[[Module]])
- auto const& exports = module_object->compiled_module()->module->export_section().entries();
- for (auto const& entry : exports) {
+ 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)) {
+ 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);
}
@@ -176,10 +177,10 @@ Vector<Utf16FlyString> WebAssemblyModuleHostData::export_name_list()
Vector<Utf16FlyString> exports;
// 3. For each(name, type) in module_exports(module.[[Module]])
- auto module_exports = module->compiled_module()->module->export_section().entries();
- for (auto const& entry : module_exports) {
+ 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(entry.name()));
+ exports.append(Utf16FlyString::from_utf8(compiled_module.module_export(index).name));
}
// AD-HOC: Cache exports
@@ -242,25 +243,27 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
// 2. Let record be this WebAssembly Module Record.
auto& record_host_data = host_data_of_webassembly_module_record(record);
auto& realm = record.realm();
- auto cache = Detail::get_cache(realm);
// 3. Let module be record.[[ModuleSource]].[[Module]].
- auto module = record_host_data.module_source()->compiled_module();
+ auto& module = *record_host_data.module_source()->compiled_module()->module;
+ auto& store = Detail::WebAssemblyCache::the().store();
// 4. Let imports be « ».
- Vector<Wasm::ExternValue> imports;
+ Vector<Wasm::Runtime::Extern> imports;
size_t imported_function_count = 0;
// 5. For each (importedModuleName, name, importtype) in module_imports(module),
- for (auto const& entry : module->module->import_section().imports()) {
+ 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()) });
+ 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()));
+ 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());
@@ -283,92 +286,23 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
// 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 module = resolved_module_host_data.module_source()->compiled_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 externval = resolved_module_host_data.instance()->module_instance()->exports().first_matching([resolved_name](auto const& export_instance) { return export_instance.name() == resolved_name; });
+ 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).
- auto module_export = module->module->export_section().entries().first_matching([resolved_name](auto& element) { return element.name() == resolved_name; });
- VERIFY(module_export.has_value());
-
// 8. Let externtype be the value of type for the element (resolvedName, type) in module_exports(module).
- auto externtype = module_export->description();
-
// 9. If importtype is not an extern subtype of externtype, throw a LinkError exception.
- // https://webassembly.github.io/spec/core/valid/types.html#match-externtype
- auto& store = cache->abstract_machine().store();
- auto invalid = entry.description().visit(
- [&](Wasm::MemoryType const& mem_type) -> Optional<ByteString> {
- if (!externtype.has<Wasm::MemoryIndex>())
- return "Expected memory import"sv;
- auto other_mem_type = store.get(Wasm::MemoryAddress { externtype.get<Wasm::MemoryIndex>().value() })->type();
- if (other_mem_type.limits().is_subset_of(mem_type.limits()))
- return {};
- return ByteString::formatted("Memory import and extern do not match: {}-{} vs {}-{}", mem_type.limits().min(), mem_type.limits().max(), other_mem_type.limits().min(), other_mem_type.limits().max());
- },
- [&](Wasm::TableType const& table_type) -> Optional<ByteString> {
- if (!externtype.has<Wasm::TableIndex>())
- return "Expected table import"sv;
- auto other_table_type = store.get(Wasm::TableAddress { externtype.get<Wasm::TableIndex>().value() })->type();
- if (table_type.element_type() == other_table_type.element_type()
- && other_table_type.limits().is_subset_of(table_type.limits()))
- return {};
-
- return ByteString::formatted("Table import and extern do not match: {}-{} vs {}-{}", table_type.limits().min(), table_type.limits().max(), other_table_type.limits().min(), other_table_type.limits().max());
- },
- [&](Wasm::GlobalType const& global_type) -> Optional<ByteString> {
- if (!externtype.has<Wasm::GlobalIndex>())
- return "Expected global import"sv;
- auto other_global_type = store.get(Wasm::GlobalAddress { externtype.get<Wasm::GlobalIndex>().value() })->type();
- if (global_type.type() == other_global_type.type()
- && global_type.is_mutable() == other_global_type.is_mutable())
- return {};
- return "Global import and extern do not match"sv;
- },
- [&](Wasm::FunctionType const& type) -> Optional<ByteString> {
- if (!externtype.has<Wasm::FunctionIndex>())
- return "Expected function import"sv;
- auto other_type = store.get(Wasm::FunctionAddress { externtype.get<Wasm::FunctionIndex>().value() })->visit([&](Wasm::WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](Wasm::HostFunction const& host_func) { return host_func.type(); });
- if (type.results() != other_type.results())
- return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
- if (type.parameters() != other_type.parameters())
- return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
- return {};
- },
- [&](Wasm::TagType const& type) -> Optional<ByteString> {
- if (!externtype.has<Wasm::TagIndex>())
- return "Expected tag import"sv;
- auto* other_tag_instance = store.get(Wasm::TagAddress { externtype.get<Wasm::TagIndex>().value() });
- if (other_tag_instance->flags() != type.flags())
- return "Tag import and extern do not match"sv;
-
- auto const& this_type = module->module->type_section().types()[type.type().value()];
-
- if (other_tag_instance->type().parameters() != this_type.function().parameters())
- return "Tag import and extern do not match"sv;
- return {};
- },
- [&](Wasm::TypeIndex type_index) -> Optional<ByteString> {
- if (!externtype.has<Wasm::FunctionIndex>())
- return "Expected function import"sv;
- auto other_type = store.get(Wasm::FunctionAddress { externtype.get<Wasm::FunctionIndex>().value() })->visit([&](Wasm::WasmFunction const& wasm_func) { return wasm_func.type(); }, [&](Wasm::HostFunction const& host_func) { return host_func.type(); });
- auto const& type = module->module->type_section().types()[type_index.value()].function();
- if (type.results() != other_type.results())
- return ByteString::formatted("Function import and extern do not match, results: {} vs {}", type.results(), other_type.results());
- if (type.parameters() != other_type.parameters())
- return ByteString::formatted("Function import and extern do not match, parameters: {} vs {}", type.parameters(), other_type.parameters());
- return {};
- });
- if (invalid.has_value())
- return vm.throw_completion<LinkError>(ByteString::formatted("{}::{}: {}", entry.module(), entry.name(), invalid.release_value()));
+ // NB: Instantiation checks the type of every import, and throws that LinkError.
// 10. Append externval to imports.
- imports.append(externval.value().value());
+ imports.append(*externval);
}
// 8. Otherwise,
@@ -379,61 +313,53 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
// 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,
- // AD-HOC: Resolve type index
- if (entry.description().has<Wasm::FunctionType>() || entry.description().has<Wasm::TypeIndex>()) {
- auto functype = entry.description().visit(
- [](Wasm::FunctionType function_type) { return function_type; },
- [&module](Wasm::TypeIndex type_index) { return module->module->type_section().types()[type_index.value()].function(); },
- [](auto) -> Wasm::FunctionType { VERIFY_NOT_REACHED(); });
-
+ 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,
- Optional<Wasm::FunctionAddress> funcaddr;
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;
+ funcaddr = *exported_address;
}
// 3. Otherwise,
else {
- cache->add_imported_object(function);
-
// 1. Create a host function from v and functype, and let funcaddr be the result.
// 2. Let index be the number of external functions in imports, defining the index of the host function funcaddr.
- auto host_function = Detail::create_host_function(realm, function, functype, imported_function_count);
- funcaddr = cache->abstract_machine().store().allocate(move(host_function));
+ auto functype = module.function_type(entry.type.type_index);
+ VERIFY(functype.has_value());
+ funcaddr = Detail::create_host_function(vm, function, functype.release_value(), imported_function_count);
}
// 4. Let externfunc be the external value func funcaddr.
- Wasm::ExternValue externfunc { Wasm::FunctionAddress { *funcaddr } };
-
// 5. Append externfunc to imports.
- imports.append(externfunc);
+ imports.append({ Wasm::Runtime::ExternKind::Function, funcaddr });
+ break;
}
// 4. If importtype is of the form global mut valtype,
- if (entry.description().has<Wasm::GlobalType>()) {
- auto valtype = entry.description().get<Wasm::GlobalType>();
+ case Wasm::Runtime::ExternKind::Global: {
+ auto valtype = entry.type.value_type;
+ auto is_mutable = entry.type.is_mutable;
// 1. Let store be the surrounding agent’s associated store.
- auto& store = cache->abstract_machine().store();
-
// 2. If v implements Global,
- Optional<Wasm::GlobalAddress> globaladdr;
- auto* global = Bindings::global_from_value(v);
- if (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).
- auto* valuetype = store.get(*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 (!valtype.is_mutable() && valuetype->is_mutable()) {
+ if (!is_mutable && target_is_mutable) {
return vm.throw_completion<LinkError>("Mutable globals are not supported for immutable imports"sv);
}
}
@@ -441,42 +367,41 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
// 3. Otherwise,
else {
// AD-HOC: If valtype is i64 and v is a Number, throw a LinkError exception.
- if (valtype.type().kind() == Wasm::ValueType::I64 && v.is_number()) {
+ 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.type().kind() != Wasm::ValueType::I64 && v.is_bigint()) {
+ 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.type().kind() == Wasm::ValueType::V128) {
+ 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 (valtype.is_mutable()) {
+ 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(realm, v, valtype.type()));
+ 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 = cache->abstract_machine().store().allocate(valtype, value);
+ globaladdr = store.allocate_global(valtype, is_mutable, value);
}
// 4. Let externglobal be global globaladdr.
- Wasm::ExternValue externglobal { Wasm::GlobalAddress { *globaladdr } };
-
// 5. Append externglobal to imports.
- imports.append(externglobal);
+ imports.append({ Wasm::Runtime::ExternKind::Global, globaladdr });
+ break;
}
// 5. If importtype is of the form mem memtype,
- if (entry.description().has<Wasm::MemoryType>()) {
+ 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) {
@@ -484,14 +409,13 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
}
// 2. Let externmem be the external value mem v.[[Memory]].
- auto externmem = memory->address();
-
// 3. Append externmem to imports.
- imports.append(externmem);
+ imports.append({ Wasm::Runtime::ExternKind::Memory, memory->address() });
+ break;
}
// 6. If importtype is of the form table tabletype,
- if (entry.description().has<Wasm::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) {
@@ -499,59 +423,49 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
}
// 2. Let tableaddr be v.[[Table]].
- auto tableaddr = table->address();
-
// 3. Let externtable be the external value table tableaddr.
- Wasm::ExternValue externtable { tableaddr };
-
// 4. Append externtable to imports.
- imports.append(externtable);
+ imports.append({ Wasm::Runtime::ExternKind::Table, table->address() });
+ break;
+ }
+
+ // FIXME: Import tags once WebAssembly.Tag exists.
+ case Wasm::Runtime::ExternKind::Tag:
+ return vm.throw_completion<LinkError>("Tag imports are not supported"sv);
}
}
- if (entry.description().has<Wasm::FunctionType>() || entry.description().has<Wasm::TypeIndex>())
+ 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.
- // https://webassembly.github.io/spec/js-api/index.html#instantiate-the-core-of-a-webassembly-module
- auto instantiation_result = cache->abstract_machine().instantiate(module->module, imports);
- if (instantiation_result.is_error()) {
- auto instantiation_error = instantiation_result.release_error();
- switch (instantiation_error.source) {
- case Wasm::InstantiationErrorSource::Linking:
- return vm.throw_completion<LinkError>(instantiation_error.error);
- case Wasm::InstantiationErrorSource::StartFunction:
- return vm.throw_completion<RuntimeError>(instantiation_error.error);
- }
- VERIFY_NOT_REACHED();
- }
+ auto instance_address = TRY(Detail::instantiate_core_module(vm, module, imports));
// 7. Set record.[[Instance]] to instance.
- auto instance = Instance::create(cache, instantiation_result.release_value());
+ auto instance = Instance::create(instance_address);
record_host_data.set_instance(instance);
// 8. For each (name, externtype) of module_exports(module),
- for (auto const& entry : module->module->export_section().entries()) {
+ for (auto const& entry : store.instance_exports(instance_address)) {
// 1. If externtype is of the form global mut globaltype,
- if (entry.description().has<Wasm::GlobalIndex>()) {
+ 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 = Wasm::GlobalAddress { entry.description().get<Wasm::GlobalIndex>().value() };
- auto* global_value = cache->abstract_machine().store().get(globaladdr);
- VERIFY(global_value);
+ auto globaladdr = entry.value.entity;
+ bool is_mutable = false;
+ auto type = store.global_type(globaladdr, is_mutable);
// 4. If globaltype is not v128,
- auto type = global_value->type();
- if (type.type().kind() != Wasm::ValueType::Kind::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 = global_value->value();
- MUST(record.environment()->initialize_binding(vm, Utf16FlyString::from_utf8(entry.name()), Detail::to_js_value(realm, value, type.type()), JS::Environment::InitializeBindingHint::Normal));
+ 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)
@@ -562,7 +476,7 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
// 2. Otherwise,
else {
// 1. Perform !record.[[Environment]].InitializeBinding(name, !Get(instance.[[Exports]], name)).
- auto name = Utf16FlyString::from_utf8(entry.name());
+ auto name = Utf16FlyString::from_utf8(entry.name);
MUST(Bindings::initialize_webassembly_export_binding(realm, *record.environment(), name, instance));
}
}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index dc665c3a256..1a5a17942a3 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -76,7 +76,7 @@ ALLOWED_REALM_MENTIONS = {
"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),
"WebAssembly": (
12,
- 95,
+ 83,
"WebAssembly constructors/exports instantiate JS objects/functions in spec-selected realms",
),
"WebAudio": (
diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp
index 5bd894bad05..140fc8a50e5 100644
--- a/Tests/LibWasm/test-wasm.cpp
+++ b/Tests/LibWasm/test-wasm.cpp
@@ -6,6 +6,7 @@
#include <AK/ByteBuffer.h>
#include <AK/HashMap.h>
+#include <AK/NeverDestroyed.h>
#include <LibCore/File.h>
#include <LibGC/CellAllocator.h>
#include <LibJS/Heap/Cell.h>
@@ -24,6 +25,7 @@
#include <LibTest/JavaScriptTestHost.h>
#include <LibWasm/Runtime/Runtime.h>
#include <string.h>
+#include <sys/resource.h>
TEST_ROOT("Libraries/LibWasm/Tests");
@@ -107,17 +109,33 @@ public:
static Wasm::Runtime::Store& store()
{
if (!s_store)
- s_store = make<Wasm::Runtime::Store>();
+ s_store = new Wasm::Runtime::Store(GC::Heap::the());
return *s_store;
}
static void reset_store()
{
s_spec_test_namespace.clear();
+ roots().clear();
+ delete s_store;
s_store = nullptr;
}
- u32 instance() const { return m_instance; }
+ Wasm::Runtime::Entity instance() const { return m_instance; }
+
+ // Keep an entity of the current file alive, since the tests refer to entities by number.
+ static Wasm::Runtime::Entity keep(Wasm::Runtime::Entity entity)
+ {
+ roots().append(GC::Root<GC::ForeignCell> { entity });
+ return entity;
+ }
+
+ // NB: Like the last store, the last roots are left for the process to reclaim, since the heap is gone at exit.
+ static Vector<GC::Root<GC::ForeignCell>>& roots()
+ {
+ static NeverDestroyed<Vector<GC::Root<GC::ForeignCell>>> roots;
+ return *roots;
+ }
static JS::ThrowCompletionOr<GC::Ref<JS::HostObject>> create(JS::Realm& realm, NonnullRefPtr<Wasm::Runtime::Module> module, HashMap<ImportName, Wasm::Runtime::Extern> const& registered)
{
@@ -143,7 +161,7 @@ public:
auto instance = realm.create<WebAssemblyModule>();
instance->m_module = move(module);
- instance->m_instance = result.value();
+ instance->m_instance = keep(result.value());
auto object = JS::HostObject::create(realm, web_assembly_module_host_class, realm.intrinsics().object_prototype(), {}, instance);
object->define_native_function(realm, "getExport"_utf16_fly_string, get_export, 1, JS::default_attributes);
object->define_native_function(realm, "invoke"_utf16_fly_string, wasm_invoke, 1, JS::default_attributes);
@@ -153,6 +171,12 @@ public:
~WebAssemblyModule() override = default;
private:
+ virtual void visit_edges(Visitor& visitor) override
+ {
+ Base::visit_edges(visitor);
+ visitor.visit(m_instance);
+ }
+
JS_DECLARE_NATIVE_FUNCTION(get_export);
JS_DECLARE_NATIVE_FUNCTION(wasm_invoke);
@@ -163,10 +187,10 @@ private:
return s_spec_test_namespace;
auto add_print = [](StringView name, Vector<ValueType> parameters) {
- auto address = store().allocate_host_function({ move(parameters), {} }, [](auto&, auto, auto) -> ErrorOr<void, ByteString> {
+ auto address = keep(store().allocate_host_function({ move(parameters), {} }, [](auto&, auto, auto) -> ErrorOr<void, Wasm::Runtime::HostError> {
// Noop, this just needs to exist.
return {};
- });
+ }));
s_spec_test_namespace.set({ "spectest", name }, { ExternKind::Function, address });
};
auto i32 = ValueType::scalar(ValueKind::I32);
@@ -183,30 +207,31 @@ private:
auto funcref = ValueType::reference(HeapKind::Function);
auto table = store().allocate_table(funcref, { 10, 20, true, false, false }, 0);
- s_spec_test_namespace.set({ "spectest", "table" }, { ExternKind::Table, table });
+ s_spec_test_namespace.set({ "spectest", "table" }, { ExternKind::Table, keep(table.value()) });
auto table64 = store().allocate_table(funcref, { 10, 20, true, true, false }, 0);
- s_spec_test_namespace.set({ "spectest", "table64" }, { ExternKind::Table, table64 });
+ s_spec_test_namespace.set({ "spectest", "table64" }, { ExternKind::Table, keep(table64.value()) });
auto memory = store().allocate_memory({ 1, 2, true, false, false });
- s_spec_test_namespace.set({ "spectest", "memory" }, { ExternKind::Memory, memory.value() });
+ s_spec_test_namespace.set({ "spectest", "memory" }, { ExternKind::Memory, keep(memory.value()) });
- s_spec_test_namespace.set({ "spectest", "global_i32" }, { ExternKind::Global, store().allocate_global(i32, false, Value::from_i32(666)) });
- s_spec_test_namespace.set({ "spectest", "global_i64" }, { ExternKind::Global, store().allocate_global(i64, false, Value::from_i64(666)) });
- s_spec_test_namespace.set({ "spectest", "global_f32" }, { ExternKind::Global, store().allocate_global(f32, false, Value::from_f32(666.6f)) });
- s_spec_test_namespace.set({ "spectest", "global_f64" }, { ExternKind::Global, store().allocate_global(f64, false, Value::from_f64(666.6)) });
+ s_spec_test_namespace.set({ "spectest", "global_i32" }, { ExternKind::Global, keep(store().allocate_global(i32, false, Value::from_i32(666))) });
+ s_spec_test_namespace.set({ "spectest", "global_i64" }, { ExternKind::Global, keep(store().allocate_global(i64, false, Value::from_i64(666))) });
+ s_spec_test_namespace.set({ "spectest", "global_f32" }, { ExternKind::Global, keep(store().allocate_global(f32, false, Value::from_f32(666.6f))) });
+ s_spec_test_namespace.set({ "spectest", "global_f64" }, { ExternKind::Global, keep(store().allocate_global(f64, false, Value::from_f64(666.6))) });
return s_spec_test_namespace;
}
static HashMap<ImportName, Wasm::Runtime::Extern> s_spec_test_namespace;
- static OwnPtr<Wasm::Runtime::Store> s_store;
+ // NB: The last store is left for the process to reclaim, since the heap it roots its cells in is gone at exit.
+ static Wasm::Runtime::Store* s_store;
RefPtr<Wasm::Runtime::Module> m_module;
- u32 m_instance { 0 };
+ Wasm::Runtime::Entity m_instance { nullptr };
};
GC_DEFINE_ALLOCATOR(WebAssemblyModule);
-OwnPtr<Wasm::Runtime::Store> WebAssemblyModule::s_store;
+Wasm::Runtime::Store* WebAssemblyModule::s_store;
HashMap<ImportName, Wasm::Runtime::Extern> WebAssemblyModule::s_spec_test_namespace;
}
@@ -276,6 +301,19 @@ TESTJS_GLOBAL_FUNCTION(is_cranelift_eligible, isCraneliftEligible)
return JS::Value(false);
}
+// The most memory the process has had resident, in bytes.
+TESTJS_GLOBAL_FUNCTION(peak_resident_memory_size, peakResidentMemorySize)
+{
+ struct rusage usage {};
+ if (getrusage(RUSAGE_SELF, &usage) != 0)
+ return vm.throw_completion<JS::TypeError>("getrusage failed"_utf16);
+#if defined(AK_OS_MACOS)
+ return JS::Value(static_cast<double>(usage.ru_maxrss));
+#else
+ return JS::Value(static_cast<double>(usage.ru_maxrss) * 1024);
+#endif
+}
+
TESTJS_GLOBAL_FUNCTION(compare_typed_arrays, compareTypedArrays)
{
auto lhs = TRY(vm.argument(0).to_object(vm));
@@ -382,7 +420,8 @@ TESTJS_GLOBAL_FUNCTION(is_valid_funcref_in, isValidFuncrefIn)
auto module_object = TRY(vm.argument(1).to_object(vm));
if (!WebAssemblyModule::from_object(*module_object))
return vm.throw_completion<JS::TypeError>("Expected a WebAssemblyModule"_utf16);
- return JS::Value(value < NumericLimits<u32>::max());
+ // NB: A function reference surfaces as its function's address, which is never zero.
+ return JS::Value(value != 0);
}
static JS::Value reference_to_js_value(Wasm::Runtime::Value value, Wasm::Runtime::ValueType type)
@@ -396,8 +435,7 @@ static JS::Value reference_to_js_value(Wasm::Runtime::Value value, Wasm::Runtime
if ((bits & 1) != 0)
return JS::Value(static_cast<double>(static_cast<i32>(bits) >> 1));
if (type.heap == HeapKind::Function || type.heap == HeapKind::NoFunction || type.heap == HeapKind::Concrete) {
- if (auto function = WebAssemblyModule::store().function_from_reference(bits); function.has_value())
- return JS::Value(static_cast<double>(*function));
+ return JS::Value(static_cast<double>(bit_cast<FlatPtr>(WebAssemblyModule::store().function_from_reference(bits))));
}
return JS::js_undefined();
}
@@ -426,6 +464,11 @@ static JS::ThrowCompletionOr<JS::Value> to_js_value(JS::VM& vm, Wasm::Runtime::V
VERIFY_NOT_REACHED();
}
+static Wasm::Runtime::Entity function_entity(double number)
+{
+ return bit_cast<GC::ForeignCell*>(static_cast<FlatPtr>(number));
+}
+
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
{
using namespace Wasm::Runtime;
@@ -437,12 +480,13 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
auto value = store().find_export(instance->instance(), name);
if (!value.has_value())
return vm.throw_completion<JS::TypeError>(Utf16String::formatted("'{}' could not be found", name));
+ // NB: A function is its entity's address, which a double holds exactly.
if (value->kind == ExternKind::Function)
- return JS::Value(static_cast<double>(value->address));
+ return JS::Value(static_cast<double>(bit_cast<FlatPtr>(value->entity)));
if (value->kind == ExternKind::Global) {
bool is_mutable = false;
- auto type = store().global_type(value->address, is_mutable);
- auto global = store().global_get(value->address);
+ auto type = store().global_type(value->entity, is_mutable);
+ auto global = store().global_get(value->entity);
switch (type.kind) {
case ValueKind::I32:
return JS::Value(static_cast<double>(global.to_i32()));
@@ -466,7 +510,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::get_export)
JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
{
using namespace Wasm::Runtime;
- auto address = static_cast<u32>(TRY(vm.argument(0).to_double(vm)));
+ auto address = function_entity(TRY(vm.argument(0).to_double(vm)));
auto type = store().function_type(address);
Vector<Value> arguments;
@@ -517,7 +561,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
}
switch (parameter.heap) {
case HeapKind::Function:
- arguments.append(Value::from_reference(store().function_reference(static_cast<u32>(double_value))));
+ arguments.append(Value::from_reference(store().function_reference(function_entity(double_value))));
break;
case HeapKind::Extern:
case HeapKind::Any:
@@ -532,7 +576,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
auto result = store().invoke(address, arguments);
if (result.is_error())
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Execution trapped: {}", result.error()));
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Execution trapped: {}", result.error().message));
auto& values = result.value();
if (values.is_empty())
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index 5185ac5f794..d38dca32406 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -71,7 +71,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)
+target_link_libraries(TestStructuredSerializeDurability PRIVATE LibGC LibJS LibCrypto LibGfx LibIPC LibWasmRuntime)
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/TestStructuredSerializeDurability.cpp b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
index 492b0e23f1f..a31cc9cb427 100644
--- a/Tests/LibWeb/TestStructuredSerializeDurability.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeDurability.cpp
@@ -579,8 +579,8 @@ TEST_CASE(webassembly_module_decodes_from_frozen_bytes)
auto module = GC::Ref { unwrap_wrappable<Web::WebAssembly::Module>(value) };
auto compiled_module = module->compiled_module();
- EXPECT(compiled_module->module->import_section().imports().is_empty());
- EXPECT(compiled_module->module->export_section().entries().is_empty());
+ EXPECT_EQ(compiled_module->module->import_count(), 0u);
+ EXPECT_EQ(compiled_module->module->export_count(), 0u);
}
TEST_CASE(crypto_key_algorithm_variants_decode_from_frozen_bytes)
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cross-realm-imports.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cross-realm-imports.txt
new file mode 100644
index 00000000000..712e9a16191
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cross-realm-imports.txt
@@ -0,0 +1,8 @@
+memory of another realm: 123
+grown from WebAssembly: 1, old buffer detached: true, new length: 131072
+table of another realm: 42
+global of another realm: 7
+global written from both sides: 10
+function of another realm: 42
+re-exported function is the same object: true
+re-exported function's realm: true
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cycle-collection.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cycle-collection.txt
new file mode 100644
index 00000000000..7ea678ce647
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-cycle-collection.txt
@@ -0,0 +1,5 @@
+struct field after collection: boxed object
+table element after collection: 42
+global after collection: a string
+frame object is held by wasm: true
+frame object collected with its frame: true
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt
index e222715cfb5..11b5bc6e212 100644
--- a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-error-objects.txt
@@ -269,25 +269,25 @@ new.target from this realm without a prototype: uses RuntimeError.prototype: tru
other realm's constructor is distinct: true
other realm's error: prototype is that realm's prototype: true, instanceof this realm's RuntimeError: false, Object.prototype.toString: [object Error]
== Errors thrown by the engine
-invalid module: CompileError: Unexpected end-of-file
+invalid module: CompileError: malformed module: unexpected end of section or function
own keys: message
prototype is CompileError.prototype: true
instanceof CompileError: true, instanceof Error: true
constructor: true
Object.prototype.toString: [object Error]
Error.isError: true
- name: CompileError, message: "Unexpected end-of-file"
- stack head: CompileError: Unexpected end-of-file
+ name: CompileError, message: "malformed module: unexpected end of section or function"
+ stack head: CompileError: malformed module: unexpected end of section or function
stack frames: Module > <script> > thrownBy > <script> > <script>
-rejected compile: CompileError: Unexpected end-of-file
+rejected compile: CompileError: malformed module: unexpected end of section or function
own keys: message
prototype is CompileError.prototype: true
instanceof CompileError: true, instanceof Error: true
constructor: true
Object.prototype.toString: [object Error]
Error.isError: true
- name: CompileError, message: "Unexpected end-of-file"
- stack head: CompileError: Unexpected end-of-file
+ name: CompileError, message: "malformed module: unexpected end of section or function"
+ stack head: CompileError: malformed module: unexpected end of section or function
stack frames:
missing import: LinkError: 42 is not a function (evaluated from '[wasm import object]["f"]')
own keys: message
@@ -309,15 +309,15 @@ rejected instantiate: LinkError: undefined is not a function (evaluated from '[w
name: LinkError, message: "undefined is not a function (evaluated from '[wasm import object][\"f\"]')"
stack head: LinkError: undefined is not a function (evaluated from '[wasm import object]["f"]')
stack frames:
-trapping start function: RuntimeError: Start function trapped
+trapping start function: RuntimeError: Wasm execution trapped (WIP): unreachable
own keys: message
prototype is RuntimeError.prototype: true
instanceof RuntimeError: true, instanceof Error: true
constructor: true
Object.prototype.toString: [object Error]
Error.isError: true
- name: RuntimeError, message: "Start function trapped"
- stack head: RuntimeError: Start function trapped
+ name: RuntimeError, message: "Wasm execution trapped (WIP): unreachable"
+ stack head: RuntimeError: Wasm execution trapped (WIP): unreachable
stack frames: Instance > <script> > thrownBy > <script> > <script> > <unknown> > <unknown>
trap: RuntimeError
own keys: message
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAsssembly-invalid-module-crashes.txt b/Tests/LibWeb/Text/expected/Wasm/WebAsssembly-invalid-module-crashes.txt
index ad8c4885e5d..d27bec30e0d 100644
--- a/Tests/LibWeb/Text/expected/Wasm/WebAsssembly-invalid-module-crashes.txt
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAsssembly-invalid-module-crashes.txt
@@ -1,3 +1,3 @@
-CompileError: A parsed type did not make sense in context
-CompileError: Invalid TypeIndex
+CompileError: malformed module: unexpected end of section or function
+CompileError: invalid module: unknown type
PASS! (Didn't crash)
diff --git a/Tests/LibWeb/Text/expected/wpt-import/wasm/core/call_indirect.wast.js.txt b/Tests/LibWeb/Text/expected/wpt-import/wasm/core/call_indirect.wast.js.txt
index 38bea2b0d40..1c51f7f4d17 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/wasm/core/call_indirect.wast.js.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/wasm/core/call_indirect.wast.js.txt
@@ -2,8 +2,7 @@ Harness status: OK
Found 350 tests
-349 Pass
-1 Fail
+350 Pass
Pass #1 Reinitialize the default imports
Pass #2 Test that WebAssembly compilation succeeds (call_indirect.wast:3)
Pass #3 Test that WebAssembly compilation succeeds (wrapper)
@@ -125,7 +124,7 @@ Pass #118 Run a WebAssembly test without special assertions (call_indirect.wast:
Pass #119 Test that WebAssembly compilation succeeds (wrapper)
Pass #120 Test that WebAssembly instantiation succeeds (wrapper)
Pass #121 Run a WebAssembly test without special assertions (call_indirect.wast:490)
-Fail #122 Test that a WebAssembly code returns a specific result (call_indirect.wast:491)
+Pass #122 Test that a WebAssembly code returns a specific result (call_indirect.wast:491)
Pass #123 Test that a WebAssembly code returns a specific result (call_indirect.wast:493)
Pass #124 Test that a WebAssembly code returns a specific result (call_indirect.wast:494)
Pass #125 Test that a WebAssembly code returns a specific result (call_indirect.wast:495)
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 18457a7ddba..9c644e90f83 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,8 @@ Harness status: OK
Found 3 tests
-1 Pass
-2 Fail
-Fail multiple return values from wasm to js
+2 Pass
+1 Fail
+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
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-cross-realm-imports.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-cross-realm-imports.html
new file mode 100644
index 00000000000..2ad225bf368
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-cross-realm-imports.html
@@ -0,0 +1,71 @@
+<!doctype html>
+<script src="../include.js"></script>
+<iframe id="frame"></iframe>
+<script>
+ // (module
+ // (type $answer (func (result i32)))
+ // (import "m" "memory" (memory 1))
+ // (import "m" "table" (table 1 funcref))
+ // (import "m" "global" (global $global (mut i32)))
+ // (import "m" "f" (func $f (result i32)))
+ // (func (export "readMemory") (result i32) (i32.load8_u (i32.const 0)))
+ // (func (export "growMemory") (result i32) (memory.grow (i32.const 1)))
+ // (func (export "callTable") (result i32) (call_indirect (type $answer) (i32.const 0)))
+ // (func (export "getGlobal") (result i32) (global.get $global))
+ // (func (export "setGlobal") (param i32) (global.set $global (local.get 0)))
+ // (func (export "callF") (result i32) (call $f))
+ // (export "f" (func $f)))
+ const mainBytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x09, 0x02, 0x60, 0x00, 0x01, 0x7f, 0x60,
+ 0x01, 0x7f, 0x00, 0x02, 0x2b, 0x04, 0x01, 0x6d, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02,
+ 0x00, 0x01, 0x01, 0x6d, 0x05, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x01, 0x70, 0x00, 0x01, 0x01, 0x6d,
+ 0x06, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x03, 0x7f, 0x01, 0x01, 0x6d, 0x01, 0x66, 0x00, 0x00,
+ 0x03, 0x07, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x4b, 0x07, 0x0a, 0x72, 0x65, 0x61,
+ 0x64, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x00, 0x01, 0x0a, 0x67, 0x72, 0x6f, 0x77, 0x4d, 0x65,
+ 0x6d, 0x6f, 0x72, 0x79, 0x00, 0x02, 0x09, 0x63, 0x61, 0x6c, 0x6c, 0x54, 0x61, 0x62, 0x6c, 0x65,
+ 0x00, 0x03, 0x09, 0x67, 0x65, 0x74, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x00, 0x04, 0x09, 0x73,
+ 0x65, 0x74, 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x00, 0x05, 0x05, 0x63, 0x61, 0x6c, 0x6c, 0x46,
+ 0x00, 0x06, 0x01, 0x66, 0x00, 0x00, 0x0a, 0x29, 0x06, 0x07, 0x00, 0x41, 0x00, 0x2d, 0x00, 0x00,
+ 0x0b, 0x06, 0x00, 0x41, 0x01, 0x40, 0x00, 0x0b, 0x07, 0x00, 0x41, 0x00, 0x11, 0x00, 0x00, 0x0b,
+ 0x04, 0x00, 0x23, 0x00, 0x0b, 0x06, 0x00, 0x20, 0x00, 0x24, 0x00, 0x0b, 0x04, 0x00, 0x10, 0x00,
+ 0x0b, 0x00, 0x21, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x01, 0x04, 0x01, 0x00, 0x01, 0x66, 0x04, 0x09,
+ 0x01, 0x00, 0x06, 0x61, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x07, 0x09, 0x01, 0x00, 0x06, 0x67, 0x6c,
+ 0x6f, 0x62, 0x61, 0x6c,
+ ]);
+
+ // (module (func (export "answer") (result i32) (i32.const 42)))
+ const frameBytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f, 0x03,
+ 0x02, 0x01, 0x00, 0x07, 0x0a, 0x01, 0x06, 0x61, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x00, 0x00, 0x0a,
+ 0x06, 0x01, 0x04, 0x00, 0x41, 0x2a, 0x0b,
+ ]);
+
+ test(() => {
+ const frameWindow = document.getElementById("frame").contentWindow;
+ const FrameWebAssembly = frameWindow.WebAssembly;
+ const answer = new FrameWebAssembly.Instance(new FrameWebAssembly.Module(frameBytes)).exports.answer;
+ const memory = new FrameWebAssembly.Memory({ initial: 1, maximum: 4 });
+ const table = new FrameWebAssembly.Table({ element: "anyfunc", initial: 1 });
+ const global = new FrameWebAssembly.Global({ value: "i32", mutable: true }, 7);
+ table.set(0, answer);
+
+ const instance = new WebAssembly.Instance(new WebAssembly.Module(mainBytes), { m: { memory, table, global, f: answer } });
+ const exports = instance.exports;
+
+ new frameWindow.Uint8Array(memory.buffer)[0] = 123;
+ println(`memory of another realm: ${exports.readMemory()}`);
+ const oldBuffer = memory.buffer;
+ println(`grown from WebAssembly: ${exports.growMemory()}, old buffer detached: ${oldBuffer.byteLength === 0}, new length: ${memory.buffer.byteLength}`);
+
+ println(`table of another realm: ${exports.callTable()}`);
+
+ println(`global of another realm: ${exports.getGlobal()}`);
+ global.value = 9;
+ exports.setGlobal(exports.getGlobal() + 1);
+ println(`global written from both sides: ${global.value}`);
+
+ println(`function of another realm: ${exports.callF()}`);
+ println(`re-exported function is the same object: ${exports.f === answer}`);
+ println(`re-exported function's realm: ${Object.getPrototypeOf(exports.f) === frameWindow.Function.prototype}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-cycle-collection.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-cycle-collection.html
new file mode 100644
index 00000000000..d63c33582e4
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-cycle-collection.html
@@ -0,0 +1,62 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // (module
+ // (type $box (struct (field externref)))
+ // (global $boxed (mut (ref null $box)) (ref.null $box))
+ // (global (export "global") (mut externref) (ref.null extern))
+ // (table (export "table") 1 externref)
+ // (func (export "box") (param externref) (global.set $boxed (struct.new $box (local.get 0))))
+ // (func (export "unbox") (result externref) (struct.get $box 0 (global.get $boxed))))
+ const bytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x0d, 0x03, 0x5f, 0x01, 0x6f, 0x00, 0x60,
+ 0x01, 0x6f, 0x00, 0x60, 0x00, 0x01, 0x6f, 0x03, 0x03, 0x02, 0x01, 0x02, 0x04, 0x04, 0x01, 0x6f,
+ 0x00, 0x01, 0x06, 0x0c, 0x02, 0x63, 0x00, 0x01, 0xd0, 0x00, 0x0b, 0x6f, 0x01, 0xd0, 0x6f, 0x0b,
+ 0x07, 0x20, 0x04, 0x06, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x03, 0x01, 0x05, 0x74, 0x61, 0x62,
+ 0x6c, 0x65, 0x01, 0x00, 0x03, 0x62, 0x6f, 0x78, 0x00, 0x00, 0x05, 0x75, 0x6e, 0x62, 0x6f, 0x78,
+ 0x00, 0x01, 0x0a, 0x14, 0x02, 0x09, 0x00, 0x20, 0x00, 0xfb, 0x00, 0x00, 0x24, 0x00, 0x0b, 0x08,
+ 0x00, 0x23, 0x00, 0xfb, 0x02, 0x00, 0x00, 0x0b, 0x00, 0x17, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x04,
+ 0x06, 0x01, 0x00, 0x03, 0x62, 0x6f, 0x78, 0x07, 0x08, 0x01, 0x00, 0x05, 0x62, 0x6f, 0x78, 0x65,
+ 0x64,
+ ]);
+
+ async function collectGarbage() {
+ for (let index = 0; index < 4; ++index) {
+ await animationFrame();
+ await internals.gcAsync();
+ }
+ }
+
+ // The frame's object refers to the frame's instance, whose global, table, and GC struct refer back to the object.
+ function createCycleInRemovedFrame() {
+ const frame = document.createElement("iframe");
+ document.body.append(frame);
+ const frameWindow = frame.contentWindow;
+ const instance = new frameWindow.WebAssembly.Instance(new frameWindow.WebAssembly.Module(bytes));
+ const object = new frameWindow.Object();
+ object.instance = instance;
+ instance.exports.global.value = object;
+ instance.exports.table.set(0, object);
+ instance.exports.box(object);
+ println(`frame object is held by wasm: ${instance.exports.unbox() === object}`);
+ const weakObject = new WeakRef(object);
+ frame.remove();
+ return weakObject;
+ }
+
+ asyncTest(async done => {
+ const instance = new WebAssembly.Instance(new WebAssembly.Module(bytes));
+ instance.exports.box({ name: "boxed object" });
+ instance.exports.table.set(0, 42);
+ instance.exports.global.value = "a string";
+ await collectGarbage();
+ println(`struct field after collection: ${instance.exports.unbox().name}`);
+ println(`table element after collection: ${instance.exports.table.get(0)}`);
+ println(`global after collection: ${instance.exports.global.value}`);
+
+ const weakObject = createCycleInRemovedFrame();
+ await collectGarbage();
+ println(`frame object collected with its frame: ${weakObject.deref() === undefined}`);
+ done();
+ });
+</script>
diff --git a/Utilities/CMakeLists.txt b/Utilities/CMakeLists.txt
index 8fcce1e2a4e..e422f3ff676 100644
--- a/Utilities/CMakeLists.txt
+++ b/Utilities/CMakeLists.txt
@@ -2,7 +2,7 @@ ladybird_utility(js SOURCES js.cpp LIBS LibJSStandalone LibMain)
if (NOT WIN32 AND NOT ANDROID)
target_link_libraries(js PRIVATE PkgConfig::LIBEDIT)
endif()
-ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasm LibMain LibJSStandalone LibCrypto LibGC)
+ladybird_utility(wasm SOURCES wasm.cpp LIBS LibFileSystem LibWasmRuntime LibMain LibJSStandalone LibCrypto LibGC)
ladybird_utility(xml SOURCES xml.cpp LIBS LibFileSystem LibMain LibXML LibURL)
ladybird_utility(dns SOURCES dns.cpp LIBS LibDNS LibMain LibTLS LibCrypto)
diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cpp
index a60ec6ab50c..d9a2cef54f1 100644
--- a/Utilities/wasm.cpp
+++ b/Utilities/wasm.cpp
@@ -1,51 +1,44 @@
/*
* Copyright (c) 2021, Ali Mohammad Pur <[email protected]>
* Copyright (c) 2022, the SerenityOS developers.
+ * Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/GenericLexer.h>
#include <AK/Hex.h>
+#include <AK/JsonArray.h>
#include <AK/JsonObject.h>
-#include <AK/MemoryStream.h>
#include <AK/ScopeGuard.h>
-#include <AK/StackInfo.h>
+#include <AK/UFixedBigInt.h>
#include <AK/Utf16String.h>
#include <AK/Utf16StringBuilder.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/ElapsedTimer.h>
#include <LibCore/EventLoop.h>
-#include <LibCore/File.h>
#include <LibCore/MappedFile.h>
#include <LibCrypto/BigInt/SignedBigInteger.h>
#include <LibFileSystem/FileSystem.h>
+#include <LibGC/Root.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/BigInt.h>
+#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/NativeFunction.h>
#include <LibJS/Runtime/Object.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Script.h>
-#if defined(AK_OS_WINDOWS)
-# include <AK/Windows.h>
-#endif
#include <LibMain/Main.h>
-#include <LibWasm/AbstractMachine/AbstractMachine.h>
-#include <LibWasm/AbstractMachine/BytecodeInterpreter.h>
-#include <LibWasm/AbstractMachine/Validator.h>
-#include <LibWasm/Printer/Printer.h>
-#include <LibWasm/Types.h>
-#if !defined(AK_OS_WINDOWS)
-# include <LibWasm/Wasi.h>
-#endif
-#include <LibCore/Process.h>
+#include <LibWasm/Runtime/Runtime.h>
#include <math.h>
-#if !defined(AK_OS_WINDOWS)
-# include <unistd.h>
-#endif
-static OwnPtr<Stream> g_stdout {};
-static OwnPtr<Wasm::Printer> g_printer {};
+using Wasm::Runtime::Entity;
+using Wasm::Runtime::ExternKind;
+using Wasm::Runtime::HeapKind;
+using Wasm::Runtime::HostError;
+using Wasm::Runtime::ValueKind;
+using Wasm::Runtime::ValueType;
+using WasmValue = Wasm::Runtime::Value;
struct BenchmarkTimings {
JsonArray parse;
@@ -65,12 +58,22 @@ struct BenchmarkTimings {
return json;
}
};
-static StackInfo g_stack_info;
-static Wasm::BytecodeInterpreter g_interpreter(g_stack_info);
struct ParsedValue {
- Wasm::Value value;
- Wasm::ValueType type;
+ WasmValue value;
+ ValueType type;
+};
+
+struct ImportName {
+ ByteString module;
+ ByteString name;
+
+ bool operator==(ImportName const&) const = default;
+};
+
+template<>
+struct AK::Traits<ImportName> : public DefaultTraits<ImportName> {
+ static unsigned hash(ImportName const& name) { return pair_int_hash(name.module.hash(), name.name.hash()); }
};
static Optional<u128> convert_to_uint(StringView string)
@@ -79,14 +82,11 @@ static Optional<u128> convert_to_uint(StringView string)
return {};
u128 value = 0;
- auto const characters = string.characters_without_null_termination();
-
- for (size_t i = 0; i < string.length(); i++) {
- if (characters[i] < '0' || characters[i] > '9')
+ for (auto character : string) {
+ if (character < '0' || character > '9')
return {};
-
value *= 10;
- value += u128 { static_cast<u64>(characters[i] - '0'), 0 };
+ value += u128 { static_cast<u64>(character - '0'), 0 };
}
return value;
}
@@ -97,534 +97,413 @@ static Optional<u128> convert_to_uint_from_hex(StringView string)
return {};
u128 value = 0;
- auto const count = string.length();
- auto const upper_bound = NumericLimits<u128>::max();
-
- for (size_t i = 0; i < count; i++) {
- char digit = string[i];
- if (value > (upper_bound >> 4))
+ for (auto digit : string) {
+ if (value > (NumericLimits<u128>::max() >> 4))
return {};
-
- auto digit_val = decode_hex_digit(digit);
- if (digit_val == 255)
+ auto digit_value = decode_hex_digit(digit);
+ if (digit_value == 255)
return {};
-
- value = (value << 4) + digit_val;
+ value = (value << 4) + digit_value;
}
return value;
}
+static WasmValue v128_value(u128 value)
+{
+ return WasmValue::from_v128(value.low(), value.high());
+}
+
static ErrorOr<ParsedValue> parse_value(StringView spec)
{
- constexpr auto is_sep = [](char c) { return is_ascii_space(c) || c == ':'; };
+ constexpr auto is_separator = [](char c) { return is_ascii_space(c) || c == ':'; };
+
// Scalar: 'T.const[:\s]v' (i32.const 42)
- auto parse_scalar = []<typename T>(StringView text) -> ErrorOr<Wasm::Value> {
- if constexpr (IsFloatingPoint<T>) {
- if (text.trim_whitespace().equals_ignoring_ascii_case("nan"sv)) {
- if constexpr (IsSame<T, float>)
- return Wasm::Value { nanf("") };
- else
- return Wasm::Value { nan("") };
- }
- if (text.trim_whitespace().equals_ignoring_ascii_case("inf"sv)) {
- if constexpr (IsSame<T, float>)
- return Wasm::Value { HUGE_VALF };
- else
- return Wasm::Value { HUGE_VAL };
- }
- }
- if (auto v = text.to_number<T>(); v.has_value())
- return Wasm::Value { *v };
+ auto parse_integer = []<typename T>(StringView text) -> ErrorOr<T> {
+ if (auto value = text.to_number<T>(); value.has_value())
+ return *value;
+ return Error::from_string_literal("Invalid scalar value");
+ };
+ auto parse_float = []<typename T>(StringView text) -> ErrorOr<T> {
+ if (text.trim_whitespace().equals_ignoring_ascii_case("nan"sv))
+ return static_cast<T>(NAN);
+ if (text.trim_whitespace().equals_ignoring_ascii_case("inf"sv))
+ return static_cast<T>(INFINITY);
+ if (auto value = text.to_number<T>(); value.has_value())
+ return *value;
return Error::from_string_literal("Invalid scalar value");
};
- // Vector: 'v128.const[:\s]v' (v128.const 0x01000000020000000300000004000000) or 'v(T.const[:\s]v, ...)' (v(i32.const 1, i32.const 2, i32.const 3, i32.const 4))
- auto parse_u128 = [](StringView text) -> ErrorOr<Wasm::Value> {
- u128 value;
- if (text.starts_with("0x"sv)) {
- if (auto v = convert_to_uint_from_hex(text); v.has_value())
- value = *v;
- else
- return Error::from_string_literal("Invalid hex v128 value");
- } else {
- if (auto v = convert_to_uint(text); v.has_value())
- value = *v;
- else
- return Error::from_string_literal("Invalid v128 value");
- }
- return Wasm::Value { value };
+ // Vector: 'v128.const[:\s]v' (v128.const 0x01000000020000000300000004000000) or 'v(T.const[:\s]v, ...)'.
+ auto parse_u128 = [](StringView text) -> ErrorOr<u128> {
+ auto value = text.starts_with("0x"sv) ? convert_to_uint_from_hex(text.substring_view(2)) : convert_to_uint(text);
+ if (!value.has_value())
+ return Error::from_string_literal("Invalid v128 value");
+ return *value;
};
GenericLexer lexer(spec);
- if (lexer.consume_specific("v128.const"sv)) {
- lexer.ignore_while(is_sep);
- // The rest of the string is the value
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_u128(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::V128)
- };
- }
-
- if (lexer.consume_specific("i8.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<i8>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::I32)
- };
- }
- if (lexer.consume_specific("i16.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<i16>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::I32)
- };
- }
- if (lexer.consume_specific("i32.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<i32>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::I32)
- };
- }
- if (lexer.consume_specific("i64.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<i64>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::I64)
- };
- }
- if (lexer.consume_specific("f32.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<float>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::F32)
- };
- }
- if (lexer.consume_specific("f64.const"sv)) {
- lexer.ignore_while(is_sep);
- auto text = lexer.consume_all();
- return ParsedValue {
- .value = TRY(parse_scalar.operator()<double>(text)),
- .type = Wasm::ValueType(Wasm::ValueType::Kind::F64)
- };
- }
+ auto rest = [&] {
+ lexer.ignore_while(is_separator);
+ return lexer.consume_all();
+ };
+ if (lexer.consume_specific("v128.const"sv))
+ return ParsedValue { v128_value(TRY(parse_u128(rest()))), ValueType::scalar(ValueKind::V128) };
+ if (lexer.consume_specific("i8.const"sv))
+ return ParsedValue { WasmValue::from_i32(TRY(parse_integer.operator()<i8>(rest()))), ValueType::scalar(ValueKind::I32) };
+ if (lexer.consume_specific("i16.const"sv))
+ return ParsedValue { WasmValue::from_i32(TRY(parse_integer.operator()<i16>(rest()))), ValueType::scalar(ValueKind::I32) };
+ if (lexer.consume_specific("i32.const"sv))
+ return ParsedValue { WasmValue::from_i32(TRY(parse_integer.operator()<i32>(rest()))), ValueType::scalar(ValueKind::I32) };
+ if (lexer.consume_specific("i64.const"sv))
+ return ParsedValue { WasmValue::from_i64(TRY(parse_integer.operator()<i64>(rest()))), ValueType::scalar(ValueKind::I64) };
+ if (lexer.consume_specific("f32.const"sv))
+ return ParsedValue { WasmValue::from_f32(TRY(parse_float.operator()<float>(rest()))), ValueType::scalar(ValueKind::F32) };
+ if (lexer.consume_specific("f64.const"sv))
+ return ParsedValue { WasmValue::from_f64(TRY(parse_float.operator()<double>(rest()))), ValueType::scalar(ValueKind::F64) };
if (lexer.consume_specific("v("sv)) {
Vector<ParsedValue> values;
for (;;) {
- lexer.ignore_while(is_sep);
+ lexer.ignore_while(is_separator);
if (lexer.consume_specific(")"sv))
break;
if (lexer.is_eof()) {
warnln("Expected ')' to close vector");
break;
}
- auto value = parse_value(lexer.consume_until(is_any_of(",)"sv)));
- if (value.is_error())
- return value.release_error();
+ values.append(TRY(parse_value(lexer.consume_until(is_any_of(",)"sv)))));
lexer.consume_specific(',');
- values.append(value.release_value());
}
-
if (values.is_empty())
return Error::from_string_literal("Empty vector");
- auto element_type = values.first().type;
- for (auto& value : values) {
- if (value.type != element_type)
- return Error::from_string_literal("Mixed types in vector");
+ auto element_kind = values.first().type.kind;
+ unsigned width = 0;
+ switch (element_kind) {
+ case ValueKind::I32:
+ case ValueKind::F32:
+ width = 32;
+ break;
+ case ValueKind::I64:
+ case ValueKind::F64:
+ width = 64;
+ break;
+ default:
+ return Error::from_string_literal("Invalid vector element");
}
- unsigned total_size = 0;
- unsigned width = 0;
u128 result = 0;
u128 last_value = 0;
+ unsigned total_size = 0;
for (auto& parsed : values) {
+ if (parsed.type.kind != element_kind)
+ return Error::from_string_literal("Mixed types in vector");
if (total_size >= 128)
return Error::from_string_literal("Vector too large");
-
- switch (parsed.type.kind()) {
- case Wasm::ValueType::F32:
- case Wasm::ValueType::I32:
- width = sizeof(u32);
- break;
- case Wasm::ValueType::F64:
- case Wasm::ValueType::I64:
- width = sizeof(u64);
- break;
- case Wasm::ValueType::V128:
- case Wasm::ValueType::I8:
- case Wasm::ValueType::I16:
- case Wasm::ValueType::FunctionReference:
- case Wasm::ValueType::NoFunctionReference:
- case Wasm::ValueType::ExternReference:
- case Wasm::ValueType::NoExternReference:
- case Wasm::ValueType::ExceptionReference:
- case Wasm::ValueType::NoExceptionReference:
- case Wasm::ValueType::AnyReference:
- case Wasm::ValueType::EqReference:
- case Wasm::ValueType::I31Reference:
- case Wasm::ValueType::StructReference:
- case Wasm::ValueType::ArrayReference:
- case Wasm::ValueType::NoneReference:
- case Wasm::ValueType::TypeUseReference:
- VERIFY_NOT_REACHED();
- }
- last_value = parsed.value.value();
-
+ last_value = width == 32 ? u128 { parsed.value.low & 0xffff'ffff, 0 } : u128 { parsed.value.low, 0 };
result |= last_value << total_size;
- total_size += width * 8;
+ total_size += width;
}
-
if (total_size < 128)
- warnln("Vector value '{}' is only {} bytes wide, repeating last element", spec, total_size);
+ warnln("Vector value '{}' is only {} bytes wide, repeating last element", spec, total_size / 8);
while (total_size < 128) {
- // Repeat the last value until we fill the 128 bits
result |= last_value << total_size;
- total_size += width * 8;
+ total_size += width;
}
-
- return ParsedValue {
- .value = Wasm::Value { result },
- .type = Wasm::ValueType(Wasm::ValueType::Kind::V128)
- };
+ return ParsedValue { v128_value(result), ValueType::scalar(ValueKind::V128) };
}
return Error::from_string_literal("Invalid value");
}
-static RefPtr<Wasm::Module> parse(StringView filename)
+static RefPtr<Wasm::Runtime::Module> compile(StringView filename)
{
- auto result = Core::MappedFile::map(filename);
- if (result.is_error()) {
- warnln("Failed to open {}: {}", filename, result.error());
+ auto file = Core::MappedFile::map(filename);
+ if (file.is_error()) {
+ warnln("Failed to open {}: {}", filename, file.error());
return {};
}
-
- auto parse_result = Wasm::Module::parse(*result.value());
- if (parse_result.is_error()) {
- warnln("Something went wrong, either the file is invalid, or there's a bug with LibWasm!");
- warnln("The parse error was {}", Wasm::parse_error_to_byte_string(parse_result.error()));
+ auto module = Wasm::Runtime::Module::compile(file.value()->bytes());
+ if (module.is_error()) {
+ warnln("Failed to compile {}: {}", filename, module.error());
return {};
}
- return parse_result.release_value();
+ return module.release_value();
}
-static void print_link_error(Wasm::LinkError const& error)
+static ByteString format_value(WasmValue value, ValueType type)
{
- for (auto const& missing : error.missing_imports)
- warnln("Missing import '{}'", missing);
+ switch (type.kind) {
+ case ValueKind::I32:
+ return ByteString::formatted("{}", value.to_i32());
+ case ValueKind::I64:
+ return ByteString::formatted("{}", value.to_i64());
+ case ValueKind::F32:
+ return ByteString::formatted("{}", value.to_f32());
+ case ValueKind::F64:
+ return ByteString::formatted("{}", value.to_f64());
+ case ValueKind::V128:
+ return ByteString::formatted("v128({:x})", u128 { value.low, value.high });
+ case ValueKind::Reference:
+ if (value.is_null_reference())
+ return "addr(null)";
+ return ByteString::formatted("addr({:#x})", value.reference_bits());
+ }
+ VERIFY_NOT_REACHED();
}
-template<typename T>
-static ErrorOr<T, Wasm::Result> trap_for_js_exception(JS::VM& vm, JS::ThrowCompletionOr<T> const& result)
+static Optional<ValueKind> consume_scalar_type(GenericLexer& lexer)
{
- if (!result.is_error())
- return result.value();
-
- auto const& completion = result.error();
- auto& exception = completion.value();
- warnln("JS exception: {}", MUST(exception.to_utf16_string(vm)));
- return Wasm::Trap { ByteString("JS exception") };
+ if (lexer.consume_specific("i32"sv))
+ return ValueKind::I32;
+ if (lexer.consume_specific("i64"sv))
+ return ValueKind::I64;
+ if (lexer.consume_specific("f32"sv))
+ return ValueKind::F32;
+ if (lexer.consume_specific("f64"sv))
+ return ValueKind::F64;
+ if (lexer.consume_specific("v128"sv))
+ return ValueKind::V128;
+ return {};
}
ErrorOr<int> ladybird_main(Main::Arguments arguments)
{
StringView filename;
- bool print = false;
- bool print_compiled = false;
- bool dump_native = false;
bool attempt_instantiate = false;
bool export_all_imports = false;
bool benchmark_timings = false;
- [[maybe_unused]] bool wasi = false;
- Optional<u64> specific_function_address;
+ bool wasi = false;
ByteString exported_function_to_execute;
Vector<ParsedValue> values_to_push;
Vector<ByteString> modules_to_link_in;
Vector<StringView> args_if_wasi;
Vector<StringView> wasi_preopened_mappings;
- HashMap<Wasm::Linker::Name, Wasm::ExternValue> js_exports;
+ HashMap<ImportName, Wasm::Runtime::Extern> js_exports;
- IGNORE_USE_IN_ESCAPING_LAMBDA Wasm::AbstractMachine machine;
auto vm = JS::VM::create();
auto root_execution_context = JS::create_simple_execution_context<JS::GlobalObject>(*vm);
auto& realm = *root_execution_context->realm;
- IGNORE_USE_IN_ESCAPING_LAMBDA Wasm::ModuleInstance* reentry_instance = nullptr;
+ Wasm::Runtime::Store store { vm->heap() };
+ // NB: The entities the utility allocates live until it exits.
+ Vector<GC::Root<GC::ForeignCell>> roots;
+ auto keep = [&](Entity entity) {
+ roots.append(GC::Root<GC::ForeignCell> { entity });
+ return entity;
+ };
+ IGNORE_USE_IN_ESCAPING_LAMBDA Entity main_instance = nullptr;
Core::ArgsParser parser;
- parser.add_positional_argument(filename, "File name to parse", "file");
- parser.add_option(print, "Print the parsed module", "print", 'p');
- parser.add_option(print_compiled, "Print the compiled module", "print-compiled");
- parser.add_option(dump_native, "Disassemble Cranelift-compiled native code for each function", "dump-native");
- parser.add_option(specific_function_address, "Optional compiled function address to print", "print-function", 'f', "address");
+ parser.add_positional_argument(filename, "File name to run", "file");
parser.add_option(attempt_instantiate, "Attempt to instantiate the module", "instantiate", 'i');
parser.add_option(exported_function_to_execute, "Attempt to execute the named exported function from the module (implies -i)", "execute", 'e', "name");
parser.add_option(export_all_imports, "Export noop functions corresponding to imports", "export-noop");
parser.add_option(benchmark_timings, "Emit machine-readable Wasm phase timings to stderr", "benchmark-timings");
-#if !defined(AK_OS_WINDOWS)
parser.add_option(wasi, "Enable WASI", "wasi", 'w');
-#endif
parser.add_option(Core::ArgsParser::Option {
.argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
.help_string = "Export js `function(arg...) { source }` returning T as [module].[function]",
.long_name = "export-js",
.short_name = 0,
.value_name = "module.function(arg:T...):T=source",
- .accept_value = [&](StringView str) {
- GenericLexer lexer(str);
+ .accept_value = [&](StringView text) {
+ GenericLexer lexer(text);
// [module] <.> [function] <(> {[name] <:> [type]} <)> (<:> [type])? <=> [text]
auto module = lexer.consume_until('.');
if (!lexer.consume_specific('.')) {
- warnln("Invalid JS export module in '{}'", str);
+ warnln("Invalid JS export module in '{}'", text);
return false;
}
- auto fn_name = lexer.consume_until(is_any_of("(=:"sv));
- struct Arg {
- Wasm::ValueType type;
+ auto function_name = lexer.consume_until(is_any_of("(=:"sv));
+ struct Parameter {
+ ValueKind kind;
StringView name;
};
- Vector<Arg> formal_params;
+ Vector<Parameter> parameters;
if (lexer.consume_specific('(')) {
while (!lexer.consume_specific(')')) {
auto name = lexer.consume_until(is_any_of(",:)"sv));
if (name.is_empty()) {
- warnln("Invalid JS export argument name in '{}'", str);
+ warnln("Invalid JS export argument name in '{}'", text);
return false;
}
- auto type_kind = Wasm::ValueType::I32;
+ auto kind = ValueKind::I32;
if (lexer.consume_specific(':')) {
- if (lexer.consume_specific("i32"sv)) {
- type_kind = Wasm::ValueType::I32;
- } else if (lexer.consume_specific("i64"sv)) {
- type_kind = Wasm::ValueType::I64;
- } else if (lexer.consume_specific("f32"sv)) {
- type_kind = Wasm::ValueType::F32;
- } else if (lexer.consume_specific("f64"sv)) {
- type_kind = Wasm::ValueType::F64;
- } else if (lexer.consume_specific("v128"sv)) {
- type_kind = Wasm::ValueType::V128;
- } else {
- warnln("Invalid JS export argument type in '{}'", str);
+ auto type = consume_scalar_type(lexer);
+ if (!type.has_value()) {
+ warnln("Invalid JS export argument type in '{}'", text);
return false;
}
+ kind = *type;
}
- formal_params.append(Arg { Wasm::ValueType(type_kind), name });
+ parameters.append({ kind, name });
lexer.consume_specific(',');
}
}
- Vector<Wasm::ValueType::Kind> returns;
+ Optional<ValueKind> result_kind;
if (lexer.consume_specific(':')) {
- if (lexer.consume_specific("i32"sv)) {
- returns.append(Wasm::ValueType::I32);
- } else if (lexer.consume_specific("i64"sv)) {
- returns.append(Wasm::ValueType::I64);
- } else if (lexer.consume_specific("f32"sv)) {
- returns.append(Wasm::ValueType::F32);
- } else if (lexer.consume_specific("f64"sv)) {
- returns.append(Wasm::ValueType::F64);
- } else if (lexer.consume_specific("v128"sv)) {
- returns.append(Wasm::ValueType::V128);
- } else {
- warnln("Invalid JS export return type in '{}'", str);
+ result_kind = consume_scalar_type(lexer);
+ if (!result_kind.has_value()) {
+ warnln("Invalid JS export return type in '{}'", text);
return false;
}
}
-
if (!lexer.consume_specific('=') || lexer.is_eof()) {
- warnln("Invalid JS export source in '{}'", str);
+ warnln("Invalid JS export source in '{}'", text);
return false;
}
- auto source_text = lexer.consume_all().trim_whitespace();
Utf16StringBuilder builder;
builder.append_ascii("(function ("sv);
- auto first = true;
- for (auto& arg : formal_params) {
- if (!first)
+ for (size_t index = 0; index < parameters.size(); ++index) {
+ if (index != 0)
builder.append_ascii(", "sv);
- first = false;
- auto argument_name = Utf16String::from_utf8(arg.name);
- builder.append(argument_name.utf16_view());
+ auto parameter_name = Utf16String::from_utf8(parameters[index].name);
+ builder.append(parameter_name.utf16_view());
}
builder.append_ascii(") { return ("sv);
- auto source_text_utf16 = Utf16String::from_utf8(source_text);
- builder.append(source_text_utf16.utf16_view());
+ auto source = Utf16String::from_utf8(lexer.consume_all().trim_whitespace());
+ builder.append(source.utf16_view());
builder.append_ascii("); })"sv);
- auto js_function = builder.to_string();
- auto name = ByteString::formatted("{}.{}", module, fn_name);
- auto script = JS::Script::parse(js_function, realm, name);
+ auto name = ByteString::formatted("{}.{}", module, function_name);
+ auto script = JS::Script::parse(builder.to_string(), realm, name);
if (script.is_error()) {
- warnln("Failed to parse JS export source '{}':", js_function);
- return false;
- }
-
- auto js_script = script.release_value();
- auto maybe_function = vm->run(*js_script);
- if (maybe_function.is_error()) {
- warnln("Failed to run JS export source '{}'", js_function);
+ warnln("Failed to parse JS export source of '{}'", name);
return false;
}
- auto function_val = maybe_function.release_value();
- if (!function_val.is_function()) {
- warnln("JS export source '{}' did not parse as a function", js_function);
+ auto function_value = vm->run(*script.release_value());
+ if (function_value.is_error() || !function_value.value().is_function()) {
+ warnln("JS export source of '{}' did not evaluate to a function", name);
return false;
}
+ auto function = function_value.value();
+
+ Wasm::Runtime::FunctionType function_type;
+ for (auto& parameter : parameters)
+ function_type.parameters.append(ValueType::scalar(parameter.kind));
+ if (result_kind.has_value())
+ function_type.results.append(ValueType::scalar(*result_kind));
+
+ auto host_function = store.allocate_host_function(function_type, [&vm, &realm, function, &store, &main_instance, function_type, name](Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) mutable -> ErrorOr<void, HostError> {
+ GC::RootVector<JS::Value> js_arguments;
+ for (size_t index = 0; index < arguments.size(); ++index) {
+ auto argument = arguments[index];
+ switch (function_type.parameters[index].kind) {
+ case ValueKind::I32:
+ js_arguments.append(JS::Value(static_cast<u32>(argument.to_i32())));
+ break;
+ case ValueKind::I64:
+ js_arguments.append(JS::Value(static_cast<double>(static_cast<u64>(argument.to_i64()))));
+ break;
+ case ValueKind::F32:
+ js_arguments.append(JS::Value(static_cast<double>(argument.to_f32())));
+ break;
+ case ValueKind::F64:
+ js_arguments.append(JS::Value(argument.to_f64()));
+ break;
+ case ValueKind::V128: {
+ u64 halves[2] = { argument.low, argument.high };
+ js_arguments.append(JS::BigInt::create(*vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger::import_data({ reinterpret_cast<u8 const*>(halves), sizeof(halves) }) }));
+ break;
+ }
+ case ValueKind::Reference:
+ return HostError { "Unsupported argument type" };
+ }
+ }
- auto& function = function_val.as_function();
-
- Vector<Wasm::ValueType> results;
- Vector<Wasm::ValueType> params;
- for (auto& type : returns)
- results.append(Wasm::ValueType(type));
- for (auto& arg : formal_params)
- params.append(Wasm::ValueType(arg.type));
-
- Wasm::FunctionType function_type = { move(params), move(results) };
- auto host_function = Wasm::HostFunction {
- [&vm, &function, &machine, &realm, &reentry_instance, formal_params, returns, name](Wasm::Configuration&, Span<Wasm::Value> args) mutable -> Wasm::Result {
- Vector<JS::Value> js_args;
- js_args.ensure_capacity(args.size());
- for (size_t i = 0; i < formal_params.size(); ++i) {
- auto type = formal_params[i].type;
- if (i >= args.size()) {
- warnln("Not enough arguments provided to JS export function '{}'", name);
- return Wasm::Trap { ByteString("Not enough arguments") };
- }
- auto& arg = args[i];
- switch (type.kind()) {
- case Wasm::ValueType::I32:
- js_args.append(JS::Value(arg.to<u32>()));
- break;
- case Wasm::ValueType::I64:
- js_args.append(JS::Value(arg.to<u64>()));
- break;
- case Wasm::ValueType::F32:
- js_args.append(JS::Value(arg.to<f32>()));
- break;
- case Wasm::ValueType::F64:
- js_args.append(JS::Value(arg.to<f64>()));
- break;
- case Wasm::ValueType::V128: {
- auto value = arg.to<u128>();
- ReadonlyBytes data { bit_cast<u8 const*>(&value), sizeof(u128) };
- js_args.append(JS::BigInt::create(*vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger { data } }));
- break;
+ // The function's `this` can call back into the main instance's exports.
+ auto reentry_this = JS::Object::create(realm, realm.intrinsics().object_prototype());
+ auto invoke = JS::NativeFunction::create(
+ realm, [&store, &main_instance](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
+ if (!main_instance)
+ return vm.throw_completion<JS::TypeError>("wasm reentry: instance not ready yet"_utf16);
+ auto export_name = TRY(vm.argument(0).to_utf16_string(vm)).to_byte_string();
+ auto callee = store.find_export(main_instance, export_name);
+ if (!callee.has_value() || callee->kind != ExternKind::Function)
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry: no exported function '{}'", export_name));
+ auto type = store.function_type(callee->entity);
+ Wasm::Runtime::Values wasm_arguments;
+ for (size_t index = 0; index < type.parameters.size(); ++index) {
+ auto value = vm.argument(index + 1);
+ switch (type.parameters[index].kind) {
+ case ValueKind::I32:
+ wasm_arguments.append(WasmValue::from_i32(static_cast<i32>(TRY(value.to_u32(vm)))));
+ break;
+ case ValueKind::I64:
+ wasm_arguments.append(WasmValue::from_i64(static_cast<i64>(TRY(value.to_bigint_uint64(vm)))));
+ break;
+ case ValueKind::F32:
+ wasm_arguments.append(WasmValue::from_f32(static_cast<float>(TRY(value.to_double(vm)))));
+ break;
+ case ValueKind::F64:
+ wasm_arguments.append(WasmValue::from_f64(TRY(value.to_double(vm))));
+ break;
+ default:
+ return vm.throw_completion<JS::TypeError>("wasm reentry: unsupported parameter type"_utf16);
+ }
}
+ auto result = store.invoke(callee->entity, wasm_arguments);
+ if (result.is_error())
+ return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry trapped: {}", result.error().message));
+ if (result.value().is_empty())
+ return JS::js_undefined();
+ if (type.results.size() > 1)
+ return vm.throw_completion<JS::TypeError>("wasm reentry: multi-value results are not yet supported"_utf16);
+ auto returned = result.value().first();
+ switch (type.results.first().kind) {
+ case ValueKind::I32:
+ return JS::Value(returned.to_i32());
+ case ValueKind::I64:
+ return JS::Value(static_cast<double>(returned.to_i64()));
+ case ValueKind::F32:
+ return JS::Value(static_cast<double>(returned.to_f32()));
+ case ValueKind::F64:
+ return JS::Value(returned.to_f64());
default:
- warnln("Unsupported argument type '{}' for JS export function '{}'", type.kind_name(), name);
- return Wasm::Trap { ByteString("Unsupported argument type") };
+ return JS::js_undefined();
}
- }
- auto reentry_this = JS::Object::create(realm, realm.intrinsics().object_prototype());
- auto invoke = JS::NativeFunction::create(
- realm, [&machine, &reentry_instance](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
- if (!reentry_instance)
- return vm.throw_completion<JS::TypeError>("wasm reentry: instance not ready yet"_utf16);
- auto export_name = TRY(vm.argument(0).to_utf16_string(vm)).to_byte_string();
- Optional<Wasm::FunctionAddress> address;
- for (auto& entry : reentry_instance->exports()) {
- if (entry.name() == export_name) {
- if (auto* addr = entry.value().get_pointer<Wasm::FunctionAddress>())
- address = *addr;
- }
- }
- if (!address.has_value())
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry: no exported function '{}'"sv, export_name));
- auto* callee = machine.store().get(*address);
- if (!callee || !callee->has<Wasm::WasmFunction>())
- return vm.throw_completion<JS::TypeError>("wasm reentry: target is not a wasm function"_utf16);
- auto const& type = callee->get<Wasm::WasmFunction>().type();
- Vector<Wasm::Value> wasm_args;
- for (size_t i = 0; i < type.parameters().size(); ++i) {
- auto value = vm.argument(i + 1);
- switch (type.parameters()[i].kind()) {
- case Wasm::ValueType::I32:
- wasm_args.append(Wasm::Value(TRY(value.to_u32(vm))));
- break;
- case Wasm::ValueType::I64:
- wasm_args.append(Wasm::Value(TRY(value.to_bigint_uint64(vm))));
- break;
- case Wasm::ValueType::F32:
- wasm_args.append(Wasm::Value(static_cast<f32>(TRY(value.to_double(vm)))));
- break;
- case Wasm::ValueType::F64:
- wasm_args.append(Wasm::Value(TRY(value.to_double(vm))));
- break;
- default:
- return vm.throw_completion<JS::TypeError>("wasm reentry: unsupported parameter type"_utf16);
- }
- }
- auto result = machine.invoke(g_interpreter, *address, move(wasm_args));
- if (result.is_trap())
- return vm.throw_completion<JS::TypeError>(Utf16String::formatted("wasm reentry trapped: {}"sv, result.trap().format()));
- if (result.values().is_empty() || type.results().is_empty())
- return JS::js_undefined();
- if (type.results().size() > 1)
- return vm.throw_completion<JS::TypeError>("wasm reentry: multi-value results are not yet supported"_utf16);
- auto const& returned = result.values().first();
- switch (type.results()[0].kind()) {
- case Wasm::ValueType::I32:
- return JS::Value(returned.to<i32>());
- case Wasm::ValueType::I64:
- return JS::Value(static_cast<double>(returned.to<i64>()));
- case Wasm::ValueType::F32:
- return JS::Value(static_cast<double>(returned.to<f32>()));
- case Wasm::ValueType::F64:
- return JS::Value(returned.to<f64>());
- default:
- return JS::js_undefined();
- }
- },
- 1, "invoke"_utf16);
- reentry_this->define_direct_property("invoke"_utf16, invoke, JS::default_attributes);
-
- auto result = TRY(trap_for_js_exception(vm, JS::call(vm, function, reentry_this, js_args.span())));
- if (returns.is_empty())
- return Wasm::Result { Vector<Wasm::Value> {} };
-
- if (returns.size() != 1)
- return Wasm::Trap { ByteString("NYI") };
+ },
+ 1, "invoke"_utf16);
+ reentry_this->define_direct_property("invoke"_utf16, invoke, JS::default_attributes);
- switch (returns[0]) {
- case Wasm::ValueType::I32:
- return Wasm::Result { Vector<Wasm::Value> { Wasm::Value { TRY(trap_for_js_exception(*vm, result.to_u32(vm))) } } };
- case Wasm::ValueType::I64:
- return Wasm::Result { Vector<Wasm::Value> { Wasm::Value { TRY(trap_for_js_exception(*vm, result.to_bigint_uint64(vm))) } } };
- case Wasm::ValueType::F32:
- return Wasm::Result { Vector<Wasm::Value> { Wasm::Value { static_cast<f32>(TRY(trap_for_js_exception(*vm, result.to_double(vm)))) } } };
- case Wasm::ValueType::F64:
- return Wasm::Result { Vector<Wasm::Value> { Wasm::Value { TRY(trap_for_js_exception(*vm, result.to_double(vm))) } } };
- case Wasm::ValueType::V128: {
- auto value = TRY(trap_for_js_exception(*vm, result.to_bigint(vm)));
- u128 out {};
- Bytes data { bit_cast<u8*>(&out), sizeof(u128) };
- if (value->big_integer().unsigned_value().export_data(data).size() != data.size()) {
- dbgln("JS export function '{}' returned a v128 value that is not 128 bits wide", name);
- return Wasm::Trap { ByteString("Invalid v128 value") };
- }
- return Wasm::Result { Vector<Wasm::Value> { Wasm::Value { out } } };
+ auto result = JS::call(*vm, function, reentry_this, js_arguments.span());
+ if (result.is_error()) {
+ warnln("JS exception: {}", MUST(result.error_value().to_utf16_string(*vm)));
+ return HostError { "JS exception" };
+ }
+ if (function_type.results.is_empty())
+ return {};
+
+ auto value = result.value();
+ auto converted = [&]() -> JS::ThrowCompletionOr<WasmValue> {
+ switch (function_type.results.first().kind) {
+ case ValueKind::I32:
+ return WasmValue::from_i32(static_cast<i32>(TRY(value.to_u32(*vm))));
+ case ValueKind::I64:
+ return WasmValue::from_i64(static_cast<i64>(TRY(value.to_bigint_uint64(*vm))));
+ case ValueKind::F32:
+ return WasmValue::from_f32(static_cast<float>(TRY(value.to_double(*vm))));
+ case ValueKind::F64:
+ return WasmValue::from_f64(TRY(value.to_double(*vm)));
+ case ValueKind::V128: {
+ auto bigint = TRY(value.to_bigint(*vm));
+ u64 halves[2] = {};
+ (void)bigint->big_integer().unsigned_value().export_data({ reinterpret_cast<u8*>(halves), sizeof(halves) });
+ return WasmValue::from_v128(halves[0], halves[1]);
}
- default:
- warnln("Unsupported return type for JS export function '{}'", name);
- return Wasm::Trap { ByteString("Unsupported return type") };
+ case ValueKind::Reference:
+ break;
}
- },
- function_type,
- name,
- };
- auto host_function_instance = machine.store().allocate(move(host_function));
- if (!host_function_instance.has_value()) {
- warnln("Failed to allocate host function instance for '{}'", name);
- return false;
- }
- js_exports.set({ .module = module, .name = fn_name, .type = function_type }, *host_function_instance);
+ VERIFY_NOT_REACHED();
+ }();
+ if (converted.is_error()) {
+ warnln("JS export function '{}' returned a value of the wrong type", name);
+ return HostError { "JS exception" };
+ }
+ results[0] = converted.release_value();
+ return {};
+ });
+ js_exports.set({ module, function_name }, { ExternKind::Function, keep(host_function) });
return true;
},
});
@@ -634,12 +513,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
.long_name = "wasi-map-dir",
.short_name = 0,
.value_name = "path[:path]",
- .accept_value = [&](StringView str) {
- if (!str.is_empty()) {
- wasi_preopened_mappings.append(str);
- return true;
- }
- return false;
+ .accept_value = [&](StringView text) {
+ if (text.is_empty())
+ return false;
+ wasi_preopened_mappings.append(text);
+ return true;
},
});
parser.add_option(Core::ArgsParser::Option {
@@ -648,12 +526,11 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
.long_name = "link",
.short_name = 'l',
.value_name = "file",
- .accept_value = [&](StringView str) {
- if (!str.is_empty()) {
- modules_to_link_in.append(str);
- return true;
- }
- return false;
+ .accept_value = [&](StringView text) {
+ if (text.is_empty())
+ return false;
+ modules_to_link_in.append(text);
+ return true;
},
});
parser.add_option(Core::ArgsParser::Option {
@@ -662,8 +539,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
.long_name = "arg",
.short_name = 0,
.value_name = "value",
- .accept_value = [&](StringView str) -> bool {
- auto result = parse_value(str);
+ .accept_value = [&](StringView text) -> bool {
+ auto result = parse_value(text);
if (result.is_error()) {
warnln("Failed to parse value: {}", result.error());
return false;
@@ -677,587 +554,180 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
BenchmarkTimings timings;
ScopeGuard dump_benchmark_timings = [&] {
- if (!benchmark_timings)
- return;
- warnln("wasm-benchmark-timings: {}", timings.to_json().serialized());
+ if (benchmark_timings)
+ warnln("wasm-benchmark-timings: {}", timings.to_json().serialized());
+ };
+ auto timed = [&](JsonArray& phase, auto&& callback) {
+ auto timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
+ auto result = callback();
+ if (benchmark_timings)
+ phase.must_append(timer.elapsed_time().to_seconds_f64());
+ return result;
};
if (!exported_function_to_execute.is_empty())
attempt_instantiate = true;
- Optional<Core::ElapsedTimer> parse_timer;
- if (benchmark_timings)
- parse_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
-
- auto parse_result = parse(filename);
-
- if (benchmark_timings)
- timings.parse.must_append(parse_timer->elapsed_time().to_seconds_f64());
-
- if (parse_result.is_null())
+ // NB: Compiling a module parses and validates it.
+ auto module = timed(timings.parse, [&] { return compile(filename); });
+ if (!module)
return 1;
-
- g_stdout = TRY(Core::File::standard_output());
- g_printer = TRY(try_make<Wasm::Printer>(*g_stdout));
-
- if (print && !attempt_instantiate) {
- Wasm::Printer printer(*g_stdout);
- printer.print(*parse_result);
- }
-
- if (attempt_instantiate || print_compiled || dump_native) {
-#if !defined(AK_OS_WINDOWS)
- Optional<Wasm::Wasi::Implementation> wasi_impl;
-
- if (wasi) {
- wasi_impl.emplace(Wasm::Wasi::Implementation::Details {
- .provide_arguments = [&] {
- Vector<String> strings;
- for (auto& string : args_if_wasi)
- strings.append(String::from_utf8(string).release_value_but_fixme_should_propagate_errors());
- return strings; },
- .provide_environment = {},
- .provide_preopened_directories = [&] {
- Vector<Wasm::Wasi::Implementation::MappedPath> paths;
- for (auto& string : wasi_preopened_mappings) {
- auto split_index = string.find(':');
- if (split_index.has_value()) {
- LexicalPath host_path { FileSystem::real_path(string.substring_view(0, *split_index)).release_value_but_fixme_should_propagate_errors() };
- LexicalPath mapped_path { string.substring_view(*split_index + 1) };
- paths.append({move(host_path), move(mapped_path)});
- } else {
- LexicalPath host_path { FileSystem::real_path(string).release_value_but_fixme_should_propagate_errors() };
- LexicalPath mapped_path { string };
- paths.append({move(host_path), move(mapped_path)});
- }
- }
- return paths; },
- });
+ if (!attempt_instantiate)
+ return 0;
+
+ Core::EventLoop::initialize_for_current_thread();
+
+ OwnPtr<Wasm::Runtime::Wasi> wasi_implementation;
+ if (wasi) {
+ Vector<ByteString> wasi_arguments;
+ for (auto argument : args_if_wasi)
+ wasi_arguments.append(argument);
+ Vector<Wasm::Runtime::Wasi::Preopen> preopens;
+ for (auto mapping : wasi_preopened_mappings) {
+ auto split_index = mapping.find(':');
+ auto host_path = split_index.has_value() ? mapping.substring_view(0, *split_index) : mapping;
+ auto guest_path = split_index.has_value() ? mapping.substring_view(*split_index + 1) : mapping;
+ preopens.append({ TRY(FileSystem::real_path(host_path)), guest_path });
}
-#endif
-
- Core::EventLoop::initialize_for_current_thread();
- auto prepare_module = [&](Wasm::Module& module) -> ErrorOr<void, Wasm::ValidationError> {
- if (!benchmark_timings)
- return {};
-
- auto validation_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
- auto validation_result = machine.validate(module, {}, Wasm::CompileToNative::No);
- timings.validation.must_append(validation_timer.elapsed_time().to_seconds_f64());
- if (validation_result.is_error())
- return validation_result.release_error();
-
- auto compilation_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
- Wasm::start_cranelift_compilation(module);
- timings.native_compilation.must_append(compilation_timer.elapsed_time().to_seconds_f64());
- return {};
- };
-
- if (auto preparation_result = prepare_module(*parse_result); preparation_result.is_error()) {
- warnln("Validation failed: {}", preparation_result.error());
- return 1;
- }
-
- // First, resolve the linked modules
- Vector<NonnullRefPtr<Wasm::ModuleInstance>> linked_instances;
- Vector<NonnullRefPtr<Wasm::Module>> linked_modules;
- for (auto& name : modules_to_link_in) {
- Optional<Core::ElapsedTimer> linked_module_parse_timer;
- if (benchmark_timings)
- linked_module_parse_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
-
- auto linked_module = parse(name);
-
- if (benchmark_timings)
- timings.parse.must_append(linked_module_parse_timer->elapsed_time().to_seconds_f64());
-
- if (linked_module.is_null()) {
- warnln("Failed to parse linked module '{}'", name);
- return 1;
- }
- if (auto preparation_result = prepare_module(*linked_module); preparation_result.is_error()) {
- warnln("Validation of imported module '{}' failed: {}", name, preparation_result.error());
- return 1;
- }
- linked_modules.append(linked_module.release_nonnull());
- Wasm::Linker linker { linked_modules.last() };
- for (auto& instance : linked_instances)
- linker.link(*instance);
- auto link_result = linker.finish();
- if (link_result.is_error()) {
- warnln("Linking imported module '{}' failed", name);
- print_link_error(link_result.error());
- return 1;
- }
- Optional<Core::ElapsedTimer> instantiation_timer;
- if (benchmark_timings)
- instantiation_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
-
- auto instantiation_result = machine.instantiate(linked_modules.last(), link_result.release_value());
-
- if (benchmark_timings)
- timings.instantiation.must_append(instantiation_timer->elapsed_time().to_seconds_f64());
-
- if (instantiation_result.is_error()) {
- warnln("Instantiation of imported module '{}' failed: {}", name, instantiation_result.error().error);
- return 1;
- }
- linked_instances.append(instantiation_result.release_value());
- }
-
- Wasm::Linker linker { *parse_result };
- for (auto& instance : linked_instances)
- linker.link(*instance);
+ wasi_implementation = make<Wasm::Runtime::Wasi>(wasi_arguments, ReadonlySpan<ByteString> {}, preopens);
+ }
-#if !defined(AK_OS_WINDOWS)
- if (wasi) {
- HashMap<Wasm::Linker::Name, Wasm::ExternValue> wasi_exports;
- for (auto& entry : linker.unresolved_imports()) {
- if (entry.module != "wasi_snapshot_preview1"sv)
- continue;
- auto function = wasi_impl->function_by_name(entry.name);
- if (function.is_error()) {
- dbgln("wasi function {} not implemented :(", entry.name);
+ // Each linked module's exports resolve the imports of the ones after it, and of the main module, by name.
+ HashMap<ByteString, Wasm::Runtime::Extern> linked_exports;
+ auto resolve_imports = [&](Wasm::Runtime::Module const& module_to_link) -> Optional<Vector<Wasm::Runtime::Extern>> {
+ Vector<Wasm::Runtime::Extern> imports;
+ bool missing = false;
+ for (size_t index = 0; index < module_to_link.import_count(); ++index) {
+ auto import = module_to_link.import(index);
+ if (auto value = linked_exports.get(import.name); value.has_value()) {
+ imports.append(*value);
+ continue;
+ }
+ if (wasi_implementation && import.module == Wasm::Runtime::Wasi::module_name) {
+ if (auto function = wasi_implementation->allocate_function(store, import.name); function.has_value()) {
+ imports.append({ ExternKind::Function, keep(*function) });
continue;
}
- auto address = machine.store().allocate(function.release_value());
- wasi_exports.set(entry, *address);
- }
-
- linker.link(wasi_exports);
- }
-#endif
-
- linker.link(js_exports);
-
- if (export_all_imports) {
- HashMap<Wasm::Linker::Name, Wasm::ExternValue> exports;
-
- auto allocate_function_stub = [&](Wasm::FunctionType const& func, ByteString const& name) {
- return *machine.store().allocate(Wasm::HostFunction(
- [name, func](auto&, auto arguments) -> Wasm::Result {
- StringBuilder argument_builder;
- bool first = true;
- size_t index = 0;
- for (auto& argument : arguments) {
- AllocatingMemoryStream stream;
- auto value_type = func.parameters()[index];
- Wasm::Printer { stream }.print(argument, value_type);
- if (first)
- first = false;
- else
- argument_builder.append(", "sv);
- auto buffer = ByteBuffer::create_uninitialized(stream.used_buffer_size()).release_value_but_fixme_should_propagate_errors();
- stream.read_until_filled(buffer).release_value_but_fixme_should_propagate_errors();
- argument_builder.append(StringView(buffer).trim_whitespace());
- ++index;
- }
- dbgln("[wasm runtime] Stub function {} was called with the following arguments: {}", name, argument_builder.to_byte_string());
- Vector<Wasm::Value> result;
- result.ensure_capacity(func.results().size());
- for (auto expect_result : func.results())
- result.append(Wasm::Value(expect_result));
- return Wasm::Result { move(result) };
- },
- func,
- name));
- };
-
- for (auto& entry : linker.unresolved_imports()) {
- Optional<Wasm::ExternValue> address;
- entry.type.visit(
- [&](Wasm::TypeIndex const& type_index) {
- auto& type = parse_result->type_section().types()[type_index.value()];
- if (!type.is_function()) {
- dbgln("[wasm runtime] Cannot stub import {}::{} of non-function {}", entry.module, entry.name, type.name());
- return;
- }
- address = allocate_function_stub(type.function(), entry.name);
- },
- [&](Wasm::FunctionType const& func) {
- address = allocate_function_stub(func, entry.name);
- },
- [&](Wasm::TableType const& table_type) {
- address = *machine.store().allocate(table_type);
- },
- [&](Wasm::MemoryType const& memory_type) {
- address = *machine.store().allocate(memory_type);
- },
- [&](Wasm::GlobalType const& global_type) {
- address = *machine.store().allocate(global_type, Wasm::Value(global_type.type()));
- },
- [&](Wasm::TagType const& tag_type) {
- auto& type = parse_result->type_section().types()[tag_type.type().value()];
- if (!type.is_function()) {
- dbgln("[wasm runtime] Cannot stub tag import {}::{}: type is not a function", entry.module, entry.name);
- return;
- }
- // The module is not yet validated here, so its canonical types may not be known.
- address = *machine.store().allocate(type.function(), nullptr, tag_type.flags());
- });
-
- if (address.has_value())
- exports.set(entry, address.release_value());
- }
-
- linker.link(exports);
- }
-
- auto link_result = linker.finish();
- if (link_result.is_error()) {
- warnln("Linking main module failed");
- print_link_error(link_result.error());
- return 1;
- }
-
- Optional<Core::ElapsedTimer> instantiation_timer;
- if (benchmark_timings)
- instantiation_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
-
- auto instantiation_result = machine.instantiate(*parse_result, link_result.release_value());
-
- if (benchmark_timings)
- timings.instantiation.must_append(instantiation_timer->elapsed_time().to_seconds_f64());
-
- if (instantiation_result.is_error()) {
- warnln("Module instantiation failed: {}", instantiation_result.error().error);
- return 1;
- }
- auto module_instance = instantiation_result.release_value();
- reentry_instance = module_instance.ptr();
-
- if (print_compiled) {
- Span<Wasm::FunctionAddress const> functions = module_instance->functions();
- Wasm::FunctionAddress spec = specific_function_address.value_or(0);
-
- if (specific_function_address.has_value())
- functions = { &spec, 1 };
- for (auto address : functions) {
- auto function = machine.store().get(address)->get_pointer<Wasm::WasmFunction>();
- if (!function)
- continue;
- auto& expression = function->code().func().body();
- if (expression.compiled_instructions.dispatches.is_empty())
- continue;
-
- ByteString export_name;
- for (auto& entry : function->module().exports()) {
- if (entry.value() == address) {
- export_name = ByteString::formatted(" '{}'", entry.name());
+ dbgln("wasi function {} not implemented :(", import.name);
+ }
+ if (auto value = js_exports.get({ import.module, import.name }); value.has_value()) {
+ imports.append(*value);
+ continue;
+ }
+ if (export_all_imports) {
+ Optional<Entity> stub;
+ switch (import.type.kind) {
+ case ExternKind::Function: {
+ auto type = module_to_link.function_type(import.type.type_index);
+ if (!type.has_value())
break;
- }
- }
-
- TRY(g_stdout->write_until_depleted(ByteString::formatted("Function #{}{} (stack usage = {}):\n", address.value(), export_name, expression.stack_usage_hint())));
-
- Wasm::Printer printer { *g_stdout, 1 };
- for (size_t ip = 0; ip < expression.compiled_instructions.dispatches.size(); ++ip) {
- auto& dispatch = expression.compiled_instructions.dispatches[ip];
- auto& addresses = expression.compiled_instructions.src_dst_mappings[ip];
- ByteString regs;
- auto first = true;
- ssize_t in_count = 0;
- ssize_t out_count = 0;
-#define M(name, _, ins, outs) \
- case Wasm::Instructions::name.value(): \
- in_count = ins; \
- out_count = outs; \
- break;
- switch (dispatch.instruction->opcode().value()) {
- ENUMERATE_WASM_OPCODES(M)
- }
-#undef M
- constexpr auto reg_name = [](Wasm::Dispatch::RegisterOrStack reg) -> ByteString {
- if (reg == Wasm::Dispatch::RegisterOrStack::Stack)
- return "stack"sv;
- if (reg >= Wasm::Dispatch::RegisterOrStack::CallRecord)
- return ByteString::formatted("cr{}", to_underlying(reg) - to_underlying(Wasm::Dispatch::RegisterOrStack::CallRecord));
- return ByteString::formatted("reg{}", to_underlying(reg));
- };
- if (in_count > -1) {
- for (ssize_t index = 0; index < in_count; ++index) {
- if (first)
- regs = ByteString::formatted("{} ({}", regs, reg_name(addresses.sources[index]));
- else
- regs = ByteString::formatted("{}, {}", regs, reg_name(addresses.sources[index]));
- first = false;
- }
- if (out_count > 0) {
- if (first)
- regs = ByteString::formatted(" () -> {}", reg_name(addresses.destination));
- else
- regs = ByteString::formatted("{}) -> {}", regs, reg_name(addresses.destination));
- } else if (out_count == 0) {
- if (first)
- regs = ByteString::formatted(" () -x");
- else
- regs = ByteString::formatted("{}) -x", regs);
- } else {
- if (first)
- regs = ByteString::formatted(" () -?");
- else
- regs = ByteString::formatted("{}) -?", regs);
+ stub = store.allocate_host_function(*type, [name = ByteString(import.name), type = *type](auto&, ReadonlySpan<WasmValue> stub_arguments, Span<WasmValue>) -> ErrorOr<void, HostError> {
+ StringBuilder builder;
+ for (size_t argument = 0; argument < stub_arguments.size(); ++argument) {
+ if (argument != 0)
+ builder.append(", "sv);
+ builder.append(format_value(stub_arguments[argument], type.parameters[argument]));
}
- } else if (dispatch.instruction->opcode() == Wasm::Instructions::call || dispatch.instruction->opcode() == Wasm::Instructions::call_indirect) {
- if (addresses.destination != Wasm::Dispatch::RegisterOrStack::Stack)
- regs = ByteString::formatted("(?) -> {}", reg_name(addresses.destination));
- }
-
- if (regs.is_empty())
- regs = ByteString::formatted(" {{{:-<34}}}", regs);
- else
- regs = ByteString::formatted(" {{{: <33} }}", regs);
-
- TRY(g_stdout->write_until_depleted(ByteString::formatted(" [{:>03}]", ip)));
- TRY(g_stdout->write_until_depleted(regs.bytes()));
- printer.print(*dispatch.instruction);
- }
-
- TRY(g_stdout->write_until_depleted("\n"sv.bytes()));
- }
- }
-
- if (dump_native) {
- Span<Wasm::FunctionAddress const> functions = module_instance->functions();
- Wasm::FunctionAddress spec = specific_function_address.value_or(0);
-
- if (specific_function_address.has_value())
- functions = { &spec, 1 };
- for (auto address : functions) {
- auto* function = machine.store().get(address)->get_pointer<Wasm::WasmFunction>();
- if (!function)
- continue;
- auto& ci = function->code().func().body().compiled_instructions;
- if (!ci.cranelift_compiled || ci.cranelift_code_size == 0)
- continue;
-
- ByteString export_name;
- for (auto& entry : function->module().exports()) {
- if (entry.value() == address) {
- export_name = ByteString::formatted(" '{}'", entry.name());
- break;
- }
- }
-
- auto const* code_ptr = bit_cast<u8 const*>(Wasm::cranelift_entry_acquire(ci));
- auto code_size = ci.cranelift_code_size;
-
-#if defined(AK_OS_WINDOWS)
- char tmp_path[MAX_PATH];
- {
- char tmp_dir[MAX_PATH];
- GetTempPathA(MAX_PATH, tmp_dir);
- GetTempFileNameA(tmp_dir, "wn", 0, tmp_path);
+ dbgln("[wasm runtime] Stub function {} was called with the following arguments: {}", name, builder.string_view());
+ return {};
+ });
+ break;
}
- {
- auto tmp_file = Core::File::open(StringView { tmp_path, strlen(tmp_path) }, Core::File::OpenMode::Write);
- if (tmp_file.is_error()) {
- warnln("Failed to create temp file for function #{}", address.value());
- continue;
- }
- (void)tmp_file.value()->write_until_depleted({ code_ptr, code_size });
+ case ExternKind::Table:
+ stub = store.allocate_table(import.type.value_type, import.type.limits, 0);
+ break;
+ case ExternKind::Memory:
+ stub = store.allocate_memory(import.type.limits);
+ break;
+ case ExternKind::Global:
+ stub = store.allocate_global(import.type.value_type, import.type.is_mutable, WasmValue::default_for(import.type.value_type));
+ break;
+ case ExternKind::Tag:
+ break;
}
-#else
- char tmp_path[] = "/tmp/wasm-native-XXXXXX";
- int fd = mkstemp(tmp_path);
- if (fd < 0) {
- warnln("Failed to create temp file for function #{}", address.value());
+ if (stub.has_value()) {
+ imports.append({ import.type.kind, keep(*stub) });
continue;
}
-
- {
- auto tmp_file = MUST(Core::File::adopt_fd(fd, Core::File::OpenMode::Write));
-
-# if ARCH(AARCH64) && defined(AK_OS_MACOS)
- // Write a minimal Mach-O object file so objdump can disassemble it.
- struct [[gnu::packed]] {
- u32 magic = 0xFEEDFACF;
- u32 cputype = 0x0100000C; // CPU_TYPE_ARM64
- u32 cpusubtype = 0;
- u32 filetype = 1; // MH_OBJECT
- u32 ncmds = 1;
- u32 sizeofcmds = 72 + 80; // segment + section
- u32 flags = 0;
- u32 reserved = 0;
- } mach_header;
-
- struct [[gnu::packed]] {
- u32 cmd = 0x19; // LC_SEGMENT_64
- u32 cmdsize = 72 + 80;
- char segname[16] = {};
- u64 vmaddr = 0;
- u64 vmsize;
- u64 fileoff;
- u64 filesize;
- u32 maxprot = 7;
- u32 initprot = 7;
- u32 nsects = 1;
- u32 flags = 0;
- } segment;
- segment.vmsize = code_size;
- segment.fileoff = sizeof(mach_header) + sizeof(segment) + 80;
- segment.filesize = code_size;
-
- struct [[gnu::packed]] {
- char sectname[16] = "__text";
- char segname[16] = "__TEXT";
- u64 addr = 0;
- u64 size;
- u32 offset;
- u32 align = 2;
- u32 reloff = 0;
- u32 nreloc = 0;
- u32 flags = 0x80000400; // S_REGULAR | S_ATTR_PURE_INSTRUCTIONS
- u32 reserved1 = 0;
- u32 reserved2 = 0;
- u32 reserved3 = 0;
- } section;
- static_assert(sizeof(section) == 80);
- section.size = code_size;
- section.offset = static_cast<u32>(segment.fileoff);
-
- (void)tmp_file->write_until_depleted({ &mach_header, sizeof(mach_header) });
- (void)tmp_file->write_until_depleted({ &segment, sizeof(segment) });
- (void)tmp_file->write_until_depleted({ &section, sizeof(section) });
-# endif
- (void)tmp_file->write_until_depleted({ code_ptr, code_size });
- }
-#endif
-
- outln("Function #{}{} ({} bytes):", address.value(), export_name, code_size);
- fflush(stdout);
-
-#if defined(AK_OS_WINDOWS)
- auto result = Core::Process::spawn({
- .name = "ndisasm"sv,
- .executable = "ndisasm"sv,
- .search_for_executable_in_path = true,
- .arguments = Vector<ByteString> { "-b"sv, (sizeof(void*) == sizeof(u64) ? "64"sv : "32"sv), tmp_path },
- });
-#elif defined(AK_OS_MACOS)
- auto cmd = ByteString::formatted("/usr/bin/objdump -d {} | tail -n +7", tmp_path);
- auto result = Core::Process::spawn({
- .name = "sh"sv,
- .executable = "/bin/sh"sv,
- .arguments = Vector<ByteString> { "-c"sv, cmd },
- });
-#else
-# if ARCH(X86_64)
- auto cmd = ByteString::formatted("/usr/bin/objdump -D -b binary -m i386:x86-64 {} | tail -n +8", tmp_path);
-# elif ARCH(AARCH64)
- auto cmd = ByteString::formatted("/usr/bin/objdump -D -b binary -m aarch64 {} | tail -n +8", tmp_path);
-# else
- auto cmd = ByteString::formatted("/usr/bin/objdump -D -b binary {} | tail -n +8", tmp_path);
-# endif
- auto result = Core::Process::spawn({
- .name = "sh"sv,
- .executable = "/bin/sh"sv,
- .arguments = Vector<ByteString> { "-c"sv, cmd },
- });
-#endif
- if (!result.is_error())
- (void)result.release_value().wait_for_termination();
- else
- warnln("Failed to run disassembler: {}", result.error());
-
-#if defined(AK_OS_WINDOWS)
- DeleteFileA(tmp_path);
-#else
- unlink(tmp_path);
-#endif
- outln();
}
+ warnln("Missing import '{}::{}'", import.module, import.name);
+ missing = true;
}
-
- auto print_func = [&](auto const& address) {
- Wasm::FunctionInstance* fn = machine.store().get(address);
- g_stdout->write_until_depleted(ByteString::formatted("- Function with address {}, ptr = {}\n", address.value(), fn)).release_value_but_fixme_should_propagate_errors();
- if (fn) {
- g_stdout->write_until_depleted(ByteString::formatted(" wasm function? {}\n", fn->has<Wasm::WasmFunction>())).release_value_but_fixme_should_propagate_errors();
- fn->visit(
- [&](Wasm::WasmFunction const& func) {
- Wasm::Printer printer { *g_stdout, 3 };
- g_stdout->write_until_depleted(" type:\n"sv).release_value_but_fixme_should_propagate_errors();
- printer.print(func.type());
- g_stdout->write_until_depleted(" code:\n"sv).release_value_but_fixme_should_propagate_errors();
- printer.print(func.code());
- },
- [](Wasm::HostFunction const&) { });
- }
- };
- if (print) {
- // Now, let's dump the functions!
- for (auto& address : module_instance->functions()) {
- print_func(address);
- }
+ if (missing)
+ return {};
+ return imports;
+ };
+ auto instantiate = [&](Wasm::Runtime::Module const& module_to_instantiate, StringView name) -> Optional<Entity> {
+ auto imports = resolve_imports(module_to_instantiate);
+ if (!imports.has_value()) {
+ warnln("Linking {} failed", name);
+ return {};
}
+ auto instance = timed(timings.instantiation, [&] { return store.instantiate(module_to_instantiate, *imports); });
+ if (instance.is_error()) {
+ warnln("Instantiation of {} failed: {}", name, instance.error().message);
+ return {};
+ }
+ return keep(instance.value());
+ };
- if (!exported_function_to_execute.is_empty()) {
- Optional<Wasm::FunctionAddress> run_address;
- Vector<Wasm::Value> values;
- for (auto& entry : module_instance->exports()) {
- if (entry.name() == exported_function_to_execute) {
- if (auto addr = entry.value().get_pointer<Wasm::FunctionAddress>())
- run_address = *addr;
- }
- }
- if (!run_address.has_value()) {
- warnln("No such exported function, sorry :(");
- return 1;
- }
-
- auto instance = machine.store().get(*run_address);
- VERIFY(instance);
-
- if (instance->has<Wasm::HostFunction>()) {
- warnln("Exported function is a host function, cannot run that yet");
- return 1;
- }
-
- for (auto& param : instance->get<Wasm::WasmFunction>().type().parameters()) {
- if (values_to_push.is_empty()) {
- values.append(Wasm::Value(param));
- } else if (param == values_to_push.last().type) {
- values.append(values_to_push.take_last().value);
- } else {
- warnln("Type mismatch in argument: expected {}, but got {}", param.kind_name(), values_to_push.last().type.kind_name());
- return 1;
- }
- }
+ for (auto& name : modules_to_link_in) {
+ auto linked_module = timed(timings.parse, [&] { return compile(name); });
+ if (!linked_module) {
+ warnln("Failed to compile linked module '{}'", name);
+ return 1;
+ }
+ auto instance = instantiate(*linked_module, name);
+ if (!instance.has_value())
+ return 1;
+ for (auto& entry : store.instance_exports(*instance))
+ linked_exports.set(entry.name, entry.value);
+ }
- if (print) {
- outln("Executing ");
- print_func(*run_address);
- outln();
- }
+ auto instance = instantiate(*module, filename);
+ if (!instance.has_value())
+ return 1;
+ main_instance = *instance;
+ if (wasi_implementation) {
+ if (auto memory = store.find_export(main_instance, "memory"sv); memory.has_value() && memory->kind == ExternKind::Memory)
+ wasi_implementation->set_memory(memory->entity);
+ }
- Optional<Core::ElapsedTimer> execution_timer;
- if (benchmark_timings)
- execution_timer = Core::ElapsedTimer::start_new(Core::TimerType::Precise);
+ if (exported_function_to_execute.is_empty())
+ return 0;
- auto execution_result = machine.invoke(g_interpreter, run_address.value(), move(values));
+ auto function = store.find_export(main_instance, exported_function_to_execute);
+ if (!function.has_value() || function->kind != ExternKind::Function) {
+ warnln("No such exported function, sorry :(");
+ return 1;
+ }
- if (benchmark_timings)
- timings.execution.must_append(execution_timer->elapsed_time().to_seconds_f64());
+ auto type = store.function_type(function->entity);
+ Wasm::Runtime::Values values;
+ for (auto& parameter : type.parameters) {
+ if (values_to_push.is_empty()) {
+ values.append(WasmValue::default_for(parameter));
+ } else if (parameter.kind == values_to_push.last().type.kind) {
+ values.append(values_to_push.take_last().value);
+ } else {
+ warnln("Type mismatch in argument");
+ return 1;
+ }
+ }
- if (execution_result.is_trap()) {
- auto trap_reason = execution_result.trap().format();
- if (trap_reason.starts_with("exit:"sv))
- return -trap_reason.substring_view(5).to_number<i32>().value_or(-1);
- warnln("Execution trapped: {}", trap_reason);
- } else {
- if (!execution_result.values().is_empty())
- warnln("Returned:");
- auto result_type = instance->get<Wasm::WasmFunction>().type().results();
- size_t index = 0;
- for (auto& value : execution_result.values()) {
- g_stdout->write_until_depleted(" -> "sv.bytes()).release_value_but_fixme_should_propagate_errors();
- g_printer->print(value, result_type[index]);
- ++index;
- }
- }
+ auto result = timed(timings.execution, [&] { return store.invoke(function->entity, values); });
+ if (result.is_error()) {
+ if (wasi_implementation) {
+ if (auto exit_code = wasi_implementation->exit_code(); exit_code.has_value())
+ return *exit_code;
}
+ warnln("Execution trapped: {}", result.error().message);
+ return 0;
}
+ if (!result.value().is_empty())
+ warnln("Returned:");
+ for (size_t index = 0; index < result.value().size(); ++index)
+ outln(" -> {}", format_value(result.value()[index], type.results[index]));
return 0;
}