rsemu 0.0.4

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
//! What the protocol talks to: the debug seam, and a [`Machine`] behind it.
//!
//! [`DebugTarget`] is everything [`stub`](super::stub) needs and nothing more —
//! registers, memory, breakpoints, and two ways to make time pass. Keeping it a
//! trait means the packet layer is testable against a stub target with no
//! machine at all, which is how the protocol tests below run in a `--no-default-
//! features` build's worth of time.
//!
//! # The two rules
//!
//! **Every debugger access sets [`MemAttrs::debug`]** — `ROADMAP.md` §15
//! invariant 5. There is exactly one place in this file that builds a
//! `MemAttrs`, [`debug_attrs`], and it starts from [`MemAttrs::DEBUG`]. A
//! debugger read must not acknowledge an interrupt, pop a FIFO or advance a
//! pointer, and the watchpoint implementation below *polls memory after every
//! instruction*, so a single careless access would be a side effect a thousand
//! times a second.
//!
//! **Every address in a packet is virtual.** `m`, `M`, `X` and the `Z` packets
//! name addresses the *guest* uses, so with an MMU on they are not the
//! addresses the bus wants. [`MachineTarget::translate`] is where that is
//! answered, through [`Device::debug_translate`](crate::core::device::Device::debug_translate)
//! — which means the page-table walk is the core's, runs with `debug` set, and
//! sets no accessed or dirty bit on the way. A core with no MMU answers the
//! identity and pays nothing. Breakpoints need none of this: they are compared
//! against the program counter, which is itself virtual, so a `Z0` address and
//! a `$pc` are already in the same space. [`MachineTarget::read_physical`] is
//! the deliberate way out for a caller that really does mean a bus address.
//!
//! **Attaching stops the world.** The machine advances only inside
//! [`DebugTarget::resume`] and [`DebugTarget::step`], both of which are called
//! from the same thread that services packets and never while a packet is being
//! answered. `Machine::step_until` returns at a scheduling boundary with every
//! runnable unwound to the scheduler, which is §4.7's safe point — under
//! `parallel` as much as under `deterministic`, because a parallel round joins
//! every job it submitted before it returns and that join is the rendezvous.
//! Nothing here reaches into a running CPU, and nothing races the scheduler.
//! See [`super`]'s "Stopping the world", and `tests/gdb_multicpu.rs`.

use core::fmt;
use core::fmt::Write as _;

use crate::core::clock::GlobalTime;
use crate::core::device::DeviceClass;
use crate::core::space::{AddressSpace, MemAttrs, RequesterId};
use crate::core::state::{ChunkReader, MachineShape, StateReader, StateWriter};
use crate::machine::Machine;

use super::arch::Arch;

/// Attributes for every access a debugger makes.
///
/// The single constructor, so "does the gdbstub set `debug`?" has one place to
/// look. `requester` is the CPU's own, so an IOMMU or a per-master filter
/// translates a debugger read exactly as it would translate that CPU's.
#[must_use]
pub fn debug_attrs(requester: RequesterId) -> MemAttrs {
    MemAttrs::DEBUG.with_requester(requester)
}

/// Why a target refused.
#[derive(Debug)]
pub enum TargetError {
    /// No CPU with that index — a thread id the client made up.
    NoSuchCpu,
    /// No register with that number.
    NoSuchRegister,
    /// The guest bus refused the access, or there is no address space to make
    /// it in.
    Fault,
    /// The CPU's page tables map nothing at that virtual address.
    ///
    /// Distinct from [`TargetError::Fault`] because the two send a user to
    /// different places: a fault means the machine has no memory there, and
    /// this means the *guest* has not mapped any — usually that the debugger is
    /// looking at an address belonging to a process that is not current.
    Unmapped,
    /// A well-formed request this target cannot serve.
    Unsupported,
    /// A core changed its snapshot layout out from under its register map.
    LayoutMismatch {
        /// The device class whose layout moved.
        class: &'static str,
        /// The version the map was written against.
        expected: u32,
        /// The version the class is at now.
        found: u32,
    },
    /// Whatever the machine reported.
    Machine(crate::Error),
}

impl TargetError {
    /// The number this becomes in an `E<xx>` reply.
    ///
    /// GDB shows these to the user as errno values, so they are chosen to read
    /// sensibly: `EIO` for a bus fault, `EINVAL` for a bad request, `ESRCH` for
    /// a thread that does not exist.
    #[must_use]
    pub const fn code(&self) -> u8 {
        match self {
            TargetError::NoSuchCpu => 3,                                  // ESRCH
            TargetError::Fault | TargetError::Machine(_) => 5,            // EIO
            TargetError::Unmapped => 14,                                  // EFAULT
            TargetError::NoSuchRegister | TargetError::Unsupported => 22, // EINVAL
            TargetError::LayoutMismatch { .. } => 8,                      // ENOEXEC
        }
    }
}

impl fmt::Display for TargetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TargetError::NoSuchCpu => f.write_str("no such cpu"),
            TargetError::NoSuchRegister => f.write_str("no such register"),
            TargetError::Fault => f.write_str("the guest bus refused the access"),
            TargetError::Unmapped => f.write_str("nothing is mapped at that virtual address"),
            TargetError::Unsupported => f.write_str("unsupported"),
            TargetError::LayoutMismatch {
                class,
                expected,
                found,
            } => write!(
                f,
                "`{class}` state version {found} but its gdb register map was written \
                 against version {expected}"
            ),
            TargetError::Machine(e) => write!(f, "{e}"),
        }
    }
}

impl std::error::Error for TargetError {}

impl From<crate::Error> for TargetError {
    fn from(e: crate::Error) -> TargetError {
        TargetError::Machine(e)
    }
}

/// The usual result in this module.
pub type TargetResult<T> = Result<T, TargetError>;

/// Why the target stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopKind {
    /// A step finished, or the client asked for a halt.
    Trap,
    /// A `Z0`/`Z1` breakpoint address was reached.
    Breakpoint {
        /// Whether the client asked for a *hardware* breakpoint (`Z1`).
        ///
        /// Both are the same mechanism here — a program-counter comparison —
        /// but the stop reply is not the same packet, and GDB matches the
        /// reason it is given against the breakpoint it set. Telling it
        /// `swbreak` about a `Z1` is telling it about a breakpoint it does not
        /// have. (GDB manual, "Stop Reply Packets".)
        hardware: bool,
    },
    /// A `Z2` watchpoint's memory changed.
    Watchpoint {
        /// The first address in the watched range whose value changed.
        addr: u64,
    },
    /// The client sent Ctrl-C.
    Interrupt,
}

/// A stop, as a stop reply will report it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stop {
    /// Which CPU stopped, as an index into the target's CPU list.
    pub cpu: usize,
    /// What happened.
    pub kind: StopKind,
}

impl Stop {
    /// The signal number GDB is told about.
    #[must_use]
    pub const fn signal(&self) -> u8 {
        match self.kind {
            // SIGINT, so Ctrl-C in GDB reads as an interrupt rather than a
            // mysterious trap.
            StopKind::Interrupt => 2,
            _ => 5, // SIGTRAP
        }
    }
}

/// Which watchpoint kinds a target can honour.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct WatchSupport {
    /// `Z2` — stop when the watched bytes change.
    pub write: bool,
    /// `Z3` — stop when the guest reads the watched bytes.
    pub read: bool,
    /// `Z4` — stop on either.
    pub access: bool,
}

/// What the debugger can do to a machine.
///
/// Every method takes an explicit CPU index rather than an implicit "current
/// thread": which thread a packet applies to is the protocol's business (the
/// `H` packets), and leaking that into the target is how a stub ends up reading
/// the wrong CPU's registers after a `vCont`.
pub trait DebugTarget {
    /// How many CPUs this machine presents as GDB threads.
    fn cpu_count(&self) -> usize;

    /// The instance path of a CPU, which is also what `qThreadExtraInfo`
    /// reports.
    fn cpu_path(&self, cpu: usize) -> TargetResult<&str>;

    /// The register map for a CPU.
    fn arch(&self, cpu: usize) -> TargetResult<&'static Arch>;

    /// Every register, concatenated in `g`-packet order.
    fn read_registers(&self, cpu: usize) -> TargetResult<Vec<u8>>;

    /// Overwrite every register from a `G` payload.
    fn write_registers(&mut self, cpu: usize, data: &[u8]) -> TargetResult<()>;

    /// One register, by its number in the target description.
    fn read_register(&self, cpu: usize, index: usize) -> TargetResult<Vec<u8>>;

    /// Overwrite one register.
    fn write_register(&mut self, cpu: usize, index: usize, data: &[u8]) -> TargetResult<()>;

    /// Read guest memory as this CPU sees it, with no side effects.
    ///
    /// **`addr` is virtual.** Every address GDB sends in an `m`, `M`, `X` or
    /// `Z` packet is one the guest would use — that is what "as this CPU sees
    /// it" has always meant — so an implementation with an MMU must translate
    /// it, with [`Device::debug_translate`](crate::core::device::Device::debug_translate)
    /// or its own equivalent. On a machine with no MMU, or with the MMU off,
    /// that translation is the identity and nothing changes.
    fn read_memory(&self, cpu: usize, addr: u64, dst: &mut [u8]) -> TargetResult<()>;

    /// Write guest memory as this CPU sees it.
    ///
    /// `addr` is virtual, exactly as in [`read_memory`](DebugTarget::read_memory).
    fn write_memory(&mut self, cpu: usize, addr: u64, src: &[u8]) -> TargetResult<()>;

    /// Arm a breakpoint at `addr`. Arming one twice is not an error.
    ///
    /// `hardware` is `Z1` rather than `Z0`. It changes nothing about how the
    /// breakpoint works — see [`MachineTarget`] — and everything about which
    /// stop reply reports it.
    fn add_breakpoint(&mut self, addr: u64, hardware: bool) -> TargetResult<()>;

    /// Disarm a breakpoint. Disarming one that is not set is not an error.
    fn remove_breakpoint(&mut self, addr: u64, hardware: bool) -> TargetResult<()>;

    /// Which watchpoint kinds this target honours.
    fn watch_support(&self) -> WatchSupport {
        WatchSupport::default()
    }

    /// Arm a write watchpoint over `len` bytes at `addr`, as `cpu` sees it.
    ///
    /// **`addr` is virtual, and it belongs to a CPU**, exactly as in
    /// [`read_memory`](DebugTarget::read_memory). The watched bytes are read
    /// back repeatedly while the guest runs, so the space and the page tables
    /// they are read through have to be the ones the address was written
    /// against — which is the thread GDB had selected, not thread 1.
    fn add_watchpoint(&mut self, _cpu: usize, _addr: u64, _len: u64) -> TargetResult<()> {
        Err(TargetError::Unsupported)
    }

    /// Disarm a write watchpoint.
    fn remove_watchpoint(&mut self, _cpu: usize, _addr: u64, _len: u64) -> TargetResult<()> {
        Err(TargetError::Unsupported)
    }

    /// Run one instruction on `cpu`.
    fn step(&mut self, cpu: usize) -> TargetResult<Stop>;

    /// Told that a continue is starting, before the first [`DebugTarget::resume`].
    ///
    /// A target that stopped *on* a breakpoint has to get off it before it
    /// starts looking again, or `continue` reports the same breakpoint forever.
    fn begin_resume(&mut self) {}

    /// Let the machine run for a bounded slice, and report a stop if one
    /// happened.
    ///
    /// Bounded rather than open-ended so the caller keeps servicing the socket:
    /// this is what makes Ctrl-C work.
    fn resume(&mut self) -> TargetResult<Option<Stop>>;

    /// Answer a `qRcmd` monitor command. `None` means "no such command".
    ///
    /// `cpu` is the thread GDB had selected when the user typed it, because
    /// half of what a monitor is for — reading memory, translating an address —
    /// has no answer without one.
    fn monitor(&mut self, _cpu: usize, _command: &str) -> Option<String> {
        None
    }
}

// ---------------------------------------------------------------------------
// A Machine as a target
// ---------------------------------------------------------------------------

/// How much virtual time one free-running slice covers.
///
/// Ten milliseconds, matching the console loop in `src/bin/rsemu.rs`: short
/// enough that a Ctrl-C is noticed straight away, long enough that the socket
/// poll is not the bottleneck.
const FREE_SLICE: GlobalTime = GlobalTime::from_nanos(10_000_000);

/// How many single ticks one breakpoint-checking slice covers.
///
/// With a breakpoint or a watchpoint armed the machine advances one clock tick
/// at a time so nothing can be stepped over, which costs one or two orders of
/// magnitude of speed. That is the price of not patching trap instructions into
/// guest memory — see [`MachineTarget`]'s docs.
const FINE_TICKS: u32 = 4096;

/// The largest span a single translation is trusted for.
///
/// One kibibyte, because that is the *smallest* page any MMU in the tree can
/// map: VMSAv5's tiny page (ARM ARM B4.3.2) is 1 KiB, and RISC-V's smallest is
/// four times that. A run that fits inside an aligned granule cannot straddle a
/// page boundary, so one translation covers it. Lowering this is always safe;
/// raising it needs an MMU with no page smaller than the new value.
const TRANSLATION_GRANULE: u64 = 1024;

/// How many ticks one instruction is allowed to take before the stepper gives
/// up and reports what it has.
///
/// The slowest documented instruction on any core rsemu has is well under
/// twenty cycles; the margin is for a core that is paying down scheduler debt,
/// which costs ticks without retiring anything.
const MAX_TICKS_PER_INSN: u32 = 4096;

/// One CPU, as the debugger sees it.
#[derive(Debug)]
struct Cpu {
    /// Index into `Machine::devices`.
    device: usize,
    path: String,
    class: &'static DeviceClass,
    arch: &'static Arch,
    domain: crate::core::clock::DomainId,
    requester: RequesterId,
    space: Option<usize>,
}

/// A watched range and the bytes it last held.
#[derive(Debug)]
struct Watch {
    /// The CPU whose address space and MMU `addr` is to be read through.
    ///
    /// Not a decoration and not CPU 0: on a machine with two cores the same
    /// number is two different bytes, and polling the wrong space reads
    /// whatever `unassigned` says — usually a constant, so the shadow never
    /// changes and the watchpoint silently never fires.
    cpu: usize,
    addr: u64,
    len: u64,
    shadow: Vec<u8>,
}

/// An armed breakpoint: an address, and which `Z` packet set it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Breakpoint {
    addr: u64,
    hardware: bool,
}

/// A realized [`Machine`], as a GDB target.
///
/// # Breakpoints are compared, not planted
///
/// The usual gdbstub writes a trap instruction over the guest's code and puts
/// the original byte back afterwards. That needs a per-architecture trap
/// encoding, it does not work in ROM — which is where an Apple 1 or a NES spends
/// most of its time — and it makes the guest's own view of its code wrong. This
/// target instead compares each CPU's program counter against the armed set
/// after every clock tick. It costs speed while a breakpoint is armed and
/// nothing at all while none is, it works identically in RAM and ROM, and it
/// cannot corrupt the guest.
///
/// # Watchpoints are polled
///
/// `Z2` is honoured the same way: the watched bytes are read (with
/// [`MemAttrs::debug`] set, so the read itself cannot be what changed them) after
/// every tick and compared against a shadow copy. `Z3` and `Z4` — read and
/// access watchpoints — are **not** implementable here, and are refused rather
/// than faked: seeing a guest *read* requires interposing on the access path,
/// and `core::space` exposes no hook to interpose with. See the module docs of
/// [`super`].
#[derive(Debug)]
pub struct MachineTarget<'a> {
    machine: &'a mut Machine,
    cpus: Vec<Cpu>,
    breakpoints: Vec<Breakpoint>,
    watchpoints: Vec<Watch>,
    /// Per CPU: an address the resume loop must not report until the program
    /// counter has moved off it. Set by [`DebugTarget::begin_resume`].
    suppress: Vec<Option<u64>>,
}

impl<'a> MachineTarget<'a> {
    /// Wrap a machine, discovering its CPUs.
    ///
    /// A device is a CPU here when this build has a register map for its class
    /// ([`super::arch::for_class`]) and the machine gave it a clock domain. A
    /// core with no domain cannot be stepped, and presenting a thread that
    /// cannot be stepped is worse than not presenting it.
    #[must_use]
    pub fn new(machine: &'a mut Machine) -> MachineTarget<'a> {
        let mut cpus = Vec::new();
        for (index, entry) in machine.devices().iter().enumerate() {
            let Some(arch) = super::arch::for_class(entry.class().name) else {
                continue;
            };
            let Some(domain) = entry.domain() else {
                continue;
            };
            cpus.push(Cpu {
                device: index,
                path: entry.path().to_string(),
                class: entry.class(),
                arch,
                domain,
                requester: entry.requester(),
                space: entry.space_index(),
            });
        }
        let suppress = vec![None; cpus.len()];
        MachineTarget {
            machine,
            cpus,
            breakpoints: Vec::new(),
            watchpoints: Vec::new(),
            suppress,
        }
    }

    /// The machine being debugged.
    #[must_use]
    pub fn machine(&self) -> &Machine {
        self.machine
    }

    /// Read guest memory at a **physical** address, skipping translation.
    ///
    /// The untranslated half of the pair, and it is not a leftover: a monitor
    /// inspecting a boot ROM, a board bring-up check and anything that wants to
    /// see what is under a page table rather than through it all name bus
    /// addresses. GDB's own packets never do — there is no physical-address
    /// packet in the protocol — which is why this is an inherent method on the
    /// concrete target rather than part of [`DebugTarget`].
    ///
    /// # Errors
    ///
    /// [`TargetError::Fault`] if the bus refuses.
    pub fn read_physical(&self, cpu: usize, addr: u64, dst: &mut [u8]) -> TargetResult<()> {
        let entry = self.cpu(cpu)?;
        let space = self.space(entry)?;
        space
            .read_bytes(addr, dst, debug_attrs(entry.requester))
            .map_err(|_| TargetError::Fault)
    }

    /// Write guest memory at a **physical** address, skipping translation.
    ///
    /// See [`read_physical`](MachineTarget::read_physical).
    ///
    /// # Errors
    ///
    /// [`TargetError::Fault`] if the bus refuses.
    pub fn write_physical(&mut self, cpu: usize, addr: u64, src: &[u8]) -> TargetResult<()> {
        {
            let entry = self.cpu(cpu)?;
            let space = self.space(entry)?;
            space
                .write_bytes(addr, src, debug_attrs(entry.requester))
                .map_err(|_| TargetError::Fault)?;
        }
        self.resync_watchpoints();
        Ok(())
    }

    /// The machine being debugged, mutably.
    ///
    /// For a front end that has work of its own between session turns — pumping
    /// a console, checking a deadline. Running it from here would race the
    /// debugger's own idea of whether the guest is stopped, so do not.
    pub fn machine_mut(&mut self) -> &mut Machine {
        self.machine
    }

    fn cpu(&self, index: usize) -> TargetResult<&Cpu> {
        self.cpus.get(index).ok_or(TargetError::NoSuchCpu)
    }

    /// The address space a CPU's accesses go through.
    fn space(&self, cpu: &Cpu) -> TargetResult<&AddressSpace> {
        let index = cpu.space.ok_or(TargetError::Fault)?;
        self.machine
            .spaces()
            .get(index)
            .map(|entry| entry.space().as_ref())
            .ok_or(TargetError::Fault)
    }

    /// Where a virtual address lives, as this CPU's MMU maps it.
    ///
    /// The whole of the debugger's answer to paging: a `m` packet names an
    /// address the *guest* would use, and with the MMU on that is not the
    /// address the bus wants. A core with no MMU — or one whose MMU is off —
    /// answers [`DebugTranslation::Identity`](crate::core::device::DebugTranslation::Identity)
    /// and this is free.
    ///
    /// The walk itself is the core's, runs with [`MemAttrs::debug`] set, and
    /// sets no accessed or dirty bit; see
    /// [`Device::debug_translate`](crate::core::device::Device::debug_translate).
    ///
    /// # Errors
    ///
    /// [`TargetError::Unmapped`] when the tables map nothing there.
    pub fn translate(&self, cpu: usize, va: u64) -> TargetResult<u64> {
        let device = self.cpu(cpu)?.device;
        let entry = self
            .machine
            .devices()
            .get(device)
            .ok_or(TargetError::NoSuchCpu)?;
        entry
            .device()
            .debug_translate(va)
            .phys(va)
            .ok_or(TargetError::Unmapped)
    }

    /// Split a virtual range into runs that are contiguous in physical memory.
    ///
    /// Returns `(physical address, offset into the caller's buffer, length)`.
    ///
    /// Translating once per byte would be correct and unusably slow — a
    /// watchpoint poll runs this on every clock tick — and translating once for
    /// the whole range would be wrong the moment it crosses a page boundary,
    /// which a `m` packet for a 4 KiB region routinely does. So the range is cut
    /// on [`TRANSLATION_GRANULE`] boundaries: no MMU in the tree has a page
    /// smaller than that, so a run inside one is guaranteed contiguous, and the
    /// common case — a request that fits inside a single granule — is one
    /// translation and one bulk bus access, exactly as it was before this
    /// existed. Bulk, and not a byte at a time, because a 32-bit-only register
    /// must still see a 32-bit access.
    fn chunks(&self, cpu: usize, addr: u64, len: usize) -> TargetResult<Vec<(u64, usize, usize)>> {
        let mut out = Vec::new();
        let mut at = 0usize;
        while at < len {
            let va = addr.wrapping_add(at as u64);
            // How far to the next granule boundary, capped by what is left.
            let to_boundary = TRANSLATION_GRANULE - (va & (TRANSLATION_GRANULE - 1));
            let run = to_boundary.min((len - at) as u64) as usize;
            out.push((self.translate(cpu, va)?, at, run));
            at += run;
        }
        Ok(out)
    }

    /// A CPU's architectural state, as its snapshot chunk.
    ///
    /// This is `Device::save` into a chunk of its own rather than
    /// `Machine::save` of everything: a register read happens on every stop and
    /// on every tick of a breakpoint-checking run, and serialising the guest's
    /// RAM each time would make the debugger unusable.
    fn chunk(&self, cpu: &Cpu) -> TargetResult<Vec<u8>> {
        if !cpu.arch.check() {
            return Err(TargetError::LayoutMismatch {
                class: cpu.class.name,
                expected: cpu.arch.verified_version,
                found: cpu.class.version,
            });
        }
        let entry = self
            .machine
            .devices()
            .get(cpu.device)
            .ok_or(TargetError::NoSuchCpu)?;
        let mut writer = StateWriter::new(MachineShape::new());
        {
            let mut chunk = writer.chunk(&cpu.path, cpu.class.name, cpu.class.version)?;
            entry.device().save(&mut chunk)?;
        }
        let bytes = writer.to_vec()?;
        let reader = StateReader::new(&bytes)?;
        let (_, _, data) = reader.load_raw(&cpu.path)?;
        if data.len() < cpu.arch.chunk_reach() {
            return Err(TargetError::LayoutMismatch {
                class: cpu.class.name,
                expected: cpu.arch.verified_version,
                found: cpu.class.version,
            });
        }
        Ok(data.to_vec())
    }

    /// Put a patched chunk back.
    fn set_chunk(&mut self, cpu: usize, data: &[u8]) -> TargetResult<()> {
        let device = self.cpu(cpu)?.device;
        let entry = self
            .machine
            .devices()
            .get(device)
            .ok_or(TargetError::NoSuchCpu)?;
        let mut reader = ChunkReader::new(data);
        entry.device().load(&mut reader)?;
        Ok(())
    }

    /// A little-endian field of the chunk, widened.
    fn field(chunk: &[u8], offset: usize, bytes: usize) -> TargetResult<u64> {
        let slice = chunk
            .get(offset..offset.checked_add(bytes).ok_or(TargetError::Fault)?)
            .ok_or(TargetError::Fault)?;
        let mut value: u64 = 0;
        for (i, byte) in slice.iter().enumerate() {
            value |= u64::from(*byte) << (i * 8);
        }
        Ok(value)
    }

    /// A CPU's program counter.
    fn pc_of(&self, index: usize) -> TargetResult<u64> {
        let cpu = self.cpu(index)?;
        let chunk = self.chunk(cpu)?;
        let reg = cpu
            .arch
            .regs
            .get(cpu.arch.pc)
            .ok_or(TargetError::NoSuchRegister)?;
        Self::field(&chunk, reg.offset, reg.bytes)
    }

    /// A CPU's instruction-retirement counter, if it has one.
    fn retired(&self, index: usize) -> TargetResult<Option<u64>> {
        let cpu = self.cpu(index)?;
        let Some(counter) = cpu.arch.retire else {
            return Ok(None);
        };
        let chunk = self.chunk(cpu)?;
        Self::field(&chunk, counter.offset, counter.bytes).map(Some)
    }

    /// Advance virtual time by one tick of the finest CPU clock domain.
    ///
    /// The finest, so that on a machine with a fast and a slow core neither is
    /// stepped over. Time is advanced through `Machine::step_until`, which
    /// returns with every runnable unwound — the safe point of §4.7.
    fn tick(&mut self) -> TargetResult<()> {
        let now = self.machine.now();
        let mut deadline: Option<GlobalTime> = None;
        {
            let forest = self.machine.clocks();
            for cpu in &self.cpus {
                let Ok(tick) = forest.ticks(cpu.domain) else {
                    continue;
                };
                // A domain whose next tick has already gone by (it is behind
                // the timeline, or gated) needs the next one that has not.
                let mut ahead = 1u64;
                while let Ok(at) =
                    forest.global_time_of_tick(cpu.domain, tick.saturating_add(ahead))
                {
                    if at > now {
                        deadline = Some(match deadline {
                            Some(best) if best <= at => best,
                            _ => at,
                        });
                        break;
                    }
                    ahead += 1;
                    if ahead > 1024 {
                        break;
                    }
                }
            }
        }
        // No CPU could name a future tick — a machine with every clock gated.
        // Fall back to a plain slice so the scheduler's own events still fire.
        let deadline = deadline.unwrap_or_else(|| now.saturating_add(FREE_SLICE));
        // `step_until`, not `run_until`: one CPU tick is far inside a
        // scheduling round, and `run_until` declines a round its deadline falls
        // inside so that a sliced run and an unsliced one agree (§11.6). A
        // debugger is the one caller that needs the fragment instead — waiting
        // for the round's own boundary would step over every breakpoint between
        // here and it.
        self.machine.step_until(deadline)?;
        Ok(())
    }

    /// Re-read every watched range, and report the first one that moved.
    fn poll_watchpoints(&mut self) -> TargetResult<Option<(usize, u64)>> {
        if self.watchpoints.is_empty() {
            return Ok(None);
        }
        let mut hit = None;
        for i in 0..self.watchpoints.len() {
            let (cpu, addr, len) = {
                let watch = &self.watchpoints[i];
                (watch.cpu, watch.addr, watch.len)
            };
            let mut now = vec![0u8; usize::try_from(len).unwrap_or(0)];
            // A range the bus refuses is not a hit; it is a watchpoint the user
            // put somewhere there is no memory, and saying so once a tick would
            // drown the session.
            if self.read_memory(cpu, addr, &mut now).is_err() {
                continue;
            }
            let watch = &mut self.watchpoints[i];
            if watch.shadow != now {
                watch.shadow = now;
                if hit.is_none() {
                    hit = Some((cpu, addr));
                }
            }
        }
        Ok(hit)
    }

    /// Refresh every shadow without reporting a hit.
    ///
    /// Called after the debugger writes memory itself, so that GDB poking a
    /// watched byte does not immediately trip its own watchpoint.
    fn resync_watchpoints(&mut self) {
        for i in 0..self.watchpoints.len() {
            let (cpu, addr, len) = {
                let watch = &self.watchpoints[i];
                (watch.cpu, watch.addr, watch.len)
            };
            let mut now = vec![0u8; usize::try_from(len).unwrap_or(0)];
            if self.read_memory(cpu, addr, &mut now).is_ok() {
                self.watchpoints[i].shadow = now;
            }
        }
    }

    /// Whether any CPU is standing on an armed breakpoint.
    fn breakpoint_hit(&mut self) -> TargetResult<Option<Stop>> {
        if self.breakpoints.is_empty() {
            return Ok(None);
        }
        for index in 0..self.cpus.len() {
            let pc = self.pc_of(index)?;
            if self.suppress.get(index).copied().flatten() == Some(pc) {
                continue;
            }
            if let Some(slot) = self.suppress.get_mut(index) {
                *slot = None;
            }
            if let Some(point) = self.breakpoints.iter().find(|b| b.addr == pc) {
                return Ok(Some(Stop {
                    cpu: index,
                    kind: StopKind::Breakpoint {
                        hardware: point.hardware,
                    },
                }));
            }
        }
        Ok(None)
    }
}

/// `rwx` for a mapping's terms, which is what a user reads a memory map for.
///
/// `Perms` is a bitfield newtype and its `Debug` is the number, which is not
/// what anybody wants in a map dump.
fn perms_text(perms: crate::core::space::Perms) -> String {
    let bit = |set: bool, c: char| if set { c } else { '-' };
    [
        bit(perms.contains(crate::core::space::Perms::READ), 'r'),
        bit(perms.contains(crate::core::space::Perms::WRITE), 'w'),
        bit(perms.contains(crate::core::space::Perms::EXEC), 'x'),
    ]
    .into_iter()
    .collect()
}

/// What `monitor help` prints.
///
/// The commands are the ones with machinery already behind them, and the pair
/// that justifies the whole surface is `x` and `xp`: GDB's own `x` is always
/// virtual, because the protocol has no physical-address packet, so a *bus*
/// address — a boot ROM under a page table, a BAR before the guest has mapped
/// it — is not reachable from a GDB session by any other route.
const MONITOR_HELP: &str = "\
rsemu monitor commands (addresses are hex, lengths decimal):
  devices            the device tree, with class and instance path
  spaces             the machine's address spaces
  map [space]        what is mapped where, for this CPU's space or a named one
  x <addr> [len]     read guest memory at a VIRTUAL address, through this CPU
  xp <addr> [len]    read guest memory at a PHYSICAL address, no translation
  translate <addr>   where this CPU's MMU maps a virtual address
  time               the machine's current virtual instant
  hash               the machine state hash (ROADMAP.md \u{a7}0)
Every read here sets MemAttrs::debug, so nothing it looks at changes.
";

/// How many bytes `x` and `xp` show when nobody says.
const MONITOR_DUMP_DEFAULT: u64 = 64;

/// The most they will show, so a typo cannot ask for a megabyte over a socket
/// that frames one packet at a time.
const MONITOR_DUMP_MAX: u64 = 1024;

impl MachineTarget<'_> {
    /// `<addr>` as a monitor command writes it: hex, with an optional `0x`.
    fn monitor_addr(text: Option<&str>) -> Result<u64, String> {
        let text = text.ok_or_else(|| String::from("an address is needed\n"))?;
        let body = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X"));
        u64::from_str_radix(body.unwrap_or(text), 16)
            .map_err(|_| format!("`{text}` is not a hex address\n"))
    }

    /// `[len]` as a monitor command writes it: decimal, bounded.
    fn monitor_len(text: Option<&str>) -> Result<u64, String> {
        let Some(text) = text else {
            return Ok(MONITOR_DUMP_DEFAULT);
        };
        let len: u64 = text
            .parse()
            .map_err(|_| format!("`{text}` is not a length\n"))?;
        if len == 0 || len > MONITOR_DUMP_MAX {
            return Err(format!("a length must be 1..={MONITOR_DUMP_MAX}\n"));
        }
        Ok(len)
    }

    /// `x` and `xp`: the same dump, one translated and one not.
    fn monitor_dump(
        &self,
        cpu: usize,
        addr: Option<&str>,
        len: Option<&str>,
        physical: bool,
    ) -> String {
        let (addr, len) = match (Self::monitor_addr(addr), Self::monitor_len(len)) {
            (Ok(a), Ok(l)) => (a, l),
            (Err(e), _) | (_, Err(e)) => return e,
        };
        let mut buf = vec![0u8; len as usize];
        let read = if physical {
            self.read_physical(cpu, addr, &mut buf)
        } else {
            self.read_memory(cpu, addr, &mut buf)
        };
        if let Err(e) = read {
            return format!("{e}\n");
        }
        let mut out = String::new();
        for (row, chunk) in buf.chunks(16).enumerate() {
            let at = addr.wrapping_add(row as u64 * 16);
            let _ = write!(out, "{at:08x} ");
            for byte in chunk {
                let _ = write!(out, " {byte:02x}");
            }
            for _ in chunk.len()..16 {
                out.push_str("   ");
            }
            out.push_str("  |");
            for byte in chunk {
                out.push(if byte.is_ascii_graphic() || *byte == b' ' {
                    char::from(*byte)
                } else {
                    '.'
                });
            }
            out.push_str("|\n");
        }
        out
    }

    /// `translate`: the debug MMU walk, on its own, so a user can see the
    /// answer the `x`/`xp` pair differ by.
    fn monitor_translate(&self, cpu: usize, addr: Option<&str>) -> String {
        let addr = match Self::monitor_addr(addr) {
            Ok(a) => a,
            Err(e) => return e,
        };
        match self.translate(cpu, addr) {
            Ok(pa) if pa == addr => format!("{addr:#x} -> {pa:#x} (identity)\n"),
            Ok(pa) => format!("{addr:#x} -> {pa:#x}\n"),
            Err(e) => format!("{addr:#x}: {e}\n"),
        }
    }

    /// `map`: what is mapped where in a space.
    fn monitor_map(&self, cpu: usize, name: Option<&str>) -> String {
        let index = match name {
            Some(name) => {
                match self
                    .machine
                    .spaces()
                    .iter()
                    .position(|entry| entry.name() == name)
                {
                    Some(i) => i,
                    None => return format!("no address space named `{name}`\n"),
                }
            }
            None => match self.cpu(cpu).ok().and_then(|entry| entry.space) {
                Some(i) => i,
                None => return String::from("this CPU has no address space\n"),
            },
        };
        let Some(entry) = self.machine.spaces().get(index) else {
            return String::from("no such address space\n");
        };
        let space = entry.space();
        // `try_view` rather than `view`: the map is a nicety, and blocking a
        // debugger behind a topology change that is mid-flight is not.
        let Some(view) = space.try_view() else {
            return String::from("the address space is being rebuilt; try again\n");
        };
        let mut rows: Vec<(u64, u64, String, String)> = view
            .mappings()
            .map(|(_, m)| {
                (
                    m.base,
                    m.region.len(),
                    m.region.name().to_string(),
                    perms_text(m.perms),
                )
            })
            .collect();
        rows.sort_by_key(|(base, len, _, _)| (*base, *len));
        let mut out = format!("{} ({} bits)\n", entry.name(), space.bits());
        for (base, len, name, perms) in rows {
            let _ = writeln!(
                out,
                "  {base:#014x}-{:#014x}  {name}  {perms}",
                base.saturating_add(len).saturating_sub(1)
            );
        }
        out
    }
}

impl DebugTarget for MachineTarget<'_> {
    fn cpu_count(&self) -> usize {
        self.cpus.len()
    }

    fn cpu_path(&self, cpu: usize) -> TargetResult<&str> {
        Ok(self.cpu(cpu)?.path.as_str())
    }

    fn arch(&self, cpu: usize) -> TargetResult<&'static Arch> {
        Ok(self.cpu(cpu)?.arch)
    }

    fn read_registers(&self, cpu: usize) -> TargetResult<Vec<u8>> {
        let entry = self.cpu(cpu)?;
        let chunk = self.chunk(entry)?;
        let mut out = Vec::with_capacity(entry.arch.packet_len());
        for reg in entry.arch.regs {
            let slice = chunk
                .get(reg.offset..reg.offset + reg.bytes)
                .ok_or(TargetError::NoSuchRegister)?;
            out.extend_from_slice(slice);
        }
        Ok(out)
    }

    fn write_registers(&mut self, cpu: usize, data: &[u8]) -> TargetResult<()> {
        let entry = self.cpu(cpu)?;
        if data.len() != entry.arch.packet_len() {
            return Err(TargetError::NoSuchRegister);
        }
        let mut chunk = self.chunk(entry)?;
        let mut at = 0usize;
        for reg in entry.arch.regs {
            let src = data.get(at..at + reg.bytes).ok_or(TargetError::Fault)?;
            let dst = chunk
                .get_mut(reg.offset..reg.offset + reg.bytes)
                .ok_or(TargetError::Fault)?;
            dst.copy_from_slice(src);
            at += reg.bytes;
        }
        self.set_chunk(cpu, &chunk)
    }

    fn read_register(&self, cpu: usize, index: usize) -> TargetResult<Vec<u8>> {
        let entry = self.cpu(cpu)?;
        let reg = entry
            .arch
            .regs
            .get(index)
            .ok_or(TargetError::NoSuchRegister)?;
        let chunk = self.chunk(entry)?;
        chunk
            .get(reg.offset..reg.offset + reg.bytes)
            .map(<[u8]>::to_vec)
            .ok_or(TargetError::NoSuchRegister)
    }

    fn write_register(&mut self, cpu: usize, index: usize, data: &[u8]) -> TargetResult<()> {
        let entry = self.cpu(cpu)?;
        let reg = *entry
            .arch
            .regs
            .get(index)
            .ok_or(TargetError::NoSuchRegister)?;
        if data.len() != reg.bytes {
            return Err(TargetError::NoSuchRegister);
        }
        let mut chunk = self.chunk(entry)?;
        let dst = chunk
            .get_mut(reg.offset..reg.offset + reg.bytes)
            .ok_or(TargetError::Fault)?;
        dst.copy_from_slice(data);
        self.set_chunk(cpu, &chunk)
    }

    fn read_memory(&self, cpu: usize, addr: u64, dst: &mut [u8]) -> TargetResult<()> {
        let entry = self.cpu(cpu)?;
        let space = self.space(entry)?;
        let attrs = debug_attrs(entry.requester);
        for (pa, at, len) in self.chunks(cpu, addr, dst.len())? {
            space
                .read_bytes(pa, &mut dst[at..at + len], attrs)
                .map_err(|_| TargetError::Fault)?;
        }
        Ok(())
    }

    fn write_memory(&mut self, cpu: usize, addr: u64, src: &[u8]) -> TargetResult<()> {
        {
            let entry = self.cpu(cpu)?;
            let space = self.space(entry)?;
            let attrs = debug_attrs(entry.requester);
            for (pa, at, len) in self.chunks(cpu, addr, src.len())? {
                space
                    .write_bytes(pa, &src[at..at + len], attrs)
                    .map_err(|_| TargetError::Fault)?;
            }
        }
        self.resync_watchpoints();
        Ok(())
    }

    fn add_breakpoint(&mut self, addr: u64, hardware: bool) -> TargetResult<()> {
        let point = Breakpoint { addr, hardware };
        if !self.breakpoints.contains(&point) {
            self.breakpoints.push(point);
        }
        Ok(())
    }

    fn remove_breakpoint(&mut self, addr: u64, hardware: bool) -> TargetResult<()> {
        self.breakpoints
            .retain(|b| !(b.addr == addr && b.hardware == hardware));
        Ok(())
    }

    fn watch_support(&self) -> WatchSupport {
        WatchSupport {
            write: true,
            // Seeing a guest *read* needs a hook on the access path, and
            // `core::space` has none. Refused rather than faked.
            read: false,
            access: false,
        }
    }

    fn add_watchpoint(&mut self, cpu: usize, addr: u64, len: u64) -> TargetResult<()> {
        if len == 0 || len > 4096 {
            return Err(TargetError::Unsupported);
        }
        // A CPU index the client made up is refused here rather than papered
        // over with zero, which is what the polling loop used to do.
        self.cpu(cpu)?;
        if self
            .watchpoints
            .iter()
            .any(|w| w.cpu == cpu && w.addr == addr && w.len == len)
        {
            return Ok(());
        }
        let mut shadow = vec![0u8; usize::try_from(len).map_err(|_| TargetError::Unsupported)?];
        self.read_memory(cpu, addr, &mut shadow)?;
        self.watchpoints.push(Watch {
            cpu,
            addr,
            len,
            shadow,
        });
        Ok(())
    }

    fn remove_watchpoint(&mut self, cpu: usize, addr: u64, len: u64) -> TargetResult<()> {
        self.watchpoints
            .retain(|w| !(w.cpu == cpu && w.addr == addr && w.len == len));
        Ok(())
    }

    fn step(&mut self, cpu: usize) -> TargetResult<Stop> {
        let before_pc = self.pc_of(cpu)?;
        let before_retired = self.retired(cpu)?;
        for _ in 0..MAX_TICKS_PER_INSN {
            self.tick()?;
            let moved = match before_retired {
                Some(before) => self.retired(cpu)? != Some(before),
                // No retirement counter: fall back to the program counter,
                // which is right except for an instruction that branches to
                // itself.
                None => self.pc_of(cpu)? != before_pc,
            };
            if moved {
                break;
            }
        }
        if let Some(slot) = self.suppress.get_mut(cpu) {
            *slot = None;
        }
        if let Some((watched, addr)) = self.poll_watchpoints()? {
            return Ok(Stop {
                cpu: watched,
                kind: StopKind::Watchpoint { addr },
            });
        }
        Ok(Stop {
            cpu,
            kind: StopKind::Trap,
        })
    }

    fn begin_resume(&mut self) {
        for index in 0..self.cpus.len() {
            let here = self.pc_of(index).ok();
            if let Some(slot) = self.suppress.get_mut(index) {
                *slot = here;
            }
        }
    }

    fn resume(&mut self) -> TargetResult<Option<Stop>> {
        // Nothing armed: run flat out. This is the case that matters for
        // "attach, look around, continue".
        if self.breakpoints.is_empty() && self.watchpoints.is_empty() {
            let deadline = self.machine.now().saturating_add(FREE_SLICE);
            self.machine.run_until(deadline)?;
            return Ok(None);
        }
        for _ in 0..FINE_TICKS {
            self.tick()?;
            if let Some(stop) = self.breakpoint_hit()? {
                return Ok(Some(stop));
            }
            if let Some((cpu, addr)) = self.poll_watchpoints()? {
                return Ok(Some(Stop {
                    cpu,
                    kind: StopKind::Watchpoint { addr },
                }));
            }
        }
        Ok(None)
    }

    fn monitor(&mut self, cpu: usize, command: &str) -> Option<String> {
        let mut words = command.split_whitespace();
        match words.next()? {
            "help" => Some(String::from(MONITOR_HELP)),
            "devices" => {
                let mut out = String::new();
                for entry in self.machine.devices() {
                    out.push_str(entry.path());
                    out.push_str("  ");
                    out.push_str(entry.class().name);
                    out.push('\n');
                }
                Some(out)
            }
            "spaces" => {
                let mut out = String::new();
                for entry in self.machine.spaces() {
                    let space = entry.space();
                    let _ = writeln!(
                        out,
                        "{}  {} bits, {} bytes",
                        entry.name(),
                        space.bits(),
                        space.size()
                    );
                }
                Some(out)
            }
            "map" => Some(self.monitor_map(cpu, words.next())),
            "x" => Some(self.monitor_dump(cpu, words.next(), words.next(), false)),
            "xp" => Some(self.monitor_dump(cpu, words.next(), words.next(), true)),
            "translate" => Some(self.monitor_translate(cpu, words.next())),
            "time" => Some(format!("{} ns\n", self.machine.now().as_nanos())),
            "hash" => Some(match self.machine.state_hash() {
                Ok(hash) => format!("{hash:#018x}\n"),
                Err(e) => format!("cannot hash state: {e}\n"),
            }),
            _ => None,
        }
    }
}