Skip to main content

vihaco_stdlib/debugger/
mod.rs

1// SPDX-FileCopyrightText: 2026 The vihaco Authors
2// SPDX-License-Identifier: MIT
3
4//! Breakpoints and single stepping for program-image execution.
5//!
6//! Use [`crate::ExecutionState<DebuggerState>`] as the machine's program device
7//! and [`Debugger<u32, I>`] as a debugger device, where `I` is the machine's
8//! runtime instruction type. Implement [`HasBreakpointInstruction`] for `I`.
9//! The debugger's authored `Step` builds a [`BreakpointMessage`], executes the
10//! debugger, and applies its [`Break`] effect to the execution state.
11//!
12//! Call [`crate::Loadable::start`] to initialize an invocation, then
13//! [`crate::Loadable::resume_with_breaks`] with [`DebugAction::Continue`] or
14//! [`DebugAction::Step`]. A gutter breakpoint pauses before its displaced
15//! instruction; continuing or stepping executes that instruction once. An
16//! explicit breakpoint resumes at the following instruction. Ordinary
17//! [`crate::Loadable::resume`] leaves a breakpoint-suspended invocation untouched.
18//!
19//! Breakpoint bookkeeping belongs to the patched image. After successful image
20//! replacement, or before reusing the machine with a different image, call
21//! [`Debugger::forget_breakpoints`]. To remove breakpoints while keeping the old
22//! image usable, restore its instructions with [`Debugger::clear_all`] instead.
23//! Invocation-only resets retain installed breakpoints.
24//!
25//! Run the complete wiring, stepping, replacement, and reuse example with:
26//!
27//! ```text
28//! cargo run -p vihaco-stdlib --features program-image-execution --example debugger
29//! ```
30
31pub mod dialect;
32
33mod loadable;
34mod runner;
35
36pub use runner::resume_with_breaks;
37
38use crate::{ExecutionState, RunState, debugger::dialect::debug};
39use std::{collections::BTreeMap, convert::Infallible};
40use vihaco_module::module::LocalModule;
41use vihaco_runtime::{
42    Apply, Execute, HasProgram, Message, Reset, ReusableMessageRecipe, component,
43};
44
45/// Select continuous execution or a single step.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum DebugAction {
48    Continue,
49    Step,
50}
51
52enum PausedBreakpoint<K> {
53    Explicit,
54    Gutter { key: K },
55}
56
57/// A component that manages breakpoints.
58///
59/// This component can handle both explicit breakpoints (those appearing in
60/// source) and "gutter" breakpoints, or those that are inserted (similar to
61/// gdb's `INT3` insertion on `b`).
62#[component]
63#[instructions { debug }]
64pub struct Debugger<K: Ord + 'static, I> {
65    displaced: BTreeMap<K, I>,
66    paused: Option<PausedBreakpoint<K>>,
67}
68
69impl<K: Ord + 'static, I> Default for Debugger<K, I> {
70    fn default() -> Self {
71        Self {
72            displaced: BTreeMap::new(),
73            paused: None,
74        }
75    }
76}
77
78impl<K: Ord + 'static, I> Reset for Debugger<K, I> {
79    fn reset(&mut self) {
80        self.paused = None;
81    }
82}
83
84impl<K: Ord + 'static, I> Debugger<K, I> {
85    /// Discard all saved breakpoint instructions and paused-breakpoint state.
86    ///
87    /// Use this when discarding the patched program, before using this debugger
88    /// with a different image. This does not restore instructions in the old
89    /// program. To remove breakpoints while keeping that program usable, call
90    /// [`Self::clear_all`] instead. Invocation-only resets retain breakpoints.
91    pub fn forget_breakpoints(&mut self) {
92        self.displaced.clear();
93        self.paused = None;
94    }
95}
96
97pub enum IsBreakpointToggled {
98    Toggled,
99    Untoggled,
100}
101
102impl From<IsBreakpointInstalled> for IsBreakpointToggled {
103    fn from(value: IsBreakpointInstalled) -> Self {
104        match value {
105            IsBreakpointInstalled::Installed(_) => Self::Toggled,
106            IsBreakpointInstalled::No => Self::Untoggled,
107        }
108    }
109}
110
111impl<K: Ord + Clone + 'static, I: Clone> Debugger<K, I> {
112    /// Installs a gutter breakpoint and retains the displaced instruction.
113    pub fn set_breakpoint<P>(&mut self, program: &mut P, key: K) -> IsBreakpointToggled
114    where
115        P: BreakpointPatchableProgram<K, Instruction = I>,
116    {
117        if self.displaced.contains_key(&key) {
118            return IsBreakpointToggled::Toggled;
119        }
120        let IsBreakpointInstalled::Installed(displaced) = program.install_breakpoint(&key) else {
121            return IsBreakpointToggled::Untoggled;
122        };
123        self.displaced.insert(key, displaced);
124        IsBreakpointToggled::Toggled
125    }
126
127    /// Restores a gutter breakpoint's displaced instruction.
128    pub fn clear_breakpoint<P>(&mut self, program: &mut P, key: K) -> IsBreakpointToggled
129    where
130        P: BreakpointPatchableProgram<K, Instruction = I>,
131    {
132        let Some(displaced) = self.displaced.get(&key).cloned() else {
133            return IsBreakpointToggled::Untoggled;
134        };
135        if program
136            .uninstall_breakpoint(&key, displaced)
137            .is_not_installed()
138        {
139            return IsBreakpointToggled::Toggled;
140        }
141        self.displaced.remove(&key);
142        IsBreakpointToggled::Untoggled
143    }
144
145    pub fn toggle_breakpoint<P>(&mut self, program: &mut P, key: K) -> IsBreakpointToggled
146    where
147        P: BreakpointPatchableProgram<K, Instruction = I>,
148    {
149        if self.displaced.contains_key(&key) {
150            self.clear_breakpoint(program, key)
151        } else {
152            self.set_breakpoint(program, key)
153        }
154    }
155
156    pub fn clear_all<P>(&mut self, program: &mut P)
157    where
158        P: BreakpointPatchableProgram<K, Instruction = I>,
159    {
160        let keys: Vec<_> = self.displaced.keys().cloned().collect();
161        for key in keys {
162            self.clear_breakpoint(program, key);
163        }
164    }
165
166    pub fn breakpoints(&self) -> impl ExactSizeIterator<Item = &K> + '_ {
167        self.displaced.keys()
168    }
169
170    pub fn displaced(&self, key: &K) -> Option<&I> {
171        self.displaced.get(key)
172    }
173
174    pub fn contains(&self, key: &K) -> bool {
175        self.displaced.contains_key(key)
176    }
177}
178
179/// An effect that propagates a hit breakpoint.
180pub struct Break;
181
182/// Identify the breakpoint being executed.
183#[derive(Debug)]
184pub struct BreakpointMessage<K = u32> {
185    pub key: K,
186}
187
188impl<K: 'static> Message for BreakpointMessage<K> {}
189
190impl<P, F, Context: ?Sized> ReusableMessageRecipe<P, F, debug::Breakpoint, Context>
191    for BreakpointMessage
192where
193    P: HasProgram<Program = ExecutionState<DebuggerState>>,
194{
195    fn prepare(parent: &mut P, _: &debug::Breakpoint, _: &Context) -> eyre::Result<Self> {
196        let program = parent.program();
197        eyre::ensure!(
198            matches!(program.run_state(), RunState::Runnable),
199            "program is not running"
200        );
201        let key = program
202            .pc()
203            .checked_sub(1)
204            .ok_or_else(|| eyre::eyre!("breakpoint has no instruction position"))?;
205        Ok(Self { key })
206    }
207}
208
209/// Debugger-specific execution suspension.
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum DebuggerState {
212    Breakpoint { resume_pc: u32 },
213}
214
215impl Apply<Break> for ExecutionState<DebuggerState> {
216    fn apply(&mut self, _: Break) {
217        self.suspend(DebuggerState::Breakpoint {
218            resume_pc: self.pc(),
219        });
220    }
221}
222
223/// This instruction set has a breakpoint instruction. Implement this for your
224/// component's runtime instruction set to define how it can build a breakpoint
225/// instruction.
226pub trait HasBreakpointInstruction: Sized + Clone {
227    fn new_breakpoint() -> Self;
228}
229
230pub enum IsBreakpointInstalled<I = ()> {
231    Installed(I),
232    No,
233}
234
235impl<I> IsBreakpointInstalled<I> {
236    pub fn is_installed(&self) -> bool {
237        matches!(self, IsBreakpointInstalled::Installed(_))
238    }
239
240    pub fn is_not_installed(&self) -> bool {
241        !self.is_installed()
242    }
243}
244
245pub trait BreakpointPatchableProgram<K> {
246    type Instruction: HasBreakpointInstruction;
247
248    fn install_breakpoint(&mut self, index: &K) -> IsBreakpointInstalled<Self::Instruction>;
249    /// Restore the instruction displaced by a breakpoint.
250    fn uninstall_breakpoint(
251        &mut self,
252        index: &K,
253        displaced: Self::Instruction,
254    ) -> IsBreakpointInstalled;
255}
256
257impl<I, V, Ty, Info> BreakpointPatchableProgram<u32> for LocalModule<I, V, Ty, Info>
258where
259    I: HasBreakpointInstruction,
260{
261    type Instruction = I;
262
263    fn install_breakpoint(&mut self, index: &u32) -> IsBreakpointInstalled<I> {
264        let Some(slot) = self.code.get_mut(*index as usize) else {
265            return IsBreakpointInstalled::No;
266        };
267        IsBreakpointInstalled::Installed(std::mem::replace(slot, I::new_breakpoint()))
268    }
269
270    fn uninstall_breakpoint(&mut self, index: &u32, displaced: I) -> IsBreakpointInstalled {
271        let Some(slot) = self.code.get_mut(*index as usize) else {
272            return IsBreakpointInstalled::No;
273        };
274        *slot = displaced;
275        IsBreakpointInstalled::Installed(())
276    }
277}
278
279impl<K: Ord + 'static, I> Execute<debug::Breakpoint> for Debugger<K, I> {
280    type Message = BreakpointMessage<K>;
281    type Effect = Break;
282    type Error = Infallible;
283
284    fn execute(
285        &mut self,
286        _instruction: &debug::Breakpoint,
287        message: Self::Message,
288    ) -> Result<Self::Effect, Self::Error> {
289        self.paused = Some(if self.displaced.contains_key(&message.key) {
290            PausedBreakpoint::Gutter { key: message.key }
291        } else {
292            PausedBreakpoint::Explicit
293        });
294        Ok(Break)
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[derive(Clone, Debug, PartialEq, Eq)]
303    enum Instruction {
304        Value(u64),
305        Breakpoint,
306    }
307
308    impl HasBreakpointInstruction for Instruction {
309        fn new_breakpoint() -> Self {
310            Self::Breakpoint
311        }
312    }
313
314    #[test]
315    fn forgetting_breakpoints_cannot_restore_old_instructions_into_a_new_program() {
316        let mut debugger = Debugger::<u32, Instruction>::default();
317        let mut original = LocalModule::<Instruction, (), ()> {
318            code: vec![Instruction::Value(11)],
319            ..Default::default()
320        };
321        debugger.set_breakpoint(&mut original, 0);
322        debugger
323            .execute(&debug::Breakpoint, BreakpointMessage { key: 0 })
324            .unwrap();
325
326        debugger.forget_breakpoints();
327        assert_eq!(debugger.breakpoints().len(), 0);
328        assert!(debugger.paused.is_none());
329
330        let mut replacement = LocalModule::<Instruction, (), ()> {
331            code: vec![Instruction::Value(42)],
332            ..Default::default()
333        };
334        assert!(matches!(
335            debugger.clear_breakpoint(&mut replacement, 0),
336            IsBreakpointToggled::Untoggled
337        ));
338        assert_eq!(replacement.code, vec![Instruction::Value(42)]);
339        assert_eq!(original.code, vec![Instruction::Breakpoint]);
340
341        debugger.set_breakpoint(&mut replacement, 0);
342        debugger.clear_all(&mut replacement);
343        assert_eq!(replacement.code, vec![Instruction::Value(42)]);
344    }
345
346    #[test]
347    fn invocation_reset_retains_saved_breakpoint_instructions() {
348        let mut debugger = Debugger::<u32, Instruction>::default();
349        let mut program = LocalModule::<Instruction, (), ()> {
350            code: vec![Instruction::Value(11)],
351            ..Default::default()
352        };
353        debugger.set_breakpoint(&mut program, 0);
354        debugger
355            .execute(&debug::Breakpoint, BreakpointMessage { key: 0 })
356            .unwrap();
357
358        debugger.reset();
359        assert!(debugger.paused.is_none());
360        assert!(debugger.contains(&0));
361        debugger.clear_all(&mut program);
362        assert_eq!(program.code, vec![Instruction::Value(11)]);
363    }
364}