Skip to main content

tetanes/nes/
debug.rs

1//! What the Debugger remembers about a ROM between sessions.
2//!
3//! One file per ROM beside its save states and battery RAM: what execution has shown the cart's
4//! bytes to be, the breakpoints set on the console, and the names its addresses have been given.
5//! A code map indexes one cart's arena, so one recorded against another is dropped on load.
6//!
7//! The two halves have different owners. The window owns [`Marks`] and the emulation thread owns
8//! the [`CodeMap`], so the marks travel to the emulation thread to be written and come back when
9//! a ROM loads. Only the small half crosses the channel.
10
11use crate::nes::{config::Config, renderer::gui::debugger::Breakpoint};
12use serde::{Deserialize, Serialize};
13use std::{
14    collections::HashMap,
15    path::{Path, PathBuf},
16};
17use tetanes_core::{debug::CodeMap, fs, memory::Memory};
18use tracing::{error, info};
19
20/// The version this format is at.
21///
22/// Independent of the save-state version, the way the game database's is: a change to how a
23/// console is serialized says nothing about whether a debug file is still readable.
24const DEBUG_VERSION: &str = "2";
25
26/// The version of debug files written in the bincode format, which [`fs::v3`] reads.
27const DEBUG_VERSION_V3: u8 = b'1';
28
29/// What a labeled address is called, and what was written about it.
30// Not `Label`: the window that draws these takes that name from egui.
31#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[must_use]
33pub struct AddrLabel {
34    /// The name the disassembly prints in place of the address.
35    ///
36    /// Empty for an address that only carries a comment, which is a row worth annotating without
37    /// a name for.
38    pub name: String,
39    /// A note about the address, printed after the instruction.
40    pub comment: String,
41}
42
43impl AddrLabel {
44    /// Whether this says nothing, in which case it is dropped rather than stored.
45    pub fn is_empty(&self) -> bool {
46        self.name.trim().is_empty() && self.comment.trim().is_empty()
47    }
48}
49
50/// What a label is filed under.
51///
52/// The split [`Breakpoint::offset`] already makes: cart memory is keyed by where the byte sits in
53/// the arena, so a name follows it through a bank switch, and everything else by CPU address,
54/// since work RAM and the registers do not move.
55#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[must_use]
57pub enum LabelKey {
58    /// A byte of the cartridge, by its offset in the [`Memory`] arena.
59    Cart(u32),
60    /// An address the arena does not address: work RAM, the registers, an unmapped page.
61    Cpu(u16),
62}
63
64impl LabelKey {
65    /// How `addr` is filed, given where the mapping the window is drawing puts it.
66    pub const fn new(addr: u16, offset: Option<u32>) -> Self {
67        match offset {
68            Some(offset) => Self::Cart(offset),
69            None => Self::Cpu(addr),
70        }
71    }
72}
73
74/// What the Debugger's window keeps for a ROM.
75#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
76#[must_use]
77pub struct Marks {
78    /// The breakpoints the window lists, disarmed ones included.
79    pub breakpoints: Vec<Breakpoint>,
80    /// What the addresses of this ROM have been named and annotated.
81    pub labels: HashMap<LabelKey, AddrLabel>,
82}
83
84impl Marks {
85    /// Whether there is nothing here to write.
86    pub fn is_empty(&self) -> bool {
87        self.breakpoints.is_empty() && self.labels.is_empty()
88    }
89}
90
91/// One ROM's debugging session, as it is written to disk.
92#[derive(Debug, Default, Clone, Serialize, Deserialize)]
93#[must_use]
94pub struct Session {
95    /// What execution has shown the cart's bytes to be, or `None` where nothing has been recorded.
96    pub code_map: Option<CodeMap>,
97    /// What the window set on them.
98    pub marks: Marks,
99}
100
101impl Session {
102    /// Directory the files live in, under the data directory beside `save` and `sram`.
103    const DIR: &'static str = "debug";
104    /// Extension the files take.
105    const EXTENSION: &'static str = "dbg";
106
107    /// Where the file for the ROM named `name` lives.
108    pub fn path(name: &str) -> PathBuf {
109        Config::default_data_dir()
110            .join(Self::DIR)
111            .join(name)
112            .with_extension(Self::EXTENSION)
113    }
114
115    /// Read what was saved for `name`, or an empty session where there is nothing to read.
116    ///
117    /// A file that will not parse is reported and skipped. Losing the marks a session made is
118    /// worth saying out loud, and is not a reason to refuse the ROM.
119    pub fn load(name: &str) -> Self {
120        Self::load_path(Self::path(name))
121    }
122
123    /// [`Session::load`] from an explicit path.
124    pub fn load_path(path: impl AsRef<Path>) -> Self {
125        let path = path.as_ref();
126        if !fs::exists(path) {
127            return Self::default();
128        }
129        let session = fs::load_data_path(path).and_then(|(version, data)| {
130            if version == DEBUG_VERSION_V3 {
131                return fs::v3::decode(&data).map(|(session, _)| session);
132            }
133            fs::check_version(version, DEBUG_VERSION)?;
134            fs::decode_value(&data)
135        });
136        match session {
137            Ok(session) => {
138                info!("loaded debug session: {path:?}");
139                session
140            }
141            Err(err) => {
142                error!("failed to load debug session {path:?}: {err:?}");
143                Self::default()
144            }
145        }
146    }
147
148    /// Write this session for `name`.
149    ///
150    /// # Errors
151    ///
152    /// If the file cannot be written.
153    pub fn save(&self, name: &str) -> fs::Result<()> {
154        self.save_path(Self::path(name))
155    }
156
157    /// [`Session::save`] to an explicit path.
158    ///
159    /// # Errors
160    ///
161    /// If the file cannot be written.
162    pub fn save_path(&self, path: impl AsRef<Path>) -> fs::Result<()> {
163        // A session with nothing in it writes nothing, so opening the Debugger on a ROM and
164        // closing it again leaves no file behind.
165        if self.is_empty() {
166            return Ok(());
167        }
168        fs::save_version_path(path, self, DEBUG_VERSION)
169    }
170
171    /// Whether there is nothing here worth writing.
172    pub fn is_empty(&self) -> bool {
173        self.code_map.is_none() && self.marks.is_empty()
174    }
175
176    /// Drop what does not describe `memory`.
177    ///
178    /// A code map's offsets only address the arena the cart it was recorded against produces, so
179    /// one read for another game is dropped rather than applied to this one. What is keyed by CPU
180    /// address stays: work RAM and the registers are the console's, whatever is in the slot.
181    pub fn accept(&mut self, memory: &Memory) {
182        if !self
183            .code_map
184            .as_ref()
185            .is_some_and(|code_map| code_map.covers(memory))
186        {
187            self.code_map = None;
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use tetanes_core::{
196        cart::Cart,
197        debug::{Access, ByteKind},
198        mapper::Nrom,
199    };
200
201    fn cart() -> Cart {
202        let mut cart = Cart::empty();
203        *cart.mapper_mut() = Nrom::load(&mut cart).expect("valid mapper");
204        cart
205    }
206
207    fn marked(cart: &Cart) -> Session {
208        let mut code_map = CodeMap::new(cart.memory().len(), cart.memory().rom_crc32());
209        code_map.mark(0x10, ByteKind::CODE);
210        Session {
211            code_map: Some(code_map),
212            marks: Marks {
213                breakpoints: vec![Breakpoint {
214                    id: 7,
215                    addr: 0x8123,
216                    end: 0x8123,
217                    offset: Some(0x1234),
218                    access: Access::EXEC,
219                    enabled: true,
220                    breaks: true,
221                    condition: "a == 0x10".to_string(),
222                }],
223                labels: HashMap::from([(
224                    LabelKey::Cart(0x1234),
225                    AddrLabel {
226                        name: "reset".to_string(),
227                        comment: "where it all starts".to_string(),
228                    },
229                )]),
230            },
231        }
232    }
233
234    /// What a session is worth keeping has to survive the file, or the next run of the Debugger
235    /// starts over. The id is not part of that: it names a breakpoint for one run of the window.
236    #[test]
237    fn a_session_reads_back_what_it_wrote() {
238        let dir = std::env::temp_dir().join("tetanes-debug-session-round-trip");
239        std::fs::create_dir_all(&dir).expect("scratch dir");
240        let path = dir.join("session.dbg");
241        let cart = cart();
242        let written = marked(&cart);
243        written.save_path(&path).expect("writes");
244
245        let read = Session::load_path(&path);
246        let code_map = read.code_map.as_ref().expect("a map was written");
247        assert!(
248            code_map.covers(cart.memory()),
249            "the map still fits the cart"
250        );
251        assert_eq!(read.marks.labels, written.marks.labels);
252        assert_eq!(read.marks.breakpoints.len(), 1);
253        let breakpoint = &read.marks.breakpoints[0];
254        assert_eq!(breakpoint.addr, 0x8123);
255        assert_eq!(breakpoint.condition, "a == 0x10");
256        assert!(breakpoint.enabled, "an armed breakpoint comes back armed");
257        assert_eq!(breakpoint.id, 0, "the window hands ids out again");
258
259        std::fs::remove_file(&path).expect("cleans up");
260    }
261
262    /// Offsets only address the cart they were recorded against, so a file that names another one
263    /// cannot be applied to this one however it came to share its name.
264    #[test]
265    fn a_map_recorded_against_another_cart_is_refused() {
266        let cart = cart();
267        let mut session = marked(&cart);
268        session.accept(cart.memory());
269        assert!(session.code_map.is_some(), "the cart it was recorded for");
270
271        let mut other = Cart::empty_sized(0x8000, 0x2000);
272        *other.mapper_mut() = Nrom::load(&mut other).expect("valid mapper");
273        let mut session = marked(&cart);
274        session.accept(other.memory());
275        assert!(session.code_map.is_none(), "a cart of another size");
276    }
277
278    /// Nothing to keep writes no file, so opening the Debugger on a ROM and closing it again does
279    /// not litter the data directory.
280    #[test]
281    fn an_empty_session_writes_no_file() {
282        let path = std::env::temp_dir().join("tetanes-debug-session-empty.dbg");
283        Session::default().save_path(&path).expect("writes nothing");
284        assert!(!fs::exists(&path));
285    }
286}