Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bytecodealliance
GitHub Repository: bytecodealliance/wasmtime
Path: blob/main/crates/unwinder/src/stackwalk.rs
1692 views
1
//! Stack-walking of a Wasm stack.
2
//!
3
//! A stack walk requires a first and last frame pointer (FP), and it
4
//! only works on code that has been compiled with frame pointers
5
//! enabled (`preserve_frame_pointers` Cranelift option enabled). The
6
//! stack walk follows the singly-linked list of saved frame pointer
7
//! and return address pairs on the stack that is naturally built by
8
//! function prologues.
9
//!
10
//! This crate makes use of the fact that Wasmtime surrounds Wasm
11
//! frames by trampolines both at entry and exit, and is "up the
12
//! stack" from the point doing the unwinding: in other words, host
13
//! code invokes Wasm code via an entry trampoline, that code may call
14
//! other Wasm code, and ultimately it calls back to host code via an
15
//! exit trampoline. That exit trampoline is able to provide the
16
//! "start FP" (FP at exit trampoline) and "end FP" (FP at entry
17
//! trampoline) and this stack-walker can visit all Wasm frames
18
//! active on the stack between those two.
19
//!
20
//! This module provides a visitor interface to frames, but is
21
//! agnostic to the desired use-case or consumer of the frames, and to
22
//! the overall runtime structure.
23
24
use core::ops::ControlFlow;
25
26
/// Implementation necessary to unwind the stack, used by `Backtrace`.
27
///
28
/// # Safety
29
///
30
/// This trait is `unsafe` because the return values of each function are
31
/// required to be semantically correct when connected to the `visit_frames`
32
/// function below. Incorrect and/or arbitrary values in this trait will cause
33
/// unwinding to segfault or otherwise result in UB.
34
pub unsafe trait Unwind {
35
/// Returns the offset, from the current frame pointer, of where to get to
36
/// the previous frame pointer on the stack.
37
fn next_older_fp_from_fp_offset(&self) -> usize;
38
39
/// Returns the offset, from the current frame pointer, of the
40
/// stack pointer of the next older frame.
41
fn next_older_sp_from_fp_offset(&self) -> usize;
42
43
/// Load the return address of a frame given the frame pointer for that
44
/// frame.
45
///
46
/// # Safety
47
///
48
/// This function is expected to read raw memory from `fp` and thus is not
49
/// safe to operate on any value of `fp` passed in, instead it must be a
50
/// trusted Cranelift-defined frame pointer.
51
unsafe fn get_next_older_pc_from_fp(&self, fp: usize) -> usize;
52
53
/// Debug assertion that the frame pointer is aligned.
54
fn assert_fp_is_aligned(&self, fp: usize);
55
}
56
57
/// A stack frame within a Wasm stack trace.
58
#[derive(Debug)]
59
pub struct Frame {
60
/// The program counter in this frame. Because every frame in the
61
/// stack-walk is paused at a call (as we are in host code called
62
/// by Wasm code below these frames), the PC is at the return
63
/// address, i.e., points to the instruction after the call
64
/// instruction.
65
pc: usize,
66
/// The frame pointer value corresponding to this frame.
67
fp: usize,
68
}
69
70
impl Frame {
71
/// Get this frame's program counter.
72
pub fn pc(&self) -> usize {
73
self.pc
74
}
75
76
/// Get this frame's frame pointer.
77
pub fn fp(&self) -> usize {
78
self.fp
79
}
80
81
/// Read out a machine-word-sized value at the given offset from
82
/// FP in this frame.
83
///
84
/// # Safety
85
///
86
/// Requires that this frame is a valid, active frame. A `Frame`
87
/// provided by `visit_frames()` will be valid for the duration of
88
/// the invoked closure.
89
///
90
/// Requires that `offset` falls within the size of this
91
/// frame. This ordinarily requires knowledge passed from the
92
/// compiler that produced the running function, e.g., Cranelift.
93
pub unsafe fn read_slot_from_fp(&self, offset: isize) -> usize {
94
// SAFETY: we required that this is a valid frame, and that
95
// `offset` is a valid offset within that frame.
96
unsafe { *(self.fp.wrapping_add_signed(offset) as *mut usize) }
97
}
98
}
99
100
/// Walk through a contiguous sequence of Wasm frames starting with
101
/// the frame at the given PC and FP and ending at
102
/// `trampoline_fp`. This FP should correspond to that of a trampoline
103
/// that was used to enter the Wasm code.
104
///
105
/// We require that the initial PC, FP, and `trampoline_fp` values are
106
/// non-null (non-zero).
107
///
108
/// # Safety
109
///
110
/// This function is not safe as `unwind`, `pc`, `fp`, and `trampoline_fp` must
111
/// all be "correct" in that if they're wrong or mistakenly have the wrong value
112
/// then this method may segfault. These values must point to valid Wasmtime
113
/// compiled code which respects the frame pointers that Wasmtime currently
114
/// requires.
115
pub unsafe fn visit_frames<R>(
116
unwind: &dyn Unwind,
117
mut pc: usize,
118
mut fp: usize,
119
trampoline_fp: usize,
120
mut f: impl FnMut(Frame) -> ControlFlow<R>,
121
) -> ControlFlow<R> {
122
log::trace!("=== Tracing through contiguous sequence of Wasm frames ===");
123
log::trace!("trampoline_fp = 0x{trampoline_fp:016x}");
124
log::trace!(" initial pc = 0x{pc:016x}");
125
log::trace!(" initial fp = 0x{fp:016x}");
126
127
// Safety requirements documented above.
128
assert_ne!(pc, 0);
129
assert_ne!(fp, 0);
130
assert_ne!(trampoline_fp, 0);
131
132
// This loop will walk the linked list of frame pointers starting
133
// at `fp` and going up until `trampoline_fp`. We know that both
134
// `fp` and `trampoline_fp` are "trusted values" aka generated and
135
// maintained by Wasmtime. This means that it should be safe to
136
// walk the linked list of pointers and inspect Wasm frames.
137
//
138
// Note, though, that any frames outside of this range are not
139
// guaranteed to have valid frame pointers. For example native code
140
// might be using the frame pointer as a general purpose register. Thus
141
// we need to be careful to only walk frame pointers in this one
142
// contiguous linked list.
143
//
144
// To know when to stop iteration all architectures' stacks currently
145
// look something like this:
146
//
147
// | ... |
148
// | Native Frames |
149
// | ... |
150
// |-------------------|
151
// | ... | <-- Trampoline FP |
152
// | Trampoline Frame | |
153
// | ... | <-- Trampoline SP |
154
// |-------------------| Stack
155
// | Return Address | Grows
156
// | Previous FP | <-- Wasm FP Down
157
// | ... | |
158
// | Cranelift Frames | |
159
// | ... | V
160
//
161
// The trampoline records its own frame pointer (`trampoline_fp`),
162
// which is guaranteed to be above all Wasm code. To check when
163
164
// to check when the next frame pointer is equal to
165
// `trampoline_fp`. Once that's hit then we know that the entire
166
// linked list has been traversed.
167
//
168
// Note that it might be possible that this loop doesn't execute
169
// at all. For example if the entry trampoline called Wasm code
170
// which `return_call`'d an exit trampoline, then `fp ==
171
// trampoline_fp` on the entry of this function, meaning the loop
172
// won't actually execute anything.
173
while fp != trampoline_fp {
174
// At the start of each iteration of the loop, we know that
175
// `fp` is a frame pointer from Wasm code. Therefore, we know
176
// it is not being used as an extra general-purpose register,
177
// and it is safe dereference to get the PC and the next older
178
// frame pointer.
179
//
180
// The stack also grows down, and therefore any frame pointer
181
// we are dealing with should be less than the frame pointer
182
// on entry to Wasm code. Finally also assert that it's
183
// aligned correctly as an additional sanity check.
184
assert!(trampoline_fp > fp, "{trampoline_fp:#x} > {fp:#x}");
185
unwind.assert_fp_is_aligned(fp);
186
187
log::trace!("--- Tracing through one Wasm frame ---");
188
log::trace!("pc = {:p}", pc as *const ());
189
log::trace!("fp = {:p}", fp as *const ());
190
191
f(Frame { pc, fp })?;
192
193
// SAFETY: this unsafe traversal of the linked list on the stack is
194
// reflected in the contract of this function where `pc`, `fp`,
195
// `trampoline_fp`, and `unwind` must all be trusted/correct values.
196
unsafe {
197
pc = unwind.get_next_older_pc_from_fp(fp);
198
199
// We rely on this offset being zero for all supported
200
// architectures in
201
// `crates/cranelift/src/component/compiler.s`r when we set
202
// the Wasm exit FP. If this ever changes, we will need to
203
// update that code as well!
204
assert_eq!(unwind.next_older_fp_from_fp_offset(), 0);
205
206
// Get the next older frame pointer from the current Wasm
207
// frame pointer.
208
let next_older_fp = *(fp as *mut usize).add(unwind.next_older_fp_from_fp_offset());
209
210
// Because the stack always grows down, the older FP must be greater
211
// than the current FP.
212
assert!(next_older_fp > fp, "{next_older_fp:#x} > {fp:#x}");
213
fp = next_older_fp;
214
}
215
}
216
217
log::trace!("=== Done tracing contiguous sequence of Wasm frames ===");
218
ControlFlow::Continue(())
219
}
220
221