1use 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
20const DEBUG_VERSION: &str = "2";
25
26const DEBUG_VERSION_V3: u8 = b'1';
28
29#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
32#[must_use]
33pub struct AddrLabel {
34 pub name: String,
39 pub comment: String,
41}
42
43impl AddrLabel {
44 pub fn is_empty(&self) -> bool {
46 self.name.trim().is_empty() && self.comment.trim().is_empty()
47 }
48}
49
50#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[must_use]
57pub enum LabelKey {
58 Cart(u32),
60 Cpu(u16),
62}
63
64impl LabelKey {
65 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#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
76#[must_use]
77pub struct Marks {
78 pub breakpoints: Vec<Breakpoint>,
80 pub labels: HashMap<LabelKey, AddrLabel>,
82}
83
84impl Marks {
85 pub fn is_empty(&self) -> bool {
87 self.breakpoints.is_empty() && self.labels.is_empty()
88 }
89}
90
91#[derive(Debug, Default, Clone, Serialize, Deserialize)]
93#[must_use]
94pub struct Session {
95 pub code_map: Option<CodeMap>,
97 pub marks: Marks,
99}
100
101impl Session {
102 const DIR: &'static str = "debug";
104 const EXTENSION: &'static str = "dbg";
106
107 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 pub fn load(name: &str) -> Self {
120 Self::load_path(Self::path(name))
121 }
122
123 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 pub fn save(&self, name: &str) -> fs::Result<()> {
154 self.save_path(Self::path(name))
155 }
156
157 pub fn save_path(&self, path: impl AsRef<Path>) -> fs::Result<()> {
163 if self.is_empty() {
166 return Ok(());
167 }
168 fs::save_version_path(path, self, DEBUG_VERSION)
169 }
170
171 pub fn is_empty(&self) -> bool {
173 self.code_map.is_none() && self.marks.is_empty()
174 }
175
176 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 #[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 #[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 #[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}