Skip to content

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

Debugging: allow frame cursor to visit all activations. (#12176)

Chris Fallin23b2fe3f4cf0
diff --git a/crates/wasmtime/src/runtime/debug.rs b/crates/wasmtime/src/runtime/debug.rs
index e256b886ba..89d11d0bba 100644
--- a/crates/wasmtime/src/runtime/debug.rs
+++ b/crates/wasmtime/src/runtime/debug.rs
@@ -6,7 +6,7 @@ use crate::{
code::StoreCodePC,
module::ModuleRegistry,
store::{AutoAssertNoGc, StoreOpaque},
- vm::{CompiledModuleId, CurrentActivationBacktrace, VMContext},
+ vm::{CompiledModuleId, FrameOrHostCode, StoreBacktrace, VMContext},
};
use alloc::collections::BTreeSet;
use alloc::vec;
@@ -43,11 +43,7 @@ impl<'a, T> StoreContextMut<'a, T> {
return None;
}
- // SAFETY: This takes a mutable borrow of `self` (the
- // `StoreOpaque`), which owns all active stacks in the
- // store. We do not provide any API that could mutate the
- // frames that we are walking on the `DebugFrameCursor`.
- let iter = unsafe { CurrentActivationBacktrace::new(self) };
+ let iter = StoreBacktrace::new(self);
let mut view = DebugFrameCursor {
iter,
is_trapping_frame: false,
@@ -90,14 +86,14 @@ impl<'a, T> StoreContext<'a, T> {
/// A view of an active stack frame, with the ability to move up the
/// stack.
///
-/// See the documentation on `Store::stack_value` for more information
+/// See the documentation on `Store::debug_frames` for more information
/// about which frames this view will show.
pub struct DebugFrameCursor<'a, T: 'static> {
/// Iterator over frames.
///
/// This iterator owns the store while the view exists (accessible
/// as `iter.store`).
- iter: CurrentActivationBacktrace<'a, T>,
+ iter: StoreBacktrace<'a, T>,
/// Is the next frame to be visited by the iterator a trapping
/// frame?
@@ -120,9 +116,25 @@ pub struct DebugFrameCursor<'a, T: 'static> {
current: Option<FrameData>,
}
+/// The result type from `DebugFrameCursor::move_to_parent()`:
+/// indicates whether the cursor skipped over host code to move to the
+/// next Wasm frame.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FrameParentResult {
+ /// The new frame is in the same Wasm activation.
+ SameActivation,
+ /// The new frame is in the next higher Wasm activation on the
+ /// stack.
+ NewActivation,
+}
+
impl<'a, T: 'static> DebugFrameCursor<'a, T> {
/// Move up to the next frame in the activation.
- pub fn move_to_parent(&mut self) {
+ ///
+ /// Returns `FrameParentMove` as an indication whether the
+ /// moved-to frame is in the same activation or skipped over host
+ /// code.
+ pub fn move_to_parent(&mut self) -> FrameParentResult {
// If there are no virtual frames to yield, take and decode
// the next physical frame.
//
@@ -133,22 +145,35 @@ impl<'a, T: 'static> DebugFrameCursor<'a, T> {
// functions or other things that we completely ignore). If
// this ever changes, we can remove the assert and convert
// this to a loop that polls until it finds virtual frames.
+ let mut result = FrameParentResult::SameActivation;
self.current = None;
- if self.frames.is_empty() {
+ while self.frames.is_empty() {
let Some(next_frame) = self.iter.next() else {
- return;
+ return result;
+ };
+ self.frames = match next_frame {
+ FrameOrHostCode::Frame(frame) => VirtualFrame::decode(
+ // SAFETY: we are using the Store only to decode
+ // frames; the only mutable aspect used here is
+ // rooting any new GC values that are read out,
+ // and we do not remove frames that we may be
+ // visiting.
+ unsafe { self.iter.store_mut() }.0.as_store_opaque(),
+ frame,
+ self.is_trapping_frame,
+ ),
+ FrameOrHostCode::HostCode => {
+ result = FrameParentResult::NewActivation;
+ continue;
+ }
};
- self.frames = VirtualFrame::decode(
- self.iter.store.0.as_store_opaque(),
- next_frame,
- self.is_trapping_frame,
- );
debug_assert!(!self.frames.is_empty());
self.is_trapping_frame = false;
}
// Take a frame and focus it as the current one.
self.current = self.frames.pop().map(|vf| FrameData::compute(vf));
+ result
}
/// Has the iterator reached the end of the activation?
@@ -178,7 +203,14 @@ impl<'a, T: 'static> DebugFrameCursor<'a, T> {
/// Get the instance associated with the current frame.
pub fn instance(&mut self) -> Instance {
let instance = self.raw_instance();
- Instance::from_wasmtime(instance.id(), self.iter.store.0.as_store_opaque())
+ Instance::from_wasmtime(
+ instance.id(),
+ // SAFETY: we are using the Store only
+ // to read the instance reference; we
+ // do not remove frames that we may be
+ // visiting.
+ unsafe { self.iter.store_mut() }.0.as_store_opaque(),
+ )
}
/// Get the module associated with the current frame, if any
@@ -229,7 +261,7 @@ impl<'a, T: 'static> DebugFrameCursor<'a, T> {
let slot_addr = data.slot_addr;
// SAFETY: compiler produced metadata to describe this local
// slot and stored a value of the correct type into it.
- unsafe { read_value(&mut self.iter.store.0, slot_addr, offset, ty) }
+ unsafe { read_value(&mut self.iter.store_mut().0, slot_addr, offset, ty) }
}
/// Get the type and value of the given operand-stack value in
@@ -246,7 +278,7 @@ impl<'a, T: 'static> DebugFrameCursor<'a, T> {
// SAFETY: compiler produced metadata to describe this
// operand-stack slot and stored a value of the correct type
// into it.
- unsafe { read_value(&mut self.iter.store.0, slot_addr, offset, ty) }
+ unsafe { read_value(&mut self.iter.store_mut().0, slot_addr, offset, ty) }
}
}
@@ -468,12 +500,15 @@ pub(crate) fn gc_refs_in_frame<'a>(ft: FrameTable<'a>, pc: u32, fp: *mut usize)
impl<'a, T: 'static> AsContext for DebugFrameCursor<'a, T> {
type Data = T;
fn as_context(&self) -> StoreContext<'_, Self::Data> {
- StoreContext(self.iter.store.0)
+ StoreContext(self.iter.store().0)
}
}
impl<'a, T: 'static> AsContextMut for DebugFrameCursor<'a, T> {
fn as_context_mut(&mut self) -> StoreContextMut<'_, Self::Data> {
- StoreContextMut(self.iter.store.0)
+ // SAFETY: `StoreContextMut` does not provide any methods that
+ // could remove frames from the stack, so the iterator remains
+ // valid.
+ unsafe { StoreContextMut(self.iter.store_mut().0) }
}
}
diff --git a/crates/wasmtime/src/runtime/instance.rs b/crates/wasmtime/src/runtime/instance.rs
index 5c4d6b2664..f46b683201 100644
--- a/crates/wasmtime/src/runtime/instance.rs
+++ b/crates/wasmtime/src/runtime/instance.rs
@@ -33,7 +33,7 @@ use wasmtime_environ::{
/// [`Linker::instantiate`](crate::Linker::instantiate) or similar
/// [`Linker`](crate::Linker) methods, but a more low-level constructor is also
/// available as [`Instance::new`].
-#[derive(Copy, Clone, Debug)]
+#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Instance {
id: StoreInstanceId,
diff --git a/crates/wasmtime/src/runtime/store.rs b/crates/wasmtime/src/runtime/store.rs
index ddd06be3cc..0ce69fc6c3 100644
--- a/crates/wasmtime/src/runtime/store.rs
+++ b/crates/wasmtime/src/runtime/store.rs
@@ -1256,11 +1256,6 @@ impl<T> Store<T> {
/// VM-level values (locals and operand stack), when debugging is
/// enabled.
///
- /// This object views the frames from the most recent Wasm entry
- /// onward (up to the exit that allows this host code to run). Any
- /// Wasm stack frames upward from the most recent entry to Wasm
- /// are not visible to this cursor.
- ///
/// Returns `None` if debug instrumentation is not enabled for
/// the engine containing this store.
#[cfg(feature = "debug")]
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers.rs b/crates/wasmtime/src/runtime/vm/traphandlers.rs
index bb86206669..ac4f63a81b 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers.rs
@@ -32,7 +32,7 @@ use wasmtime_unwinder::Handler;
pub use self::backtrace::Backtrace;
#[cfg(feature = "debug")]
-pub(crate) use self::backtrace::CurrentActivationBacktrace;
+pub(crate) use self::backtrace::{FrameOrHostCode, StoreBacktrace};
#[cfg(feature = "gc")]
pub use wasmtime_unwinder::Frame;
diff --git a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
index be9403e97f..300d596c95 100644
--- a/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
+++ b/crates/wasmtime/src/runtime/vm/traphandlers/backtrace.rs
@@ -21,8 +21,6 @@
//! exit FP and stopping once we reach the entry SP (meaning that the next older
//! frame is a host frame).
-#[cfg(feature = "debug")]
-use crate::StoreContextMut;
use crate::prelude::*;
use crate::runtime::store::StoreOpaque;
use crate::runtime::vm::stack_switching::VMStackChain;
@@ -32,6 +30,8 @@ use crate::runtime::vm::{
};
#[cfg(all(feature = "gc", feature = "stack-switching"))]
use crate::vm::stack_switching::{VMContRef, VMStackState};
+#[cfg(feature = "debug")]
+use crate::{StoreContext, StoreContextMut};
use core::ops::ControlFlow;
use wasmtime_unwinder::Frame;
@@ -39,6 +39,14 @@ use wasmtime_unwinder::Frame;
#[derive(Debug)]
pub struct Backtrace(Vec<Frame>);
+/// One activation: information sufficient to trace an activation on a
+/// frame as long as that frame remains alive.
+pub(crate) struct Activation {
+ exit_pc: usize,
+ exit_fp: usize,
+ entry_trampoline_fp: usize,
+}
+
impl Backtrace {
/// Returns an empty backtrace
pub fn empty() -> Backtrace {
@@ -69,23 +77,41 @@ impl Backtrace {
trap_pc_and_fp: Option<(usize, usize)>,
) -> Backtrace {
let mut frames = vec![];
+ let f = |activation: Activation| unsafe {
+ wasmtime_unwinder::visit_frames(
+ unwind,
+ activation.exit_pc,
+ activation.exit_fp,
+ activation.entry_trampoline_fp,
+ |frame| {
+ frames.push(frame);
+ ControlFlow::Continue(())
+ },
+ )
+ };
unsafe {
- Self::trace_with_trap_state(vm_store_context, unwind, state, trap_pc_and_fp, |frame| {
- frames.push(frame);
- ControlFlow::Continue(())
- });
+ Self::trace_with_trap_state(vm_store_context, state, trap_pc_and_fp, f);
}
Backtrace(frames)
}
/// Walk the current Wasm stack, calling `f` for each frame we walk.
#[cfg(feature = "gc")]
- pub fn trace(store: &StoreOpaque, f: impl FnMut(Frame) -> ControlFlow<()>) {
+ pub fn trace(store: &StoreOpaque, mut f: impl FnMut(Frame) -> ControlFlow<()>) {
let vm_store_context = store.vm_store_context();
let unwind = store.unwinder();
tls::with(|state| match state {
Some(state) => unsafe {
- Self::trace_with_trap_state(vm_store_context, unwind, state, None, f)
+ let f = |activation: Activation| {
+ wasmtime_unwinder::visit_frames(
+ unwind,
+ activation.exit_pc,
+ activation.exit_fp,
+ activation.entry_trampoline_fp,
+ &mut f,
+ )
+ };
+ Self::trace_with_trap_state(vm_store_context, state, None, f)
},
None => {}
});
@@ -97,7 +123,7 @@ impl Backtrace {
pub fn trace_suspended_continuation(
store: &StoreOpaque,
continuation: &VMContRef,
- f: impl FnMut(Frame) -> ControlFlow<()>,
+ mut f: impl FnMut(Frame) -> ControlFlow<()>,
) {
log::trace!("====== Capturing Backtrace (suspended continuation) ======");
@@ -122,9 +148,21 @@ impl Backtrace {
let stack_chain =
VMStackChain::Continuation(continuation as *const VMContRef as *mut VMContRef);
- if let ControlFlow::Break(()) =
- Self::trace_through_continuations(unwind, stack_chain, pc, fp, trampoline_fp, f)
- {
+ if let ControlFlow::Break(()) = Self::trace_through_continuations(
+ stack_chain,
+ pc,
+ fp,
+ trampoline_fp,
+ |activation| {
+ wasmtime_unwinder::visit_frames(
+ unwind,
+ activation.exit_pc,
+ activation.exit_fp,
+ activation.entry_trampoline_fp,
+ &mut f,
+ )
+ },
+ ) {
log::trace!("====== Done Capturing Backtrace (closure break) ======");
return;
}
@@ -153,10 +191,9 @@ impl Backtrace {
/// other opaque host code; we don't know anything about it.
pub(crate) unsafe fn trace_with_trap_state(
vm_store_context: *const VMStoreContext,
- unwind: &dyn Unwind,
state: &CallThreadState,
trap_pc_and_fp: Option<(usize, usize)>,
- mut f: impl FnMut(Frame) -> ControlFlow<()>,
+ mut f: impl FnMut(Activation) -> ControlFlow<()>,
) {
log::trace!("====== Capturing Backtrace ======");
@@ -219,9 +256,16 @@ impl Backtrace {
*pc != 0
});
- for (chain, pc, fp, sp) in activations {
- let res =
- unsafe { Self::trace_through_continuations(unwind, chain, pc, fp, sp, &mut f) };
+ for (chain, exit_pc, exit_fp, entry_trampoline_fp) in activations {
+ let res = unsafe {
+ Self::trace_through_continuations(
+ chain,
+ exit_pc,
+ exit_fp,
+ entry_trampoline_fp,
+ &mut f,
+ )
+ };
if let ControlFlow::Break(()) = res {
log::trace!("====== Done Capturing Backtrace (closure break) ======");
return;
@@ -240,20 +284,21 @@ impl Backtrace {
/// ends with the initial stack. We then trace through each of these stacks
/// individually, up to (and including) the initial stack.
unsafe fn trace_through_continuations(
- unwind: &dyn Unwind,
chain: VMStackChain,
- pc: usize,
- fp: usize,
- trampoline_fp: usize,
- mut f: impl FnMut(Frame) -> ControlFlow<()>,
+ exit_pc: usize,
+ exit_fp: usize,
+ entry_trampoline_fp: usize,
+ mut f: impl FnMut(Activation) -> ControlFlow<()>,
) -> ControlFlow<()> {
use crate::runtime::vm::stack_switching::{VMContRef, VMStackLimits};
// Handle the stack that is currently running (which may be a
// continuation or the initial stack).
- unsafe {
- wasmtime_unwinder::visit_frames(unwind, pc, fp, trampoline_fp, &mut f)?;
- }
+ f(Activation {
+ exit_pc,
+ exit_fp,
+ entry_trampoline_fp,
+ })?;
// Note that the rest of this function has no effect if `chain` is
// `Some(VMStackChain::InitialStack(_))` (i.e., there is only one stack to
@@ -307,19 +352,33 @@ impl Backtrace {
debug_assert!(parent_stack_range.contains(&parent_limits.stack_limit));
});
- unsafe {
- wasmtime_unwinder::visit_frames(
- unwind,
- resume_pc,
- resume_fp,
- parent_limits.last_wasm_entry_fp,
- &mut f,
- )?
- }
+ f(Activation {
+ exit_pc: resume_pc,
+ exit_fp: resume_fp,
+ entry_trampoline_fp: parent_limits.last_wasm_entry_fp,
+ })?;
}
ControlFlow::Continue(())
}
+ /// Capture all Activations reachable from the current point
+ /// within a hostcall.
+ #[cfg(feature = "debug")]
+ fn activations(store: &StoreOpaque) -> Vec<Activation> {
+ let mut activations = vec![];
+ let vm_store_context = store.vm_store_context();
+ tls::with(|state| match state {
+ Some(state) => unsafe {
+ Self::trace_with_trap_state(vm_store_context, state, None, |act| {
+ activations.push(act);
+ ControlFlow::Continue(())
+ });
+ },
+ None => {}
+ });
+ activations
+ }
+
/// Iterate over the frames inside this backtrace.
pub fn frames<'a>(
&'a self,
@@ -330,14 +389,14 @@ impl Backtrace {
/// An iterator over one Wasm activation.
#[cfg(feature = "debug")]
-pub(crate) struct CurrentActivationBacktrace<'a, T: 'static> {
+struct ActivationBacktrace<'a, T: 'static> {
pub(crate) store: StoreContextMut<'a, T>,
inner: Box<dyn Iterator<Item = Frame>>,
}
#[cfg(feature = "debug")]
-impl<'a, T: 'static> CurrentActivationBacktrace<'a, T> {
- /// Return an iterator over the most recent Wasm activation.
+impl<'a, T: 'static> ActivationBacktrace<'a, T> {
+ /// Return an iterator over a Wasm activation.
///
/// The iterator captures the store with a mutable borrow, and
/// then yields it back at each frame. This ensures that the stack
@@ -360,31 +419,178 @@ impl<'a, T: 'static> CurrentActivationBacktrace<'a, T> {
/// while within host code called from that activation (which will
/// ordinarily be ensured if the `store`'s lifetime came from the
/// host entry point) then everything will be sound.
- pub(crate) unsafe fn new(store: StoreContextMut<'a, T>) -> CurrentActivationBacktrace<'a, T> {
- // Get the initial exit FP, exit PC, and entry FP.
- let vm_store_context = store.0.vm_store_context();
- let exit_pc = unsafe { *(*vm_store_context).last_wasm_exit_pc.get() };
- let exit_fp = unsafe { (*vm_store_context).last_wasm_exit_fp() };
- let trampoline_fp = unsafe { *(*vm_store_context).last_wasm_entry_fp.get() };
- let inner: Box<dyn Iterator<Item = Frame>> = if exit_fp == 0 {
+ pub(crate) unsafe fn new(
+ store: StoreContextMut<'a, T>,
+ activation: Activation,
+ ) -> ActivationBacktrace<'a, T> {
+ let inner: Box<dyn Iterator<Item = Frame>> = if activation.exit_fp == 0 {
// No activations on this Store; return an empty iterator.
Box::new(core::iter::empty())
} else {
let unwind = store.0.unwinder();
// Establish the iterator.
Box::new(unsafe {
- wasmtime_unwinder::frame_iterator(unwind, exit_pc, exit_fp, trampoline_fp)
+ wasmtime_unwinder::frame_iterator(
+ unwind,
+ activation.exit_pc,
+ activation.exit_fp,
+ activation.entry_trampoline_fp,
+ )
})
};
- CurrentActivationBacktrace { store, inner }
+ ActivationBacktrace { store, inner }
}
}
#[cfg(feature = "debug")]
-impl<'a, T: 'static> Iterator for CurrentActivationBacktrace<'a, T> {
+impl<'a, T: 'static> Iterator for ActivationBacktrace<'a, T> {
type Item = Frame;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
}
+
+/// An iterator over all Wasm activations in a Store.
+#[cfg(feature = "debug")]
+pub(crate) struct StoreBacktrace<'a, T: 'static> {
+ /// The current activation iterator or the Store itself if no more
+ /// activations.
+ ///
+ /// This is `Option` so that we can move to the next while
+ /// transferring ownership of the Store without deconstructing
+ /// this whole iterator.
+ current: Option<StoreOrActivationBacktrace<'a, T>>,
+ activations: Vec<Activation>,
+}
+
+/// Either an iterator over a Wasm activation, or a `StoreContextMut`
+/// if no activations are left.
+#[cfg(feature = "debug")]
+enum StoreOrActivationBacktrace<'a, T: 'static> {
+ Store(StoreContextMut<'a, T>),
+ Activation(ActivationBacktrace<'a, T>),
+}
+
+#[cfg(feature = "debug")]
+impl<'a, T: 'static> StoreOrActivationBacktrace<'a, T> {
+ fn is_activation(&self) -> bool {
+ match self {
+ Self::Activation(_) => true,
+ _ => false,
+ }
+ }
+}
+
+#[cfg(feature = "debug")]
+impl<'a, T> StoreBacktrace<'a, T> {
+ /// Return an iterator over all Wasm activations in a Store, in
+ /// invocation order.
+ ///
+ /// The iterator captures the store with a mutable borrow, and
+ /// then yields it back at each frame. This ensures that the stack
+ /// remains live while still providing a mutable store that may be
+ /// needed to access items in the frame (e.g., to create new roots
+ /// when reading out GC refs).
+ ///
+ /// This serves as an alternative to `Backtrace::trace()` and
+ /// friends: it allows external iteration (and e.g. lazily walking
+ /// through frames in a stack) rather than visiting via a closure.
+ pub(crate) fn new(store: StoreContextMut<'a, T>) -> StoreBacktrace<'a, T> {
+ // Get all activations, in innermost-to-outermost order.
+ use crate::store::AsStoreOpaque;
+ let mut activations = Backtrace::activations(store.0.as_store_opaque());
+ // Reverse to outermost-to-innermost so we can pop off the end.
+ activations.reverse();
+ // Create our inner state: either an activation iterator on
+ // the innermost activation that owns the store, or a sentinel
+ // if there are no activations.
+ let current = match activations.pop() {
+ Some(innermost) => unsafe {
+ StoreOrActivationBacktrace::Activation(ActivationBacktrace::new(store, innermost))
+ },
+ None => StoreOrActivationBacktrace::Store(store),
+ };
+ StoreBacktrace {
+ current: Some(current),
+ activations,
+ }
+ }
+
+ /// Get the Store underlying this iteration.
+ pub fn store(&self) -> StoreContext<'_, T> {
+ match self.current.as_ref().unwrap() {
+ StoreOrActivationBacktrace::Activation(activation) => StoreContext(activation.store.0),
+ StoreOrActivationBacktrace::Store(store) => StoreContext(store.0),
+ }
+ }
+
+ /// Get the Store underlying this iteration.
+ ///
+ /// # Safety
+ ///
+ /// This mutable store access *must not* be used to mutate the
+ /// stack itself that this iterator is visiting by removing
+ /// frames, even though the `store` technically owns the stack in
+ /// question.
+ pub unsafe fn store_mut(&mut self) -> StoreContextMut<'_, T> {
+ match self.current.as_mut().unwrap() {
+ StoreOrActivationBacktrace::Activation(activation) => {
+ StoreContextMut(activation.store.0)
+ }
+ StoreOrActivationBacktrace::Store(store) => StoreContextMut(store.0),
+ }
+ }
+
+ fn take_store(&mut self) -> StoreContextMut<'a, T> {
+ match self.current.take().unwrap() {
+ StoreOrActivationBacktrace::Activation(activation) => activation.store,
+ StoreOrActivationBacktrace::Store(store) => store,
+ }
+ }
+
+ /// Move to the next activation.
+ fn next_activation(&mut self) {
+ let activation = self.activations.pop();
+ let store = self.take_store();
+ self.current = Some(match activation {
+ Some(activation) => StoreOrActivationBacktrace::Activation(unsafe {
+ ActivationBacktrace::new(store, activation)
+ }),
+ None => StoreOrActivationBacktrace::Store(store),
+ });
+ }
+}
+
+/// A single item in an iteration over a store's frames: either a Wasm
+/// frame, or a sentinel representing host code between activations.
+#[cfg(feature = "debug")]
+pub enum FrameOrHostCode {
+ /// A WebAsembly frame.
+ Frame(Frame),
+ /// Some number of host frames between Wasm activations.
+ HostCode,
+}
+
+#[cfg(feature = "debug")]
+impl<'a, T: 'static> Iterator for StoreBacktrace<'a, T> {
+ type Item = FrameOrHostCode;
+ fn next(&mut self) -> Option<Self::Item> {
+ match self.current.as_mut().unwrap() {
+ StoreOrActivationBacktrace::Store(_) => None,
+ StoreOrActivationBacktrace::Activation(act) => match act.next() {
+ Some(frame) => Some(FrameOrHostCode::Frame(frame)),
+ None => {
+ self.next_activation();
+ // If there's another activation waiting, return
+ // HostCode between the two; otherwise, don't.
+ if self.current.as_ref().unwrap().is_activation() {
+ Some(FrameOrHostCode::HostCode)
+ } else {
+ None
+ }
+ }
+ },
+ }
+ }
+}
diff --git a/tests/all/debug.rs b/tests/all/debug.rs
index 0bbe64c191..dc40326c72 100644
--- a/tests/all/debug.rs
+++ b/tests/all/debug.rs
@@ -3,8 +3,8 @@
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use wasmtime::{
- AsContextMut, Caller, Config, DebugEvent, DebugHandler, Engine, Extern, Func, Instance, Module,
- Store, StoreContextMut, Val,
+ AsContextMut, Caller, Config, DebugEvent, DebugHandler, Engine, Extern, FrameParentResult,
+ Func, Instance, Module, Store, StoreContextMut, Val,
};
#[test]
@@ -89,12 +89,12 @@ fn stack_values_two_frames() -> anyhow::Result<()> {
assert_eq!(stack.stack(0).unwrap_i32(), 1);
assert_eq!(stack.stack(1).unwrap_i32(), 2);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(!stack.done());
assert_eq!(stack.wasm_function_index_and_pc().unwrap().0.as_u32(), 0);
assert_eq!(stack.wasm_function_index_and_pc().unwrap().1, 55);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
},
)?;
@@ -124,7 +124,7 @@ fn stack_values_exceptions() -> anyhow::Result<()> {
assert!(!stack.done());
assert_eq!(stack.num_stacks(), 1);
assert_eq!(stack.stack(0).unwrap_i32(), 42);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
},
)
@@ -151,7 +151,7 @@ fn stack_values_dead_gc_ref() -> anyhow::Result<()> {
assert!(!stack.done());
assert_eq!(stack.num_stacks(), 1);
assert!(stack.stack(0).unwrap_anyref().is_some());
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
},
)
@@ -194,12 +194,103 @@ fn gc_access_during_call() -> anyhow::Result<()> {
.unwrap_struct(&stack)
.unwrap();
assert_eq!(s.field(&mut stack, 0).unwrap().unwrap_i32(), 42);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
},
)
}
+#[test]
+#[cfg_attr(miri, ignore)]
+fn stack_values_two_activations() -> anyhow::Result<()> {
+ let _ = env_logger::try_init();
+
+ let mut config = Config::default();
+ config.guest_debug(true);
+ config.wasm_exceptions(true);
+ let engine = Engine::new(&config)?;
+ let module1 = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "host1" (func (param i32 i32) (result i32)))
+ (func (export "main") (result i32)
+ i32.const 1
+ i32.const 2
+ call 0))
+ "#,
+ )?;
+ let module2 = Module::new(
+ &engine,
+ r#"
+ (module
+ (import "" "host2" (func))
+ (func (export "inner") (param i32 i32) (result i32)
+ local.get 0
+ local.get 1
+ call 0
+ i32.add))
+ "#,
+ )?;
+ let mut store = Store::new(&engine, ());
+
+ let module1_clone = module1.clone();
+ let module2_clone = module2.clone();
+ let host2 = Func::wrap(&mut store, move |mut caller: Caller<'_, ()>| {
+ let mut stack = caller.debug_frames().unwrap();
+ assert!(!stack.done());
+ assert_eq!(stack.wasm_function_index_and_pc().unwrap().0.as_u32(), 0);
+ assert_eq!(stack.wasm_function_index_and_pc().unwrap().1, 56);
+ assert!(Module::same(stack.module().unwrap(), &module2_clone));
+ assert_eq!(stack.num_locals(), 2);
+ assert_eq!(stack.num_stacks(), 2);
+ assert_eq!(stack.local(0).unwrap_i32(), 1);
+ assert_eq!(stack.local(1).unwrap_i32(), 2);
+ assert_eq!(stack.stack(0).unwrap_i32(), 1);
+ assert_eq!(stack.stack(1).unwrap_i32(), 2);
+ let inner_instance = stack.instance();
+
+ assert_eq!(stack.move_to_parent(), FrameParentResult::NewActivation);
+ assert!(!stack.done());
+
+ assert_eq!(stack.wasm_function_index_and_pc().unwrap().0.as_u32(), 0);
+ assert_eq!(stack.wasm_function_index_and_pc().unwrap().1, 56);
+ assert!(Module::same(stack.module().unwrap(), &module1_clone));
+ assert_eq!(stack.num_locals(), 0);
+ assert_eq!(stack.num_stacks(), 2);
+ assert_eq!(stack.stack(0).unwrap_i32(), 1);
+ assert_eq!(stack.stack(1).unwrap_i32(), 2);
+ let outer_instance = stack.instance();
+
+ assert_ne!(inner_instance, outer_instance);
+
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
+ assert!(stack.done());
+ });
+
+ let instance2 = Instance::new(&mut store, &module2, &[Extern::Func(host2)])?;
+ let inner = instance2.get_func(&mut store, "inner").unwrap();
+
+ let host1 = Func::wrap(
+ &mut store,
+ move |mut caller: Caller<'_, ()>, a: i32, b: i32| -> i32 {
+ let mut results = [Val::I32(0)];
+ inner
+ .call(&mut caller, &[Val::I32(a), Val::I32(b)], &mut results[..])
+ .unwrap();
+ results[0].unwrap_i32()
+ },
+ );
+
+ let instance1 = Instance::new(&mut store, &module1, &[Extern::Func(host1)])?;
+ let main = instance1.get_func(&mut store, "main").unwrap();
+
+ let mut results = [Val::I32(0)];
+ main.call(&mut store, &[], &mut results)?;
+ assert_eq!(results[0].unwrap_i32(), 3);
+ Ok(())
+}
+
#[test]
#[cfg_attr(miri, ignore)]
fn debug_frames_on_store_with_no_wasm_activation() -> anyhow::Result<()> {
@@ -293,9 +384,9 @@ async fn uncaught_exception_events() -> anyhow::Result<()> {
assert!(!stack.done());
assert_eq!(stack.num_locals(), 1);
assert_eq!(stack.local(0).unwrap_i32(), 100);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(!stack.done());
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
}
}
@@ -349,9 +440,9 @@ async fn caught_exception_events() -> anyhow::Result<()> {
assert!(!stack.done());
assert_eq!(stack.num_locals(), 1);
assert_eq!(stack.local(0).unwrap_i32(), 100);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(!stack.done());
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
}
}
@@ -485,7 +576,7 @@ async fn breakpoint_events() -> anyhow::Result<()> {
let (func, pc) = stack.wasm_function_index_and_pc().unwrap();
assert_eq!(func.as_u32(), 0);
assert_eq!(pc, 0x28);
- stack.move_to_parent();
+ assert_eq!(stack.move_to_parent(), FrameParentResult::SameActivation);
assert!(stack.done());
}
}