A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix a possible panic with small stacks and Pulley (#14757)
Alex Crichtond4fb9b08426a
diff --git a/crates/wasmtime/src/runtime/vm/interpreter.rs b/crates/wasmtime/src/runtime/vm/interpreter.rsindex 97ed6bc5b8..39045ffb76 100644--- a/crates/wasmtime/src/runtime/vm/interpreter.rs+++ b/crates/wasmtime/src/runtime/vm/interpreter.rs@@ -229,8 +229,20 @@ impl InterpreterRef<'_> {// this function's contract, and Wasm is currently// executing so no other borrows of its store are// active.- bytecode = unsafe { self.trap(pc, kind, caller) };- vm = self.vm();+ match unsafe { self.trap(pc, kind, caller) } {+ Some(resume) => {+ bytecode = resume;+ vm = self.vm();+ }+ // There's no handler to resume at, so return to the+ // host directly indicating that the call failed due to+ // a trap (recorded in TLS).+ None => {+ vm = self.vm();+ let _ = unsafe { vm.call_end(old_lr, []) };+ break false;+ }+ }}}};@@ -460,6 +472,11 @@ impl InterpreterRef<'_> {/// in TLS by reading the pc/fp of the interpreter and seeing if that's a/// valid opcode to trap at.///+ /// Returns the pc to resume at, which is the entry trampoline's trap+ /// handler, or `None` if the entry trampoline itself trapped before it set+ /// up that handler, in which case the interpreter should return directly+ /// to the host.+ ////// Trap codes are looked up in the module registry of the store that/// `caller` belongs to, rather than in any process-global state.///@@ -474,7 +491,7 @@ impl InterpreterRef<'_> {pc: NonNull<u8>,kind: Option<TrapKind>,caller: NonNull<VMContext>,- ) -> NonNull<u8> {+ ) -> Option<NonNull<u8>> {// Pulley checks for stack overflow whenever the stack pointer is// decremented, including in the `push_frame` and `push_frame_save`// instructions at the start of a function. A stack overflow there@@ -531,6 +548,17 @@ impl InterpreterRef<'_> {}}};++ // If the trapping function was called directly by the host then it's+ // the entry trampoline, and the only way it can trap is a stack+ // overflow before it has pushed its frame. It hasn't set up its trap+ // handler, and this activation has no Wasm frames for the backtrace, so+ // record the trap and return to the host directly.+ if lr.is_some() && self.vm().lr_is_host_return() {+ tls::with(|s| s.unwrap().record_jit_trap(regs.pc, None, trap, None));+ return None;+ }+let handler = tls::with(|s| {let s = s.unwrap();s.set_jit_trap(regs, None, trap);@@ -539,7 +567,7 @@ impl InterpreterRef<'_> {unsafe {self.resume_to_exception_handler(&handler, 0, 0);}- self.take_resume_at_pc()+ Some(self.take_resume_at_pc())}fn take_resume_at_pc(&mut self) -> NonNull<u8> {diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rsindex f828a00846..60ee369f68 100644--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs@@ -1114,20 +1114,31 @@ impl CallThreadState {}_ => pc,};+ self.record_jit_trap(pc, faulting_addr, trap, Some((backtrace_pc, fp)));+ }++ /// Records a trap at `pc`, capturing a backtrace starting from+ /// `backtrace_pc_and_fp` in the current activation.+ ///+ /// If `backtrace_pc_and_fp` is `None` then the current activation has no+ /// Wasm frames, and only older activations are included in the backtrace.+ pub(crate) fn record_jit_trap(+ &self,+ pc: usize,+ faulting_addr: Option<usize>,+ trap: wasmtime_environ::CompiledTrap,+ backtrace_pc_and_fp: Option<(usize, usize)>,+ ) {let mut unwind = UnwindReason::from(TrapReason::Jit {pc,faulting_addr,trap,});if let UnwindReason::Trap(Ok(trap)) = &mut unwind {- trap.backtrace = self.capture_backtrace(- self.vm_store_context.get().as_ptr(),- Some((backtrace_pc, fp)),- );- trap.coredumpstack = self.capture_coredump(- self.vm_store_context.get().as_ptr(),- Some((backtrace_pc, fp)),- );+ trap.backtrace =+ self.capture_backtrace(self.vm_store_context.get().as_ptr(), backtrace_pc_and_fp);+ trap.coredumpstack =+ self.capture_coredump(self.vm_store_context.get().as_ptr(), backtrace_pc_and_fp);}self.record_unwind(unwind);}diff --git a/pulley/src/interp.rs b/pulley/src/interp.rsindex 5b3f794453..8973a9fd8f 100644--- a/pulley/src/interp.rs+++ b/pulley/src/interp.rs@@ -204,6 +204,12 @@ impl Vm {self.state.lr}+ /// Returns whether the current `lr` register value is the return address+ /// to the host that [`Vm::call_start`] installs.+ pub fn lr_is_host_return(&self) -> bool {+ self.state.lr == HOST_RETURN_ADDR+ }+/// Sets the current `fp` register value.pub unsafe fn set_fp(&mut self, fp: *mut u8) {self.state.fp = fp;diff --git a/tests/all/stack_overflow.rs b/tests/all/stack_overflow.rsindex 1e6ececa2a..999c6d0a73 100644--- a/tests/all/stack_overflow.rs+++ b/tests/all/stack_overflow.rs@@ -181,3 +181,27 @@ fn infinite_wasm_stack_does_not_panic() -> Result<()> {func.call(&mut store, ())?;Ok(())}++// Try to execute on some tiny stacks. This should either succeed or fail with a+// stack overflow, nothing else.+#[wasmtime_test]+fn tiny_wasm_stack_traps_on_entry(config: &mut Config) -> Result<()> {+ for size in (0..=10).map(|i| 1 << i) {+ config.max_wasm_stack(size);+ let engine = Engine::new(config)?;+ let mut store = Store::new(&engine, ());+ let module = Module::new(+ &engine,+ r#"(module (func (export "f") (result i32) i32.const 1))"#,+ )?;+ let instance = Instance::new(&mut store, &module, &[])?;+ let func = instance.get_typed_func::<(), i32>(&mut store, "f")?;+ for _ in 0..2 {+ match func.call(&mut store, ()) {+ Ok(n) => assert_eq!(n, 1),+ Err(e) => assert_eq!(e.downcast_ref::<Trap>(), Some(&Trap::StackOverflow)),+ }+ }+ }+ Ok(())+}