rgy 0.1.0

No-std Rust GameBoy emulator library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use rgy::cpu::Cpu;
use rgy::device::IoHandler;
use rgy::inst::mnem;
use rgy::mmu::{MemRead, MemWrite, Mmu};

use std::collections::{HashSet, VecDeque};
use std::fmt;
use std::string::ToString;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};

use signal_hook;

use rustyline::error::ReadlineError;
use rustyline::Editor;

use structopt::StructOpt;

use lazy_static::lazy_static;

const HISTORY_FILE: &'static str = ".gy.txt";

#[derive(Debug)]
struct CmdError(String);

impl fmt::Display for CmdError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl CmdError {
    fn new<T: ToString>(s: T) -> CmdError {
        CmdError(s.to_string())
    }
}

impl From<std::io::Error> for CmdError {
    fn from(e: std::io::Error) -> CmdError {
        CmdError(e.to_string())
    }
}

impl From<std::num::ParseIntError> for CmdError {
    fn from(e: std::num::ParseIntError) -> CmdError {
        CmdError(e.to_string())
    }
}

type CmdResult<T> = std::result::Result<T, CmdError>;

pub struct Debugger {
    breaks: HashSet<u16>,
    rd_watches: HashSet<u16>,
    wr_watches: HashSet<u16>,
    prompt: bool,
    stepping: bool,
    cpu_state: Cpu,
    signal: Signal,
    exec_path: VecDeque<u16>,
}

impl Debugger {
    pub fn new() -> Self {
        Self {
            breaks: HashSet::new(),
            rd_watches: HashSet::new(),
            wr_watches: HashSet::new(),
            prompt: false,
            stepping: false,
            cpu_state: Cpu::new(),
            signal: Signal::new(),
            exec_path: VecDeque::new(),
        }
    }

    fn add_exec_path(&mut self, pc: u16) {
        if let Some(p) = self.exec_path.back() {
            if pc == *p {
                return;
            }
        }

        self.exec_path.push_back(pc);
    }

    fn check_break(&self, pc: u16, _mmu: &Mmu) -> bool {
        if self.prompt {
            false
        } else if self.stepping {
            true
        } else {
            self.breaks.contains(&pc)
        }
    }

    fn do_break(&mut self, msg: &str, mmu: &Mmu) {
        let (code, _) = self.cpu_state.fetch(mmu);

        println!(
            "{} at {:04x}: {:04x}: {}",
            msg,
            self.cpu_state.get_pc(),
            code,
            mnem(code)
        );

        self.prompt(mmu)
    }

    fn prompt(&mut self, mmu: &Mmu) {
        self.prompt = true;

        let mut rl = Editor::<()>::new();

        if rl.load_history(HISTORY_FILE).is_err() {
            println!("No previous history");
        }

        let abort = loop {
            let readline = rl.readline(">> ");

            match readline {
                Ok(line) => {
                    rl.add_history_entry(line.as_str());

                    match exec_cmd(self, mmu, &line) {
                        Ok(end) => {
                            if end {
                                break false;
                            } else {
                                continue;
                            }
                        }
                        Err(e) => {
                            println!("{}", e);
                            continue;
                        }
                    }
                }
                Err(ReadlineError::Interrupted) => {
                    println!("Abort");
                    break true;
                }
                Err(ReadlineError::Eof) => {
                    println!("Resume");
                    break false;
                }
                Err(err) => {
                    println!("Error: {:?}", err);
                    break true;
                }
            }
        };

        let _ = rl.save_history(HISTORY_FILE);

        if abort {
            std::process::exit(1);
        }

        self.prompt = false;
    }
}

impl rgy::debug::Debugger for Debugger {
    fn init(&mut self, mmu: &Mmu) {
        println!("Entering debug shell...");

        self.prompt(mmu)
    }

    fn take_cpu_snapshot(&mut self, cpu: Cpu) {
        self.cpu_state = cpu;
    }

    fn on_decode(&mut self, mmu: &Mmu) {
        let pc = self.cpu_state.get_pc();

        self.add_exec_path(pc);

        if self.check_break(pc, mmu) {
            self.do_break("Break", mmu);
        }
    }

    fn check_signal(&mut self) {
        if self.signal.signaled() {
            println!("Signaled.");
            self.stepping = true;
        }
    }
}

impl IoHandler for Debugger {
    fn on_read(&mut self, mmu: &Mmu, addr: u16) -> MemRead {
        if self.rd_watches.contains(&addr) {
            self.do_break(&format!("Reading {:04x}", addr), mmu);
        }

        MemRead::PassThrough
    }

    fn on_write(&mut self, mmu: &Mmu, addr: u16, value: u8) -> MemWrite {
        if self.wr_watches.contains(&addr) {
            self.do_break(&format!("Writing {:02x} to {:04x}", value, addr), mmu);
        }

        MemWrite::PassThrough
    }
}

fn exec_cmd(inner: &mut Debugger, mmu: &Mmu, line: &str) -> CmdResult<bool> {
    let cmd = match line.split_whitespace().next() {
        Some(cmd) => cmd,
        None => return Ok(false),
    };

    match find_cmd(cmd) {
        Some(cmd) => (cmd.handler)(inner, mmu, line),
        None => Err(CmdError::new(format!("Command not found: {}", line))),
    }
}

fn find_cmd(s: &str) -> Option<&'static CmdInfo> {
    for cmd in COMMANDS.iter() {
        if cmd.name == s || cmd.short == Some(s) {
            return Some(cmd);
        }
    }

    None
}

struct CmdInfo {
    name: &'static str,
    short: Option<&'static str>,
    desc: &'static str,
    handler: Box<dyn Fn(&mut Debugger, &Mmu, &str) -> CmdResult<bool> + Send + Sync + 'static>,
}

trait CmdHandler: StructOpt + Sized {
    fn handle(&self, inner: &mut Debugger, mmu: &Mmu) -> CmdResult<bool>;

    fn parse(inner: &mut Debugger, mmu: &Mmu, s: &str) -> CmdResult<bool> {
        let s = s.split_whitespace();
        match Self::from_iter_safe(s) {
            Ok(p) => p.handle(inner, mmu),
            Err(e) => Err(CmdError::new(e)),
        }
    }
}

macro_rules! cc {
    ($vec: ident, $name: expr, $short: expr, $desc: expr, $handler: tt) => {
        $vec.push(CmdInfo {
            name: $name,
            desc: $desc,
            short: $short,
            handler: Box::new(|inner, mmu, line| $handler::parse(inner, mmu, line)),
        });
    };
}

lazy_static! {
    static ref COMMANDS: Vec<CmdInfo> = {
        let mut m = Vec::new();
        cc!(m, "break", Some("b"), "Manage break points.", CmdBreak);
        cc!(m, "watch", Some("w"), "Manage memory watches.", CmdWatch);
        cc!(
            m,
            "help",
            Some("h"),
            "Show the list of commands available.",
            CmdHelp
        );
        cc!(m, "quit", None, "Quit this emulator.", CmdQuit);
        cc!(m, "cont", Some("c"), "Continue execution.", CmdContinue);
        cc!(m, "step", Some("n"), "Step execution.", CmdStep);
        cc!(m, "dump", Some("d"), "Dump information.", CmdDump);
        m
    };
}

fn parse_addr(s: &str) -> CmdResult<u16> {
    u16::from_str_radix(s, 16).map_err(|e| CmdError::new(e))
}

#[derive(StructOpt, Debug)]
#[structopt(name = "break", about = "Manage break points.")]
enum CmdBreak {
    /// Add a break point
    #[structopt(name = "add")]
    Add {
        /// Address in hex
        #[structopt(name = "addr", parse(try_from_str = "parse_addr"))]
        addr: u16,
    },
    /// Remove a break point
    #[structopt(name = "remove")]
    Remove {
        /// Address in hex
        #[structopt(name = "addr", parse(try_from_str = "parse_addr"))]
        addr: u16,
    },
    /// List break points
    #[structopt(name = "list")]
    List,
}

impl CmdHandler for CmdBreak {
    fn handle(&self, inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        match self {
            CmdBreak::Add { addr } => {
                if inner.breaks.insert(*addr) {
                    println!("Set break point at {:04x}", addr);
                } else {
                    println!("Break point already set at {:04x}", addr);
                }
            }
            CmdBreak::Remove { addr } => {
                if inner.breaks.remove(&addr) {
                    println!("Remove break point at {:04x}", addr);
                } else {
                    println!("Break point isn't set at {:04x}", addr);
                }
            }
            CmdBreak::List => {
                println!("Break points: ");

                for addr in inner.breaks.iter() {
                    println!("* {:04x}", addr);
                }
            }
        }

        Ok(false)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "help", about = "Show the list of available commands.")]
struct CmdHelp {}

impl CmdHandler for CmdHelp {
    fn handle(&self, _inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        println!("List of available commands:");

        for cmd in COMMANDS.iter() {
            println!(
                "{:>8}: {} {}",
                cmd.name,
                cmd.desc,
                if let Some(short) = cmd.short {
                    format!("(short: {})", short)
                } else {
                    "".into()
                }
            );
        }

        Ok(false)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "quit", about = "Quit this emulator.")]
struct CmdQuit {}

impl CmdHandler for CmdQuit {
    fn handle(&self, _inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        println!("Quit.");

        std::process::exit(1)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "cont", about = "Continue execution.")]
struct CmdContinue {}

impl CmdHandler for CmdContinue {
    fn handle(&self, inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        println!("Continue.");

        inner.stepping = false;

        Ok(true)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "step", about = "Step execution.")]
struct CmdStep {}

impl CmdHandler for CmdStep {
    fn handle(&self, inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        println!("Step.");

        inner.stepping = true;

        Ok(true)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "dump", about = "Dump information.")]
enum CmdDump {
    /// Dump cpu state
    #[structopt(name = "cpu")]
    Cpu,
    /// Dump stack
    #[structopt(name = "stack")]
    Stack {
        /// The size of stack to dump
        #[structopt(name = "size", default_value = "10")]
        size: u16,
    },
    /// Dump memory
    #[structopt(name = "mem")]
    Mem {
        /// The start of the memory region to dump
        #[structopt(name = "from", parse(try_from_str = "parse_addr"))]
        from: u16,
        /// The end of the memory region to dump (inclusive)
        #[structopt(name = "to", parse(try_from_str = "parse_addr"))]
        to: u16,
    },
    /// Execution path
    #[structopt(name = "path")]
    Path {
        /// The number of step to dump
        #[structopt(name = "size", default_value = "10")]
        size: usize,
    },
}

impl CmdHandler for CmdDump {
    fn handle(&self, inner: &mut Debugger, mmu: &Mmu) -> CmdResult<bool> {
        match self {
            CmdDump::Cpu => {
                println!("{}", inner.cpu_state);
            }
            CmdDump::Stack { size } => {
                let sp = inner.cpu_state.get_sp();

                for i in 0..*size {
                    let (p, of) = sp.overflowing_add(i * 2);
                    if of {
                        break;
                    }
                    println!("{}: {:04x} [{:04x}]", i + 1, p, mmu.get16(p));
                }
            }
            CmdDump::Mem { from, to } => {
                print!("      ");
                for i in 0..16 {
                    if i % 2 == 0 {
                        print!("{:02x}", i)
                    } else {
                        print!("{:02x} ", i)
                    }
                }
                println!();

                let pad = from % 16;

                if pad != 0 {
                    print!("{:04x}: ", from - pad);
                    for i in 0..pad {
                        if i % 2 == 0 {
                            print!("  ");
                        } else {
                            print!("   ");
                        }
                    }
                }

                for i in *from..=*to {
                    if i % 16 == 0 {
                        print!("{:04x}: ", i);
                    }

                    let b = mmu.get8(i);

                    if i % 2 == 0 {
                        print!("{:02x}", b);
                    } else {
                        print!("{:02x} ", b);
                    }

                    if i % 16 == 15 {
                        println!()
                    }
                }

                if to % 16 != 15 {
                    println!()
                }
            }
            CmdDump::Path { size } => {
                for (i, pc) in inner.exec_path.iter().rev().take(*size).enumerate() {
                    let mut cpu = inner.cpu_state.clone();
                    cpu.set_pc(*pc);
                    let (code, _) = cpu.fetch(mmu);

                    println!("-{}: {:04x}: {}", i, pc, mnem(code));
                }
            }
        }

        Ok(false)
    }
}

#[derive(StructOpt, Debug)]
#[structopt(name = "watch", about = "Manage watch points.")]
enum CmdWatch {
    /// Add a watch point
    #[structopt(name = "add")]
    Add {
        /// Address in hex
        #[structopt(name = "addr", parse(try_from_str = "parse_addr"))]
        addr: u16,
        /// Add watch only for read access
        #[structopt(long = "readonly", short = "r")]
        readonly: bool,
        /// Add watch only for write access
        #[structopt(long = "writeonly", short = "w")]
        writeonly: bool,
    },
    /// Remove a watch point
    #[structopt(name = "remove")]
    Remove {
        /// Address in hex
        #[structopt(name = "addr", parse(try_from_str = "parse_addr"))]
        addr: u16,
        /// Remove watch only for read access
        #[structopt(long = "readonly", short = "r")]
        readonly: bool,
        /// Remove watch only for write access
        #[structopt(long = "writeonly", short = "w")]
        writeonly: bool,
    },
    /// List watch points
    #[structopt(name = "list")]
    List,
}

impl CmdHandler for CmdWatch {
    fn handle(&self, inner: &mut Debugger, _mmu: &Mmu) -> CmdResult<bool> {
        match self {
            CmdWatch::Add {
                addr,
                readonly,
                writeonly,
            } => {
                if *readonly && *writeonly {
                    println!("Nothing set because both readonly and writeonly are set");
                    return Ok(false);
                }
                if !writeonly {
                    if inner.rd_watches.insert(*addr) {
                        println!("Set read watch at {:04x}", addr);
                    } else {
                        println!("Read watch already set at {:04x}", addr);
                    }
                }
                if !readonly {
                    if inner.wr_watches.insert(*addr) {
                        println!("Set write watch at {:04x}", addr);
                    } else {
                        println!("Write watch already set at {:04x}", addr);
                    }
                }
            }
            CmdWatch::Remove {
                addr,
                readonly,
                writeonly,
            } => {
                if *readonly && *writeonly {
                    println!("Nothing unset because both readonly and writeonly are set");
                    return Ok(false);
                }
                if !writeonly {
                    if inner.rd_watches.remove(&addr) {
                        println!("Remove read watch at {:04x}", addr);
                    } else {
                        println!("Read watch is already unset at {:04x}", addr);
                    }
                }
                if !readonly {
                    if inner.wr_watches.remove(&addr) {
                        println!("Remove writeonly watch at {:04x}", addr);
                    } else {
                        println!("Write watch is already unset at {:04x}", addr);
                    }
                }
            }
            CmdWatch::List => {
                println!("Watch points: ");

                for addr in inner.rd_watches.union(&inner.wr_watches) {
                    let wr = if inner.wr_watches.contains(addr) {
                        'w'
                    } else {
                        '_'
                    };
                    let rd = if inner.rd_watches.contains(addr) {
                        'r'
                    } else {
                        '_'
                    };

                    println!("* {:04x} ({}{})", addr, rd, wr);
                }
            }
        }

        Ok(false)
    }
}

struct Signal {
    sig: Arc<AtomicBool>,
}

impl Signal {
    fn new() -> Signal {
        let sig = Arc::new(AtomicBool::new(false));
        signal_hook::flag::register(signal_hook::SIGINT, sig.clone())
            .expect("Couldn't hook signal");
        Signal { sig }
    }

    fn signaled(&self) -> bool {
        self.sig.swap(false, Ordering::Relaxed)
    }
}