Truly independent web browser
LibWasm: Use inline struct data offsets in the JIT only for final types
Tim Ledbetter5c52b75f7ff4
diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex d977e002593..a78da975751 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -284,8 +284,9 @@ unshared memory traps, and notifying one wakes nobody, without a call.**GC** (`builder/gc.rs`). Objects are cells of the runtime's heap: the Rtt first, the address of thedata, an array's length, then the data inline if it has at most 4096 bytes. A struct's fields are atconstant offsets (8 bytes each, 16 for v128, packed and 32-bit values zero-extended in their word), so-`struct.get` is a null check and a load at the object plus the field's offset; a large struct's data-is reached through its address first. `array.get` and `array.set` access the element at its+`struct.get` is a null check and a load at the object plus the field's offset; a large struct's data,+or the data of any struct accessed through a type that is not final, is reached through its address+first. `array.get` and `array.set` access the element at its`ElementAddress`. Allocation, filling, copying and initializing from segments call the runtime(`Helper`); the allocation traps with `TRAP_RUNTIME` where the runtime returns null. `ref.test`,`ref.cast`, `br_on_cast` and `br_on_cast_fail` are a `RefTest`: abstract heap types test thediff --git a/Libraries/LibWasm/JIT/src/builder/gc.rs b/Libraries/LibWasm/JIT/src/builder/gc.rsindex e2c004f42d8..9384588df03 100644--- a/Libraries/LibWasm/JIT/src/builder/gc.rs+++ b/Libraries/LibWasm/JIT/src/builder/gc.rs@@ -9,8 +9,8 @@//! Objects are cells of the runtime's heap (see `abi::Rtt`): the Rtt first, the data's address at OBJECT_DATA_OFFSET//! and an array's length at OBJECT_LENGTH_OFFSET. Data of up to `MAX_INLINE_DATA_SIZE` bytes is inline at//! OBJECT_INLINE_DATA_OFFSET, so a struct's fields are at constant offsets from the object where the struct is small-//! enough. Fields take `StorageType::object_field_size()` bytes, with packed and 32-bit values zero-extended in them:-//! the runtime's layout, which `abi` and `types` define for both.+//! enough and its type is final. Fields take `StorageType::object_field_size()` bytes, with packed and 32-bit values+//! zero-extended in them: the runtime's layout, which `abi` and `types` define for both.//!//! GC references in compiled frames need nothing special: the collector scans the stack conservatively and recognizes//! pointers into cells, and every allocation is a call of the runtime, around which values live in stack slots or in@@ -103,10 +103,19 @@ impl Builder {)}+ /// The size of the data of every struct that a reference to the module's struct type `type_index` can refer to.+ fn struct_data_size(&mut self, module: &Module, type_index: u32) -> Option<u32> {+ if !module.types[type_index as usize].is_final {+ return None;+ }+ let count = struct_fields(module, type_index).len() as u32;+ Some(self.field_offset(module, type_index, count))+ }+/// Where the data of an object with `size` bytes of it is: the object and the offset of its inline data, or the- /// address of data outside the heap.- fn object_data(func: &mut Func, object: Value, size: u32) -> (Value, u32) {- if size as usize <= MAX_INLINE_DATA_SIZE {+ /// address of its data.+ fn object_data(func: &mut Func, object: Value, size: Option<u32>) -> (Value, u32) {+ if size.is_some_and(|size| size as usize <= MAX_INLINE_DATA_SIZE) {return (object, OBJECT_INLINE_DATA_OFFSET as u32);}let data = Self::append(@@ -260,7 +269,7 @@ impl Builder {let zero = self.constant(func, Type::I64, 0);let object = self.allocate(func, first, size_value, zero);if !values.is_empty() {- let (base, data_offset) = Self::object_data(func, object, size);+ let (base, data_offset) = Self::object_data(func, object, Some(size));for (index, &value) in values.iter().enumerate() {if self.is_zero(func, value) {continue;@@ -275,8 +284,7 @@ impl Builder {STRUCT_GET | STRUCT_GET_S | STRUCT_GET_U => {let object = func.resolve(self.pop());Self::check_null(func, object);- let count = struct_fields(module, first).len() as u32;- let size = self.field_offset(module, first, count);+ let size = self.struct_data_size(module, first);let (base, data_offset) = Self::object_data(func, object, size);let offset = data_offset + self.field_offset(module, first, second);let storage = struct_fields(module, first)[second as usize].storage;@@ -287,8 +295,7 @@ impl Builder {let value = self.pop();let object = func.resolve(self.pop());Self::check_null(func, object);- let count = struct_fields(module, first).len() as u32;- let size = self.field_offset(module, first, count);+ let size = self.struct_data_size(module, first);let (base, data_offset) = Self::object_data(func, object, size);let offset = data_offset + self.field_offset(module, first, second);let storage = struct_fields(module, first)[second as usize].storage;@@ -322,7 +329,7 @@ impl Builder {let size = self.constant(func, Type::I64, u64::from(data_size));let length = self.constant(func, Type::I64, u64::from(second));let array = self.allocate(func, first, size, length);- let (base, data_offset) = Self::object_data(func, array, data_size);+ let (base, data_offset) = Self::object_data(func, array, Some(data_size));for (index, &value) in values.iter().enumerate() {if self.is_zero(func, value) {continue;diff --git a/Libraries/LibWasm/JIT/tests/struct_supertype_access.rs b/Libraries/LibWasm/JIT/tests/struct_supertype_access.rsnew file mode 100644index 00000000000..3cabe05ce15--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/struct_supertype_access.rs@@ -0,0 +1,68 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Struct accesses through a supertype that is not final, compiled in full, on an object of a subtype whose data is+//! outside the heap.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use harness::{CompiledModule, Outcome, TestBinding};+use libwasm_engine::runtime::{ExternValue, Store, Value};+use std::sync::Arc;++#[test]+fn struct_accesses_through_a_supertype_that_is_not_final_reach_the_data_of_a_subtype() {+ let path =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../Tests/Fixtures/Modules/struct-supertype-access.wasm");+ let module = Arc::new(libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap());+ for stress_registers in [false, true] {+ let options = libwasm_jit::Options {+ verify_ir: true,+ stress_registers,+ ..Default::default()+ };+ let mut store = Store::new();+ let instance = store.instantiate(module.clone(), &[]).unwrap();+ let function = |store: &Store, name: &str| {+ let Some(ExternValue::Function(address)) = store.instance(instance).export(name) else {+ panic!("no {name} export");+ };+ harness::function_index(store, address, instance).unwrap()+ };+ let (allocate, get, set) = (+ function(&store, "allocate"),+ function(&store, "get"),+ function(&store, "set"),+ );+ let compiled = CompiledModule::compile(module.clone(), options);+ for index in [allocate, get, set] {+ assert!(+ compiled.runnable[index as usize],+ "{:?}",+ compiled.failures[index as usize]+ );+ }+ let mut binding = TestBinding::new(&compiled, &store, instance);+ assert_eq!(+ binding.call(&mut store, &compiled, allocate, &[]),+ Outcome::Values(vec![])+ );+ assert_eq!(+ binding.call(&mut store, &compiled, get, &[Value::I32(10)]),+ Outcome::Values(vec![Value::I64(100)])+ );+ assert_eq!(+ binding.call(&mut store, &compiled, set, &[Value::I64(100), Value::I32(10)]),+ Outcome::Values(vec![Value::I64(406)])+ );+ assert_eq!(+ binding.call(&mut store, &compiled, get, &[Value::I32(1)]),+ Outcome::Values(vec![Value::I64(406)])+ );+ }+}diff --git a/Libraries/LibWasm/Tests/Executor/test-struct-supertype-access.js b/Libraries/LibWasm/Tests/Executor/test-struct-supertype-access.jsnew file mode 100644index 00000000000..df5ee65fc8a--- /dev/null+++ b/Libraries/LibWasm/Tests/Executor/test-struct-supertype-access.js@@ -0,0 +1,13 @@+const module = parseWebAssemblyModule(readBinaryWasmFile("Fixtures/Modules/struct-supertype-access.wasm"));+const call = (name, ...args) => module.invoke(module.getExport(name), ...args);++test("struct.get through a supertype reads the subtype's data", () => {+ call("allocate");+ for (let round = 0; round < 3; ++round) expect(call("get", 100000)).toBe(1000000n);+});++test("struct.set through a supertype writes the subtype's data", () => {+ call("allocate");+ for (let round = 0; round < 3; ++round)+ expect(call("set", BigInt(round * 100), 100000)).toBe(BigInt(round * 400 + 6));+});diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.wasmnew file mode 100644index 00000000000..0a87f76c4c6Binary files /dev/null and b/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.wasm differdiff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.watnew file mode 100644index 00000000000..affc9aea62d--- /dev/null+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/struct-supertype-access.wat@@ -0,0 +1,64 @@+(module+ (type $small (sub (struct (field (mut i64)) (field (mut i64)) (field (mut i64)) (field (mut i64)))))+ (type $large (sub $small (struct+ (field (mut i64)) (field (mut i64)) (field (mut i64)) (field (mut i64))+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128 v128)+ (field v128 v128 v128 v128 v128))))++ (global $object (mut (ref null $small)) (ref.null $small))+ (global $neighbor (mut (ref null $small)) (ref.null $small))++ (func (export "allocate")+ (local $object (ref null $large))+ (local.set $object (struct.new_default $large))+ (struct.set $large 0 (local.get $object) (i64.const 1))+ (struct.set $large 1 (local.get $object) (i64.const 2))+ (struct.set $large 2 (local.get $object) (i64.const 3))+ (struct.set $large 3 (local.get $object) (i64.const 4))+ (global.set $object (local.get $object))+ (global.set $neighbor (struct.new_default $large)))++ (func (export "get") (param $count i32) (result i64)+ (local $i i32)+ (local $sum i64)+ (loop $again+ (local.set $sum+ (i64.add (local.get $sum)+ (i64.add+ (i64.add (struct.get $small 0 (global.get $object)) (struct.get $small 1 (global.get $object)))+ (i64.add (struct.get $small 2 (global.get $object)) (struct.get $small 3 (global.get $object))))))+ (local.set $i (i32.add (local.get $i) (i32.const 1)))+ (br_if $again (i32.lt_u (local.get $i) (local.get $count))))+ (local.get $sum))++ (func (export "set") (param $value i64) (param $count i32) (result i64)+ (local $i i32)+ (local $object (ref null $large))+ (local $neighbor (ref null $large))+ (loop $again+ (struct.set $small 0 (global.get $object) (local.get $value))+ (struct.set $small 1 (global.get $object) (i64.add (local.get $value) (i64.const 1)))+ (struct.set $small 2 (global.get $object) (i64.add (local.get $value) (i64.const 2)))+ (struct.set $small 3 (global.get $object) (i64.add (local.get $value) (i64.const 3)))+ (local.set $i (i32.add (local.get $i) (i32.const 1)))+ (br_if $again (i32.lt_u (local.get $i) (local.get $count))))+ (local.set $object (ref.cast (ref $large) (global.get $object)))+ (local.set $neighbor (ref.cast (ref $large) (global.get $neighbor)))+ (i64.add+ (i64.add+ (i64.add (struct.get $large 0 (local.get $object)) (struct.get $large 1 (local.get $object)))+ (i64.add (struct.get $large 2 (local.get $object)) (struct.get $large 3 (local.get $object))))+ (i64.add+ (i64.add (struct.get $large 0 (local.get $neighbor)) (struct.get $large 1 (local.get $neighbor)))+ (i64.add (struct.get $large 2 (local.get $neighbor)) (struct.get $large 3 (local.get $neighbor)))))))