Skip to content

Truly independent web browser

LibWeb: Keep small numeric WebAssembly calls on the stack

Timothy Flynn869c8b475f53
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
index 45eda9caf73..694b0d9f2b1 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
@@ -22,7 +22,7 @@ use libwasm_engine::runtime::heap::Visitor as StoreVisitor;
use libwasm_engine::runtime::{
FunctionAddress, FunctionInstance, FunctionKind, HostCallback, HostFunction, Store, Trap, Value as WasmValue,
};
-use libwasm_engine::types::FuncType;
+use libwasm_engine::types::{FuncType, ValType};
use crate::web_assembly::exception::Exception;
use crate::web_assembly::values::{
@@ -36,8 +36,11 @@ use crate::web_assembly::{
struct ExportedFunction {
function: EntityRef<FunctionInstance>,
ty: FuncType,
+ use_stack_slots: bool,
}
+const STACK_SLOT_CAPACITY: usize = 8;
+
// SAFETY: The type holds no cells, so the function is the one cell the slots reach.
unsafe impl Trace for ExportedFunction {
fn trace(&self, visitor: &mut Visitor) {
@@ -83,6 +86,14 @@ pub(crate) fn create_exported_function(vm: &Vm, realm: Gc<Realm>, function: Func
let ty = store.function(function).ty.clone();
let arity = ty.params.len() as i32;
let name = name_of_webassembly_function(store, function);
+ let use_stack_slots = matches!(store.function(function).kind, FunctionKind::Wasm { .. })
+ && ty.params.len() <= STACK_SLOT_CAPACITY
+ && ty.results.len() <= STACK_SLOT_CAPACITY
+ && ty
+ .params
+ .iter()
+ .chain(&ty.results)
+ .all(|ty| matches!(ty, ValType::I32 | ValType::I64 | ValType::F32 | ValType::F64));
// NB: The function has its name on call stacks too, as a HostFunction of the C++ API would.
let object = NativeFunction::create_with_name(
@@ -92,6 +103,7 @@ pub(crate) fn create_exported_function(vm: &Vm, realm: Gc<Realm>, function: Func
ExportedFunction {
function: EntityRef(function),
ty,
+ use_stack_slots,
},
|vm: &Vm, function: &ExportedFunction| call_an_exported_function(vm, function),
);
@@ -117,6 +129,31 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
results,
} = &function.ty;
+ // Numeric values need no GC roots. Keep small signatures on the stack and pass their slots directly to the
+ // engine, avoiding the traced containers and temporary vectors of the general path. Convert arguments in
+ // JavaScript order even though the engine's operand stack stores them in reverse order: conversion can run JS.
+ if function.use_stack_slots {
+ let mut argument_slots = [0; STACK_SLOT_CAPACITY];
+ for (i, &ty) in parameters.iter().enumerate() {
+ let value = to_webassembly_value(vm, vm.argument(i), ty)?;
+ argument_slots[parameters.len() - i - 1] = value.to_slots().0[0];
+ }
+ let mut result_slots = [0; STACK_SLOT_CAPACITY];
+ Agent::the(vm)
+ .store()
+ .invoke_slots(
+ function.function.0,
+ &argument_slots[..parameters.len()],
+ &mut result_slots[..results.len()],
+ )
+ .map_err(|trap| throw_of_trap(vm, trap))?;
+ let mut values = [WasmValue::I32(0); STACK_SLOT_CAPACITY];
+ for (i, &ty) in results.iter().enumerate() {
+ values[i] = WasmValue::from_slots(ty, &result_slots[results.len() - i - 1..]);
+ }
+ return results_to_js_value(vm, &values[..results.len()], results);
+ }
+
// 4. If any type in parameters or results matches v128 or exnref, throw a TypeError.
// Note: the above error is thrown each time the [[Call]] method is invoked.
if parameters.iter().chain(results).any(|&ty| matches_v128_or_exnref(ty)) {
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-numeric-call-conversions.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-numeric-call-conversions.txt
new file mode 100644
index 00000000000..effe0429b28
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-numeric-call-conversions.txt
@@ -0,0 +1,11 @@
+conversion order: 0, 1, 2, 3, 4, 5, 6, 7
+mixed results: true
+conversion exception: true
+import exception: true
+empty result: undefined
+missing integer: 0
+missing float: true
+invalid BigInt: TypeError
+extra argument: 42
+wide results: 1, 2, 3, 4, 5, 6, 7, 8, 9
+reference result: true
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-numeric-call-conversions.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-numeric-call-conversions.html
new file mode 100644
index 00000000000..fe52f0e15df
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-numeric-call-conversions.html
@@ -0,0 +1,66 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // Build (module (type (func (param T...) (result T...))) (type (func))
+ // (import "m" "hook" (func (type 1)))
+ // (func (export "echo") (type 0) (call 0) (local.get 0) ...)).
+ // These small sections and indices fit in single-byte LEB128 values.
+ function echoFunction(types, hook = () => {}) {
+ const section = (id, bytes) => [id, bytes.length, ...bytes];
+ const body = [0, 0x10, 0, ...types.flatMap((_, i) => [0x20, i]), 0x0b];
+ const bytes = new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0,
+ ...section(1, [2, 0x60, types.length, ...types, types.length, ...types, 0x60, 0, 0]),
+ ...section(2, [1, 1, 109, 4, 104, 111, 111, 107, 0, 1]),
+ ...section(3, [1, 0]),
+ ...section(7, [1, 4, 101, 99, 104, 111, 0, 1]),
+ ...section(10, [1, body.length, ...body]),
+ ]);
+ return new WebAssembly.Instance(new WebAssembly.Module(bytes), { m: { hook } }).exports.echo;
+ }
+
+ test(() => {
+ const i32 = 0x7f, i64 = 0x7e, f32 = 0x7d, f64 = 0x7c;
+ const mixed = echoFunction([i32, i64, f32, f64, i32, i64, f32, f64], () => internals.gc());
+ const inputs = [4294967297, (1n << 64n) + 2n, 1 / 3, -0, -3, -4n, Infinity, NaN];
+ const expected = [1, 2n, Math.fround(1 / 3), -0, -3, -4n, Infinity, NaN];
+ const order = [];
+ const converted = inputs.map((value, index) => ({
+ valueOf() {
+ order.push(index);
+ internals.gc();
+ // Reenter wasm while the outer call is still converting its arguments.
+ if (echoFunction([i32])(17) !== 17)
+ throw new Error("reentry failed");
+ return value;
+ },
+ }));
+ const result = mixed(...converted);
+ println(`conversion order: ${order.join(", ")}`);
+ println(`mixed results: ${result.every((v, i) => Object.is(v, expected[i]))}`);
+
+ const sentinel = {};
+ try {
+ mixed(1, { valueOf() { throw sentinel; } }, { valueOf() { throw new Error("unreachable"); } });
+ } catch (e) {
+ println(`conversion exception: ${e === sentinel}`);
+ }
+ try {
+ echoFunction([], () => { throw sentinel; })();
+ } catch (e) {
+ println(`import exception: ${e === sentinel}`);
+ }
+ println(`empty result: ${echoFunction([])()}`);
+ println(`missing integer: ${echoFunction([i32])()}`);
+ println(`missing float: ${Number.isNaN(echoFunction([f64])())}`);
+ try {
+ echoFunction([i64])(1);
+ } catch (e) {
+ println(`invalid BigInt: ${e.name}`);
+ }
+ println(`extra argument: ${echoFunction([i32])(42, { valueOf() { throw sentinel; } })}`);
+ println(`wide results: ${echoFunction(Array(9).fill(i32))(1, 2, 3, 4, 5, 6, 7, 8, 9).join(", ")}`);
+ const object = {};
+ println(`reference result: ${echoFunction([0x6f], () => internals.gc())(object) === object}`);
+ });
+</script>