1use crate::{bus::Bus, memory::Memory};
8use bitflags::bitflags;
9use serde::{Deserialize, Serialize};
10use std::sync::Arc;
11
12pub mod expr;
13
14#[derive(Debug, Clone)]
21#[must_use]
22pub struct PcHistory {
23 entries: Box<[u16]>,
24 head: usize,
26 len: usize,
28}
29
30impl PcHistory {
31 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 #[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 pub fn iter(&self) -> impl ExactSizeIterator<Item = u16> + '_ {
50 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 #[must_use]
57 pub const fn len(&self) -> usize {
58 self.len
59 }
60
61 #[must_use]
63 pub const fn is_empty(&self) -> bool {
64 self.len == 0
65 }
66
67 pub const fn clear(&mut self) {
69 self.head = 0;
70 self.len = 0;
71 }
72}
73
74#[derive(Debug, Copy, Clone, PartialEq, Eq)]
76#[must_use]
77pub enum FrameKind {
78 Call,
80 Nmi,
82 Irq,
84 Brk,
86}
87
88#[derive(Debug, Copy, Clone, PartialEq, Eq)]
90#[must_use]
91pub struct CallFrame {
92 pub caller: u16,
94 pub entry: u16,
96 pub sp: u8,
99 pub kind: FrameKind,
101}
102
103#[derive(Debug, Default, Clone)]
110#[must_use]
111pub struct CallStack {
112 frames: Vec<CallFrame>,
113}
114
115impl CallStack {
116 const MAX_DEPTH: usize = 128;
119
120 pub fn new() -> Self {
122 Self {
123 frames: Vec::with_capacity(16),
124 }
125 }
126
127 #[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 pub fn push(&mut self, frame: CallFrame) {
141 if self.frames.len() < Self::MAX_DEPTH {
142 self.frames.push(frame);
143 }
144 }
145
146 pub fn frames(&self) -> &[CallFrame] {
148 &self.frames
149 }
150
151 #[must_use]
153 pub const fn len(&self) -> usize {
154 self.frames.len()
155 }
156
157 #[must_use]
159 pub const fn is_empty(&self) -> bool {
160 self.frames.is_empty()
161 }
162
163 pub fn clear(&mut self) {
165 self.frames.clear();
166 }
167}
168
169bitflags! {
170 #[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
172 pub struct ByteKind: u8 {
173 const CODE = 1;
175 const SUB_ENTRY = 1 << 1;
177 }
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
193#[must_use]
194pub struct CodeMap {
195 kinds: Box<[ByteKind]>,
196 #[serde(skip)]
197 generation: u64,
198 rom_crc32: u32,
200}
201
202impl CodeMap {
203 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 #[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 pub fn kind(&self, offset: usize) -> ByteKind {
229 self.kinds
230 .get(offset)
231 .copied()
232 .unwrap_or_else(ByteKind::empty)
233 }
234
235 pub fn is_code(&self, offset: usize) -> bool {
237 self.kind(offset).contains(ByteKind::CODE)
238 }
239
240 pub const fn generation(&self) -> u64 {
245 self.generation
246 }
247
248 pub fn covers(&self, memory: &Memory) -> bool {
255 self.rom_crc32 == memory.rom_crc32() && self.kinds.len() == memory.len()
256 }
257}
258
259bitflags! {
260 #[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
265 #[must_use]
266 pub struct Access: u8 {
267 const EXEC = 1;
278 const READ = 1 << 1;
283 const WRITE = 1 << 2;
288 }
289}
290
291#[derive(Debug, Copy, Clone, PartialEq, Eq)]
296#[must_use]
297pub enum RunTo {
298 Address(u16),
300 Nmi,
302 Irq,
304 Interrupt,
306}
307
308impl RunTo {
309 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#[derive(Debug, Clone, PartialEq, Eq)]
330#[must_use]
331pub struct Breakpoint {
332 pub start: u16,
334 pub end: u16,
336 pub offset: Option<u32>,
344 pub access: Access,
346 pub breaks: bool,
348 pub condition: Option<expr::Expr>,
354}
355
356impl Breakpoint {
357 #[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 #[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 #[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#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
394#[must_use]
395pub struct Verdict {
396 pub stop: bool,
398 pub record: bool,
400}
401
402#[derive(Debug, Copy, Clone, PartialEq, Eq)]
404#[must_use]
405pub struct AccessHit {
406 pub pc: u16,
408 pub addr: u16,
410 pub access: Access,
412 pub value: u8,
414}
415
416#[derive(Debug, Clone, PartialEq)]
422#[must_use]
423pub struct Breakpoints {
424 covered: Box<[u64; Self::WORDS]>,
426 list: Vec<Breakpoint>,
428 hits: Vec<AccessHit>,
430}
431
432impl Breakpoints {
433 const WORDS: usize = (u16::MAX as usize + 1) / 64;
435 pub const MAX: usize = 64;
437 const MAX_HITS: usize = 256;
440
441 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 #[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 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 pub fn record(&mut self, hit: AccessHit) {
495 if self.hits.len() < Self::MAX_HITS {
496 self.hits.push(hit);
497 }
498 }
499
500 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 pub fn drain_hits(&mut self) -> Vec<AccessHit> {
511 std::mem::take(&mut self.hits)
512 }
513
514 pub fn restore_hits(&mut self, hits: Vec<AccessHit>) {
519 self.hits = hits;
520 }
521
522 pub const fn is_empty(&self) -> bool {
524 self.list.is_empty()
525 }
526}
527
528#[derive(Clone)]
530#[must_use]
531pub struct Debugger {
532 pub cycle: u16,
534 pub scanline: u16,
536 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 #[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 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 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 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 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 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 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 #[test]
681 fn discarding_a_return_address_drops_the_frame() {
682 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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[test]
1121 fn a_recording_breakpoint_logs_each_execution() {
1122 let mut bus = bus_with_cart();
1123 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 #[test]
1148 fn a_read_breakpoint_does_not_fire_on_an_instruction_fetch() {
1149 let mut bus = bus_with_cart();
1150 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 #[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 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 #[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 #[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 #[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}