wasmtime/runtime/vm/traphandlers/backtrace.rs
1//! Backtrace and stack walking functionality for Wasm.
2//!
3//! Walking the Wasm stack is comprised of
4//!
5//! 1. identifying sequences of contiguous Wasm frames on the stack
6//! (i.e. skipping over native host frames), and
7//!
8//! 2. walking the Wasm frames within such a sequence.
9//!
10//! To perform (1) we maintain the entry stack pointer (SP) and exit frame
11//! pointer (FP) and program counter (PC) each time we call into Wasm and Wasm
12//! calls into the host via trampolines (see
13//! `crates/wasmtime/src/runtime/vm/trampolines`). The most recent entry is
14//! stored in `VMStoreContext` and older entries are saved in
15//! `CallThreadState`. This lets us identify ranges of contiguous Wasm frames on
16//! the stack.
17//!
18//! To solve (2) and walk the Wasm frames within a region of contiguous Wasm
19//! frames on the stack, we configure Cranelift's `preserve_frame_pointers =
20//! true` setting. Then we can do simple frame pointer traversal starting at the
21//! exit FP and stopping once we reach the entry SP (meaning that the next older
22//! frame is a host frame).
23
24use crate::prelude::*;
25use crate::runtime::store::StoreOpaque;
26use crate::runtime::vm::stack_switching::VMStackChain;
27use crate::runtime::vm::{
28 Unwind, VMStoreContext,
29 traphandlers::{CallThreadState, tls},
30};
31#[cfg(all(feature = "gc", feature = "stack-switching"))]
32use crate::vm::{VMContRef, stack_switching::VMStackState};
33use core::ops::ControlFlow;
34use wasmtime_unwinder::Frame;
35#[cfg(feature = "debug")]
36use wasmtime_unwinder::FrameCursor;
37
38/// A WebAssembly stack trace.
39#[derive(Debug)]
40pub struct Backtrace(TryVec<Frame>);
41
42/// One activation: information sufficient to trace an activation on a
43/// frame as long as that frame remains alive.
44pub(crate) struct Activation {
45 exit_pc: usize,
46 exit_fp: usize,
47 entry_trampoline_fp: usize,
48}
49
50impl Activation {
51 /// Create a frame cursor starting at the exit frame of this activation.
52 ///
53 /// # Safety
54 ///
55 /// This activation must currently be valid (i.e., execution must
56 /// not have returned into the activation to unwind any frames,
57 /// and the stack must not have been freed).
58 #[cfg(feature = "debug")]
59 pub(crate) unsafe fn cursor(&self) -> FrameCursor {
60 // SAFETY: validity of this activation is ensured by our
61 // safety condition.
62 unsafe { FrameCursor::new(self.exit_pc, self.exit_fp, self.entry_trampoline_fp) }
63 }
64}
65
66impl Backtrace {
67 /// Returns an empty backtrace
68 pub fn empty() -> Backtrace {
69 Backtrace(TryVec::new())
70 }
71
72 /// Capture the current Wasm stack in a backtrace.
73 pub fn new(store: &StoreOpaque) -> Backtrace {
74 let vm_store_context = store.vm_store_context();
75 let unwind = store.unwinder();
76 tls::with(|state| match state {
77 Some(state) => unsafe {
78 Self::new_with_trap_state(vm_store_context, unwind, state, None)
79 },
80 None => Backtrace(TryVec::new()),
81 })
82 }
83
84 /// Capture the current Wasm stack trace.
85 ///
86 /// If Wasm hit a trap, and we calling this from the trap handler, then the
87 /// Wasm exit trampoline didn't run, and we use the provided PC and FP
88 /// instead of looking them up in `VMStoreContext`.
89 pub(crate) unsafe fn new_with_trap_state(
90 vm_store_context: *const VMStoreContext,
91 unwind: &dyn Unwind,
92 state: &CallThreadState,
93 trap_pc_and_fp: Option<(usize, usize)>,
94 ) -> Backtrace {
95 let mut frames = TryVec::new();
96 let f = |activation: Activation| unsafe {
97 wasmtime_unwinder::visit_frames(
98 unwind,
99 activation.exit_pc,
100 activation.exit_fp,
101 activation.entry_trampoline_fp,
102 |frame| match frames.push(frame) {
103 Ok(()) => ControlFlow::Continue(()),
104 Err(_) => ControlFlow::Break(()),
105 },
106 )
107 };
108 unsafe {
109 Self::trace_with_trap_state(vm_store_context, state, trap_pc_and_fp, f);
110 }
111 Backtrace(frames)
112 }
113
114 /// Walk the current Wasm stack, calling `f` for each frame we walk.
115 #[cfg(feature = "gc")]
116 pub fn trace(store: &StoreOpaque, mut f: impl FnMut(Frame) -> ControlFlow<()>) {
117 let vm_store_context = store.vm_store_context();
118 let unwind = store.unwinder();
119 tls::with(|state| match state {
120 Some(state) => unsafe {
121 let f = |activation: Activation| {
122 wasmtime_unwinder::visit_frames(
123 unwind,
124 activation.exit_pc,
125 activation.exit_fp,
126 activation.entry_trampoline_fp,
127 &mut f,
128 )
129 };
130 Self::trace_with_trap_state(vm_store_context, state, None, f)
131 },
132 None => {}
133 });
134 }
135
136 // Walk the stack of the given continuation, which must be suspended, and
137 // all of its parent continuations (if any).
138 #[cfg(all(feature = "gc", feature = "stack-switching"))]
139 pub fn trace_suspended_continuation(
140 store: &StoreOpaque,
141 continuation: &VMContRef,
142 mut f: impl FnMut(Frame) -> ControlFlow<()>,
143 ) {
144 log::trace!("====== Capturing Backtrace (suspended continuation) ======");
145
146 assert_eq!(
147 continuation.common_stack_information.state,
148 VMStackState::Suspended
149 );
150
151 let unwind = store.unwinder();
152
153 let pc = continuation.stack.control_context_instruction_pointer();
154 let fp = continuation.stack.control_context_frame_pointer();
155 let trampoline_fp = continuation
156 .common_stack_information
157 .limits
158 .last_wasm_entry_fp;
159
160 unsafe {
161 let stack_chain = VMStackChain::Continuation(continuation.into());
162
163 if let ControlFlow::Break(()) = Self::trace_through_continuations(
164 stack_chain,
165 pc,
166 fp,
167 trampoline_fp,
168 |activation| {
169 wasmtime_unwinder::visit_frames(
170 unwind,
171 activation.exit_pc,
172 activation.exit_fp,
173 activation.entry_trampoline_fp,
174 &mut f,
175 )
176 },
177 ) {
178 log::trace!("====== Done Capturing Backtrace (closure break) ======");
179 return;
180 }
181 }
182
183 log::trace!("====== Done Capturing Backtrace (reached end of stack chain) ======");
184 }
185
186 /// Walk the current Wasm stack, calling `f` for each frame we walk.
187 ///
188 /// If Wasm hit a trap and we are calling this from the trap handler, then the
189 /// Wasm exit trampoline didn't run, and we use the provided PC and FP
190 /// instead of looking them up in `VMStoreContext`.
191 ///
192 /// We define "current Wasm stack" here as "all activations
193 /// associated with the given store". That is: if we have a stack like
194 ///
195 /// ```plain
196 /// host --> (Wasm functions in store A) --> host --> (Wasm functions in store B) --> host
197 /// --> (Wasm functions in store A) --> host --> call `trace_with_trap_state` with store A
198 /// ```
199 ///
200 /// then we will see the first and third Wasm activations (those
201 /// associated with store A), but not that with store B. In
202 /// essence, activations from another store might as well be some
203 /// other opaque host code; we don't know anything about it.
204 pub(crate) unsafe fn trace_with_trap_state(
205 vm_store_context: *const VMStoreContext,
206 state: &CallThreadState,
207 trap_pc_and_fp: Option<(usize, usize)>,
208 mut f: impl FnMut(Activation) -> ControlFlow<()>,
209 ) {
210 log::trace!("====== Capturing Backtrace ======");
211
212 let (last_wasm_exit_pc, last_wasm_exit_fp) = match trap_pc_and_fp {
213 // If we exited Wasm by catching a trap, then the Wasm-to-host
214 // trampoline did not get a chance to save the last Wasm PC and FP,
215 // and we need to use the plumbed-through values instead.
216 Some((pc, fp)) => {
217 assert!(core::ptr::eq(
218 vm_store_context,
219 state.vm_store_context.get().as_ptr()
220 ));
221 (pc, fp)
222 }
223 // Either there is no Wasm currently on the stack, or we exited Wasm
224 // through the Wasm-to-host trampoline.
225 None => unsafe {
226 let pc = *(*vm_store_context).last_wasm_exit_pc.get();
227 let fp = (*vm_store_context).last_wasm_exit_fp();
228 (pc, fp)
229 },
230 };
231
232 let stack_chain = unsafe { (*(*vm_store_context).stack_chain.get()).clone() };
233
234 // The first value in `activations` is for the most recently running
235 // wasm. We thus provide the stack chain of `first_wasm_state` to
236 // traverse the potential continuation stacks. For the subsequent
237 // activations, we unconditionally use `None` as the corresponding stack
238 // chain. This is justified because only the most recent execution of
239 // wasm may execute off the initial stack (see comments in
240 // `wasmtime::invoke_wasm_and_catch_traps` for details).
241 //
242 // An activation with a zero PC entered no Wasm (e.g. `Func::call` of a
243 // host function) and is skipped, but older activations may still hold
244 // Wasm frames.
245 let activations =
246 core::iter::once((stack_chain, last_wasm_exit_pc, last_wasm_exit_fp, unsafe {
247 *(*vm_store_context).last_wasm_entry_fp.get()
248 }))
249 .chain(
250 state
251 .iter()
252 .filter(|state| {
253 core::ptr::eq(vm_store_context, state.vm_store_context.get().as_ptr())
254 })
255 .map(|state| unsafe {
256 (
257 state.old_stack_chain(),
258 state.old_last_wasm_exit_pc(),
259 state.old_last_wasm_exit_fp(),
260 state.old_last_wasm_entry_fp(),
261 )
262 }),
263 )
264 .filter(|(chain, pc, fp, sp)| {
265 if *pc == 0 {
266 debug_assert_eq!(*fp, 0);
267 debug_assert_eq!(*sp, 0);
268 } else {
269 debug_assert_ne!(chain.clone(), VMStackChain::Absent)
270 }
271 *pc != 0
272 });
273
274 for (chain, exit_pc, exit_fp, entry_trampoline_fp) in activations {
275 let res = unsafe {
276 Self::trace_through_continuations(
277 chain,
278 exit_pc,
279 exit_fp,
280 entry_trampoline_fp,
281 &mut f,
282 )
283 };
284 if let ControlFlow::Break(()) = res {
285 log::trace!("====== Done Capturing Backtrace (closure break) ======");
286 return;
287 }
288 }
289
290 log::trace!("====== Done Capturing Backtrace (reached end of activations) ======");
291 }
292
293 /// Traces through a sequence of stacks, creating a backtrace for each one,
294 /// beginning at the given `pc` and `fp`.
295 ///
296 /// If `chain` is `InitialStack`, we are tracing through the initial stack,
297 /// and this function behaves like `trace_through_wasm`.
298 /// Otherwise, we can interpret `chain` as a linked list of stacks, which
299 /// ends with the initial stack. We then trace through each of these stacks
300 /// individually, up to (and including) the initial stack.
301 unsafe fn trace_through_continuations(
302 chain: VMStackChain,
303 exit_pc: usize,
304 exit_fp: usize,
305 entry_trampoline_fp: usize,
306 mut f: impl FnMut(Activation) -> ControlFlow<()>,
307 ) -> ControlFlow<()> {
308 use crate::runtime::vm::VMStackLimits;
309
310 // Handle the stack that is currently running (which may be a
311 // continuation or the initial stack).
312 f(Activation {
313 exit_pc,
314 exit_fp,
315 entry_trampoline_fp,
316 })?;
317
318 // Note that the rest of this function has no effect if `chain` is
319 // `Some(VMStackChain::InitialStack(_))` (i.e., there is only one stack to
320 // trace through: the initial stack)
321
322 assert_ne!(chain, VMStackChain::Absent);
323
324 // Iterate through the continuation chain without collecting into Vecs,
325 // avoiding allocation. The stack_limits iterator starts one ahead of
326 // continuations (we skip the first entry, which belongs to the
327 // currently running stack already handled above). Each continuation's
328 // control context describes how to resume in its parent stack, so we
329 // pair continuations[i] with stack_limits[i + 1].
330 let mut stack_limits_iter = unsafe { chain.clone().into_stack_limits_iter() };
331 // Skip the first stack limits (current running stack, handled above).
332 let _current: Option<core::ptr::NonNull<VMStackLimits>> = stack_limits_iter.next();
333
334 let mut continuations_iter = unsafe { chain.into_continuation_iter() }.peekable();
335
336 while let Some(continuation_ptr) = continuations_iter.next() {
337 let continuation = unsafe { continuation_ptr.as_ref() };
338 let Some(parent_limits_ptr) = stack_limits_iter.next() else {
339 // A detached suspended continuation chain ends in `Absent`,
340 // unlike a running chain which ends in an initial stack. The
341 // currently suspended stack was already traced above, and the
342 // last continuation has no parent stack left to trace.
343 debug_assert_eq!(continuation.parent_chain, VMStackChain::Absent);
344 break;
345 };
346 let parent_limits = unsafe { parent_limits_ptr.as_ref() };
347
348 // The parent of `continuation` if present and not the last in the chain.
349 let parent_continuation = continuations_iter.peek().map(|c| unsafe { c.as_ref() });
350
351 let fiber_stack = continuation.fiber_stack();
352 let resume_pc = fiber_stack.control_context_instruction_pointer();
353 let resume_fp = fiber_stack.control_context_frame_pointer();
354
355 // If the parent is indeed a continuation, we know the
356 // boundaries of its stack and can perform some extra debugging
357 // checks.
358 let parent_stack_range = parent_continuation.and_then(|p| p.fiber_stack().range());
359 parent_stack_range.inspect(|parent_stack_range| {
360 debug_assert!(parent_stack_range.contains(&resume_fp));
361 debug_assert!(parent_stack_range.contains(&parent_limits.last_wasm_entry_fp));
362 debug_assert!(parent_stack_range.contains(&parent_limits.stack_limit));
363 });
364
365 f(Activation {
366 exit_pc: resume_pc,
367 exit_fp: resume_fp,
368 entry_trampoline_fp: parent_limits.last_wasm_entry_fp,
369 })?;
370 }
371 ControlFlow::Continue(())
372 }
373
374 /// Capture all Activations reachable from the current point
375 /// within a hostcall.
376 #[cfg(feature = "debug")]
377 pub(crate) fn activations(store: &StoreOpaque) -> Vec<Activation> {
378 let mut activations = vec![];
379 let vm_store_context = store.vm_store_context();
380 tls::with(|state| match state {
381 Some(state) => unsafe {
382 Self::trace_with_trap_state(vm_store_context, state, None, |act| {
383 activations.push(act);
384 ControlFlow::Continue(())
385 });
386 },
387 None => {}
388 });
389 activations
390 }
391
392 /// Iterate over the frames inside this backtrace.
393 pub fn frames<'a>(
394 &'a self,
395 ) -> impl ExactSizeIterator<Item = &'a Frame> + DoubleEndedIterator + 'a {
396 self.0.iter()
397 }
398}