Skip to main content

tetanes_core/
debug.rs

1//! Debugger hooks.
2//!
3//! A debugger is a callback plus the condition that fires it. The callback is handed the whole
4//! [`Bus`] - so it can take whatever state snapshot it needs at that point during
5//! emulation.
6
7use crate::{bus::Bus, memory::Memory};
8use bitflags::bitflags;
9use serde::{Deserialize, Serialize};
10use std::sync::Arc;
11
12pub mod expr;
13
14/// A ring buffer of the program counters most recently executed.
15///
16/// Executed instructions have to be recorded as the console runs: 6502 instructions are one to
17/// three bytes with no alignment, so the stream before an address cannot be recovered by decoding
18/// backwards without a known address to disassemble from. Recording them lets a debugger show the
19/// instructions leading up to where it stopped execution.
20#[derive(Debug, Clone)]
21#[must_use]
22pub struct PcHistory {
23    entries: Box<[u16]>,
24    /// Where the next push goes, wrapping at `entries.len()`.
25    head: usize,
26    /// How many entries have been filled, saturating at `entries.len()`.
27    len: usize,
28}
29
30impl PcHistory {
31    /// Create a history holding the last `capacity` program counters.
32    pub fn new(capacity: usize) -> Self {
33        Self {
34            entries: vec![0; capacity.max(1)].into_boxed_slice(),
35            head: 0,
36            len: 0,
37        }
38    }
39
40    /// Record an executed program counter, dropping the oldest once full.
41    #[inline]
42    pub fn push(&mut self, pc: u16) {
43        self.entries[self.head] = pc;
44        self.head = (self.head + 1) % self.entries.len();
45        self.len = (self.len + 1).min(self.entries.len());
46    }
47
48    /// The recorded program counters, oldest first, which is the order they are read in.
49    pub fn iter(&self) -> impl ExactSizeIterator<Item = u16> + '_ {
50        // `head` is one past the newest, so the oldest live entry is `len` behind it.
51        let start = (self.head + self.entries.len() - self.len) % self.entries.len();
52        (0..self.len).map(move |i| self.entries[(start + i) % self.entries.len()])
53    }
54
55    /// How many program counters are recorded.
56    #[must_use]
57    pub const fn len(&self) -> usize {
58        self.len
59    }
60
61    /// Whether nothing has been recorded yet.
62    #[must_use]
63    pub const fn is_empty(&self) -> bool {
64        self.len == 0
65    }
66
67    /// Forget what was recorded, keeping the capacity.
68    pub const fn clear(&mut self) {
69        self.head = 0;
70        self.len = 0;
71    }
72}
73
74/// Why a call frame was pushed.
75#[derive(Debug, Copy, Clone, PartialEq, Eq)]
76#[must_use]
77pub enum FrameKind {
78    /// A `JSR`.
79    Call,
80    /// The NMI vector, taken when the PPU asserts it.
81    Nmi,
82    /// The IRQ vector, taken when the board or the APU pulls the line low.
83    Irq,
84    /// A `BRK`, which reaches the IRQ vector by executing rather than by a line going low.
85    Brk,
86}
87
88/// One call execution is currently inside.
89#[derive(Debug, Copy, Clone, PartialEq, Eq)]
90#[must_use]
91pub struct CallFrame {
92    /// The `JSR`, or the instruction an interrupt arrived before.
93    pub caller: u16,
94    /// The subroutine, or the handler the vector named.
95    pub entry: u16,
96    /// The stack pointer once the return address was pushed. The frame is live while the stack
97    /// pointer is no higher than this.
98    pub sp: u8,
99    /// Why the frame was pushed.
100    pub kind: FrameKind,
101}
102
103/// The calls execution is currently inside, outermost first.
104///
105/// [`PcHistory`] says what has run, this says how the console reached where it is. A frame is
106/// pushed by a `JSR` and by an interrupt taking a vector, and dropped by watching the stack
107/// pointer rather than by watching for an `RTS`: a return address is often discarded (`PLA`,
108/// `PLA`) or reached by a jump, and the stack pointer catches all of those the same way.
109#[derive(Debug, Default, Clone)]
110#[must_use]
111pub struct CallStack {
112    frames: Vec<CallFrame>,
113}
114
115impl CallStack {
116    /// How many frames the stack records. A frame takes at least the two bytes a `JSR` pushes,
117    /// out of a 256 byte stack page.
118    const MAX_DEPTH: usize = 128;
119
120    /// Create an empty call stack.
121    pub fn new() -> Self {
122        Self {
123            frames: Vec::with_capacity(16),
124        }
125    }
126
127    /// Drop the frames the stack pointer has risen past. An `RTS` raises it back over the frame
128    /// it returns from.
129    #[inline]
130    pub fn unwind_to(&mut self, sp: u8) {
131        while self.frames.last().is_some_and(|frame| sp > frame.sp) {
132            self.frames.pop();
133        }
134    }
135
136    /// Record a call.
137    ///
138    /// Each frame sits below the one before it, so the depth is bounded by the stack page and
139    /// only a stack pointer that wrapped can reach the limit.
140    pub fn push(&mut self, frame: CallFrame) {
141        if self.frames.len() < Self::MAX_DEPTH {
142            self.frames.push(frame);
143        }
144    }
145
146    /// The frames execution is inside, outermost first.
147    pub fn frames(&self) -> &[CallFrame] {
148        &self.frames
149    }
150
151    /// How deep the stack is.
152    #[must_use]
153    pub const fn len(&self) -> usize {
154        self.frames.len()
155    }
156
157    /// Whether the stack has no frames.
158    #[must_use]
159    pub const fn is_empty(&self) -> bool {
160        self.frames.is_empty()
161    }
162
163    /// Forget the recorded frames, keeping the capacity.
164    pub fn clear(&mut self) {
165        self.frames.clear();
166    }
167}
168
169bitflags! {
170    /// What execution has shown a byte to be.
171    #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
172    pub struct ByteKind: u8 {
173        /// Ran as the first byte of an instruction.
174        const CODE = 1;
175        /// A `JSR` destination or subroutine entry instruction.
176        const SUB_ENTRY = 1 << 1;
177    }
178}
179
180/// What execution has revealed about each byte of cartridge memory.
181///
182/// Only execution writes here, nothing decodes ahead of it. A byte is only code if it has been
183/// executed, which the disassembler cannot work out on its own: 6502 instructions are one to three
184/// bytes with no alignment, so a decode that starts inside data stays out of step with the real
185/// instruction boundaries until it happens to realign.
186///
187/// Keyed by [`Memory`] offset instead of CPU address, so a mark survives bank switches to another
188/// address. Two banks that share an address do not share marks. See [`Memory::prg_offset`].
189///
190/// Saved per ROM, so a session opens knowing what earlier ones ran. The generation is left out of
191/// that: it numbers changes for a view watching this map, and one just read has none to number.
192#[derive(Debug, Clone, Serialize, Deserialize)]
193#[must_use]
194pub struct CodeMap {
195    kinds: Box<[ByteKind]>,
196    #[serde(skip)]
197    generation: u64,
198    /// Which cart the offsets address. See [`CodeMap::covers`].
199    rom_crc32: u32,
200}
201
202impl CodeMap {
203    /// A map covering `len` bytes of the cart with CRC `rom_crc32`, with nothing yet known about
204    /// any of them.
205    pub fn new(len: usize, rom_crc32: u32) -> Self {
206        Self {
207            kinds: vec![ByteKind::empty(); len].into_boxed_slice(),
208            generation: 0,
209            rom_crc32,
210        }
211    }
212
213    /// Mark what the byte at `offset` has been shown to be.
214    ///
215    /// An offset past the end of the memory this was built for is ignored, so a caller can pass
216    /// on whatever a page table gave it without checking.
217    #[inline]
218    pub fn mark(&mut self, offset: usize, kind: ByteKind) {
219        if let Some(entry) = self.kinds.get_mut(offset)
220            && !entry.contains(kind)
221        {
222            *entry |= kind;
223            self.generation += 1;
224        }
225    }
226
227    /// What is known about the byte at `offset`, empty for one nothing has revealed yet.
228    pub fn kind(&self, offset: usize) -> ByteKind {
229        self.kinds
230            .get(offset)
231            .copied()
232            .unwrap_or_else(ByteKind::empty)
233    }
234
235    /// Whether the byte at `offset` has run as the first byte of an instruction.
236    pub fn is_code(&self, offset: usize) -> bool {
237        self.kind(offset).contains(ByteKind::CODE)
238    }
239
240    /// Bumped whenever mark records something new.
241    ///
242    /// A view built from the map becomes stale as code executes. Comparing this is how a consumer
243    /// knows to rebuild.
244    pub const fn generation(&self) -> u64 {
245        self.generation
246    }
247
248    /// Whether this was recorded against `memory`.
249    ///
250    /// An offset means nothing against another arena, so a map kept across a cart change has to be
251    /// refused rather than reused. The CRC says which game and the length says the geometry - two
252    /// dumps of one game can differ in trainer or padding, and an arena built with no ROM to hash
253    /// has only the geometry to go on.
254    pub fn covers(&self, memory: &Memory) -> bool {
255        self.rom_crc32 == memory.rom_crc32() && self.kinds.len() == memory.len()
256    }
257}
258
259bitflags! {
260    /// The ways an address can be touched.
261    ///
262    /// A breakpoint has the set it stops on, so one range covers reads, writes and execution in
263    /// whatever combination the user ticked.
264    #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
265    #[must_use]
266    pub struct Access: u8 {
267        /// Fetched as an instruction.
268        ///
269        /// Checked between instructions, since a fetch and an operand read look alike on the bus.
270        /// The console stops *before* running the instruction, where a read or a write stops
271        /// after it.
272        ///
273        /// The two halves are served in different places. A breakpoint that records is offered
274        /// each instruction by `Bus::check_exec`. One that stops belongs to the driver, through
275        /// [`ControlDeck::clock_frame_until`](crate::control_deck::ControlDeck::clock_frame_until),
276        /// so that a stop unwinds to whoever is clocking rather than landing mid-instruction.
277        const EXEC = 1;
278        /// Read by an instruction, other than the fetch.
279        ///
280        /// A DMA moves its bytes without an instruction asking, through `Bus::cpu_bus_read`, so
281        /// the 256 reads an OAM transfer makes are not reported.
282        const READ = 1 << 1;
283        /// Written by an instruction.
284        ///
285        /// The write half of a DMA is likewise unreported: `$2004` takes 256 bytes during an OAM
286        /// transfer without a `STA` behind any of them.
287        const WRITE = 1 << 2;
288    }
289}
290
291/// A one-shot stop, asked alongside the breakpoints and dropped once it is reached.
292///
293/// What "run to here" and "run to the next interrupt" both are. Passed in by the caller the way
294/// a breakpoint is, so the console stops without knowing why anyone wanted it to.
295#[derive(Debug, Copy, Clone, PartialEq, Eq)]
296#[must_use]
297pub enum RunTo {
298    /// An address, however execution reaches it.
299    Address(u16),
300    /// The next NMI.
301    Nmi,
302    /// The next IRQ.
303    Irq,
304    /// Whichever of the two comes first.
305    Interrupt,
306}
307
308impl RunTo {
309    /// Whether the console has reached it.
310    ///
311    /// Asked between instructions, like every other stop condition. An interrupt is read from
312    /// [`Bus::interrupt_taken`] rather than from PC, since a handler's first address can be
313    /// jumped to like any other. A caller clears that as it arms this, so what is read belongs to
314    /// the run it started.
315    pub fn reached(self, bus: &Bus) -> bool {
316        match self {
317            Self::Address(addr) => bus.cpu.pc == addr,
318            Self::Nmi => bus.interrupt_taken == Some(FrameKind::Nmi),
319            Self::Irq => bus.interrupt_taken == Some(FrameKind::Irq),
320            Self::Interrupt => bus.interrupt_taken.is_some(),
321        }
322    }
323}
324
325/// A range of CPU addresses the console stops on, or records, when one is accessed.
326///
327/// `offset` pins it to the bytes it was set over, and `condition` narrows it to the accesses that
328/// satisfy an expression.
329#[derive(Debug, Clone, PartialEq, Eq)]
330#[must_use]
331pub struct Breakpoint {
332    /// First address covered.
333    pub start: u16,
334    /// Last address covered, inclusive. Equal to `start` for a single address.
335    pub end: u16,
336    /// Where `start` sat in the [`Memory`] arena when the breakpoint was set.
337    ///
338    /// A CPU address names a window, not a byte: the instruction at `$8123` in one bank and the
339    /// one at `$8123` in another are different code that a breakpoint on the address cannot tell
340    /// apart. Recording the offset pins the breakpoint to the bytes it was set over, the way
341    /// [`CodeMap`] pins a mark. `None` where the address has no offset to record - work RAM, the
342    /// registers, an unmapped page - which leaves those keyed by address.
343    pub offset: Option<u32>,
344    /// Which accesses trip it.
345    pub access: Access,
346    /// Cleared to record the access and let the console run on.
347    pub breaks: bool,
348    /// An expression that has to hold as well, or `None` to trip on every covered access.
349    ///
350    /// Evaluated at the access, against the console as it stands part way through the
351    /// instruction. Parsing happens when the breakpoint is set, so what is asked here is a
352    /// compiled form. See [`expr`].
353    pub condition: Option<expr::Expr>,
354}
355
356impl Breakpoint {
357    /// Whether this covers `addr` and stops on `access`.
358    #[inline]
359    pub const fn covers(&self, addr: u16, access: Access) -> bool {
360        self.start <= addr && addr <= self.end && self.access.contains(access)
361    }
362
363    /// Whether this covers `addr` and stops on `access`, with the bank it was set in still mapped
364    /// at `start`.
365    ///
366    /// The whole range answers to `start`'s bank rather than each address answering to its own.
367    /// The arena is contiguous across a range only while one bank holds all of it, so resolving
368    /// per address would leave a range typed across two windows covering its first half from the
369    /// moment it was set.
370    #[inline]
371    pub fn matches(&self, memory: &Memory, addr: u16, access: Access) -> bool {
372        self.covers(addr, access)
373            && match self.offset {
374                Some(offset) => memory.prg_offset(self.start) == Some(offset as usize),
375                None => true,
376            }
377    }
378
379    /// Whether this trips on `access` to `addr`, condition and all.
380    ///
381    /// The condition is asked last, since it is the only part that can read the whole console.
382    #[inline]
383    pub fn fires(&self, bus: &Bus, addr: u16, access: Access) -> bool {
384        self.matches(&bus.memory, addr, access)
385            && self
386                .condition
387                .as_ref()
388                .is_none_or(|condition| condition.is_true(bus))
389    }
390}
391
392/// What the armed breakpoints make of one access.
393#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
394#[must_use]
395pub struct Verdict {
396    /// A breakpoint that stops the console tripped.
397    pub stop: bool,
398    /// A breakpoint that keeps the console running tripped, so the access is worth logging.
399    pub record: bool,
400}
401
402/// An access a [`Breakpoint`] caught.
403#[derive(Debug, Copy, Clone, PartialEq, Eq)]
404#[must_use]
405pub struct AccessHit {
406    /// The instruction that made the access.
407    pub pc: u16,
408    /// The address touched.
409    pub addr: u16,
410    /// How it was touched, which is one of [`Access`]'s flags rather than a set.
411    pub access: Access,
412    /// The byte read or written.
413    pub value: u8,
414}
415
416/// The armed breakpoints, with a bitmap over every address they cover.
417///
418/// The bitmap is a pre-filter: a breakpoint has a range, and later a condition, that no bitmap
419/// expresses. An access matching none of them tests one bit and stops there, which keeps this
420/// affordable on [`Bus::read`](crate::bus::Bus) and `Bus::write`.
421#[derive(Debug, Clone, PartialEq)]
422#[must_use]
423pub struct Breakpoints {
424    /// One bit per CPU address, set where any breakpoint covers it, whatever the access.
425    covered: Box<[u64; Self::WORDS]>,
426    /// The armed breakpoints, scanned only once the bitmap says an address is covered.
427    list: Vec<Breakpoint>,
428    /// Accesses the breakpoints that keep running have caught, waiting to be drained.
429    hits: Vec<AccessHit>,
430}
431
432impl Breakpoints {
433    /// 64K addresses, one bit each.
434    const WORDS: usize = (u16::MAX as usize + 1) / 64;
435    /// How many breakpoints are kept, which bounds the scan a hit pays for.
436    pub const MAX: usize = 64;
437    /// How many recorded accesses are kept between drains, so a breakpoint on a hot address
438    /// cannot grow without limit.
439    const MAX_HITS: usize = 256;
440
441    /// Arm `breakpoints`, dropping any past [`Breakpoints::MAX`].
442    pub fn new(breakpoints: impl IntoIterator<Item = Breakpoint>) -> Self {
443        let mut covered = Box::new([0u64; Self::WORDS]);
444        let list = breakpoints.into_iter().take(Self::MAX).collect::<Vec<_>>();
445        for breakpoint in &list {
446            for addr in breakpoint.start..=breakpoint.end {
447                let addr = usize::from(addr);
448                covered[addr / 64] |= 1 << (addr % 64);
449            }
450        }
451        Self {
452            covered,
453            list,
454            hits: Vec::new(),
455        }
456    }
457
458    /// Whether any breakpoint covers `addr`, whatever the access.
459    ///
460    /// One bit test, so asking per access, and per instruction, stays affordable.
461    #[inline]
462    pub fn watches(&self, addr: u16) -> bool {
463        let addr = usize::from(addr);
464        self.covered[addr / 64] & (1 << (addr % 64)) != 0
465    }
466
467    /// What the armed breakpoints make of `access` to `addr`.
468    ///
469    /// An empty verdict for the addresses nothing watches, which is the answer almost every time.
470    /// `bus` is read only past the bitmap, so an unwatched address pays for the bit and nothing
471    /// else.
472    ///
473    /// Deciding is separate from [`Breakpoints::record`] because a condition reads the whole
474    /// console, and the console owns the breakpoints. Asking with a shared borrow and recording
475    /// with a mutable one keeps both without handing the breakpoints out.
476    pub fn check(&self, bus: &Bus, addr: u16, access: Access) -> Verdict {
477        let mut verdict = Verdict::default();
478        if !self.watches(addr) {
479            return verdict;
480        }
481        for breakpoint in &self.list {
482            if breakpoint.fires(bus, addr, access) {
483                if breakpoint.breaks {
484                    verdict.stop = true;
485                } else {
486                    verdict.record = true;
487                }
488            }
489        }
490        verdict
491    }
492
493    /// Log an access a breakpoint that records caught, dropping it once the log is full.
494    pub fn record(&mut self, hit: AccessHit) {
495        if self.hits.len() < Self::MAX_HITS {
496            self.hits.push(hit);
497        }
498    }
499
500    /// Take over what `previous` caught, for a set replacing it.
501    ///
502    /// A caught access is a record of what the console did, so it outlives the breakpoints that
503    /// were armed when it happened.
504    pub fn adopt_hits(&mut self, previous: &mut Self) {
505        self.hits = std::mem::take(&mut previous.hits);
506        self.hits.truncate(Self::MAX_HITS);
507    }
508
509    /// Take the accesses recorded since the last drain.
510    pub fn drain_hits(&mut self) -> Vec<AccessHit> {
511        std::mem::take(&mut self.hits)
512    }
513
514    /// Put back what [`Breakpoints::drain_hits`] took, dropping anything caught in between.
515    ///
516    /// Run-ahead drains before it speculates and restores once it has rewound, so the accesses
517    /// its discarded frames caught are discarded with them instead of being reported twice.
518    pub fn restore_hits(&mut self, hits: Vec<AccessHit>) {
519        self.hits = hits;
520    }
521
522    /// Whether nothing is armed, in which case the console keeps the unwatched path.
523    pub const fn is_empty(&self) -> bool {
524        self.list.is_empty()
525    }
526}
527
528/// Runs a callback once the PPU reaches a given dot.
529#[derive(Clone)]
530#[must_use]
531pub struct Debugger {
532    /// The cycle within `scanline`.
533    pub cycle: u16,
534    /// The scanline.
535    pub scanline: u16,
536    /// What to run when the cycle/scanline is reached.
537    pub callback: Arc<dyn Fn(&Bus) + Send + Sync + 'static>,
538}
539
540impl Default for Debugger {
541    fn default() -> Self {
542        Self {
543            cycle: u16::MAX,
544            scanline: u16::MAX,
545            callback: Arc::new(|_| {}),
546        }
547    }
548}
549
550impl PartialEq for Debugger {
551    fn eq(&self, other: &Self) -> bool {
552        self.cycle == other.cycle && self.scanline == other.scanline
553    }
554}
555
556impl Bus {
557    /// Set (`Some`) or clear (`None`) a debugger callback.
558    #[inline]
559    pub fn set_debugger(&mut self, debugger: Option<Debugger>) {
560        self.debugger_active = debugger.is_some();
561        self.debugger = debugger.unwrap_or_default();
562    }
563
564    /// Start recording what executes into a [`CodeMap`].
565    ///
566    /// Resumes `code_map` when it was built for the loaded cart, otherwise starts a fresh one.
567    /// Pass `None` to start fresh regardless.
568    pub fn attach_code_map(&mut self, code_map: Option<CodeMap>) {
569        self.code_map = Some(match code_map {
570            Some(code_map) if code_map.covers(&self.memory) => code_map,
571            _ => CodeMap::new(self.memory.len(), self.memory.rom_crc32()),
572        });
573    }
574
575    /// Stop recording and hand back what was recorded, for a later [`Bus::attach_code_map`].
576    ///
577    /// The marks stay valid for as long as the cart is loaded. Only execution adds to them, so a
578    /// map that misses what ran while it was detached reads as unmarked rather than as wrong.
579    pub const fn detach_code_map(&mut self) -> Option<CodeMap> {
580        self.code_map.take()
581    }
582}
583
584impl std::fmt::Debug for Debugger {
585    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
586        f.debug_struct("Debugger")
587            .field("cycle", &self.cycle)
588            .field("scanline", &self.scanline)
589            .finish_non_exhaustive()
590    }
591}
592
593#[cfg(test)]
594mod tests {
595    use super::{
596        Access, AccessHit, Breakpoint, Breakpoints, ByteKind, CallStack, CodeMap, FrameKind,
597        PcHistory, expr::Expr,
598    };
599    use crate::{
600        bus::Bus, cart::Cart, common::ResetKind, control_deck::ControlDeck, cpu::Cpu, mapper::Nrom,
601        memory::Src,
602    };
603
604    /// One 16 KiB PRG bank, which is the window the banked tests swap.
605    const BANK: usize = 0x4000;
606
607    #[test]
608    fn an_unused_history_reads_as_empty() {
609        let history = PcHistory::new(4);
610        assert!(history.is_empty());
611        assert_eq!(history.iter().count(), 0);
612    }
613
614    #[test]
615    fn a_partly_filled_history_reads_oldest_first() {
616        let mut history = PcHistory::new(4);
617        for pc in [0xC000, 0xC003, 0xC005] {
618            history.push(pc);
619        }
620        assert_eq!(history.len(), 3);
621        assert_eq!(history.iter().collect::<Vec<_>>(), [0xC000, 0xC003, 0xC005]);
622    }
623
624    #[test]
625    fn a_wrapped_history_keeps_the_most_recent_oldest_first() {
626        let mut history = PcHistory::new(3);
627        for pc in [0x8000, 0x8001, 0x8002, 0x8003, 0x8004] {
628            history.push(pc);
629        }
630        // Capacity, not push count: the two oldest have been dropped.
631        assert_eq!(history.len(), 3);
632        assert_eq!(history.iter().collect::<Vec<_>>(), [0x8002, 0x8003, 0x8004]);
633    }
634
635    #[test]
636    fn clearing_keeps_the_capacity_and_starts_over() {
637        let mut history = PcHistory::new(2);
638        history.push(0xE000);
639        history.clear();
640        assert!(history.is_empty());
641        history.push(0xE001);
642        assert_eq!(history.iter().collect::<Vec<_>>(), [0xE001]);
643    }
644
645    /// A console running `program` from `$0700`, recording the calls it makes.
646    fn running(program: &[u8]) -> Bus {
647        let mut bus = Bus::default();
648        let mut cart = Cart::empty();
649        cart.mapper = Nrom::load(&mut cart).expect("mapper");
650        bus.load_cart(cart);
651        bus.reset(ResetKind::Hard);
652        for (offset, byte) in program.iter().enumerate() {
653            bus.cpu_bus_write(0x0700 + offset as u16, *byte);
654        }
655        bus.cpu.pc = 0x0700;
656        bus.call_stack = Some(CallStack::new());
657        bus
658    }
659
660    #[test]
661    fn a_call_is_recorded_and_its_return_drops_it() {
662        // JSR $0710, landing on an RTS.
663        let mut bus = running(&[Cpu::JSR, 0x10, 0x07]);
664        bus.cpu_bus_write(0x0710, Cpu::RTS);
665
666        bus.clock_instr();
667        let frames = bus.call_stack.as_ref().expect("recording").frames();
668        assert_eq!(frames.len(), 1);
669        assert_eq!(frames[0].caller, 0x0700);
670        assert_eq!(frames[0].entry, 0x0710);
671        assert_eq!(frames[0].kind, FrameKind::Call);
672
673        bus.clock_instr();
674        assert!(bus.call_stack.expect("recording").is_empty());
675    }
676
677    /// The case that watching for an `RTS` would miss: a subroutine that pulls its own return
678    /// address off and jumps elsewhere. Half a return address is already unusable, so the frame
679    /// goes with the first `PLA`.
680    #[test]
681    fn discarding_a_return_address_drops_the_frame() {
682        // JSR $0710, landing on PLA, PLA.
683        let mut bus = running(&[Cpu::JSR, 0x10, 0x07]);
684        for (addr, byte) in [(0x0710u16, 0x68u8), (0x0711, 0x68)] {
685            bus.cpu_bus_write(addr, byte);
686        }
687
688        bus.clock_instr();
689        assert_eq!(bus.call_stack.as_ref().expect("recording").len(), 1);
690        bus.clock_instr();
691        bus.clock_instr();
692        assert!(bus.call_stack.expect("recording").is_empty());
693    }
694
695    /// Each frame sits below the one that called it, which is the order the stack pointer
696    /// unwinds them in.
697    #[test]
698    fn frames_descend_from_the_outermost_call() {
699        let mut deck = ControlDeck::new();
700        deck.load_rom_path("test_roms/spritecans.nes")
701            .expect("load rom");
702        deck.set_call_stack(true);
703
704        let mut deepest = 0;
705        for _ in 0..100_000 {
706            deck.clock_instr().expect("clock instruction");
707            let frames = deck.call_stack().expect("recording").frames();
708            deepest = deepest.max(frames.len());
709            for pair in frames.windows(2) {
710                assert!(
711                    pair[1].sp < pair[0].sp,
712                    "${:04X} sits at ${:02X}, above the ${:02X} it was called from",
713                    pair[1].entry,
714                    pair[1].sp,
715                    pair[0].sp
716                );
717            }
718        }
719        assert!(deepest > 1, "no nested call ran, so nothing was proven");
720    }
721
722    /// An NMI arriving part way through an IRQ sequence takes the other vector, so which one was
723    /// taken is read back from PC rather than from the flags.
724    #[test]
725    fn an_interrupt_is_recorded_as_the_vector_it_took() {
726        let mut deck = ControlDeck::new();
727        deck.load_rom_path("test_roms/spritecans.nes")
728            .expect("load rom");
729        deck.set_call_stack(true);
730
731        let handler = deck.bus().peek_word(Cpu::NMI_VECTOR);
732        let mut taken = 0;
733        for _ in 0..100_000 {
734            deck.clock_instr().expect("clock instruction");
735            for frame in deck.call_stack().expect("recording").frames() {
736                if frame.kind == FrameKind::Nmi {
737                    assert_eq!(frame.entry, handler);
738                    taken += 1;
739                }
740            }
741        }
742        assert!(taken > 0, "no NMI ran, so nothing was proven");
743    }
744
745    /// A caller waiting on the next interrupt has nothing to see between instructions, since the
746    /// handler's first address can be reached by a jump like any other. The marker says a vector
747    /// was taken, and reports it without a call stack recording.
748    #[test]
749    fn the_vector_an_instruction_took_is_reported_without_a_call_stack() {
750        let mut deck = ControlDeck::new();
751        deck.load_rom_path("test_roms/spritecans.nes")
752            .expect("load rom");
753
754        let handler = deck.bus().peek_word(Cpu::NMI_VECTOR);
755        let mut taken = 0;
756        for _ in 0..100_000 {
757            deck.clear_interrupt();
758            deck.clock_instr().expect("clock instruction");
759            if let Some(kind) = deck.interrupt_taken() {
760                assert_eq!(kind, FrameKind::Nmi, "spritecans takes only the NMI");
761                assert_eq!(deck.bus().cpu.pc, handler, "PC is at the handler");
762                taken += 1;
763            }
764        }
765        assert!(taken > 0, "no interrupt ran, so nothing was proven");
766        assert!(
767            deck.call_stack().is_none(),
768            "reported with nothing recording"
769        );
770    }
771
772    /// The marker stands until the next interrupt, so a caller that starts waiting after one has
773    /// already been taken clears it rather than stopping on what it missed.
774    #[test]
775    fn clearing_the_marker_forgets_the_interrupt_already_taken() {
776        let mut deck = ControlDeck::new();
777        deck.load_rom_path("test_roms/spritecans.nes")
778            .expect("load rom");
779
780        for _ in 0..100_000 {
781            deck.clock_instr().expect("clock instruction");
782            if deck.interrupt_taken().is_some() {
783                break;
784            }
785        }
786        assert!(deck.interrupt_taken().is_some(), "an interrupt was taken");
787        deck.clear_interrupt();
788        assert!(deck.interrupt_taken().is_none(), "and then forgotten");
789    }
790
791    #[test]
792    fn a_mark_records_its_kind_and_leaves_its_neighbors_alone() {
793        let mut map = CodeMap::new(4, 0);
794        map.mark(1, ByteKind::CODE);
795        assert_eq!(map.kind(1), ByteKind::CODE);
796        assert!(map.is_code(1));
797        assert_eq!(map.kind(0), ByteKind::empty());
798        assert_eq!(map.kind(2), ByteKind::empty());
799    }
800
801    #[test]
802    fn kinds_accumulate_rather_than_replace_one_another() {
803        let mut map = CodeMap::new(1, 0);
804        map.mark(0, ByteKind::SUB_ENTRY);
805        map.mark(0, ByteKind::CODE);
806        assert_eq!(map.kind(0), ByteKind::CODE | ByteKind::SUB_ENTRY);
807    }
808
809    /// Callers pass on whatever a page table gave them, so an offset outside the arena the map was
810    /// built for has to read as "nothing known" rather than panic.
811    #[test]
812    fn an_offset_past_the_end_is_ignored() {
813        let mut map = CodeMap::new(1, 0);
814        map.mark(64, ByteKind::CODE);
815        assert_eq!(map.kind(64), ByteKind::empty());
816        assert!(!map.is_code(64));
817        assert_eq!(map.generation(), 0);
818    }
819
820    #[test]
821    fn the_generation_moves_only_when_the_map_learns_something() {
822        let mut map = CodeMap::new(2, 0);
823        map.mark(0, ByteKind::CODE);
824        let learned = map.generation();
825        assert_ne!(learned, 0, "a first mark is something new");
826
827        map.mark(0, ByteKind::CODE);
828        assert_eq!(
829            map.generation(),
830            learned,
831            "re-marking what is already known rebuilds every view for nothing"
832        );
833
834        map.mark(0, ByteKind::SUB_ENTRY);
835        assert_ne!(
836            map.generation(),
837            learned,
838            "a second kind on a marked byte is still new information"
839        );
840    }
841
842    /// The write sites in `Bus::clock_instr`: an executed instruction is code, and where a call
843    /// leaves PC is the start of a subroutine.
844    #[test]
845    fn executing_marks_the_instruction_and_the_subroutines_it_calls() {
846        let mut deck = ControlDeck::new();
847        deck.load_rom_path("test_roms/spritecans.nes")
848            .expect("load rom");
849        deck.attach_code_map(None);
850
851        let mut calls = 0;
852        for _ in 0..100_000 {
853            let pc = deck.bus().cpu.pc;
854            let is_jsr = deck.bus().peek(pc) == Cpu::JSR;
855            // Read before the instruction runs: a bank switch inside it would move the byte, and
856            // the offset marked is the one that was mapped at the fetch.
857            let offset = deck.bus().memory.prg_offset(pc);
858            deck.clock_instr().expect("clock instruction");
859
860            let map = deck.code_map().expect("recording");
861            if let Some(offset) = offset {
862                assert!(map.is_code(offset), "${pc:04X} ran but is not marked code");
863            }
864            if is_jsr {
865                let dest = deck.bus().cpu.pc;
866                let offset = deck.bus().memory.prg_offset(dest).expect("mapped");
867                assert!(
868                    map.kind(offset).contains(ByteKind::SUB_ENTRY),
869                    "${dest:04X} was called from ${pc:04X} but is not marked a call target"
870                );
871                calls += 1;
872            }
873        }
874        assert!(calls > 0, "no subroutine call ran, so nothing was proven");
875    }
876
877    /// Closing a debugger stops the recording. What it recorded is still true, so reopening one
878    /// resumes rather than starting over.
879    #[test]
880    fn detaching_keeps_what_was_recorded_for_the_next_attach() {
881        let mut deck = ControlDeck::new();
882        deck.load_rom_path("test_roms/spritecans.nes")
883            .expect("load rom");
884        deck.attach_code_map(None);
885        for _ in 0..1_000 {
886            deck.clock_instr().expect("clock instruction");
887        }
888        let recorded = deck.code_map().expect("recording").generation();
889        assert_ne!(recorded, 0);
890
891        let detached = deck.detach_code_map();
892        assert!(deck.code_map().is_none(), "still recording after detaching");
893        deck.attach_code_map(detached);
894        assert_eq!(deck.code_map().expect("recording").generation(), recorded);
895    }
896
897    /// Offsets address the arena they were recorded against, so a map from another cart has to be
898    /// dropped rather than reused.
899    #[test]
900    fn a_map_recorded_against_another_cart_is_refused() {
901        let mut deck = ControlDeck::new();
902        deck.load_rom_path("test_roms/spritecans.nes")
903            .expect("load rom");
904        deck.attach_code_map(None);
905        for _ in 0..1_000 {
906            deck.clock_instr().expect("clock instruction");
907        }
908        let detached = deck.detach_code_map();
909        assert_ne!(detached.as_ref().expect("recorded").generation(), 0);
910
911        deck.load_rom_path("test_roms/cpu/nestest.nes")
912            .expect("load rom");
913        deck.attach_code_map(detached);
914        assert_eq!(
915            deck.code_map().expect("recording").generation(),
916            0,
917            "another cart's marks were kept"
918        );
919    }
920
921    /// Marks are memory offsets, so they describe bytes a different cart's arena does not contain,
922    /// and that arena is a different size, which would leave the map addressing past its end.
923    #[test]
924    fn loading_a_cart_starts_the_map_over_at_the_new_size() {
925        let mut deck = ControlDeck::new();
926        deck.load_rom_path("test_roms/spritecans.nes")
927            .expect("load rom");
928        deck.attach_code_map(None);
929        for _ in 0..1_000 {
930            deck.clock_instr().expect("clock instruction");
931        }
932        assert_ne!(deck.code_map().expect("recording").generation(), 0);
933
934        deck.load_rom_path("test_roms/cpu/nestest.nes")
935            .expect("load rom");
936        let map = deck.code_map().expect("still recording");
937        assert_eq!(map.generation(), 0, "marks survived a different cart");
938    }
939
940    fn bus_with_cart() -> Bus {
941        let mut bus = Bus::default();
942        let mut cart = Cart::empty();
943        cart.mapper = Nrom::load(&mut cart).unwrap();
944        bus.load_cart(cart);
945        bus.reset(ResetKind::Hard);
946        bus
947    }
948
949    /// A breakpoint on an address rather than on a bank, the way work RAM records one.
950    fn breakpoint(start: u16, end: u16, access: Access) -> Breakpoint {
951        Breakpoint {
952            start,
953            end,
954            offset: None,
955            access,
956            breaks: true,
957            condition: None,
958        }
959    }
960
961    /// The bitmap is only a pre-filter, so a range has to be checked at both ends and one past
962    /// each. Getting the inclusive end wrong shortens every range by one address.
963    #[test]
964    fn a_range_covers_both_ends_and_nothing_past_them() {
965        let bus = bus_with_cart();
966        let breakpoints = Breakpoints::new([breakpoint(0x0300, 0x0302, Access::WRITE)]);
967        for addr in [0x0300, 0x0301, 0x0302] {
968            assert!(
969                breakpoints.check(&bus, addr, Access::WRITE).stop,
970                "${addr:04X}"
971            );
972        }
973        for addr in [0x02FF, 0x0303] {
974            assert!(
975                !breakpoints.check(&bus, addr, Access::WRITE).stop,
976                "${addr:04X}"
977            );
978        }
979    }
980
981    /// A breakpoint stops on the accesses it was ticked for and no others.
982    #[test]
983    fn an_access_the_breakpoint_does_not_watch_is_ignored() {
984        let bus = bus_with_cart();
985        let breakpoints = Breakpoints::new([breakpoint(0x0300, 0x0300, Access::WRITE)]);
986        assert!(breakpoints.check(&bus, 0x0300, Access::WRITE).stop);
987        assert!(!breakpoints.check(&bus, 0x0300, Access::READ).stop);
988    }
989
990    /// A condition narrows a breakpoint to the accesses that satisfy it, so a write breakpoint on
991    /// a counter can wait for the one write that matters.
992    #[test]
993    fn a_condition_narrows_what_a_breakpoint_stops_on() {
994        let mut bus = bus_with_cart();
995        bus.breakpoints_active = true;
996        bus.breakpoints = Some(Box::new(Breakpoints::new([Breakpoint {
997            condition: Some(Expr::parse("a == 0x42").expect("parses")),
998            ..breakpoint(0x0300, 0x0300, Access::WRITE)
999        }])));
1000
1001        bus.cpu.acc = 0x01;
1002        bus.write(0x0300, 0x99);
1003        assert_eq!(
1004            bus.access_hit, None,
1005            "a condition that does not hold stopped it"
1006        );
1007
1008        bus.cpu.acc = 0x42;
1009        bus.write(0x0300, 0x99);
1010        assert!(
1011            bus.access_hit.is_some(),
1012            "a condition that holds did not stop it"
1013        );
1014    }
1015
1016    /// A breakpoint that records rather than stops keeps the console running, and the accesses
1017    /// come back once each.
1018    #[test]
1019    fn a_recording_breakpoint_collects_hits_without_stopping() {
1020        let mut bus = bus_with_cart();
1021        bus.breakpoints_active = true;
1022        bus.breakpoints = Some(Box::new(Breakpoints::new([Breakpoint {
1023            breaks: false,
1024            ..breakpoint(0x0300, 0x0300, Access::WRITE)
1025        }])));
1026
1027        bus.write(0x0300, 0x42);
1028        bus.write(0x0300, 0x43);
1029        assert_eq!(bus.access_hit, None, "a breakpoint that records stopped it");
1030
1031        let breakpoints = bus.breakpoints.as_mut().expect("armed");
1032        let hits = breakpoints.drain_hits();
1033        assert_eq!(hits.len(), 2);
1034        assert_eq!(hits[0].value, 0x42);
1035        assert!(
1036            breakpoints.drain_hits().is_empty(),
1037            "draining twice repeats what was already reported"
1038        );
1039    }
1040
1041    /// A breakpoint on a hot address would otherwise grow the log without limit between frames.
1042    #[test]
1043    fn a_recording_breakpoint_stops_collecting_at_its_cap() {
1044        let mut breakpoints = Breakpoints::new([Breakpoint {
1045            breaks: false,
1046            ..breakpoint(0x0300, 0x0300, Access::WRITE)
1047        }]);
1048        for _ in 0..Breakpoints::MAX_HITS * 2 {
1049            breakpoints.record(AccessHit {
1050                pc: 0xC000,
1051                addr: 0x0300,
1052                access: Access::WRITE,
1053                value: 0,
1054            });
1055        }
1056        assert_eq!(breakpoints.drain_hits().len(), Breakpoints::MAX_HITS);
1057    }
1058
1059    /// Past the cap the extras are dropped rather than scanned, so the work a hit pays for stays
1060    /// bounded.
1061    #[test]
1062    fn breakpoints_past_the_cap_are_dropped() {
1063        let breakpoints = Breakpoints::new(
1064            (0..Breakpoints::MAX as u16 + 8)
1065                .map(|i| breakpoint(0x0300 + i, 0x0300 + i, Access::WRITE)),
1066        );
1067        assert_eq!(breakpoints.list.len(), Breakpoints::MAX);
1068    }
1069
1070    /// The debugger resolves every row it draws through `peek`, so a read breakpoint that fired
1071    /// there would trip on the disassembly reading the address it was set on.
1072    #[test]
1073    fn peeking_does_not_trip_a_read_breakpoint() {
1074        let mut bus = bus_with_cart();
1075        bus.breakpoints_active = true;
1076        bus.breakpoints = Some(Box::new(Breakpoints::new([breakpoint(
1077            0x0300,
1078            0x0300,
1079            Access::READ | Access::WRITE,
1080        )])));
1081
1082        let _ = bus.peek(0x0300);
1083        assert_eq!(bus.access_hit, None);
1084
1085        let _ = bus.read(0x0300);
1086        assert!(bus.access_hit.is_some(), "a real read still stops");
1087    }
1088
1089    /// A read-modify-write puts the old value back before the new one, and only the first hit is
1090    /// kept, so reporting the re-write names a value the program never chose.
1091    #[test]
1092    fn a_write_breakpoint_reports_the_value_the_program_wrote() {
1093        let mut bus = bus_with_cart();
1094        bus.cpu_bus_write(0x0010, 0x05);
1095        // `INC $10`, which reads $10, writes $05 back, then writes $06.
1096        bus.cpu_bus_write(0x0000, 0xE6);
1097        bus.cpu_bus_write(0x0001, 0x10);
1098        bus.cpu.pc = 0x0000;
1099        bus.breakpoints_active = true;
1100        bus.breakpoints = Some(Box::new(Breakpoints::new([breakpoint(
1101            0x0010,
1102            0x0010,
1103            Access::WRITE,
1104        )])));
1105
1106        bus.clock_instr();
1107        let hit = bus.access_hit.expect("the write was caught");
1108        assert_eq!(
1109            hit.value, 0x06,
1110            "the re-write of the old value was reported instead"
1111        );
1112        assert_eq!(
1113            hit.pc, 0x0000,
1114            "the hit names where PC reached, not the instruction that wrote"
1115        );
1116    }
1117
1118    /// A breakpoint that records rather than stops is the only one served on execution, and
1119    /// nothing else on the bus can tell an instruction fetch from an operand read.
1120    #[test]
1121    fn a_recording_breakpoint_logs_each_execution() {
1122        let mut bus = bus_with_cart();
1123        // `LDA #$42`, run twice from the same address.
1124        bus.cpu_bus_write(0x0000, 0xA9);
1125        bus.cpu_bus_write(0x0001, 0x42);
1126        bus.breakpoints_active = true;
1127        bus.breakpoints = Some(Box::new(Breakpoints::new([Breakpoint {
1128            breaks: false,
1129            ..breakpoint(0x0000, 0x0000, Access::EXEC)
1130        }])));
1131
1132        for _ in 0..2 {
1133            bus.cpu.pc = 0x0000;
1134            bus.clock_instr();
1135        }
1136
1137        let hits = bus.breakpoints.as_mut().expect("armed").drain_hits();
1138        assert_eq!(hits.len(), 2);
1139        assert_eq!(hits[0].access, Access::EXEC);
1140        assert_eq!(hits[0].addr, 0x0000);
1141        assert_eq!(hits[0].value, 0xA9, "the opcode is what executed");
1142        assert_eq!(bus.access_hit, None, "a breakpoint that records stopped it");
1143    }
1144
1145    /// `Access::EXEC` covers fetches, so a read breakpoint over a bank holding both code and data
1146    /// would otherwise stop on every instruction in it.
1147    #[test]
1148    fn a_read_breakpoint_does_not_fire_on_an_instruction_fetch() {
1149        let mut bus = bus_with_cart();
1150        // `LDA #$42`, whose two bytes are both fetches and whose operand is immediate.
1151        bus.cpu_bus_write(0x0000, 0xA9);
1152        bus.cpu_bus_write(0x0001, 0x42);
1153        bus.cpu.pc = 0x0000;
1154        bus.breakpoints_active = true;
1155        bus.breakpoints = Some(Box::new(Breakpoints::new([breakpoint(
1156            0x0000,
1157            0x0001,
1158            Access::READ,
1159        )])));
1160
1161        bus.clock_instr();
1162        assert_eq!(bus.access_hit, None);
1163    }
1164
1165    /// With nothing armed the read and write paths take one `bool` test and no further work,
1166    /// which is all the hot path is allowed to spend.
1167    #[test]
1168    fn nothing_armed_leaves_the_bus_unwatched() {
1169        let mut bus = bus_with_cart();
1170        let _ = bus.read(0x0300);
1171        bus.write(0x0300, 0x42);
1172        assert!(!bus.breakpoints_active);
1173        assert!(bus.breakpoints.is_none());
1174        assert_eq!(bus.access_hit, None);
1175    }
1176
1177    /// Two 16 KiB PRG banks mapped flat, so a test can swap the second into `$8000`.
1178    fn bus_with_banked_cart() -> Bus {
1179        let mut bus = Bus::default();
1180        let mut cart = Cart::empty_sized(2 * BANK, 0x2000);
1181        cart.mapper = Nrom::load(&mut cart).unwrap();
1182        bus.load_cart(cart);
1183        bus.reset(ResetKind::Hard);
1184        bus
1185    }
1186
1187    /// A breakpoint names the bytes it was set over. Another bank at the same address holds
1188    /// unrelated code, and stopping there stops somewhere nothing was set.
1189    #[test]
1190    fn a_breakpoint_does_not_fire_on_another_bank_at_its_address() {
1191        let mut bus = bus_with_banked_cart();
1192        let offset = bus.memory.prg_offset(0x8000).expect("mapped") as u32;
1193        let breakpoint = Breakpoint {
1194            offset: Some(offset),
1195            ..breakpoint(0x8000, 0x8000, Access::EXEC)
1196        };
1197        assert!(breakpoint.matches(&bus.memory, 0x8000, Access::EXEC));
1198
1199        bus.memory.map_prg(0x8000, BANK, 1, Src::PrgRom);
1200        assert!(!breakpoint.matches(&bus.memory, 0x8000, Access::EXEC));
1201        assert!(
1202            breakpoint.covers(0x8000, Access::EXEC),
1203            "the address is still covered, so the bank is what refused it"
1204        );
1205    }
1206
1207    /// A range answers to the bank at its start, so switching that bank out takes the whole range
1208    /// with it however far past the switched window the range reaches.
1209    #[test]
1210    fn a_range_is_pinned_by_the_bank_at_its_start() {
1211        let mut bus = bus_with_banked_cart();
1212        let offset = bus.memory.prg_offset(0xBFFF).expect("mapped") as u32;
1213        let breakpoint = Breakpoint {
1214            offset: Some(offset),
1215            ..breakpoint(0xBFFF, 0xC000, Access::EXEC)
1216        };
1217        assert!(breakpoint.matches(&bus.memory, 0xC000, Access::EXEC));
1218
1219        bus.memory.map_prg(0x8000, BANK, 1, Src::PrgRom);
1220        assert!(!breakpoint.matches(&bus.memory, 0xBFFF, Access::EXEC));
1221        assert!(!breakpoint.matches(&bus.memory, 0xC000, Access::EXEC));
1222    }
1223
1224    /// Work RAM has no arena offset to pin to, so a breakpoint there is keyed by address alone.
1225    #[test]
1226    fn a_breakpoint_outside_the_cart_is_keyed_by_address() {
1227        let bus = bus_with_banked_cart();
1228        assert_eq!(bus.memory.prg_offset(0x0300), None);
1229        assert!(breakpoint(0x0300, 0x0300, Access::WRITE).matches(
1230            &bus.memory,
1231            0x0300,
1232            Access::WRITE
1233        ));
1234    }
1235}