Skip to main content

wasmtime/runtime/
debug.rs

1//! Debugging API.
2
3use super::store::AsStoreOpaque;
4use crate::code::StoreCode;
5use crate::module::RegisterBreakpointState;
6use crate::runtime::epoch_state::EpochStateHandle;
7use crate::store::WasmState;
8use crate::sync::RwLock;
9use crate::vm::{Activation, Backtrace};
10use crate::{
11    AnyRef, AsContext, AsContextMut, CodeMemory, ExnRef, Extern, ExternRef, Func, Instance, Module,
12    OwnedRooted, StoreContext, StoreContextMut, Unrooted, Val,
13    code::StoreCodePC,
14    module::ModuleRegistry,
15    store::StoreOpaque,
16    vm::{CompiledModuleId, VMContext},
17};
18use crate::{Caller, Result, Store};
19use alloc::collections::{BTreeMap, BTreeSet};
20use alloc::sync::Arc;
21use alloc::vec;
22use alloc::vec::Vec;
23use core::ops::Range;
24use core::{ffi::c_void, ptr::NonNull};
25use wasmtime_environ::FrameTable;
26// Re-export ModulePC so downstream crates can use it.
27pub use wasmtime_environ::ModulePC;
28use wasmtime_environ::{
29    DefinedFuncIndex, EntityIndex, FrameInstPos, FrameStackShape, FrameStateSlot,
30    FrameStateSlotOffset, FrameTableBreakpointData, FrameTableDescriptorIndex, FrameValType,
31    FuncIndex, FuncKey, GlobalIndex, MemoryIndex, TableIndex, TagIndex, Trap,
32};
33use wasmtime_unwinder::{Frame, FrameCursor};
34
35impl<T> Store<T> {
36    /// Provide a frame handle for all activations, in order from
37    /// innermost (most recently called) to outermost on the stack.
38    ///
39    /// An activation is a contiguous sequence of Wasm frames (called
40    /// functions) that were called from host code and called back out
41    /// to host code. If there are activations from multiple stores on
42    /// the stack, for example if Wasm code in one store calls out to
43    /// host code which invokes another Wasm function in another
44    /// store, then the other stores are "opaque" to our view here in
45    /// the same way that host code is.
46    ///
47    /// Returns an empty list if debug instrumentation is not enabled
48    /// for the engine containing this store.
49    pub fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
50        self.as_store_opaque().debug_exit_frames()
51    }
52
53    /// Edit this store's breakpoints, single-stepping, or
54    /// watchpoints, with `f`.
55    ///
56    /// The edits that `f` makes with the given [`BreakpointState`]
57    /// take effect together once it returns `Ok`, and that result is
58    /// returned. If `f` instead returns `Err` (or panics), none of its
59    /// edits take effect. See [`BreakpointState`].
60    ///
61    /// # Errors
62    ///
63    /// Returns an error, and makes no edits, if guest debugging is not
64    /// enabled, if `f` returns an error (which is returned), or if the
65    /// store's code cannot be made writable to patch it.
66    pub fn edit_breakpoints<R>(
67        &mut self,
68        f: impl FnOnce(&mut BreakpointState<'_>) -> Result<R>,
69    ) -> Result<R> {
70        self.as_store_opaque().edit_breakpoints(f)
71    }
72
73    /// Get a vector of all Instances held in the Store, for debug
74    /// purposes.
75    ///
76    /// Guest debugging must be enabled for this accessor to return
77    /// any instances. If it is not, an empty vector is returned.
78    pub fn debug_all_instances(&mut self) -> Vec<Instance> {
79        self.as_store_opaque().debug_all_instances()
80    }
81
82    /// Get a vector of all Modules held in the Store, for debug
83    /// purposes.
84    ///
85    /// Guest debugging must be enabled for this accessor to return
86    /// any modules. If it is not, an empty vector is returned.
87    pub fn debug_all_modules(&mut self) -> Vec<Module> {
88        self.as_store_opaque().debug_all_modules()
89    }
90}
91
92impl<'a, T> StoreContextMut<'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.0.as_store_opaque().debug_exit_frames()
99    }
100
101    /// Edit this store's breakpoints, single-stepping, or
102    /// watchpoints, with `f`.
103    ///
104    /// See [`Store::edit_breakpoints`] for more details.
105    pub fn edit_breakpoints<R>(
106        self,
107        f: impl FnOnce(&mut BreakpointState<'_>) -> Result<R>,
108    ) -> Result<R> {
109        self.0.as_store_opaque().edit_breakpoints(f)
110    }
111
112    /// Get a vector of all Instances held in the Store, for debug
113    /// purposes.
114    ///
115    /// See [`Store::debug_all_instances`] for more details.
116    pub fn debug_all_instances(self) -> Vec<Instance> {
117        self.0.as_store_opaque().debug_all_instances()
118    }
119
120    /// Get a vector of all Modules held in the Store, for debug
121    /// purposes.
122    ///
123    /// See [`Store::debug_all_modules`] for more details.
124    pub fn debug_all_modules(self) -> Vec<Module> {
125        self.0.as_store_opaque().debug_all_modules()
126    }
127}
128
129impl<'a, T> Caller<'a, T> {
130    /// Provide a frame handle for all activations, in order from
131    /// innermost (most recently called) to outermost on the stack.
132    ///
133    /// See [`Store::debug_exit_frames`] for more details.
134    pub fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
135        self.store.0.as_store_opaque().debug_exit_frames()
136    }
137
138    /// Edit this store's breakpoints, single-stepping, or
139    /// watchpoints, with `f`.
140    ///
141    /// See [`Store::edit_breakpoints`] for more details.
142    pub fn edit_breakpoints<R>(
143        &mut self,
144        f: impl FnOnce(&mut BreakpointState<'_>) -> Result<R>,
145    ) -> Result<R> {
146        self.store.0.as_store_opaque().edit_breakpoints(f)
147    }
148
149    /// Get a vector of all Instances held in the Store, for debug
150    /// purposes.
151    ///
152    /// See [`Store::debug_all_instances`] for more details.
153    pub fn debug_all_instances(&mut self) -> Vec<Instance> {
154        self.store.0.as_store_opaque().debug_all_instances()
155    }
156
157    /// Get a vector of all Modules held in the Store, for debug
158    /// purposes.
159    ///
160    /// See [`Store::debug_all_modules`] for more details.
161    pub fn debug_all_modules(&mut self) -> Vec<Module> {
162        self.store.0.as_store_opaque().debug_all_modules()
163    }
164}
165
166impl StoreOpaque {
167    /// Sets or clears the watch bits of the bytes in `range` of `memory`; see
168    /// [`BreakpointState::watch`].
169    /// Check that the bytes in `range` of `memory` can be watched (or
170    /// unwatched), returning the range as indices into its shadow.
171    fn debug_check_watch(&self, memory: crate::Memory, range: Range<u64>) -> Result<Range<usize>> {
172        let Some(shadow) = memory.vm_shadow(self) else {
173            crate::error::bail!("watchpoints require guest debugging");
174        };
175        let start = usize::try_from(range.start)?;
176        let end = usize::try_from(range.end)?;
177        if start > end || end > shadow.bytes().len() {
178            crate::error::bail!("watchpoint range is out of bounds of the memory");
179        }
180        Ok(start..end)
181    }
182
183    /// Watch (or unwatch) the bytes in `range` of `memory`, which
184    /// must have been checked with `debug_check_watch`.
185    fn debug_set_watch(&mut self, memory: crate::Memory, range: Range<usize>, watch: bool) {
186        let shadow = memory
187            .vm_shadow_mut(self)
188            .expect("watch range was checked when it was recorded");
189        for byte in &mut shadow.bytes_mut()[range] {
190            if watch {
191                *byte |= crate::runtime::vm::WATCH_DEBUG;
192            } else {
193                *byte &= !crate::runtime::vm::WATCH_DEBUG;
194            }
195        }
196    }
197
198    fn debug_exit_frames(&mut self) -> impl Iterator<Item = FrameHandle> {
199        let activations = if self.engine().tunables().debug_guest {
200            Backtrace::activations(self)
201        } else {
202            vec![]
203        };
204
205        activations
206            .into_iter()
207            // SAFETY: each activation is currently active and will
208            // remain so (we have a mutable borrow of the store).
209            .filter_map(|act| unsafe { FrameHandle::exit_frame(self, act) })
210    }
211
212    pub(crate) fn edit_breakpoints<R>(
213        &mut self,
214        f: impl FnOnce(&mut BreakpointState<'_>) -> Result<R>,
215    ) -> Result<R> {
216        crate::ensure!(
217            self.engine().tunables().debug_guest,
218            "guest debugging is not enabled"
219        );
220
221        let (breakpoints, _, _) = self.breakpoints_and_registry_and_engine_mut();
222        let edited = breakpoints.clone();
223        let mut state = BreakpointState {
224            store: self,
225            edited,
226            pending: BTreeMap::new(),
227            watches: Vec::new(),
228        };
229        // If `f` fails (or panics), `state` is discarded, and its edits
230        // with it: nothing has been applied to the store, and in
231        // particular all code remains executable.
232        let result = f(&mut state)?;
233        state.commit()?;
234        Ok(result)
235    }
236
237    fn debug_all_instances(&self) -> Vec<Instance> {
238        if !self.engine().tunables().debug_guest {
239            return vec![];
240        }
241
242        self.all_instances().collect()
243    }
244
245    fn debug_all_modules(&self) -> Vec<Module> {
246        if !self.engine().tunables().debug_guest {
247            return vec![];
248        }
249
250        self.modules()
251            .all_modules()
252            .map(|(_, m)| m.clone())
253            .collect()
254    }
255}
256
257impl Instance {
258    /// Get access to a global within this instance's globals index
259    /// space.
260    ///
261    /// This permits accessing globals whether they are exported or
262    /// not. However, it is only available for purposes of debugging,
263    /// and so is only permitted when `guest_debug` is enabled in the
264    /// Engine's configuration. The intent of the Wasmtime API is to
265    /// enforce the Wasm type system's encapsulation even in the host
266    /// API, except where necessary for developer tooling.
267    ///
268    /// `None` is returned for any global index that is out-of-bounds.
269    ///
270    /// `None` is returned if guest-debugging is not enabled in the
271    /// engine configuration for this Store.
272    pub fn debug_global(&self, store: impl AsContext, global_index: u32) -> Option<crate::Global> {
273        self.debug_export(
274            store.as_context().0,
275            GlobalIndex::from_bits(global_index).into(),
276        )
277        .and_then(|s| s.into_global())
278    }
279
280    /// Get access to a memory (unshared only) within this instance's
281    /// memory index space.
282    ///
283    /// This permits accessing memories whether they are exported or
284    /// not. However, it is only available for purposes of debugging,
285    /// and so is only permitted when `guest_debug` is enabled in the
286    /// Engine's configuration. The intent of the Wasmtime API is to
287    /// enforce the Wasm type system's encapsulation even in the host
288    /// API, except where necessary for developer tooling.
289    ///
290    /// `None` is returned for any memory index that is out-of-bounds.
291    ///
292    /// `None` is returned for any shared memory (use
293    /// `debug_shared_memory` instead).
294    ///
295    /// `None` is returned if guest-debugging is not enabled in the
296    /// engine configuration for this Store.
297    pub fn debug_memory(&self, store: impl AsContext, memory_index: u32) -> Option<crate::Memory> {
298        self.debug_export(
299            store.as_context().0,
300            MemoryIndex::from_bits(memory_index).into(),
301        )
302        .and_then(|s| s.into_memory())
303    }
304
305    /// Get access to a shared memory within this instance's memory
306    /// index space.
307    ///
308    /// This permits accessing memories whether they are exported or
309    /// not. However, it is only available for purposes of debugging,
310    /// and so is only permitted when `guest_debug` is enabled in the
311    /// Engine's configuration. The intent of the Wasmtime API is to
312    /// enforce the Wasm type system's encapsulation even in the host
313    /// API, except where necessary for developer tooling.
314    ///
315    /// `None` is returned for any memory index that is out-of-bounds.
316    ///
317    /// `None` is returned for any unshared memory (use `debug_memory`
318    /// instead).
319    ///
320    /// `None` is returned if guest-debugging is not enabled in the
321    /// engine configuration for this Store.
322    pub fn debug_shared_memory(
323        &self,
324        store: impl AsContext,
325        memory_index: u32,
326    ) -> Option<crate::SharedMemory> {
327        self.debug_export(
328            store.as_context().0,
329            MemoryIndex::from_bits(memory_index).into(),
330        )
331        .and_then(|s| s.into_shared_memory())
332    }
333
334    /// Get access to a table within this instance's table index
335    /// space.
336    ///
337    /// This permits accessing tables whether they are exported or
338    /// not. However, it is only available for purposes of debugging,
339    /// and so is only permitted when `guest_debug` is enabled in the
340    /// Engine's configuration. The intent of the Wasmtime API is to
341    /// enforce the Wasm type system's encapsulation even in the host
342    /// API, except where necessary for developer tooling.
343    ///
344    /// `None` is returned for any table index that is out-of-bounds.
345    ///
346    /// `None` is returned if guest-debugging is not enabled in the
347    /// engine configuration for this Store.
348    pub fn debug_table(&self, store: impl AsContext, table_index: u32) -> Option<crate::Table> {
349        self.debug_export(
350            store.as_context().0,
351            TableIndex::from_bits(table_index).into(),
352        )
353        .and_then(|s| s.into_table())
354    }
355
356    /// Get access to a function within this instance's function index
357    /// space.
358    ///
359    /// This permits accessing functions whether they are exported or
360    /// not. However, it is only available for purposes of debugging,
361    /// and so is only permitted when `guest_debug` is enabled in the
362    /// Engine's configuration. The intent of the Wasmtime API is to
363    /// enforce the Wasm type system's encapsulation even in the host
364    /// API, except where necessary for developer tooling.
365    ///
366    /// `None` is returned for any function index that is
367    /// out-of-bounds.
368    ///
369    /// `None` is returned if guest-debugging is not enabled in the
370    /// engine configuration for this Store.
371    pub fn debug_function(
372        &self,
373        mut store: impl AsContextMut,
374        function_index: u32,
375    ) -> Option<crate::Func> {
376        self.debug_export_mut(
377            store.as_context_mut().0,
378            FuncIndex::from_bits(function_index).into(),
379        )
380        .and_then(|s| s.into_func())
381    }
382
383    /// Get access to a tag within this instance's tag index space.
384    ///
385    /// This permits accessing tags whether they are exported or
386    /// not. However, it is only available for purposes of debugging,
387    /// and so is only permitted when `guest_debug` is enabled in the
388    /// Engine's configuration. The intent of the Wasmtime API is to
389    /// enforce the Wasm type system's encapsulation even in the host
390    /// API, except where necessary for developer tooling.
391    ///
392    /// `None` is returned for any tag index that is out-of-bounds.
393    ///
394    /// `None` is returned if guest-debugging is not enabled in the
395    /// engine configuration for this Store.
396    pub fn debug_tag(&self, store: impl AsContext, tag_index: u32) -> Option<crate::Tag> {
397        self.debug_export(store.as_context().0, TagIndex::from_bits(tag_index).into())
398            .and_then(|s| s.into_tag())
399    }
400
401    /// Looks up the entity at `index` in this instance's index
402    /// spaces, for debugging. Returns `None` if guest debugging is
403    /// disabled, if `index` is out of bounds, or if `index` refers to
404    /// a function.
405    ///
406    /// This needs only shared access to the store, so it cannot
407    /// return functions (because of lazy init); use
408    /// `debug_export_mut` for those.
409    fn debug_export(&self, store: &StoreOpaque, index: EntityIndex) -> Option<Extern> {
410        if !store.engine().tunables().debug_guest {
411            return None;
412        }
413
414        let env_module = self._module(store).env_module();
415        if !env_module.is_valid(index) {
416            return None;
417        }
418        let export = store[self.id].get_export_by_index(store.id(), index)?;
419        Some(Extern::from_wasmtime_export(export, store.engine()))
420    }
421
422    /// Like `debug_export`, but also returns functions.
423    ///
424    /// Looking up a function needs mutable access to the store because an
425    /// instance's defined functions' `VMFuncRef`s are initialized lazily, on
426    /// first use, and looking one up may be that first use.
427    fn debug_export_mut(&self, store: &mut StoreOpaque, index: EntityIndex) -> Option<Extern> {
428        if !store.engine().tunables().debug_guest {
429            return None;
430        }
431
432        let env_module = self._module(store).env_module();
433        if !env_module.is_valid(index) {
434            return None;
435        }
436        let store_id = store.id();
437        let (instance, registry) = store.instance_and_module_registry_mut(self.id());
438        // SAFETY: the `store` and `registry` are associated with
439        // this instance as we fetched the instance directly from
440        // the store above.
441        let export = unsafe { instance.get_export_by_index_mut(registry, store_id, index) };
442        Some(Extern::from_wasmtime_export(export, store.engine()))
443    }
444}
445
446impl<'a, T> StoreContext<'a, T> {
447    /// Get a vector of all Instances held in the Store, for debug
448    /// purposes.
449    ///
450    /// See [`Store::debug_all_instances`] for more details.
451    pub fn debug_all_instances(self) -> Vec<Instance> {
452        self.0.debug_all_instances()
453    }
454
455    /// Get a vector of all Modules held in the Store, for debug
456    /// purposes.
457    ///
458    /// See [`Store::debug_all_modules`] for more details.
459    pub fn debug_all_modules(self) -> Vec<Module> {
460        self.0.debug_all_modules()
461    }
462
463    /// Return all breakpoints.
464    pub fn breakpoints(self) -> Option<impl Iterator<Item = Breakpoint> + 'a> {
465        if !self.engine().tunables().debug_guest {
466            return None;
467        }
468
469        let (breakpoints, registry) = self.0.breakpoints_and_registry();
470        Some(breakpoints.breakpoints(registry))
471    }
472
473    /// Indicate whether single-step mode is enabled.
474    pub fn is_single_step(&self) -> bool {
475        let (breakpoints, _) = self.0.breakpoints_and_registry();
476        breakpoints.is_single_step()
477    }
478}
479
480/// A handle to a stack frame, valid as long as execution is not
481/// resumed in the associated `Store`.
482///
483/// This handle can be held and cloned and used to refer to a frame
484/// within a paused store. It is cheap: it internally consists of a
485/// pointer to the actual frame, together with some metadata to
486/// determine when that pointer has gone stale.
487///
488/// At the API level, any usage of this frame handle requires a
489/// mutable borrow of the `Store`, because the `Store` logically owns
490/// the stack(s) for any execution within it. However, the existence
491/// of the handle itself does not hold a borrow on the `Store`; hence,
492/// the `Store` can continue to be used and queried, and some state
493/// (e.g. memories, tables, GC objects) can even be mutated, as long
494/// as execution is not resumed. The intent of this API is to allow a
495/// wide variety of debugger implementation strategies that expose
496/// stack frames and also allow other commands/actions at the same
497/// time.
498///
499/// The user can use [`FrameHandle::is_valid`] to determine if the
500/// handle is still valid and usable.
501#[derive(Clone)]
502pub struct FrameHandle {
503    /// The unwinder cursor at this frame.
504    cursor: FrameCursor,
505
506    /// The index of the virtual frame within the physical frame.
507    virtual_frame_idx: usize,
508
509    /// Encapsulated proof/witness that Wasm has not executed in this
510    /// store since this handle was created. Internally this holds a
511    /// snapshot of the monotonically incrementing counter that is
512    /// bumped whenever Wasm executes in the store.
513    wasm_state: EpochStateHandle<WasmState>,
514}
515
516impl FrameHandle {
517    /// Create a new FrameHandle at the exit frame of an activation.
518    ///
519    /// # Safety
520    ///
521    /// The provided activation must be valid currently.
522    unsafe fn exit_frame(store: &StoreOpaque, activation: Activation) -> Option<FrameHandle> {
523        // SAFETY: activation is valid as per our safety condition.
524        let mut cursor = unsafe { activation.cursor() };
525
526        // Find the first virtual frame. Each physical frame may have
527        // zero or more virtual frames.
528        while !cursor.done() {
529            let frames = FrameDataCache::frames(store, cursor.frame());
530            if frames.len() > 0 {
531                return Some(FrameHandle {
532                    cursor,
533                    virtual_frame_idx: 0,
534                    wasm_state: store.wasm_state().handle(),
535                });
536            }
537            // SAFETY: activation is still valid (valid on entry per
538            // our safety condition, and we have not returned control
539            // since above).
540            unsafe {
541                cursor.advance(store.unwinder());
542            }
543        }
544
545        None
546    }
547
548    /// Determine whether this handle can still be used to refer to a
549    /// frame.
550    ///
551    /// # Panics
552    ///
553    /// Panics if `store` is not the store this frame handle came from.
554    pub fn is_valid(&self, store: impl AsContext) -> bool {
555        self.is_valid_impl(store.as_context().0)
556    }
557
558    fn is_valid_impl(&self, store: &StoreOpaque) -> bool {
559        self.wasm_state.is_valid(store.wasm_state())
560    }
561
562    /// Get a handle to the next frame up the activation (the one that
563    /// called this frame), if any.
564    ///
565    /// # Panics
566    ///
567    /// Panics if `store` is not the store this frame handle came from.
568    pub fn parent(&self, store: impl AsContext) -> Result<Option<FrameHandle>> {
569        let store = store.as_context().0;
570        if !self.is_valid_impl(store) {
571            crate::error::bail!("Frame handle is no longer valid.");
572        }
573
574        let mut parent = self.clone();
575        parent.virtual_frame_idx += 1;
576
577        while !parent.cursor.done() {
578            let frames = FrameDataCache::frames(store, parent.cursor.frame());
579            if parent.virtual_frame_idx < frames.len() {
580                return Ok(Some(parent));
581            }
582            parent.virtual_frame_idx = 0;
583            // SAFETY: activation is valid because we checked validity
584            // wrt execution version at the top of this function, and
585            // we have not returned since.
586            unsafe {
587                parent.cursor.advance(store.unwinder());
588            }
589        }
590
591        Ok(None)
592    }
593
594    fn frame_data(&self, store: &StoreOpaque) -> Result<FrameDataRef> {
595        if !self.is_valid_impl(store) {
596            crate::error::bail!("Frame handle is no longer valid.");
597        }
598        let frames = FrameDataCache::frames(store, self.cursor.frame());
599        // `virtual_frame_idx` counts up for ease of iteration
600        // behavior, while the frames are stored in outer-to-inner
601        // (i.e., caller to callee) order, so we need to reverse here.
602        let index = frames.len() - 1 - self.virtual_frame_idx;
603        Ok(FrameDataRef { frames, index })
604    }
605
606    fn raw_instance<'a>(&self, store: &StoreOpaque) -> Result<&'a crate::vm::Instance> {
607        let frame_data = self.frame_data(store)?;
608
609        // Read out the vmctx slot.
610
611        // SAFETY: vmctx is always at offset 0 in the slot.  (See
612        // crates/cranelift/src/func_environ.rs in
613        // `update_stack_slot_vmctx()`.)  The frame/activation is
614        // still valid because we verified this in `frame_data` above.
615        let vmctx: usize =
616            unsafe { *(frame_data.slot_addr(self.cursor.frame().fp()) as *mut usize) };
617        let vmctx: *mut VMContext = core::ptr::with_exposed_provenance_mut(vmctx);
618        let vmctx = NonNull::new(vmctx).expect("null vmctx in debug state slot");
619        // SAFETY: the stored vmctx value is a valid instance in this
620        // store; we only visit frames from this store in the
621        // backtrace.
622        let instance = unsafe { crate::vm::Instance::from_vmctx(vmctx) };
623        // SAFETY: the instance pointer read above is valid.
624        Ok(unsafe { instance.as_ref() })
625    }
626
627    /// Get the instance associated with the current frame.
628    ///
629    /// # Panics
630    ///
631    /// Panics if `store` is not the store this frame handle came from.
632    pub fn instance(&self, store: impl AsContext) -> Result<Instance> {
633        let store = store.as_context().0;
634        let instance = self.raw_instance(store)?;
635        Ok(Instance::from_wasmtime(instance.id(), store))
636    }
637
638    /// Get the module associated with the current frame, if any
639    /// (i.e., not a container instance for a host-created entity).
640    ///
641    /// # Panics
642    ///
643    /// Panics if `store` is not the store this frame handle came from.
644    pub fn module<'a, T: 'static>(
645        &self,
646        store: impl Into<StoreContext<'a, T>>,
647    ) -> Result<Option<&'a Module>> {
648        let store = store.into();
649        let instance = self.raw_instance(store.0)?;
650        Ok(instance.runtime_module())
651    }
652
653    /// Get the raw function index associated with the current frame, and the
654    /// module-relative PC as an offset within the module binary, if
655    /// this is a Wasm function directly from the given `Module`
656    /// (rather than a trampoline).
657    ///
658    /// # Panics
659    ///
660    /// Panics if `store` is not the store this frame handle came from.
661    pub fn wasm_function_index_and_pc(
662        &self,
663        store: impl AsContext,
664    ) -> Result<Option<(DefinedFuncIndex, ModulePC)>> {
665        let store = store.as_context();
666        let frame_data = self.frame_data(store.0)?;
667        let FuncKey::DefinedWasmFunction(module, func) = frame_data.func_key else {
668            return Ok(None);
669        };
670        let wasm_pc = frame_data.wasm_pc;
671        debug_assert_eq!(
672            module,
673            self.module(&store)?
674                .expect("module should be defined if this is a defined function")
675                .env_module()
676                .module_index
677        );
678        Ok(Some((func, wasm_pc)))
679    }
680
681    /// Get the number of locals in this frame.
682    ///
683    /// # Panics
684    ///
685    /// Panics if `store` is not the store this frame handle came from.
686    pub fn num_locals(&self, store: impl AsContext) -> Result<u32> {
687        let frame_data = self.frame_data(store.as_context().0)?;
688        Ok(u32::try_from(frame_data.locals.len()).unwrap())
689    }
690
691    /// Get the depth of the operand stack in this frame.
692    ///
693    /// # Panics
694    ///
695    /// Panics if `store` is not the store this frame handle came from.
696    pub fn num_stacks(&self, store: impl AsContext) -> Result<u32> {
697        let frame_data = self.frame_data(store.as_context().0)?;
698        Ok(u32::try_from(frame_data.stack.len()).unwrap())
699    }
700
701    /// Get the type and value of the given local in this frame.
702    ///
703    /// A GC reference is returned as an unrooted reference
704    /// ([`MaybeRooted::Unrooted`](crate::MaybeRooted::Unrooted)), valid until
705    /// the store's GC heap next changes, for example when execution resumes;
706    /// root it with [`Val::ensure_rooted`] to keep it for longer.
707    ///
708    /// # Panics
709    ///
710    /// Panics if `store` is not the store this frame handle came
711    /// from, or if the index is out-of-range (greater than
712    /// `num_locals()`).
713    pub fn local(&self, store: impl AsContext, index: u32) -> Result<Val> {
714        let store = store.as_context().0;
715        let frame_data = self.frame_data(store)?;
716        let (offset, ty) = frame_data.locals[usize::try_from(index).unwrap()];
717        let slot_addr = frame_data.slot_addr(self.cursor.frame().fp());
718        // SAFETY: compiler produced metadata to describe this local
719        // slot and stored a value of the correct type into it. Slot
720        // address is valid because we checked liveness of the
721        // activation/frame via `frame_data` above.
722        Ok(unsafe { read_value(store, slot_addr, offset, ty) })
723    }
724
725    /// Get the type and value of the given operand-stack value in
726    /// this frame.
727    ///
728    /// Index 0 corresponds to the bottom-of-stack, and higher indices
729    /// from there are more recently pushed values.  In other words,
730    /// index order reads the Wasm virtual machine's abstract stack
731    /// state left-to-right.
732    ///
733    /// A GC reference is returned as an unrooted reference, as with
734    /// [`FrameHandle::local`].
735    ///
736    /// # Panics
737    ///
738    /// Panics if `store` is not the store this frame handle came
739    /// from, or if the index is out-of-range (greater than
740    /// `num_stacks()`).
741    pub fn stack(&self, store: impl AsContext, index: u32) -> Result<Val> {
742        let store = store.as_context().0;
743        let frame_data = self.frame_data(store)?;
744        let (offset, ty) = frame_data.stack[usize::try_from(index).unwrap()];
745        let slot_addr = frame_data.slot_addr(self.cursor.frame().fp());
746        // SAFETY: compiler produced metadata to describe this
747        // operand-stack slot and stored a value of the correct type
748        // into it. Slot address is valid because we checked liveness
749        // of the activation/frame via `frame_data` above.
750        Ok(unsafe { read_value(store, slot_addr, offset, ty) })
751    }
752}
753
754/// A cache from `StoreCodePC`s for modules' private code within a
755/// store to pre-computed layout data for the virtual stack frame(s)
756/// present at that physical PC.
757pub(crate) struct FrameDataCache {
758    /// For a given physical PC, the list of virtual frames, from
759    /// outer (caller) to inner (most recently called/inlined).
760    by_pc: RwLock<BTreeMap<StoreCodePC, Arc<[FrameData]>>>,
761}
762
763impl FrameDataCache {
764    pub(crate) fn new() -> FrameDataCache {
765        FrameDataCache {
766            by_pc: RwLock::new(BTreeMap::new()),
767        }
768    }
769
770    /// Look up (or compute and cache) the list of `FrameData`s for a
771    /// physical `Frame`.
772    fn frames(store: &StoreOpaque, frame: Frame) -> Arc<[FrameData]> {
773        let pc = StoreCodePC::from_raw(frame.pc());
774        let cache = &store.frame_data_cache().by_pc;
775        if let Some(frames) = cache.read().get(&pc) {
776            return frames.clone();
777        }
778        // Compute without holding the lock. If another thread fills
779        // in the same PC meanwhile, keep whichever was inserted first;
780        // both are equal.
781        let frames: Arc<[FrameData]> = Self::compute(store.modules(), frame).into();
782        cache.write().entry(pc).or_insert(frames).clone()
783    }
784
785    fn compute(registry: &ModuleRegistry, frame: Frame) -> Vec<FrameData> {
786        // Although inlining can mix modules, `module` is the module that
787        // actually contains the physical PC (i.e., the outermost function
788        // that inlined the others).
789        let (frame_table, frames) = VirtualFrame::decode(registry, frame.pc());
790        frames
791            .into_iter()
792            .map(|frame| FrameData::compute(frame, &frame_table))
793            .collect()
794    }
795}
796
797/// A reference to one virtual frame's `FrameData` in a
798/// `FrameDataCache` entry.
799struct FrameDataRef {
800    frames: Arc<[FrameData]>,
801    index: usize,
802}
803
804impl core::ops::Deref for FrameDataRef {
805    type Target = FrameData;
806    fn deref(&self) -> &FrameData {
807        &self.frames[self.index]
808    }
809}
810
811/// Internal data pre-computed for one stack frame.
812///
813/// This represents one frame as produced by the progpoint lookup
814/// (Wasm PC, frame descriptor index, stack shape).
815struct VirtualFrame {
816    /// The module-relative Wasm PC for this frame.
817    wasm_pc: ModulePC,
818    /// The frame descriptor for this frame.
819    frame_descriptor: FrameTableDescriptorIndex,
820    /// The stack shape for this frame.
821    stack_shape: FrameStackShape,
822}
823
824impl VirtualFrame {
825    /// Return virtual frames corresponding to a physical frame, from
826    /// outermost to innermost.
827    ///
828    /// Also returns the frame table for the code containing `pc`.
829    fn decode(registry: &ModuleRegistry, pc: usize) -> (FrameTable<'_>, Vec<VirtualFrame>) {
830        // Note that this frame may be running out of the engine's copy of
831        // code, rather than the store's, if it's a store-invariant function
832        // such as a trampoline; see `code_memory_by_pc`.
833        let (code, offset) = registry
834            .code_memory_by_pc(pc)
835            .expect("Wasm frame PC does not correspond to a module");
836        let table = code.frame_table().unwrap();
837        let pc = u32::try_from(offset).expect("PC offset too large");
838        // Functions without any program points (e.g. the module
839        // start function, or trampolines) have no virtual frames.
840        let frames = table
841            .find_program_point(pc, FrameInstPos::Post)
842            .into_iter()
843            .flatten()
844            .map(|(wasm_pc, frame_descriptor, stack_shape)| VirtualFrame {
845                wasm_pc,
846                frame_descriptor,
847                stack_shape,
848            })
849            .collect();
850
851        (table, frames)
852    }
853}
854
855/// Data computed when we visit a given frame.
856#[derive(Clone)]
857struct FrameData {
858    slot_to_fp_offset: usize,
859    func_key: FuncKey,
860    wasm_pc: ModulePC,
861    /// Shape of locals in this frame.
862    ///
863    /// We need to store this locally because `FrameView` cannot
864    /// borrow the store: it needs a mut borrow, and an iterator
865    /// cannot yield the same mut borrow multiple times because it
866    /// cannot control the lifetime of the values it yields (the
867    /// signature of `next()` does not bound the return value to the
868    /// `&mut self` arg).
869    locals: Vec<(FrameStateSlotOffset, FrameValType)>,
870    /// Shape of the stack slots at this program point in this frame.
871    ///
872    /// In addition to the borrowing-related reason above, we also
873    /// materialize this because we want to provide O(1) access to the
874    /// stack by depth, and the frame slot descriptor stores info in a
875    /// linked-list (actually DAG, with dedup'ing) way.
876    stack: Vec<(FrameStateSlotOffset, FrameValType)>,
877}
878
879impl FrameData {
880    fn compute(frame: VirtualFrame, frame_table: &FrameTable<'_>) -> Self {
881        // Parse the frame descriptor.
882        let (data, slot_to_fp_offset) = frame_table
883            .frame_descriptor(frame.frame_descriptor)
884            .unwrap();
885        let frame_state_slot = FrameStateSlot::parse(data).unwrap();
886        let slot_to_fp_offset = usize::try_from(slot_to_fp_offset).unwrap();
887
888        // Materialize the stack shape so we have O(1) access to its
889        // elements, and so we don't need to keep the borrow to the
890        // module alive.
891        let mut stack = frame_state_slot
892            .stack(frame.stack_shape)
893            .collect::<Vec<_>>();
894        stack.reverse(); // Put top-of-stack last.
895
896        // Materialize the local offsets/types so we don't need to
897        // keep the borrow to the module alive.
898        let locals = frame_state_slot.locals().collect::<Vec<_>>();
899
900        FrameData {
901            slot_to_fp_offset,
902            func_key: frame_state_slot.func_key(),
903            wasm_pc: frame.wasm_pc,
904            stack,
905            locals,
906        }
907    }
908
909    fn slot_addr(&self, fp: usize) -> *mut u8 {
910        let fp: *mut u8 = core::ptr::with_exposed_provenance_mut(fp);
911        fp.wrapping_sub(self.slot_to_fp_offset)
912    }
913}
914
915/// Read the value at the given offset.
916///
917/// # Safety
918///
919/// The `offset` and `ty` must correspond to a valid value written
920/// to the frame by generated code of the correct type. This will
921/// be the case if this information comes from the frame tables
922/// (as long as the frontend that generates the tables and
923/// instrumentation is correct, and as long as the tables are
924/// preserved through serialization).
925unsafe fn read_value(
926    store: &StoreOpaque,
927    slot_base: *const u8,
928    offset: FrameStateSlotOffset,
929    ty: FrameValType,
930) -> Val {
931    let address = unsafe { slot_base.offset(isize::try_from(offset.offset()).unwrap()) };
932
933    // SAFETY: each case reads a value from memory that should be valid
934    // according to our safety condition. State-slot values are packed without
935    // alignment padding, so these loads must accept unaligned addresses.
936    let raw = || unsafe { (address as *const u32).read_unaligned() };
937    match ty {
938        FrameValType::I32 => Val::I32(unsafe { (address as *const i32).read_unaligned() }),
939        FrameValType::I64 => Val::I64(unsafe { (address as *const i64).read_unaligned() }),
940        FrameValType::F32 => Val::F32(raw()),
941        FrameValType::F64 => Val::F64(unsafe { (address as *const u64).read_unaligned() }),
942        FrameValType::V128 => {
943            // Vectors are always stored as little-endian.
944            let value =
945                unsafe { u128::from_le_bytes((address as *const [u8; 16]).read_unaligned()) };
946            Val::V128(value.into())
947        }
948        FrameValType::AnyRef => Val::from(Unrooted::<AnyRef>::from_raw_u32(store, raw())),
949        FrameValType::ExnRef => Val::from(Unrooted::<ExnRef>::from_raw_u32(store, raw())),
950        FrameValType::ExternRef => Val::from(Unrooted::<ExternRef>::from_raw_u32(store, raw())),
951        FrameValType::FuncRef => {
952            let value = unsafe { (address as *const *mut c_void).read_unaligned() };
953            // SAFETY: the slot holds a function reference of this store.
954            let value = NonNull::new(value.cast())
955                .map(|f| unsafe { Func::from_vm_func_ref(store.id(), f) });
956            Val::FuncRef(value)
957        }
958        FrameValType::ContRef => {
959            unimplemented!("contref values are not implemented in the host API yet")
960        }
961    }
962}
963
964/// Compute raw pointers to all GC refs in the given frame.
965// Note: ideally this would be an impl Iterator, but this is quite
966// awkward because of the locally computed data (FrameStateSlot::parse
967// structured result) within the closure borrowed by a nested closure.
968#[cfg(feature = "gc")]
969pub(crate) fn gc_refs_in_frame<'a>(ft: FrameTable<'a>, pc: u32, fp: *mut usize) -> Vec<*mut u32> {
970    let fp = fp.cast::<u8>();
971    let mut ret = vec![];
972    if let Some(frames) = ft.find_program_point(pc, FrameInstPos::Post) {
973        for (_wasm_pc, frame_desc, stack_shape) in frames {
974            let (frame_desc_data, slot_to_fp_offset) = ft.frame_descriptor(frame_desc).unwrap();
975            let frame_base = unsafe { fp.offset(-isize::try_from(slot_to_fp_offset).unwrap()) };
976            let frame_desc = FrameStateSlot::parse(frame_desc_data).unwrap();
977            for (offset, ty) in frame_desc.stack_and_locals(stack_shape) {
978                match ty {
979                    FrameValType::AnyRef | FrameValType::ExnRef | FrameValType::ExternRef => {
980                        let slot = unsafe {
981                            frame_base
982                                .offset(isize::try_from(offset.offset()).unwrap())
983                                .cast::<u32>()
984                        };
985                        ret.push(slot);
986                    }
987                    FrameValType::ContRef | FrameValType::FuncRef => {}
988                    FrameValType::I32
989                    | FrameValType::I64
990                    | FrameValType::F32
991                    | FrameValType::F64
992                    | FrameValType::V128 => {}
993                }
994            }
995        }
996    }
997    ret
998}
999
1000/// One debug event that occurs when running Wasm code on a store with
1001/// a debug handler attached.
1002#[derive(Debug)]
1003pub enum DebugEvent<'a> {
1004    /// A [`wasmtime::Error`](crate::Error) was raised by a hostcall.
1005    HostcallError(&'a crate::Error),
1006    /// An exception is thrown by wasm.
1007    ///
1008    /// Note that the exception may be caught by wasm if there's an appropriate
1009    /// handler on the stack, but the stack hasn't been searched yet. The
1010    /// debugger can inject its own exception or overwrite this exception if
1011    /// desired.
1012    Exception(OwnedRooted<ExnRef>),
1013    /// A Wasm trap occurred.
1014    Trap(Trap),
1015    /// A breakpoint was reached.
1016    Breakpoint,
1017    /// An epoch yield occurred.
1018    EpochYield,
1019    /// Guest code is about to write watched bytes of a linear memory; see
1020    /// [`BreakpointState::watch`]. The write happens
1021    /// once the handler returns.
1022    Watchpoint(WatchpointHit),
1023}
1024
1025/// A guest write to watched bytes of a linear memory, reported before the
1026/// write happens.
1027#[derive(Clone, Copy, Debug)]
1028pub struct WatchpointHit {
1029    /// The memory being written.
1030    pub memory: crate::Memory,
1031    /// The address of the write's first byte.
1032    pub address: u64,
1033    /// The number of bytes written, of which at least one is watched.
1034    pub len: u64,
1035    /// For a store of up to 16 bytes, the bits being stored (in
1036    /// little-endian order, so the first byte is the least significant).
1037    /// `None` for bulk memory operations.
1038    pub value: Option<u128>,
1039}
1040
1041impl PartialEq for WatchpointHit {
1042    fn eq(&self, other: &Self) -> bool {
1043        self.memory.same(&other.memory)
1044            && (self.address, self.len, self.value) == (other.address, other.len, other.value)
1045    }
1046}
1047
1048impl Eq for WatchpointHit {}
1049
1050/// A handler for debug events.
1051///
1052/// This is an async callback that is invoked directly within the
1053/// context of a debug event that occurs, i.e., with the Wasm code
1054/// still on the stack. The callback can thus observe that stack, up
1055/// to the most recent entry to Wasm.[^1]
1056///
1057/// Because this callback receives a `StoreContextMut`, it has full
1058/// access to any state that any other hostcall has, including the
1059/// `T`. In that way, it is like an epoch-deadline callback or a
1060/// call-hook callback. It also "freezes" the entire store for the
1061/// duration of the debugger callback future.
1062///
1063/// In the future, we expect to provide an "externally async" API on
1064/// the `Store` that allows receiving a stream of debug events and
1065/// accessing the store mutably while frozen; that will need to
1066/// integrate with [`Store::run_concurrent`] to properly timeslice and
1067/// scope the mutable access to the store, and has not been built
1068/// yet. In the meantime, it should be possible to build a fully
1069/// functional debugger with this async-callback API by channeling
1070/// debug events out, and requests to read the store back in, over
1071/// message-passing channels between the callback and an external
1072/// debugger main loop.
1073///
1074/// Note that the `handle` hook may use its mutable store access to
1075/// invoke another Wasm. Debug events will also be caught and will
1076/// cause further `handle` invocations during this recursive
1077/// invocation. It is up to the debugger to handle any implications of
1078/// this reentrancy (e.g., implications on a duplex channel protocol
1079/// with an event/continue handshake) if it does so.
1080///
1081/// Note also that this trait has `Clone` as a supertrait, and the
1082/// handler is cloned at every invocation as an artifact of the
1083/// internal ownership structure of Wasmtime: the handler itself is
1084/// owned by the store, but also receives a mutable borrow to the
1085/// whole store, so we need to clone it out to invoke it. It is
1086/// recommended that this trait be implemented by a type that is cheap
1087/// to clone: for example, a single `Arc` handle to debugger state.
1088///
1089/// [^1]: Providing visibility further than the most recent entry to
1090///       Wasm is not directly possible because it could see into
1091///       another async stack, and the stack that polls the future
1092///       running a particular Wasm invocation could change after each
1093///       suspend point in the handler.
1094///
1095/// [`Store::run_concurrent`]: crate::Store::run_concurrent
1096pub trait DebugHandler: Clone + Send + Sync + 'static {
1097    /// The data expected on the store that this handler is attached
1098    /// to.
1099    type Data;
1100
1101    /// Handle a debug event.
1102    fn handle(
1103        &self,
1104        store: StoreContextMut<'_, Self::Data>,
1105        event: DebugEvent<'_>,
1106    ) -> impl Future<Output = ()> + Send;
1107}
1108
1109/// Breakpoint state for modules within a store.
1110#[derive(Clone, Default)]
1111pub(crate) struct Breakpoints {
1112    /// Single-step mode.
1113    single_step: bool,
1114    /// Breakpoints added individually. Maps from the actual
1115    /// (possibly slipped-forward) breakpoint key to a reference
1116    /// count. Multiple requested PCs may map to the same actual
1117    /// breakpoint when they are slipped forward.
1118    ///
1119    /// Slipping is a pure function of the module and requested PC
1120    /// (see `BreakpointState::actual_key`), so `remove_breakpoint`
1121    /// recomputes it rather than recording it per request.
1122    breakpoints: BTreeMap<BreakpointKey, usize>,
1123}
1124
1125/// A breakpoint.
1126pub struct Breakpoint {
1127    /// Reference to the module in which we are setting the breakpoint.
1128    pub module: Module,
1129    /// Module-relative Wasm PC offset.
1130    pub pc: ModulePC,
1131}
1132
1133#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
1134struct BreakpointKey(CompiledModuleId, ModulePC);
1135
1136impl BreakpointKey {
1137    fn from_raw(module: &Module, pc: ModulePC) -> BreakpointKey {
1138        BreakpointKey(module.id(), pc)
1139    }
1140
1141    fn get(&self, registry: &ModuleRegistry) -> Breakpoint {
1142        let module = registry
1143            .module_by_compiled_id(self.0)
1144            .expect("Module should not have been removed from Store")
1145            .clone();
1146        Breakpoint { module, pc: self.1 }
1147    }
1148}
1149
1150/// A store's breakpoint state: its breakpoints, single-stepping, and
1151/// watchpoints, borrowed for editing.
1152///
1153/// Available within [`Store::edit_breakpoints`] (or the same method on
1154/// [`StoreContextMut`] and [`Caller`]).
1155///
1156/// Edits made with a `BreakpointState` take effect together once the
1157/// closure passed to `edit_breakpoints` returns `Ok`. This batches the
1158/// code-patching that breakpoints and single-stepping require, which
1159/// has some overhead (e.g. syscalls to write-protect/re-publish code).
1160/// If the closure instead returns `Err` or panics, or applying the
1161/// edits fails, none of them take effect.
1162///
1163/// An edit method that returns an error makes no edit, so the closure
1164/// may handle the error and carry on to make (and keep) other edits.
1165pub struct BreakpointState<'a> {
1166    store: &'a mut StoreOpaque,
1167    /// The store's breakpoint state with the edits made so far, which
1168    /// replaces the store's on commit.
1169    edited: Breakpoints,
1170    /// Code that must be re-patched on commit, to match `edited`.
1171    ///
1172    /// Code is patched only on commit, rather than as edits are made,
1173    /// so that it is never left unpublished (non-executable) if the
1174    /// edits are not committed (e.g. on a panic).
1175    pending: BTreeMap<StoreCodePC, PendingPatches>,
1176    /// Watchpoint edits to apply on commit, in order: memory, range
1177    /// (already checked) within its shadow, and whether to watch or
1178    /// unwatch.
1179    watches: Vec<(crate::Memory, Range<usize>, bool)>,
1180}
1181
1182/// Breakpoint sites within one `StoreCode` that must be re-patched.
1183#[derive(Default)]
1184struct PendingPatches {
1185    /// Modules all of whose breakpoint sites must be re-patched
1186    /// (because single-stepping is toggled).
1187    modules: BTreeSet<CompiledModuleId>,
1188    /// Individual breakpoint sites that must be re-patched.
1189    sites: BTreeSet<BreakpointKey>,
1190}
1191
1192impl Breakpoints {
1193    pub(crate) fn breakpoints<'a>(
1194        &'a self,
1195        registry: &'a ModuleRegistry,
1196    ) -> impl Iterator<Item = Breakpoint> + 'a {
1197        self.breakpoints.keys().map(|key| key.get(registry))
1198    }
1199
1200    pub(crate) fn is_single_step(&self) -> bool {
1201        self.single_step
1202    }
1203
1204    /// Internal helper to patch a new module for
1205    /// single-stepping. When a module is newly registered in a
1206    /// `Store`, we need to patch all breakpoints into the copy for
1207    /// this `Store` if single-stepping is currently enabled.
1208    pub(crate) fn patch_new_module(&self, code: &mut StoreCode, module: &Module) -> Result<()> {
1209        // Apply single-step state if single-stepping is enabled. Note
1210        // that no other individual breakpoints will exist yet (as
1211        // this is a newly registered module).
1212        //
1213        // Note that this may run while a `BreakpointState` is editing
1214        // other modules that share this code (as the modules within a
1215        // component do). That is fine: the `BreakpointState` leaves
1216        // code published until its edits are committed.
1217        if self.single_step {
1218            let mem = code.code_memory_mut().unwrap();
1219            mem.unpublish()?;
1220            BreakpointState::apply_single_step(mem, module, true, |_key| false);
1221            mem.publish()?;
1222        }
1223        Ok(())
1224    }
1225}
1226
1227impl<'a> BreakpointState<'a> {
1228    /// Errors if `module` does not belong to the same engine as the store
1229    /// being edited.
1230    ///
1231    /// The module registry rejects foreign modules on its own, but breakpoint
1232    /// bookkeeping is updated before a module reaches the registry, and
1233    /// removing a breakpoint that was never added does not touch the registry
1234    /// at all. So this editing session checks up front as well.
1235    fn check_engine(&self, module: &Module) -> Result<()> {
1236        crate::ensure!(
1237            crate::Engine::same(self.store.engine(), module.engine()),
1238            "cross-`Engine` breakpoint editing is not supported"
1239        );
1240        Ok(())
1241    }
1242
1243    /// Register `module` with the store if it is not already, and get
1244    /// the base of its code, for which patches are pending.
1245    fn register(&mut self, module: &Module) -> Result<StoreCodePC> {
1246        let (committed, registry, _) = self.store.breakpoints_and_registry_and_engine_mut();
1247        let store_code_pc =
1248            registry.store_code_base_or_register(module, RegisterBreakpointState(committed))?;
1249        let pending = self.pending.entry(store_code_pc).or_default();
1250        // The module's code is patched for the committed
1251        // single-stepping state (including if it was just registered,
1252        // above), so if this transaction changes it, all of the
1253        // module's sites must be re-patched.
1254        if committed.single_step != self.edited.single_step {
1255            pending.modules.insert(module.id());
1256        }
1257        Ok(store_code_pc)
1258    }
1259
1260    /// Get the `CodeMemory` for the code at `store_code_base`.
1261    fn code_memory(registry: &mut ModuleRegistry, store_code_base: StoreCodePC) -> &mut CodeMemory {
1262        registry
1263            .store_code_mut(store_code_base)
1264            .expect("code with pending patches must be registered")
1265            .code_memory_mut()
1266            .expect("Must have unique ownership of StoreCode in guest-debug mode")
1267    }
1268
1269    fn patch<'b>(
1270        patches: impl Iterator<Item = FrameTableBreakpointData<'b>> + 'b,
1271        mem: &mut CodeMemory,
1272        enable: bool,
1273    ) {
1274        let mem = mem.text_mut();
1275        for patch in patches {
1276            let data = if enable { patch.enable } else { patch.disable };
1277            let mem = &mut mem[patch.offset..patch.offset + data.len()];
1278            log::trace!(
1279                "patch: offset 0x{:x} with enable={enable}: data {data:?} replacing {mem:?}",
1280                patch.offset
1281            );
1282            mem.copy_from_slice(data);
1283        }
1284    }
1285
1286    /// The key for the breakpoint actually set for a request at `pc`
1287    /// in `module`: if `pc` does not fall exactly on an opcode
1288    /// boundary, it is "slipped" forward to the next available opcode
1289    /// PC.
1290    fn actual_key(module: &Module, pc: ModulePC) -> BreakpointKey {
1291        let frame_table = module
1292            .frame_table()
1293            .expect("Frame table must be present when guest-debug is enabled");
1294        let index = module.compiled_module().module_index();
1295        let actual_pc = frame_table.nearest_breakpoint(index, pc).unwrap_or(pc);
1296        if actual_pc != pc {
1297            log::trace!(
1298                "slipping breakpoint from {:?} to {actual_pc:?}",
1299                BreakpointKey::from_raw(module, pc)
1300            );
1301        }
1302        BreakpointKey::from_raw(module, actual_pc)
1303    }
1304
1305    /// Add a breakpoint in the given module at the given PC in that
1306    /// module.
1307    ///
1308    /// If the requested PC does not fall exactly on an opcode
1309    /// boundary, the breakpoint is "slipped" forward to the next
1310    /// available opcode PC.
1311    ///
1312    /// No effect if the breakpoint is already set.
1313    ///
1314    /// # Errors
1315    ///
1316    /// Returns an error if `module` was not compiled by the same engine as
1317    /// the store being edited.
1318    pub fn add_breakpoint(&mut self, module: &Module, pc: ModulePC) -> Result<()> {
1319        self.check_engine(module)?;
1320        let actual_key = Self::actual_key(module, pc);
1321
1322        // Register the module first, so that on failure no breakpoint
1323        // is recorded.
1324        let store_code_pc = self.register(module)?;
1325        let refcount = self.edited.breakpoints.entry(actual_key).or_insert(0);
1326        *refcount += 1;
1327        if *refcount == 1 {
1328            // First reference: the code must be patched.
1329            self.pending
1330                .entry(store_code_pc)
1331                .or_default()
1332                .sites
1333                .insert(actual_key);
1334        }
1335        Ok(())
1336    }
1337
1338    /// Remove a breakpoint in the given module at the given PC in
1339    /// that module.
1340    ///
1341    /// No effect if the breakpoint was not set.
1342    ///
1343    /// # Errors
1344    ///
1345    /// Returns an error if `module` was not compiled by the same engine as
1346    /// the store being edited.
1347    pub fn remove_breakpoint(&mut self, module: &Module, pc: ModulePC) -> Result<()> {
1348        self.check_engine(module)?;
1349        let actual_key = Self::actual_key(module, pc);
1350        if !self.edited.breakpoints.contains_key(&actual_key) {
1351            return Ok(());
1352        }
1353
1354        // Register the module (it already is, since it has a
1355        // breakpoint) before editing, so that on failure nothing
1356        // changes.
1357        let store_code_pc = self.register(module)?;
1358        let refcount = self.edited.breakpoints.get_mut(&actual_key).unwrap();
1359        *refcount -= 1;
1360        if *refcount == 0 {
1361            self.edited.breakpoints.remove(&actual_key);
1362            self.pending
1363                .entry(store_code_pc)
1364                .or_default()
1365                .sites
1366                .insert(actual_key);
1367        }
1368        Ok(())
1369    }
1370
1371    fn apply_single_step<F: Fn(&BreakpointKey) -> bool>(
1372        mem: &mut CodeMemory,
1373        module: &Module,
1374        enabled: bool,
1375        key_enabled: F,
1376    ) {
1377        let table = module
1378            .frame_table()
1379            .expect("Frame table must be present when guest-debug is enabled");
1380        let index = module.compiled_module().module_index();
1381        for (wasm_pc, patch) in table.breakpoint_patches(index) {
1382            let key = BreakpointKey::from_raw(&module, wasm_pc);
1383            let this_enabled = enabled || key_enabled(&key);
1384            log::trace!(
1385                "single_step: enabled {enabled} key {key:?} -> this_enabled {this_enabled}"
1386            );
1387            Self::patch(core::iter::once(patch), mem, this_enabled);
1388        }
1389    }
1390
1391    /// Turn on or off single-step mode.
1392    ///
1393    /// In single-step mode, a breakpoint event is emitted at every
1394    /// Wasm PC.
1395    pub fn single_step(&mut self, enabled: bool) -> Result<()> {
1396        log::trace!(
1397            "single_step({enabled}) with breakpoint set {:?}",
1398            self.edited.breakpoints
1399        );
1400        if self.edited.single_step == enabled {
1401            // No change to current state; don't go through the effort
1402            // of re-patching code.
1403            return Ok(());
1404        }
1405        self.edited.single_step = enabled;
1406        let modules = self
1407            .store
1408            .modules()
1409            .all_modules()
1410            .map(|(_, m)| m.clone())
1411            .collect::<Vec<_>>();
1412        for module in modules {
1413            // Already registered, so this cannot fail.
1414            let store_code_pc = self.register(&module)?;
1415            self.pending
1416                .entry(store_code_pc)
1417                .or_default()
1418                .modules
1419                .insert(module.id());
1420        }
1421        Ok(())
1422    }
1423
1424    /// Watches guest writes to the bytes in `range` of `memory`. A guest
1425    /// store or bulk memory operation that writes a watched byte raises
1426    /// [`DebugEvent::Watchpoint`] before writing.
1427    ///
1428    /// Whether a byte is watched is a per-byte property: watching an
1429    /// already-watched byte has no further effect. See
1430    /// [`BreakpointState::unwatch`].
1431    ///
1432    /// # Errors
1433    ///
1434    /// Returns an error if `range` extends beyond the memory's current size.
1435    ///
1436    /// # Panics
1437    ///
1438    /// Panics if `memory` does not belong to this store.
1439    pub fn watch(&mut self, memory: crate::Memory, range: Range<u64>) -> Result<()> {
1440        let range = self.store.debug_check_watch(memory, range)?;
1441        self.watches.push((memory, range, true));
1442        Ok(())
1443    }
1444
1445    /// Stops watching guest writes to the bytes in `range` of `memory`.
1446    ///
1447    /// Whether a byte is watched is a per-byte property, so this unwatches
1448    /// every byte in `range`, regardless of how many (possibly overlapping)
1449    /// calls to [`BreakpointState::watch`] watched it.
1450    ///
1451    /// # Errors
1452    ///
1453    /// Returns an error if `range` extends beyond the memory's current size.
1454    ///
1455    /// # Panics
1456    ///
1457    /// Panics if `memory` does not belong to this store.
1458    pub fn unwatch(&mut self, memory: crate::Memory, range: Range<u64>) -> Result<()> {
1459        let range = self.store.debug_check_watch(memory, range)?;
1460        self.watches.push((memory, range, false));
1461        Ok(())
1462    }
1463
1464    /// Apply all edits made with this `BreakpointState`.
1465    ///
1466    /// Returns an error if the store's code cannot be made writable to
1467    /// patch it. In that case, none of the edits take effect.
1468    fn commit(self) -> Result<()> {
1469        let BreakpointState {
1470            store,
1471            edited,
1472            pending,
1473            watches,
1474        } = self;
1475        let (committed, registry, _) = store.breakpoints_and_registry_and_engine_mut();
1476
1477        // Look up the modules to patch before borrowing their code
1478        // mutably.
1479        let module = |id: CompiledModuleId| {
1480            registry
1481                .module_by_compiled_id(id)
1482                .expect("Module with pending breakpoint patches must be registered")
1483                .clone()
1484        };
1485        let regions = pending
1486            .into_iter()
1487            .map(|(store_code_base, pending)| {
1488                let modules = pending
1489                    .modules
1490                    .iter()
1491                    .map(|&id| module(id))
1492                    .collect::<Vec<_>>();
1493                let sites = pending
1494                    .sites
1495                    .iter()
1496                    .map(|key| (*key, module(key.0)))
1497                    .collect::<Vec<_>>();
1498                (store_code_base, modules, sites)
1499            })
1500            .collect::<Vec<_>>();
1501
1502        // Make all code to patch writable first, so that if that fails,
1503        // we can back out without having changed anything.
1504        for (i, (store_code_base, _, _)) in regions.iter().enumerate() {
1505            if let Err(e) = Self::code_memory(registry, *store_code_base).unpublish() {
1506                // The code that failed remains executable; re-publish
1507                // the rest.
1508                for (store_code_base, _, _) in &regions[..i] {
1509                    if let Err(e) = Self::code_memory(registry, *store_code_base).publish() {
1510                        abort_on_republish_error(e);
1511                    }
1512                }
1513                return Err(e);
1514            }
1515        }
1516
1517        // Patch every pending site to match the edited breakpoint
1518        // state, regardless of the edits that led to it.
1519        let enabled =
1520            |key: &BreakpointKey| edited.single_step || edited.breakpoints.contains_key(key);
1521        for (store_code_base, modules, sites) in &regions {
1522            let mem = Self::code_memory(registry, *store_code_base);
1523            for module in modules {
1524                Self::apply_single_step(mem, module, false, enabled);
1525            }
1526            for (key, module) in sites {
1527                let frame_table = module
1528                    .frame_table()
1529                    .expect("Frame table must be present when guest-debug is enabled");
1530                let index = module.compiled_module().module_index();
1531                let patches = frame_table.lookup_breakpoint_patches_by_pc(index, key.1);
1532                Self::patch(patches, mem, enabled(key));
1533            }
1534            if let Err(e) = mem.publish() {
1535                abort_on_republish_error(e);
1536            }
1537        }
1538
1539        *committed = edited;
1540        for (memory, range, watch) in watches {
1541            store.debug_set_watch(memory, range, watch);
1542        }
1543        Ok(())
1544    }
1545}
1546
1547/// Abort when we cannot re-publish executable code.
1548///
1549/// Note that this puts us in quite a conundrum. Typically we will
1550/// have been editing breakpoints from within a hostcall context
1551/// (e.g. inside a debugger hook while execution is paused) with JIT
1552/// code on the stack. Wasmtime's usual path to return errors is back
1553/// through that JIT code: we do not panic-unwind across the JIT code,
1554/// we return into the exit trampoline and that then re-enters the
1555/// raise libcall to use a Cranelift exception-throw to cross most of
1556/// the JIT frames to the entry trampoline. When even trampolines are
1557/// no longer executable, we have no way out. Even an ordinary
1558/// `panic!` cannot work, because we catch panics and carry them
1559/// across JIT code using that trampoline-based error path. Our only
1560/// way out is to directly abort the whole process.
1561///
1562/// This is not without precedent: other engines have similar failure
1563/// paths. For example, SpiderMonkey directly aborts the process when
1564/// failing to re-apply executable permissions (see [1]).
1565///
1566/// Note that we don't really expect to ever hit this case in
1567/// practice: it's unlikely that `mprotect` applying `PROT_EXEC` would
1568/// fail due to, e.g., resource exhaustion in the kernel, because we
1569/// will have the same net number of virtual memory areas before and
1570/// after the permissions change. Nevertheless, we have to account for
1571/// the possibility of error.
1572///
1573/// [1]: https://searchfox.org/firefox-main/rev/7496c8515212669451d7e775a00c2be07da38ca5/js/src/jit/AutoWritableJitCode.h#26-56
1574#[cfg(feature = "std")]
1575fn abort_on_republish_error(e: crate::Error) -> ! {
1576    log::error!(
1577        "Failed to re-publish executable code: {e:?}. Wasmtime cannot return through JIT code on the stack and cannot even panic; aborting the process."
1578    );
1579    std::process::abort();
1580}
1581
1582/// In the `no_std` case, we don't have a concept of a "process
1583/// abort", so rely on `panic!`. Typically an embedded scenario that
1584/// uses `no_std` will build with `panic=abort` so the effect is the
1585/// same. If it doesn't, there is truly nothing we can do here so
1586/// let's panic anyway; the panic propagation through the trampolines
1587/// will at least deterministically crash.
1588#[cfg(not(feature = "std"))]
1589fn abort_on_republish_error(e: crate::Error) -> ! {
1590    panic!("Failed to re-publish executable code: {e:?}");
1591}