Truly independent web browser
LibWasm: Keep CalleeInstance behind the null check of its call
Andreas Kling482200622839
diff --git a/Libraries/LibWasm/JIT/ARCHITECTURE.md b/Libraries/LibWasm/JIT/ARCHITECTURE.mdindex c9c9644998f..2956d005a01 100644--- a/Libraries/LibWasm/JIT/ARCHITECTURE.md+++ b/Libraries/LibWasm/JIT/ARCHITECTURE.md@@ -95,7 +95,7 @@ truncations, unless their flags say they cannot), and are neither removed nor mo| VectorUnary, VectorBinary, VectorTernary | SIMD operations, by their sub-opcode: splats, lane-wise arithmetic, comparisons, conversions, shifts by an i32, bitselect and the relaxed multiply-adds, and reductions to an i32. || ExtractLane, ReplaceLane, Shuffle | Lane access, and `i8x16.shuffle`. || VectorLoad | A SIMD load of memory 0, by its sub-opcode (whole, extending, splatting or zero-filling); may trap. |-| CalleeInstance | The instance a call of a function passes: the header's, or the caller's for host functions. |+| CalleeInstance | The instance a call of a function passes: the header's, or the caller's for host functions. Pure only for imports, whose header is never null: a function reference may be null where the call's check does not dominate. || CheckFunction, CheckNull | The checks of `call_indirect` (null, then type identity, then the subtype check of GC types) and of references that must not be null. || Call | A call through a `FunctionHeader`, direct or not; its value is the first result. || Helper | A call of a function of the runtime, which takes its operands in the context and may return a trap code. |diff --git a/Libraries/LibWasm/JIT/src/builder/calls.rs b/Libraries/LibWasm/JIT/src/builder/calls.rsindex 09da3347c0b..b39784d3275 100644--- a/Libraries/LibWasm/JIT/src/builder/calls.rs+++ b/Libraries/LibWasm/JIT/src/builder/calls.rs@@ -12,7 +12,7 @@//! they get the caller's, through which their stub finds the runtime.use super::{Builder, instance_offset, ir_type};-use crate::ir::{Func, NONE, Node, Op, Type, Value};+use crate::ir::{FLAG_NOT_NULL, Func, NONE, Node, Op, Type, Value};use libwasm_module::Module;use libwasm_module::abi::{InstanceData, TRAP_NULL_REFERENCE, TRAP_UNDEFINED_ELEMENT, TRAP_UNINITIALIZED_ELEMENT};use libwasm_module::types::FuncType;@@ -73,7 +73,7 @@ impl Builder {let ty = module.function_type(function).expect("functions have function types");let header = self.instance_pointer(func, offset_of!(InstanceData, functions), function, Type::Pointer);let (instance, memory_base) = if function < module.imported_function_count {- self.callee_instance(func, header)+ self.callee_instance(func, header, true)} else {(self.instance, self.memory_base)};@@ -112,7 +112,7 @@ impl Builder {[element, identity, 0],),);- let (instance, memory_base) = self.callee_instance(func, element);+ let (instance, memory_base) = self.callee_instance(func, element, false);self.emit_call(func, ty, [element, instance, memory_base], NONE, kind);}@@ -125,16 +125,24 @@ impl Builder {func,Node::new(Op::CheckNull, Type::None, TRAP_NULL_REFERENCE as u8, [reference, 0, 0]),);- let (instance, memory_base) = self.callee_instance(func, reference);+ let (instance, memory_base) = self.callee_instance(func, reference, false);self.emit_call(func, ty, [reference, instance, memory_base], NONE, kind);}- /// The instance and memory base a call of the function whose header is `header` passes.- fn callee_instance(&mut self, func: &mut Func, header: Value) -> (Value, Value) {- let instance = self.pure(- func,- Node::new(Op::CalleeInstance, Type::Pointer, 0, [header, self.instance, 0]),+ /// The instance and memory base a call of the function whose header is `header` passes. Only a header that is+ /// never null is value numbered: any other is read where the call's null check guards it.+ fn callee_instance(&mut self, func: &mut Func, header: Value, not_null: bool) -> (Value, Value) {+ let node = Node::new(+ Op::CalleeInstance,+ Type::Pointer,+ if not_null { FLAG_NOT_NULL } else { 0 },+ [header, self.instance, 0],);+ let instance = if not_null {+ self.pure(func, node)+ } else {+ Self::append(func, node)+ };let memory_base = self.pure(func,Node::new(diff --git a/Libraries/LibWasm/JIT/src/ir/mod.rs b/Libraries/LibWasm/JIT/src/ir/mod.rsindex 6118f987e36..c317657f605 100644--- a/Libraries/LibWasm/JIT/src/ir/mod.rs+++ b/Libraries/LibWasm/JIT/src/ir/mod.rs@@ -444,6 +444,9 @@ pub const FLAG_CANNOT_TRAP: u8 = 0x80;/// `Node::flags` bit of `GlobalGet` for globals no code can change.pub const FLAG_IMMUTABLE: u8 = 0x40;+/// `Node::flags` bit of `CalleeInstance` for a header that is never null, like an imported function's.+pub const FLAG_NOT_NULL: u8 = 0x40;+/// `Node::flags` bits of `CheckedAddress`, besides log2 of the access size in the low bits: an atomic access, which/// must be aligned, and an access of a memory64, whose index and offset may add up past 2^64.pub const CHECKED_ATOMIC: u8 = 0x08;@@ -733,8 +736,10 @@ ops! {// Calls./// args: callee FunctionHeader, the calling instance. The callee's instance: its function header's, or for a host- /// function, which has none, the caller's, through which its stub finds the runtime.- CalleeInstance: Fixed(2), Pure, "callee_instance";+ /// function, which has none, the caller's, through which its stub finds the runtime; flags: FLAG_NOT_NULL. Pure+ /// only with FLAG_NOT_NULL: a function reference may be null anywhere the null check that guards its call does+ /// not dominate, and a pure node could be hoisted above that check and fault instead of trapping.+ CalleeInstance: Fixed(2), Read, "callee_instance";/// args: function reference, the type identity it must have; flags: the TRAP_* code for null. Traps unless the/// reference is not null and of that type or a subtype.CheckFunction: Fixed(2), Write, "check_function";@@ -817,6 +822,7 @@ impl Node {pub fn effect(&self) -> Effect {match self.op {Op::GlobalGet if self.flags & FLAG_IMMUTABLE != 0 => Effect::Pure,+ Op::CalleeInstance if self.flags & FLAG_NOT_NULL != 0 => Effect::Pure,Op::DivS | Op::DivU | Op::RemS | Op::RemU | Op::TruncS | Op::TruncUif self.flags & FLAG_CANNOT_TRAP != 0 =>{diff --git a/Libraries/LibWasm/JIT/tests/tail_call_ref_loop.rs b/Libraries/LibWasm/JIT/tests/tail_call_ref_loop.rsnew file mode 100644index 00000000000..ae3d5a1cd45--- /dev/null+++ b/Libraries/LibWasm/JIT/tests/tail_call_ref_loop.rs@@ -0,0 +1,46 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A loop whose only call is a `return_call_ref` of a null reference (`tail-call-ref-loop.wat` of the engine's+//! tests), compiled in full with loop invariant code motion, as the runtime's tier-up compiles do but its OSR compiles+//! do not. Reading the callee's instance out of the null reference's header anywhere its null check does not guard+//! faults: the loop must run where it does not call, and the call must trap as null.++#![cfg(any(target_arch = "x86_64", all(target_arch = "aarch64", not(windows))))]++mod harness;++use harness::{CompiledModule, Outcome, TestBinding};+use libwasm_engine::abi::TRAP_NULL_REFERENCE;+use libwasm_engine::runtime::{ExternValue, Store, Value};+use std::sync::Arc;++#[test]+fn a_tail_call_ref_in_a_loop_reads_its_callee_behind_its_null_check() {+ let path =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../Tests/Fixtures/Modules/tail-call-ref-loop.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()+ };+ assert!(!options.no_licm);+ let mut store = Store::new();+ let instance = store.instantiate(module.clone(), &[]).unwrap();+ let Some(ExternValue::Function(run)) = store.instance(instance).export("run") else {+ panic!("no run export");+ };+ let run = harness::function_index(&store, run, instance).unwrap();+ let compiled = CompiledModule::compile(module.clone(), options);+ assert!(compiled.runnable[run as usize], "{:?}", compiled.failures[run as usize]);+ let mut binding = TestBinding::new(&compiled, &store, instance);+ let mut call = |call: i32| binding.call(&mut store, &compiled, run, &[Value::I32(call), Value::I32(10)]);+ assert_eq!(call(0), Outcome::Values(vec![Value::I32(7)]));+ assert_eq!(call(1), Outcome::Trap(TRAP_NULL_REFERENCE));+ }+}diff --git a/Libraries/LibWasm/Tests/Executor/test-tail-call-ref-loop.js b/Libraries/LibWasm/Tests/Executor/test-tail-call-ref-loop.jsnew file mode 100644index 00000000000..d4cdbd4afad--- /dev/null+++ b/Libraries/LibWasm/Tests/Executor/test-tail-call-ref-loop.js@@ -0,0 +1,10 @@+// The callee's instance of a `return_call_ref` in a loop that makes no other call is read behind the reference's+// null check, so the loop runs, and calling the null reference traps, in whichever tier runs it (see+// tail-call-ref-loop.wat). The long loops are there to have the function compiled when the JIT tiers up.+test("a loop that does not take its return_call_ref does not read the callee", () => {+ const module = parseWebAssemblyModule(readBinaryWasmFile("Fixtures/Modules/tail-call-ref-loop.wasm"));+ const run = module.getExport("run");++ for (let round = 0; round < 3; ++round) expect(module.invoke(run, 0, 100000)).toBe(7);+ expect(() => module.invoke(run, 1, 100000)).toThrowWithMessage(TypeError, "Execution trapped: null reference");+});diff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.wasm b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.wasmnew file mode 100644index 00000000000..68420554363Binary files /dev/null and b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.wasm differdiff --git a/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.wat b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.watnew file mode 100644index 00000000000..ae3c603c1d5--- /dev/null+++ b/Libraries/LibWasm/Tests/Fixtures/Modules/tail-call-ref-loop.wat@@ -0,0 +1,15 @@+;; A loop whose only call is a `return_call_ref` of a null reference, on a path that the loop takes only if `$call`+;; is nonzero. Everything the tail call needs must stay behind its null check, even though the loop never calls a+;; function and returns to its header: reading the null reference's header anywhere else would fault.+(module+ (type $t (func (result i32)))+ (global $g (mut (ref null $t)) (ref.null $t))+ (func (export "run") (param $call i32) (param $count i32) (result i32)+ (local $r (ref null $t))+ (local $i i32)+ (local.set $r (global.get $g))+ (loop $l+ (if (local.get $call) (then (return_call_ref $t (local.get $r))))+ (local.set $i (i32.add (local.get $i) (i32.const 1)))+ (br_if $l (i32.lt_u (local.get $i) (local.get $count))))+ (i32.const 7)))