Path: blob/main/crates/unwinder/src/stackwalk.rs
1692 views
//! Stack-walking of a Wasm stack.1//!2//! A stack walk requires a first and last frame pointer (FP), and it3//! only works on code that has been compiled with frame pointers4//! enabled (`preserve_frame_pointers` Cranelift option enabled). The5//! stack walk follows the singly-linked list of saved frame pointer6//! and return address pairs on the stack that is naturally built by7//! function prologues.8//!9//! This crate makes use of the fact that Wasmtime surrounds Wasm10//! frames by trampolines both at entry and exit, and is "up the11//! stack" from the point doing the unwinding: in other words, host12//! code invokes Wasm code via an entry trampoline, that code may call13//! other Wasm code, and ultimately it calls back to host code via an14//! exit trampoline. That exit trampoline is able to provide the15//! "start FP" (FP at exit trampoline) and "end FP" (FP at entry16//! trampoline) and this stack-walker can visit all Wasm frames17//! active on the stack between those two.18//!19//! This module provides a visitor interface to frames, but is20//! agnostic to the desired use-case or consumer of the frames, and to21//! the overall runtime structure.2223use core::ops::ControlFlow;2425/// Implementation necessary to unwind the stack, used by `Backtrace`.26///27/// # Safety28///29/// This trait is `unsafe` because the return values of each function are30/// required to be semantically correct when connected to the `visit_frames`31/// function below. Incorrect and/or arbitrary values in this trait will cause32/// unwinding to segfault or otherwise result in UB.33pub unsafe trait Unwind {34/// Returns the offset, from the current frame pointer, of where to get to35/// the previous frame pointer on the stack.36fn next_older_fp_from_fp_offset(&self) -> usize;3738/// Returns the offset, from the current frame pointer, of the39/// stack pointer of the next older frame.40fn next_older_sp_from_fp_offset(&self) -> usize;4142/// Load the return address of a frame given the frame pointer for that43/// frame.44///45/// # Safety46///47/// This function is expected to read raw memory from `fp` and thus is not48/// safe to operate on any value of `fp` passed in, instead it must be a49/// trusted Cranelift-defined frame pointer.50unsafe fn get_next_older_pc_from_fp(&self, fp: usize) -> usize;5152/// Debug assertion that the frame pointer is aligned.53fn assert_fp_is_aligned(&self, fp: usize);54}5556/// A stack frame within a Wasm stack trace.57#[derive(Debug)]58pub struct Frame {59/// The program counter in this frame. Because every frame in the60/// stack-walk is paused at a call (as we are in host code called61/// by Wasm code below these frames), the PC is at the return62/// address, i.e., points to the instruction after the call63/// instruction.64pc: usize,65/// The frame pointer value corresponding to this frame.66fp: usize,67}6869impl Frame {70/// Get this frame's program counter.71pub fn pc(&self) -> usize {72self.pc73}7475/// Get this frame's frame pointer.76pub fn fp(&self) -> usize {77self.fp78}7980/// Read out a machine-word-sized value at the given offset from81/// FP in this frame.82///83/// # Safety84///85/// Requires that this frame is a valid, active frame. A `Frame`86/// provided by `visit_frames()` will be valid for the duration of87/// the invoked closure.88///89/// Requires that `offset` falls within the size of this90/// frame. This ordinarily requires knowledge passed from the91/// compiler that produced the running function, e.g., Cranelift.92pub unsafe fn read_slot_from_fp(&self, offset: isize) -> usize {93// SAFETY: we required that this is a valid frame, and that94// `offset` is a valid offset within that frame.95unsafe { *(self.fp.wrapping_add_signed(offset) as *mut usize) }96}97}9899/// Walk through a contiguous sequence of Wasm frames starting with100/// the frame at the given PC and FP and ending at101/// `trampoline_fp`. This FP should correspond to that of a trampoline102/// that was used to enter the Wasm code.103///104/// We require that the initial PC, FP, and `trampoline_fp` values are105/// non-null (non-zero).106///107/// # Safety108///109/// This function is not safe as `unwind`, `pc`, `fp`, and `trampoline_fp` must110/// all be "correct" in that if they're wrong or mistakenly have the wrong value111/// then this method may segfault. These values must point to valid Wasmtime112/// compiled code which respects the frame pointers that Wasmtime currently113/// requires.114pub unsafe fn visit_frames<R>(115unwind: &dyn Unwind,116mut pc: usize,117mut fp: usize,118trampoline_fp: usize,119mut f: impl FnMut(Frame) -> ControlFlow<R>,120) -> ControlFlow<R> {121log::trace!("=== Tracing through contiguous sequence of Wasm frames ===");122log::trace!("trampoline_fp = 0x{trampoline_fp:016x}");123log::trace!(" initial pc = 0x{pc:016x}");124log::trace!(" initial fp = 0x{fp:016x}");125126// Safety requirements documented above.127assert_ne!(pc, 0);128assert_ne!(fp, 0);129assert_ne!(trampoline_fp, 0);130131// This loop will walk the linked list of frame pointers starting132// at `fp` and going up until `trampoline_fp`. We know that both133// `fp` and `trampoline_fp` are "trusted values" aka generated and134// maintained by Wasmtime. This means that it should be safe to135// walk the linked list of pointers and inspect Wasm frames.136//137// Note, though, that any frames outside of this range are not138// guaranteed to have valid frame pointers. For example native code139// might be using the frame pointer as a general purpose register. Thus140// we need to be careful to only walk frame pointers in this one141// contiguous linked list.142//143// To know when to stop iteration all architectures' stacks currently144// look something like this:145//146// | ... |147// | Native Frames |148// | ... |149// |-------------------|150// | ... | <-- Trampoline FP |151// | Trampoline Frame | |152// | ... | <-- Trampoline SP |153// |-------------------| Stack154// | Return Address | Grows155// | Previous FP | <-- Wasm FP Down156// | ... | |157// | Cranelift Frames | |158// | ... | V159//160// The trampoline records its own frame pointer (`trampoline_fp`),161// which is guaranteed to be above all Wasm code. To check when162163// to check when the next frame pointer is equal to164// `trampoline_fp`. Once that's hit then we know that the entire165// linked list has been traversed.166//167// Note that it might be possible that this loop doesn't execute168// at all. For example if the entry trampoline called Wasm code169// which `return_call`'d an exit trampoline, then `fp ==170// trampoline_fp` on the entry of this function, meaning the loop171// won't actually execute anything.172while fp != trampoline_fp {173// At the start of each iteration of the loop, we know that174// `fp` is a frame pointer from Wasm code. Therefore, we know175// it is not being used as an extra general-purpose register,176// and it is safe dereference to get the PC and the next older177// frame pointer.178//179// The stack also grows down, and therefore any frame pointer180// we are dealing with should be less than the frame pointer181// on entry to Wasm code. Finally also assert that it's182// aligned correctly as an additional sanity check.183assert!(trampoline_fp > fp, "{trampoline_fp:#x} > {fp:#x}");184unwind.assert_fp_is_aligned(fp);185186log::trace!("--- Tracing through one Wasm frame ---");187log::trace!("pc = {:p}", pc as *const ());188log::trace!("fp = {:p}", fp as *const ());189190f(Frame { pc, fp })?;191192// SAFETY: this unsafe traversal of the linked list on the stack is193// reflected in the contract of this function where `pc`, `fp`,194// `trampoline_fp`, and `unwind` must all be trusted/correct values.195unsafe {196pc = unwind.get_next_older_pc_from_fp(fp);197198// We rely on this offset being zero for all supported199// architectures in200// `crates/cranelift/src/component/compiler.s`r when we set201// the Wasm exit FP. If this ever changes, we will need to202// update that code as well!203assert_eq!(unwind.next_older_fp_from_fp_offset(), 0);204205// Get the next older frame pointer from the current Wasm206// frame pointer.207let next_older_fp = *(fp as *mut usize).add(unwind.next_older_fp_from_fp_offset());208209// Because the stack always grows down, the older FP must be greater210// than the current FP.211assert!(next_older_fp > fp, "{next_older_fp:#x} > {fp:#x}");212fp = next_older_fp;213}214}215216log::trace!("=== Done tracing contiguous sequence of Wasm frames ===");217ControlFlow::Continue(())218}219220221