1 //! Debugging API.
2 
3 use super::store::AsStoreOpaque;
4 use crate::store::StoreId;
5 use crate::vm::{Activation, Backtrace};
6 use crate::{
7     AnyRef, AsContextMut, CodeMemory, ExnRef, Extern, ExternRef, Func, Instance, Module,
8     OwnedRooted, StoreContext, StoreContextMut, Val,
9     code::StoreCodePC,
10     module::ModuleRegistry,
11     store::{AutoAssertNoGc, StoreOpaque},
12     vm::{CompiledModuleId, VMContext},
13 };
14 use crate::{Caller, Result, Store};
15 use alloc::collections::{BTreeMap, BTreeSet, btree_map::Entry};
16 use alloc::vec;
17 use alloc::vec::Vec;
18 use core::{ffi::c_void, ptr::NonNull};
19 #[cfg(feature = "gc")]
20 use wasmtime_environ::FrameTable;
21 use wasmtime_environ::{
22     DefinedFuncIndex, EntityIndex, FrameInstPos, FrameStackShape, FrameStateSlot,
23     FrameStateSlotOffset, FrameTableBreakpointData, FrameTableDescriptorIndex, FrameValType,
24     FuncIndex, FuncKey, GlobalIndex, MemoryIndex, TableIndex, TagIndex, Trap,
25 };
26 use wasmtime_unwinder::{Frame, FrameCursor};
27 
28 impl<T> Store<T> {
29     /// Provide a frame handle for all activations, in order from
30     /// innermost (most recently called) to outermost on the stack.
31     ///
32     /// An activation is a contiguous sequence of Wasm frames (called
33     /// functions) that were called from host code and called back out
34     /// to host code. If there are activations from multiple stores on
35     /// the stack, for example if Wasm code in one store calls out to
36     /// host code which invokes another Wasm function in another
37     /// store, then the other stores are "opaque" to our view here in
38     /// the same way that host code is.
39     ///
40     /// Returns an empty list if debug instrumentation is not enabled
41     /// for the engine containing this store.
42     pub fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
43         self.as_store_opaque().debug_exit_frames()
44     }
45 
46     /// Start an edit session to update breakpoints.
47     pub fn edit_breakpoints<'a>(&'a mut self) -> Option<BreakpointEdit<'a>> {
48         self.as_store_opaque().edit_breakpoints()
49     }
50 }
51 
52 impl StoreOpaque {
53     fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
54         let activations = if self.engine().tunables().debug_guest {
55             Backtrace::activations(self)
56         } else {
57             vec![]
58         };
59 
60         activations
61             .into_iter()
62             // SAFETY: each activation is currently active and will
63             // remain so (we have a mutable borrow of the store).
64             .filter_map(|act| unsafe { FrameHandle::exit_frame(self, act) })
65     }
66 
67     fn edit_breakpoints<'a>(&'a mut self) -> Option<BreakpointEdit<'a>> {
68         if !self.engine().tunables().debug_guest {
69             return None;
70         }
71 
72         let (breakpoints, registry) = self.breakpoints_and_registry_mut();
73         Some(breakpoints.edit(registry))
74     }
75 }
76 
77 impl<'a, T> StoreContextMut<'a, T> {
78     /// Provide a frame handle for all activations, in order from
79     /// innermost (most recently called) to outermost on the stack.
80     ///
81     /// See [`Store::debug_exit_frames`] for more details.
82     pub fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
83         self.0.as_store_opaque().debug_exit_frames()
84     }
85 
86     /// Start an edit session to update breakpoints.
87     pub fn edit_breakpoints(self) -> Option<BreakpointEdit<'a>> {
88         self.0.as_store_opaque().edit_breakpoints()
89     }
90 }
91 
92 impl<'a, T> Caller<'a, T> {
93     /// Provide a frame handle for all activations, in order from
94     /// innermost (most recently called) to outermost on the stack.
95     ///
96     /// See [`Store::debug_exit_frames`] for more details.
97     pub fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
98         self.store.0.as_store_opaque().debug_exit_frames()
99     }
100 }
101 
102 impl Instance {
103     /// Get access to a global within this instance's globals index
104     /// space.
105     ///
106     /// This permits accessing globals whether they are exported or
107     /// not. However, it is only available for purposes of debugging,
108     /// and so is only permitted when `guest_debug` is enabled in the
109     /// Engine's configuration. The intent of the Wasmtime API is to
110     /// enforce the Wasm type system's encapsulation even in the host
111     /// API, except where necessary for developer tooling.
112     ///
113     /// `None` is returned for any global index that is out-of-bounds.
114     ///
115     /// `None` is returned if guest-debugging is not enabled in the
116     /// engine configuration for this Store.
117     pub fn debug_global(
118         &self,
119         mut store: impl AsContextMut,
120         global_index: u32,
121     ) -> Option<crate::Global> {
122         self.debug_export(
123             store.as_context_mut().0,
124             GlobalIndex::from_bits(global_index).into(),
125         )
126         .and_then(|s| s.into_global())
127     }
128 
129     /// Get access to a memory (unshared only) within this instance's
130     /// memory index space.
131     ///
132     /// This permits accessing memories whether they are exported or
133     /// not. However, it is only available for purposes of debugging,
134     /// and so is only permitted when `guest_debug` is enabled in the
135     /// Engine's configuration. The intent of the Wasmtime API is to
136     /// enforce the Wasm type system's encapsulation even in the host
137     /// API, except where necessary for developer tooling.
138     ///
139     /// `None` is returned for any memory index that is out-of-bounds.
140     ///
141     /// `None` is returned for any shared memory (use
142     /// `debug_shared_memory` instead).
143     ///
144     /// `None` is returned if guest-debugging is not enabled in the
145     /// engine configuration for this Store.
146     pub fn debug_memory(
147         &self,
148         mut store: impl AsContextMut,
149         memory_index: u32,
150     ) -> Option<crate::Memory> {
151         self.debug_export(
152             store.as_context_mut().0,
153             MemoryIndex::from_bits(memory_index).into(),
154         )
155         .and_then(|s| s.into_memory())
156     }
157 
158     /// Get access to a shared memory within this instance's memory
159     /// index space.
160     ///
161     /// This permits accessing memories whether they are exported or
162     /// not. However, it is only available for purposes of debugging,
163     /// and so is only permitted when `guest_debug` is enabled in the
164     /// Engine's configuration. The intent of the Wasmtime API is to
165     /// enforce the Wasm type system's encapsulation even in the host
166     /// API, except where necessary for developer tooling.
167     ///
168     /// `None` is returned for any memory index that is out-of-bounds.
169     ///
170     /// `None` is returned for any unshared memory (use `debug_memory`
171     /// instead).
172     ///
173     /// `None` is returned if guest-debugging is not enabled in the
174     /// engine configuration for this Store.
175     pub fn debug_shared_memory(
176         &self,
177         mut store: impl AsContextMut,
178         memory_index: u32,
179     ) -> Option<crate::SharedMemory> {
180         self.debug_export(
181             store.as_context_mut().0,
182             MemoryIndex::from_bits(memory_index).into(),
183         )
184         .and_then(|s| s.into_shared_memory())
185     }
186 
187     /// Get access to a table within this instance's table index
188     /// space.
189     ///
190     /// This permits accessing tables whether they are exported or
191     /// not. However, it is only available for purposes of debugging,
192     /// and so is only permitted when `guest_debug` is enabled in the
193     /// Engine's configuration. The intent of the Wasmtime API is to
194     /// enforce the Wasm type system's encapsulation even in the host
195     /// API, except where necessary for developer tooling.
196     ///
197     /// `None` is returned for any table index that is out-of-bounds.
198     ///
199     /// `None` is returned if guest-debugging is not enabled in the
200     /// engine configuration for this Store.
201     pub fn debug_table(
202         &self,
203         mut store: impl AsContextMut,
204         table_index: u32,
205     ) -> Option<crate::Table> {
206         self.debug_export(
207             store.as_context_mut().0,
208             TableIndex::from_bits(table_index).into(),
209         )
210         .and_then(|s| s.into_table())
211     }
212 
213     /// Get access to a function within this instance's function index
214     /// space.
215     ///
216     /// This permits accessing functions whether they are exported or
217     /// not. However, it is only available for purposes of debugging,
218     /// and so is only permitted when `guest_debug` is enabled in the
219     /// Engine's configuration. The intent of the Wasmtime API is to
220     /// enforce the Wasm type system's encapsulation even in the host
221     /// API, except where necessary for developer tooling.
222     ///
223     /// `None` is returned for any function index that is
224     /// out-of-bounds.
225     ///
226     /// `None` is returned if guest-debugging is not enabled in the
227     /// engine configuration for this Store.
228     pub fn debug_function(
229         &self,
230         mut store: impl AsContextMut,
231         function_index: u32,
232     ) -> Option<crate::Func> {
233         self.debug_export(
234             store.as_context_mut().0,
235             FuncIndex::from_bits(function_index).into(),
236         )
237         .and_then(|s| s.into_func())
238     }
239 
240     /// Get access to a tag within this instance's tag index space.
241     ///
242     /// This permits accessing tags whether they are exported or
243     /// not. However, it is only available for purposes of debugging,
244     /// and so is only permitted when `guest_debug` is enabled in the
245     /// Engine's configuration. The intent of the Wasmtime API is to
246     /// enforce the Wasm type system's encapsulation even in the host
247     /// API, except where necessary for developer tooling.
248     ///
249     /// `None` is returned for any tag index that is out-of-bounds.
250     ///
251     /// `None` is returned if guest-debugging is not enabled in the
252     /// engine configuration for this Store.
253     pub fn debug_tag(&self, mut store: impl AsContextMut, tag_index: u32) -> Option<crate::Tag> {
254         self.debug_export(
255             store.as_context_mut().0,
256             TagIndex::from_bits(tag_index).into(),
257         )
258         .and_then(|s| s.into_tag())
259     }
260 
261     fn debug_export(&self, store: &mut StoreOpaque, index: EntityIndex) -> Option<Extern> {
262         if !store.engine().tunables().debug_guest {
263             return None;
264         }
265 
266         let env_module = self._module(store).env_module();
267         if !env_module.is_valid(index) {
268             return None;
269         }
270         let store_id = store.id();
271         let (instance, registry) = store.instance_and_module_registry_mut(self.id());
272         // SAFETY: the `store` and `registry` are associated with
273         // this instance as we fetched the instance directly from
274         // the store above.
275         let export = unsafe { instance.get_export_by_index_mut(registry, store_id, index) };
276         Some(Extern::from_wasmtime_export(export, store))
277     }
278 }
279 
280 impl<'a, T> StoreContext<'a, T> {
281     /// Return all breakpoints.
282     pub fn breakpoints(self) -> Option<impl Iterator<Item = Breakpoint> + 'a> {
283         if !self.engine().tunables().debug_guest {
284             return None;
285         }
286 
287         let (breakpoints, registry) = self.0.breakpoints_and_registry();
288         Some(breakpoints.breakpoints(registry))
289     }
290 
291     /// Indicate whether single-step mode is enabled.
292     pub fn is_single_step(&self) -> bool {
293         let (breakpoints, _) = self.0.breakpoints_and_registry();
294         breakpoints.is_single_step()
295     }
296 }
297 
298 /// A handle to a stack frame, valid as long as execution is not
299 /// resumed in the associated `Store`.
300 ///
301 /// This handle can be held and cloned and used to refer to a frame
302 /// within a paused store. It is cheap: it internally consists of a
303 /// pointer to the actual frame, together with some metadata to
304 /// determine when that pointer has gone stale.
305 ///
306 /// At the API level, any usage of this frame handle requires a
307 /// mutable borrow of the `Store`, because the `Store` logically owns
308 /// the stack(s) for any execution within it. However, the existence
309 /// of the handle itself does not hold a borrow on the `Store`; hence,
310 /// the `Store` can continue to be used and queried, and some state
311 /// (e.g. memories, tables, GC objects) can even be mutated, as long
312 /// as execution is not resumed. The intent of this API is to allow a
313 /// wide variety of debugger implementation strategies that expose
314 /// stack frames and also allow other commands/actions at the same
315 /// time.
316 ///
317 /// The user can use [`FrameHandle::is_valid`] to determine if the
318 /// handle is still valid and usable.
319 #[derive(Clone)]
320 pub struct FrameHandle {
321     /// The unwinder cursor at this frame.
322     cursor: FrameCursor,
323 
324     /// The index of the virtual frame within the physical frame.
325     virtual_frame_idx: usize,
326 
327     /// The unique Store this frame came from, to ensure the handle is
328     /// used with the correct Store.
329     store_id: StoreId,
330 
331     /// Store `execution_version`.
332     store_version: u64,
333 }
334 
335 impl FrameHandle {
336     /// Create a new FrameHandle at the exit frame of an activation.
337     ///
338     /// # Safety
339     ///
340     /// The provided activation must be valid currently.
341     unsafe fn exit_frame(store: &mut StoreOpaque, activation: Activation) -> Option<FrameHandle> {
342         // SAFETY: activation is valid as per our safety condition.
343         let mut cursor = unsafe { activation.cursor() };
344 
345         // Find the first virtual frame. Each physical frame may have
346         // zero or more virtual frames.
347         while !cursor.done() {
348             let (cache, registry) = store.frame_data_cache_mut_and_registry();
349             let frames = cache.lookup_or_compute(registry, cursor.frame());
350             if frames.len() > 0 {
351                 return Some(FrameHandle {
352                     cursor,
353                     virtual_frame_idx: 0,
354                     store_id: store.id(),
355                     store_version: store.vm_store_context().execution_version,
356                 });
357             }
358             // SAFETY: activation is still valid (valid on entry per
359             // our safety condition, and we have not returned control
360             // since above).
361             unsafe {
362                 cursor.advance(store.unwinder());
363             }
364         }
365 
366         None
367     }
368 
369     /// Determine whether this handle can still be used to refer to a
370     /// frame.
371     pub fn is_valid(&self, mut store: impl AsContextMut) -> bool {
372         let store = store.as_context_mut();
373         self.is_valid_impl(store.0.as_store_opaque())
374     }
375 
376     fn is_valid_impl(&self, store: &StoreOpaque) -> bool {
377         let id = store.id();
378         let version = store.vm_store_context().execution_version;
379         self.store_id == id && self.store_version == version
380     }
381 
382     /// Get a handle to the next frame up the activation (the one that
383     /// called this frame), if any.
384     pub fn parent(&self, mut store: impl AsContextMut) -> Result<Option<FrameHandle>> {
385         let mut store = store.as_context_mut();
386         if !self.is_valid(&mut store) {
387             crate::error::bail!("Frame handle is no longer valid.");
388         }
389 
390         let mut parent = self.clone();
391         parent.virtual_frame_idx += 1;
392 
393         while !parent.cursor.done() {
394             let (cache, registry) = store
395                 .0
396                 .as_store_opaque()
397                 .frame_data_cache_mut_and_registry();
398             let frames = cache.lookup_or_compute(registry, parent.cursor.frame());
399             if parent.virtual_frame_idx < frames.len() {
400                 return Ok(Some(parent));
401             }
402             parent.virtual_frame_idx = 0;
403             // SAFETY: activation is valid because we checked validity
404             // wrt execution version at the top of this function, and
405             // we have not returned since.
406             unsafe {
407                 parent.cursor.advance(store.0.as_store_opaque().unwinder());
408             }
409         }
410 
411         Ok(None)
412     }
413 
414     fn frame_data<'a>(&self, store: &'a mut StoreOpaque) -> Result<&'a FrameData> {
415         if !self.is_valid_impl(store) {
416             crate::error::bail!("Frame handle is no longer valid.");
417         }
418         let (cache, registry) = store.frame_data_cache_mut_and_registry();
419         let frames = cache.lookup_or_compute(registry, self.cursor.frame());
420         // `virtual_frame_idx` counts up for ease of iteration
421         // behavior, while the frames are stored in outer-to-inner
422         // (i.e., caller to callee) order, so we need to reverse here.
423         Ok(&frames[frames.len() - 1 - self.virtual_frame_idx])
424     }
425 
426     fn raw_instance<'a>(&self, store: &mut StoreOpaque) -> Result<&'a crate::vm::Instance> {
427         let frame_data = self.frame_data(store)?;
428 
429         // Read out the vmctx slot.
430 
431         // SAFETY: vmctx is always at offset 0 in the slot.  (See
432         // crates/cranelift/src/func_environ.rs in
433         // `update_stack_slot_vmctx()`.)  The frame/activation is
434         // still valid because we verified this in `frame_data` above.
435         let vmctx: *mut VMContext =
436             unsafe { *(frame_data.slot_addr(self.cursor.frame().fp()) as *mut _) };
437         let vmctx = NonNull::new(vmctx).expect("null vmctx in debug state slot");
438         // SAFETY: the stored vmctx value is a valid instance in this
439         // store; we only visit frames from this store in the
440         // backtrace.
441         let instance = unsafe { crate::vm::Instance::from_vmctx(vmctx) };
442         // SAFETY: the instance pointer read above is valid.
443         Ok(unsafe { instance.as_ref() })
444     }
445 
446     /// Get the instance associated with the current frame.
447     pub fn instance(&self, mut store: impl AsContextMut) -> Result<Instance> {
448         let store = store.as_context_mut();
449         let instance = self.raw_instance(store.0.as_store_opaque())?;
450         let id = instance.id();
451         Ok(Instance::from_wasmtime(id, store.0.as_store_opaque()))
452     }
453 
454     /// Get the module associated with the current frame, if any
455     /// (i.e., not a container instance for a host-created entity).
456     pub fn module<'a, T: 'static>(
457         &self,
458         store: impl Into<StoreContextMut<'a, T>>,
459     ) -> Result<Option<&'a Module>> {
460         let store = store.into();
461         let instance = self.raw_instance(store.0.as_store_opaque())?;
462         Ok(instance.runtime_module())
463     }
464 
465     /// Get the raw function index associated with the current frame, and the
466     /// PC as an offset within its code section, if it is a Wasm
467     /// function directly from the given `Module` (rather than a
468     /// trampoline).
469     pub fn wasm_function_index_and_pc(
470         &self,
471         mut store: impl AsContextMut,
472     ) -> Result<Option<(DefinedFuncIndex, u32)>> {
473         let mut store = store.as_context_mut();
474         let frame_data = self.frame_data(store.0.as_store_opaque())?;
475         let FuncKey::DefinedWasmFunction(module, func) = frame_data.func_key else {
476             return Ok(None);
477         };
478         let wasm_pc = frame_data.wasm_pc;
479         debug_assert_eq!(
480             module,
481             self.module(&mut store)?
482                 .expect("module should be defined if this is a defined function")
483                 .env_module()
484                 .module_index
485         );
486         Ok(Some((func, wasm_pc)))
487     }
488 
489     /// Get the number of locals in this frame.
490     pub fn num_locals(&self, mut store: impl AsContextMut) -> Result<u32> {
491         let store = store.as_context_mut();
492         let frame_data = self.frame_data(store.0.as_store_opaque())?;
493         Ok(u32::try_from(frame_data.locals.len()).unwrap())
494     }
495 
496     /// Get the depth of the operand stack in this frame.
497     pub fn num_stacks(&self, mut store: impl AsContextMut) -> Result<u32> {
498         let store = store.as_context_mut();
499         let frame_data = self.frame_data(store.0.as_store_opaque())?;
500         Ok(u32::try_from(frame_data.stack.len()).unwrap())
501     }
502 
503     /// Get the type and value of the given local in this frame.
504     ///
505     /// # Panics
506     ///
507     /// Panics if the index is out-of-range (greater than
508     /// `num_locals()`).
509     pub fn local(&self, mut store: impl AsContextMut, index: u32) -> Result<Val> {
510         let store = store.as_context_mut();
511         let frame_data = self.frame_data(store.0.as_store_opaque())?;
512         let (offset, ty) = frame_data.locals[usize::try_from(index).unwrap()];
513         let slot_addr = frame_data.slot_addr(self.cursor.frame().fp());
514         // SAFETY: compiler produced metadata to describe this local
515         // slot and stored a value of the correct type into it. Slot
516         // address is valid because we checked liveness of the
517         // activation/frame via `frame_data` above.
518         Ok(unsafe { read_value(store.0.as_store_opaque(), slot_addr, offset, ty) })
519     }
520 
521     /// Get the type and value of the given operand-stack value in
522     /// this frame.
523     ///
524     /// Index 0 corresponds to the bottom-of-stack, and higher indices
525     /// from there are more recently pushed values.  In other words,
526     /// index order reads the Wasm virtual machine's abstract stack
527     /// state left-to-right.
528     pub fn stack(&self, mut store: impl AsContextMut, index: u32) -> Result<Val> {
529         let store = store.as_context_mut();
530         let frame_data = self.frame_data(store.0.as_store_opaque())?;
531         let (offset, ty) = frame_data.stack[usize::try_from(index).unwrap()];
532         let slot_addr = frame_data.slot_addr(self.cursor.frame().fp());
533         // SAFETY: compiler produced metadata to describe this
534         // operand-stack slot and stored a value of the correct type
535         // into it. Slot address is valid because we checked liveness
536         // of the activation/frame via `frame_data` above.
537         Ok(unsafe { read_value(store.0.as_store_opaque(), slot_addr, offset, ty) })
538     }
539 }
540 
541 /// A cache from `StoreCodePC`s for modules' private code within a
542 /// store to pre-computed layout data for the virtual stack frame(s)
543 /// present at that physical PC.
544 pub(crate) struct FrameDataCache {
545     /// For a given physical PC, the list of virtual frames, from
546     /// inner (most recently called/inlined) to outer.
547     by_pc: BTreeMap<StoreCodePC, Vec<FrameData>>,
548 }
549 
550 impl FrameDataCache {
551     pub(crate) fn new() -> FrameDataCache {
552         FrameDataCache {
553             by_pc: BTreeMap::new(),
554         }
555     }
556 
557     /// Look up (or compute) the list of `FrameData`s from a physical
558     /// `Frame`.
559     fn lookup_or_compute<'a>(
560         &'a mut self,
561         registry: &ModuleRegistry,
562         frame: Frame,
563     ) -> &'a [FrameData] {
564         let pc = StoreCodePC::from_raw(frame.pc());
565         match self.by_pc.entry(pc) {
566             Entry::Occupied(frames) => frames.into_mut(),
567             Entry::Vacant(v) => {
568                 // Although inlining can mix modules, `module` is the
569                 // module that actually contains the physical PC
570                 // (i.e., the outermost function that inlined the
571                 // others).
572                 let (module, frames) = VirtualFrame::decode(registry, frame.pc());
573                 let frames = frames
574                     .into_iter()
575                     .map(|frame| FrameData::compute(frame, &module))
576                     .collect::<Vec<_>>();
577                 v.insert(frames)
578             }
579         }
580     }
581 }
582 
583 /// Internal data pre-computed for one stack frame.
584 ///
585 /// This represents one frame as produced by the progpoint lookup
586 /// (Wasm PC, frame descriptor index, stack shape).
587 struct VirtualFrame {
588     /// The Wasm PC for this frame.
589     wasm_pc: u32,
590     /// The frame descriptor for this frame.
591     frame_descriptor: FrameTableDescriptorIndex,
592     /// The stack shape for this frame.
593     stack_shape: FrameStackShape,
594 }
595 
596 impl VirtualFrame {
597     /// Return virtual frames corresponding to a physical frame, from
598     /// outermost to innermost.
599     fn decode(registry: &ModuleRegistry, pc: usize) -> (Module, Vec<VirtualFrame>) {
600         let (module_with_code, pc) = registry
601             .module_and_code_by_pc(pc)
602             .expect("Wasm frame PC does not correspond to a module");
603         let module = module_with_code.module();
604         let table = module.frame_table().unwrap();
605         let pc = u32::try_from(pc).expect("PC offset too large");
606         let program_points = table.find_program_point(pc, FrameInstPos::Post)
607             .expect("There must be a program point record in every frame when debug instrumentation is enabled");
608 
609         (
610             module.clone(),
611             program_points
612                 .map(|(wasm_pc, frame_descriptor, stack_shape)| VirtualFrame {
613                     wasm_pc,
614                     frame_descriptor,
615                     stack_shape,
616                 })
617                 .collect(),
618         )
619     }
620 }
621 
622 /// Data computed when we visit a given frame.
623 struct FrameData {
624     slot_to_fp_offset: usize,
625     func_key: FuncKey,
626     wasm_pc: u32,
627     /// Shape of locals in this frame.
628     ///
629     /// We need to store this locally because `FrameView` cannot
630     /// borrow the store: it needs a mut borrow, and an iterator
631     /// cannot yield the same mut borrow multiple times because it
632     /// cannot control the lifetime of the values it yields (the
633     /// signature of `next()` does not bound the return value to the
634     /// `&mut self` arg).
635     locals: Vec<(FrameStateSlotOffset, FrameValType)>,
636     /// Shape of the stack slots at this program point in this frame.
637     ///
638     /// In addition to the borrowing-related reason above, we also
639     /// materialize this because we want to provide O(1) access to the
640     /// stack by depth, and the frame slot descriptor stores info in a
641     /// linked-list (actually DAG, with dedup'ing) way.
642     stack: Vec<(FrameStateSlotOffset, FrameValType)>,
643 }
644 
645 impl FrameData {
646     fn compute(frame: VirtualFrame, module: &Module) -> Self {
647         let frame_table = module.frame_table().unwrap();
648         // Parse the frame descriptor.
649         let (data, slot_to_fp_offset) = frame_table
650             .frame_descriptor(frame.frame_descriptor)
651             .unwrap();
652         let frame_state_slot = FrameStateSlot::parse(data).unwrap();
653         let slot_to_fp_offset = usize::try_from(slot_to_fp_offset).unwrap();
654 
655         // Materialize the stack shape so we have O(1) access to its
656         // elements, and so we don't need to keep the borrow to the
657         // module alive.
658         let mut stack = frame_state_slot
659             .stack(frame.stack_shape)
660             .collect::<Vec<_>>();
661         stack.reverse(); // Put top-of-stack last.
662 
663         // Materialize the local offsets/types so we don't need to
664         // keep the borrow to the module alive.
665         let locals = frame_state_slot.locals().collect::<Vec<_>>();
666 
667         FrameData {
668             slot_to_fp_offset,
669             func_key: frame_state_slot.func_key(),
670             wasm_pc: frame.wasm_pc,
671             stack,
672             locals,
673         }
674     }
675 
676     fn slot_addr(&self, fp: usize) -> *mut u8 {
677         let fp: *mut u8 = core::ptr::with_exposed_provenance_mut(fp);
678         fp.wrapping_sub(self.slot_to_fp_offset)
679     }
680 }
681 
682 /// Read the value at the given offset.
683 ///
684 /// # Safety
685 ///
686 /// The `offset` and `ty` must correspond to a valid value written
687 /// to the frame by generated code of the correct type. This will
688 /// be the case if this information comes from the frame tables
689 /// (as long as the frontend that generates the tables and
690 /// instrumentation is correct, and as long as the tables are
691 /// preserved through serialization).
692 unsafe fn read_value(
693     store: &mut StoreOpaque,
694     slot_base: *const u8,
695     offset: FrameStateSlotOffset,
696     ty: FrameValType,
697 ) -> Val {
698     let address = unsafe { slot_base.offset(isize::try_from(offset.offset()).unwrap()) };
699 
700     // SAFETY: each case reads a value from memory that should be
701     // valid according to our safety condition.
702     match ty {
703         FrameValType::I32 => {
704             let value = unsafe { *(address as *const i32) };
705             Val::I32(value)
706         }
707         FrameValType::I64 => {
708             let value = unsafe { *(address as *const i64) };
709             Val::I64(value)
710         }
711         FrameValType::F32 => {
712             let value = unsafe { *(address as *const u32) };
713             Val::F32(value)
714         }
715         FrameValType::F64 => {
716             let value = unsafe { *(address as *const u64) };
717             Val::F64(value)
718         }
719         FrameValType::V128 => {
720             let value = unsafe { *(address as *const u128) };
721             Val::V128(value.into())
722         }
723         FrameValType::AnyRef => {
724             let mut nogc = AutoAssertNoGc::new(store);
725             let value = unsafe { *(address as *const u32) };
726             let value = AnyRef::_from_raw(&mut nogc, value);
727             Val::AnyRef(value)
728         }
729         FrameValType::ExnRef => {
730             let mut nogc = AutoAssertNoGc::new(store);
731             let value = unsafe { *(address as *const u32) };
732             let value = ExnRef::_from_raw(&mut nogc, value);
733             Val::ExnRef(value)
734         }
735         FrameValType::ExternRef => {
736             let mut nogc = AutoAssertNoGc::new(store);
737             let value = unsafe { *(address as *const u32) };
738             let value = ExternRef::_from_raw(&mut nogc, value);
739             Val::ExternRef(value)
740         }
741         FrameValType::FuncRef => {
742             let value = unsafe { *(address as *const *mut c_void) };
743             let value = unsafe { Func::_from_raw(store, value) };
744             Val::FuncRef(value)
745         }
746         FrameValType::ContRef => {
747             unimplemented!("contref values are not implemented in the host API yet")
748         }
749     }
750 }
751 
752 /// Compute raw pointers to all GC refs in the given frame.
753 // Note: ideally this would be an impl Iterator, but this is quite
754 // awkward because of the locally computed data (FrameStateSlot::parse
755 // structured result) within the closure borrowed by a nested closure.
756 #[cfg(feature = "gc")]
757 pub(crate) fn gc_refs_in_frame<'a>(ft: FrameTable<'a>, pc: u32, fp: *mut usize) -> Vec<*mut u32> {
758     let fp = fp.cast::<u8>();
759     let mut ret = vec![];
760     if let Some(frames) = ft.find_program_point(pc, FrameInstPos::Post) {
761         for (_wasm_pc, frame_desc, stack_shape) in frames {
762             let (frame_desc_data, slot_to_fp_offset) = ft.frame_descriptor(frame_desc).unwrap();
763             let frame_base = unsafe { fp.offset(-isize::try_from(slot_to_fp_offset).unwrap()) };
764             let frame_desc = FrameStateSlot::parse(frame_desc_data).unwrap();
765             for (offset, ty) in frame_desc.stack_and_locals(stack_shape) {
766                 match ty {
767                     FrameValType::AnyRef | FrameValType::ExnRef | FrameValType::ExternRef => {
768                         let slot = unsafe {
769                             frame_base
770                                 .offset(isize::try_from(offset.offset()).unwrap())
771                                 .cast::<u32>()
772                         };
773                         ret.push(slot);
774                     }
775                     FrameValType::ContRef | FrameValType::FuncRef => {}
776                     FrameValType::I32
777                     | FrameValType::I64
778                     | FrameValType::F32
779                     | FrameValType::F64
780                     | FrameValType::V128 => {}
781                 }
782             }
783         }
784     }
785     ret
786 }
787 
788 /// One debug event that occurs when running Wasm code on a store with
789 /// a debug handler attached.
790 #[derive(Debug)]
791 pub enum DebugEvent<'a> {
792     /// A [`wasmtime::Error`](crate::Error) was raised by a hostcall.
793     HostcallError(&'a crate::Error),
794     /// An exception is thrown and caught by Wasm. The current state
795     /// is at the throw-point.
796     CaughtExceptionThrown(OwnedRooted<ExnRef>),
797     /// An exception was not caught and is escaping to the host.
798     UncaughtExceptionThrown(OwnedRooted<ExnRef>),
799     /// A Wasm trap occurred.
800     Trap(Trap),
801     /// A breakpoint was reached.
802     Breakpoint,
803     /// An epoch yield occurred.
804     EpochYield,
805 }
806 
807 /// A handler for debug events.
808 ///
809 /// This is an async callback that is invoked directly within the
810 /// context of a debug event that occurs, i.e., with the Wasm code
811 /// still on the stack. The callback can thus observe that stack, up
812 /// to the most recent entry to Wasm.[^1]
813 ///
814 /// Because this callback receives a `StoreContextMut`, it has full
815 /// access to any state that any other hostcall has, including the
816 /// `T`. In that way, it is like an epoch-deadline callback or a
817 /// call-hook callback. It also "freezes" the entire store for the
818 /// duration of the debugger callback future.
819 ///
820 /// In the future, we expect to provide an "externally async" API on
821 /// the `Store` that allows receiving a stream of debug events and
822 /// accessing the store mutably while frozen; that will need to
823 /// integrate with [`Store::run_concurrent`] to properly timeslice and
824 /// scope the mutable access to the store, and has not been built
825 /// yet. In the meantime, it should be possible to build a fully
826 /// functional debugger with this async-callback API by channeling
827 /// debug events out, and requests to read the store back in, over
828 /// message-passing channels between the callback and an external
829 /// debugger main loop.
830 ///
831 /// Note that the `handle` hook may use its mutable store access to
832 /// invoke another Wasm. Debug events will also be caught and will
833 /// cause further `handle` invocations during this recursive
834 /// invocation. It is up to the debugger to handle any implications of
835 /// this reentrancy (e.g., implications on a duplex channel protocol
836 /// with an event/continue handshake) if it does so.
837 ///
838 /// Note also that this trait has `Clone` as a supertrait, and the
839 /// handler is cloned at every invocation as an artifact of the
840 /// internal ownership structure of Wasmtime: the handler itself is
841 /// owned by the store, but also receives a mutable borrow to the
842 /// whole store, so we need to clone it out to invoke it. It is
843 /// recommended that this trait be implemented by a type that is cheap
844 /// to clone: for example, a single `Arc` handle to debugger state.
845 ///
846 /// [^1]: Providing visibility further than the most recent entry to
847 ///       Wasm is not directly possible because it could see into
848 ///       another async stack, and the stack that polls the future
849 ///       running a particular Wasm invocation could change after each
850 ///       suspend point in the handler.
851 ///
852 /// [`Store::run_concurrent`]: crate::Store::run_concurrent
853 pub trait DebugHandler: Clone + Send + Sync + 'static {
854     /// The data expected on the store that this handler is attached
855     /// to.
856     type Data;
857 
858     /// Handle a debug event.
859     fn handle(
860         &self,
861         store: StoreContextMut<'_, Self::Data>,
862         event: DebugEvent<'_>,
863     ) -> impl Future<Output = ()> + Send;
864 }
865 
866 /// Breakpoint state for modules within a store.
867 #[derive(Default)]
868 pub(crate) struct BreakpointState {
869     /// Single-step mode.
870     single_step: bool,
871     /// Breakpoints added individually.
872     breakpoints: BTreeSet<BreakpointKey>,
873 }
874 
875 /// A breakpoint.
876 pub struct Breakpoint {
877     /// Reference to the module in which we are setting the breakpoint.
878     pub module: Module,
879     /// Wasm PC offset within the module.
880     pub pc: u32,
881 }
882 
883 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
884 struct BreakpointKey(CompiledModuleId, u32);
885 
886 impl BreakpointKey {
887     fn from_raw(module: &Module, pc: u32) -> BreakpointKey {
888         BreakpointKey(module.id(), pc)
889     }
890 
891     fn get(&self, registry: &ModuleRegistry) -> Breakpoint {
892         let module = registry
893             .module_by_compiled_id(self.0)
894             .expect("Module should not have been removed from Store")
895             .clone();
896         Breakpoint { module, pc: self.1 }
897     }
898 }
899 
900 /// A breakpoint-editing session.
901 ///
902 /// This enables updating breakpoint state (setting or unsetting
903 /// individual breakpoints or the store-global single-step flag) in a
904 /// batch. It is more efficient to batch these updates because
905 /// "re-publishing" the newly patched code, with update breakpoint
906 /// settings, typically requires a syscall to re-enable execute
907 /// permissions.
908 pub struct BreakpointEdit<'a> {
909     state: &'a mut BreakpointState,
910     registry: &'a mut ModuleRegistry,
911     /// Modules that have been edited.
912     ///
913     /// Invariant: each of these modules' CodeMemory objects is
914     /// *unpublished* when in the dirty set.
915     dirty_modules: BTreeSet<StoreCodePC>,
916 }
917 
918 impl BreakpointState {
919     pub(crate) fn edit<'a>(&'a mut self, registry: &'a mut ModuleRegistry) -> BreakpointEdit<'a> {
920         BreakpointEdit {
921             state: self,
922             registry,
923             dirty_modules: BTreeSet::new(),
924         }
925     }
926 
927     pub(crate) fn breakpoints<'a>(
928         &'a self,
929         registry: &'a ModuleRegistry,
930     ) -> impl Iterator<Item = Breakpoint> + 'a {
931         self.breakpoints.iter().map(|key| key.get(registry))
932     }
933 
934     pub(crate) fn is_single_step(&self) -> bool {
935         self.single_step
936     }
937 }
938 
939 impl<'a> BreakpointEdit<'a> {
940     fn get_code_memory<'b>(
941         registry: &'b mut ModuleRegistry,
942         dirty_modules: &mut BTreeSet<StoreCodePC>,
943         module: &Module,
944     ) -> Result<&'b mut CodeMemory> {
945         let store_code_pc = registry.store_code_base_or_register(module)?;
946         let code_memory = registry
947             .store_code_mut(store_code_pc)
948             .expect("Just checked presence above")
949             .code_memory_mut()
950             .expect("Must have unique ownership of StoreCode in guest-debug mode");
951         if dirty_modules.insert(store_code_pc) {
952             code_memory.unpublish()?;
953         }
954         Ok(code_memory)
955     }
956 
957     fn patch<'b>(
958         patches: impl Iterator<Item = FrameTableBreakpointData<'b>> + 'b,
959         mem: &mut CodeMemory,
960         enable: bool,
961     ) {
962         let mem = mem.text_mut();
963         for patch in patches {
964             let data = if enable { patch.enable } else { patch.disable };
965             let mem = &mut mem[patch.offset..patch.offset + data.len()];
966             log::trace!(
967                 "patch: offset 0x{:x} with enable={enable}: data {data:?} replacing {mem:?}",
968                 patch.offset
969             );
970             mem.copy_from_slice(data);
971         }
972     }
973 
974     /// Add a breakpoint in the given module at the given PC in that
975     /// module.
976     ///
977     /// No effect if the breakpoint is already set.
978     pub fn add_breakpoint(&mut self, module: &Module, pc: u32) -> Result<()> {
979         let key = BreakpointKey::from_raw(module, pc);
980         self.state.breakpoints.insert(key);
981         log::trace!("patching in breakpoint {key:?}");
982         let mem = Self::get_code_memory(self.registry, &mut self.dirty_modules, module)?;
983         let frame_table = module
984             .frame_table()
985             .expect("Frame table must be present when guest-debug is enabled");
986         let patches = frame_table.lookup_breakpoint_patches_by_pc(pc);
987         Self::patch(patches, mem, true);
988         Ok(())
989     }
990 
991     /// Remove a breakpoint in the given module at the given PC in
992     /// that module.
993     ///
994     /// No effect if the breakpoint was not set.
995     pub fn remove_breakpoint(&mut self, module: &Module, pc: u32) -> Result<()> {
996         let key = BreakpointKey::from_raw(module, pc);
997         self.state.breakpoints.remove(&key);
998         if !self.state.single_step {
999             let mem = Self::get_code_memory(self.registry, &mut self.dirty_modules, module)?;
1000             let frame_table = module
1001                 .frame_table()
1002                 .expect("Frame table must be present when guest-debug is enabled");
1003             let patches = frame_table.lookup_breakpoint_patches_by_pc(pc);
1004             Self::patch(patches, mem, false);
1005         }
1006         Ok(())
1007     }
1008 
1009     /// Turn on or off single-step mode.
1010     ///
1011     /// In single-step mode, a breakpoint event is emitted at every
1012     /// Wasm PC.
1013     pub fn single_step(&mut self, enabled: bool) -> Result<()> {
1014         log::trace!(
1015             "single_step({enabled}) with breakpoint set {:?}",
1016             self.state.breakpoints
1017         );
1018         let modules = self.registry.all_modules().cloned().collect::<Vec<_>>();
1019         for module in modules {
1020             let mem = Self::get_code_memory(self.registry, &mut self.dirty_modules, &module)?;
1021             let table = module
1022                 .frame_table()
1023                 .expect("Frame table must be present when guest-debug is enabled");
1024             for (wasm_pc, patch) in table.breakpoint_patches() {
1025                 let key = BreakpointKey::from_raw(&module, wasm_pc);
1026                 let this_enabled = enabled || self.state.breakpoints.contains(&key);
1027                 log::trace!(
1028                     "single_step: enabled {enabled} key {key:?} -> this_enabled {this_enabled}"
1029                 );
1030                 Self::patch(core::iter::once(patch), mem, this_enabled);
1031             }
1032         }
1033 
1034         self.state.single_step = enabled;
1035 
1036         Ok(())
1037     }
1038 }
1039 
1040 impl<'a> Drop for BreakpointEdit<'a> {
1041     fn drop(&mut self) {
1042         for &store_code_base in &self.dirty_modules {
1043             let store_code = self.registry.store_code_mut(store_code_base).unwrap();
1044             if let Err(e) = store_code
1045                 .code_memory_mut()
1046                 .expect("Must have unique ownership of StoreCode in guest-debug mode")
1047                 .publish()
1048             {
1049                 abort_on_republish_error(e);
1050             }
1051         }
1052     }
1053 }
1054 
1055 /// Abort when we cannot re-publish executable code.
1056 ///
1057 /// Note that this puts us in quite a conundrum. Typically we will
1058 /// have been editing breakpoints from within a hostcall context
1059 /// (e.g. inside a debugger hook while execution is paused) with JIT
1060 /// code on the stack. Wasmtime's usual path to return errors is back
1061 /// through that JIT code: we do not panic-unwind across the JIT code,
1062 /// we return into the exit trampoline and that then re-enters the
1063 /// raise libcall to use a Cranelift exception-throw to cross most of
1064 /// the JIT frames to the entry trampoline. When even trampolines are
1065 /// no longer executable, we have no way out. Even an ordinary
1066 /// `panic!` cannot work, because we catch panics and carry them
1067 /// across JIT code using that trampoline-based error path. Our only
1068 /// way out is to directly abort the whole process.
1069 ///
1070 /// This is not without precedent: other engines have similar failure
1071 /// paths. For example, SpiderMonkey directly aborts the process when
1072 /// failing to re-apply executable permissions (see [1]).
1073 ///
1074 /// Note that we don't really expect to ever hit this case in
1075 /// practice: it's unlikely that `mprotect` applying `PROT_EXEC` would
1076 /// fail due to, e.g., resource exhaustion in the kernel, because we
1077 /// will have the same net number of virtual memory areas before and
1078 /// after the permissions change. Nevertheless, we have to account for
1079 /// the possibility of error.
1080 ///
1081 /// [1]: https://searchfox.org/firefox-main/rev/7496c8515212669451d7e775a00c2be07da38ca5/js/src/jit/AutoWritableJitCode.h#26-56
1082 #[cfg(feature = "std")]
1083 fn abort_on_republish_error(e: crate::Error) -> ! {
1084     log::error!(
1085         "Failed to re-publish executable code: {e:?}. Wasmtime cannot return through JIT code on the stack and cannot even panic; aborting the process."
1086     );
1087     std::process::abort();
1088 }
1089 
1090 /// In the `no_std` case, we don't have a concept of a "process
1091 /// abort", so rely on `panic!`. Typically an embedded scenario that
1092 /// uses `no_std` will build with `panic=abort` so the effect is the
1093 /// same. If it doesn't, there is truly nothing we can do here so
1094 /// let's panic anyway; the panic propagation through the trampolines
1095 /// will at least deterministically crash.
1096 #[cfg(not(feature = "std"))]
1097 fn abort_on_republish_error(e: crate::Error) -> ! {
1098     panic!("Failed to re-publish executable code: {e:?}");
1099 }
1100