Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Fix stack walking from host functions `Func::call`ed from other host functions (#14551)

Nick Fitzgerald8357058e4978
diff --git a/crates/wasmtime/src/runtime/func.rs b/crates/wasmtime/src/runtime/func.rs
index b1caec85d5..f4ceb3f36b 100644
--- a/crates/wasmtime/src/runtime/func.rs
+++ b/crates/wasmtime/src/runtime/func.rs
@@ -1594,17 +1594,20 @@ impl EntryStoreContext {
let stack_chain =
mem::replace(&mut *vm_store_context.stack_chain.get(), new_stack_chain);
+ // Zero these out, rather than leave the previous activation's
+ // values behind, so that if we call into a host function callee
+ // (which never runs an entry trampoline to overwrite them) and it
+ // walks the stack, we don't see these values both while walking
+ // activations and in the saved state.
+ let take = |field: &core::cell::UnsafeCell<usize>| mem::replace(&mut *field.get(), 0);
+
Self {
stack_limit,
- last_wasm_exit_pc: *(*vm_store_context).last_wasm_exit_pc.get(),
- last_wasm_exit_trampoline_fp: *(*vm_store_context)
- .last_wasm_exit_trampoline_fp
- .get(),
- last_wasm_entry_fp: *(*vm_store_context).last_wasm_entry_fp.get(),
- last_wasm_entry_sp: *(*vm_store_context).last_wasm_entry_sp.get(),
- last_wasm_entry_trap_handler: *(*vm_store_context)
- .last_wasm_entry_trap_handler
- .get(),
+ last_wasm_exit_pc: take(&vm_store_context.last_wasm_exit_pc),
+ last_wasm_exit_trampoline_fp: take(&vm_store_context.last_wasm_exit_trampoline_fp),
+ last_wasm_entry_fp: take(&vm_store_context.last_wasm_entry_fp),
+ last_wasm_entry_sp: take(&vm_store_context.last_wasm_entry_sp),
+ last_wasm_entry_trap_handler: take(&vm_store_context.last_wasm_entry_trap_handler),
stack_chain,
vm_store_context,
}
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rs
index 7ea34b1473..41bea9418f 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs
@@ -1318,6 +1318,13 @@ pub(crate) mod tls {
let mut ptr = self.state;
unsafe {
while let Some(state) = ptr.as_ref() {
+ ptr = state.prev.get();
+
+ // Skip activations that entered no Wasm.
+ if state.old_last_wasm_exit_pc() == 0 {
+ continue;
+ }
+
let _ = wasmtime_unwinder::visit_frames::<()>(
unwind,
state.old_last_wasm_exit_pc(),
@@ -1328,8 +1335,6 @@ pub(crate) mod tls {
core::ops::ControlFlow::Continue(())
},
);
-
- ptr = state.prev.get();
}
}
}
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
index ce154cfed0..aac34a4b06 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
@@ -238,6 +238,10 @@ impl Backtrace {
// chain. This is justified because only the most recent execution of
// wasm may execute off the initial stack (see comments in
// `wasmtime::invoke_wasm_and_catch_traps` for details).
+ //
+ // An activation with a zero PC entered no Wasm (e.g. `Func::call` of a
+ // host function) and is skipped, but older activations may still hold
+ // Wasm frames.
let activations =
core::iter::once((stack_chain, last_wasm_exit_pc, last_wasm_exit_fp, unsafe {
*(*vm_store_context).last_wasm_entry_fp.get()
@@ -245,7 +249,6 @@ impl Backtrace {
.chain(
state
.iter()
- .flat_map(|state| state.iter())
.filter(|state| {
core::ptr::eq(vm_store_context, state.vm_store_context.get().as_ptr())
})
@@ -258,7 +261,7 @@ impl Backtrace {
)
}),
)
- .take_while(|(chain, pc, fp, sp)| {
+ .filter(|(chain, pc, fp, sp)| {
if *pc == 0 {
debug_assert_eq!(*fp, 0);
debug_assert_eq!(*sp, 0);
diff --git a/tests/all/gc.rs b/tests/all/gc.rs
index 357370cea5..34e6c7eec1 100644
--- a/tests/all/gc.rs
+++ b/tests/all/gc.rs
@@ -2219,6 +2219,56 @@ fn copying_collector_externref_survives_gc() -> Result<()> {
Ok(())
}
+/// A host function that calls, via `Func::call`, another host function that
+/// collects must not cause the Wasm frames beneath them to be traced twice.
+#[test]
+#[cfg_attr(miri, ignore)]
+fn issue_14463_nested_host_call_gc_moves_object_once() -> Result<()> {
+ let _ = env_logger::try_init();
+ for collector in [Collector::Copying, Collector::DeferredReferenceCounting] {
+ let mut config = Config::new();
+ config.wasm_gc(true);
+ config.wasm_function_references(true);
+ config.collector(collector);
+
+ let engine = Engine::new(&config)?;
+
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (type $s (struct (field i32)))
+ (type $f (func))
+ (table (export "t") 1 funcref)
+ (global $g (mut (ref null $s)) (ref.null $s))
+ (func (export "run") (result i32) (local $x (ref null $s))
+ (local.set $x (struct.new $s (i32.const 7)))
+ (global.set $g (local.get $x))
+ (call_indirect (type $f) (i32.const 0))
+ (ref.eq (local.get $x) (global.get $g))
+ )
+ )
+ "#,
+ )?;
+
+ let mut store = Store::new(&engine, ());
+
+ let inner = Func::wrap(&mut store, |mut caller: Caller<'_, ()>| caller.gc(None));
+ let outer = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>| {
+ inner.call(&mut caller, &[], &mut [])
+ });
+
+ let instance = Instance::new(&mut store, &module, &[])?;
+
+ let table = instance.get_table(&mut store, "t").unwrap();
+ table.set(&mut store, 0, Ref::Func(Some(outer)))?;
+
+ let run = instance.get_typed_func::<(), i32>(&mut store, "run")?;
+ assert_eq!(run.call(&mut store, ())?, 1, "collector = {collector:?}");
+ }
+ Ok(())
+}
+
#[test]
#[cfg_attr(miri, ignore)]
fn issue_13173_gc_heap_uses_gc_tunables_no_signals() -> Result<()> {
diff --git a/tests/all/traps.rs b/tests/all/traps.rs
index 14dd27eaf7..2455c6eed9 100644
--- a/tests/all/traps.rs
+++ b/tests/all/traps.rs
@@ -1154,6 +1154,79 @@ fn standalone_backtrace() -> Result<()> {
Ok(())
}
+/// A host function called via `Func::call` from another host function sees the
+/// Wasm frames beneath them exactly once.
+#[test]
+fn standalone_backtrace_nested_host_call() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::new(&engine, ());
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "" (func $host))
+ (func $foo (export "f") call $bar)
+ (func $bar call $host)
+ )
+ "#,
+ )?;
+ let inner = Func::wrap(&mut store, |cx: Caller<'_, ()>| {
+ let trace = WasmBacktrace::capture(&cx);
+ let names: Vec<_> = trace.frames().iter().map(|f| f.func_name()).collect();
+ assert_eq!(names, [Some("bar"), Some("foo")]);
+ });
+ let outer = Func::wrap(&mut store, move |mut cx: Caller<'_, ()>| {
+ inner.call(&mut cx, &[], &mut [])
+ });
+ let instance = Instance::new(&mut store, &module, &[outer.into()])?;
+ let f = instance.get_typed_func::<(), ()>(&mut store, "f")?;
+ f.call(&mut store, ())?;
+ Ok(())
+}
+
+/// Wasm frames on both sides of a host function called via `Func::call` from
+/// another host function each appear exactly once.
+#[test]
+fn standalone_backtrace_host_call_between_wasm() -> Result<()> {
+ let engine = Engine::default();
+ let mut store = Store::<Option<Func>>::new(&engine, None);
+
+ let module = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "a" (func $a))
+ (import "" "c" (func $c))
+ (func $foo (export "foo") call $a)
+ (func $bar (export "bar") call $c)
+ )
+ "#,
+ )?;
+
+ let c = Func::wrap(&mut store, |cx: Caller<'_, Option<Func>>| {
+ let trace = WasmBacktrace::capture(&cx);
+ let names: Vec<_> = trace.frames().iter().map(|f| f.func_name()).collect();
+ assert_eq!(names, [Some("bar"), Some("foo")]);
+ });
+
+ let b = Func::wrap(&mut store, |mut cx: Caller<'_, Option<Func>>| {
+ let bar = cx.data().unwrap();
+ bar.call(&mut cx, &[], &mut [])
+ });
+
+ let a = Func::wrap(&mut store, move |mut cx: Caller<'_, Option<Func>>| {
+ b.call(&mut cx, &[], &mut [])
+ });
+
+ let instance = Instance::new(&mut store, &module, &[a.into(), c.into()])?;
+ *store.data_mut() = instance.get_func(&mut store, "bar");
+
+ let foo = instance.get_typed_func::<(), ()>(&mut store, "foo")?;
+ foo.call(&mut store, ())?;
+
+ Ok(())
+}
+
#[test]
fn standalone_backtrace_disabled() -> Result<()> {
let mut config = Config::new();