rigless 0.2.1

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Going back. The run is deterministic, so putting it back to a checkpoint and running forward
//! again is the same run, as long as what came into it from outside the guest comes in again at
//! the same place. That's a debugger's writes, its steps, which hold interrupts off for their
//! instruction, its resets, its stops, which leave their mark on the core, and what GDB answered
//! the firmware's file calls with, each kept here with where the run stood before it. A run going
//! forward over what it already did puts each back where it came, what came in at a stop once the
//! core has stopped there again, and the driver hears nothing of it a second time. Something new
//! while it does, a write that isn't the one the history has next say, takes the run a new way
//! from there, and what the history had past that point goes.
//!
//! Going back, `bs` and `bc`, "Debugging with GDB" for GDB 18.1, section E.3, is putting the run
//! back to a checkpoint the history keeps and going forward from there: to the instruction before
//! for `bs`, and for `bc` to the last place going forward would have stopped, found a span between
//! checkpoints at a time, newest first.

use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;

use super::super::{Checkpoint, Core, Position};
use super::hosted::Fresult;
use super::registers::set_registers;
use super::threads::Reason;
use super::{Debugger, Held};
use crate::emulator::{Exit, HaltReason};
use crate::snapshot;

/// How many instructions apart the history keeps checkpoints, while a debugger is attached to a run
/// that may go back.
const CHECKPOINT_EVERY: u64 = 1 << 22;

/// The most checkpoints the history keeps. When it's kept one more, every other one of the older
/// half goes, so recent ones stay close and old ones reach far.
const CHECKPOINTS: usize = 64;

/// What came into the run from outside the guest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Input {
    /// Bytes a debugger wrote, as `M` and `X` write them.
    Write { address: u64, bytes: Vec<u8> },
    /// Bytes a debugger flashed, as `vFlashErase` and `vFlashWrite` place them.
    Flash { address: u64, bytes: Vec<u8> },
    /// A firmware's read a debugger made, with `monitor peek off`.
    Read { address: u64, length: u64 },
    /// A register by GDB's number and its bytes, as `P` or a resume from an address writes it.
    Register { number: usize, bytes: Vec<u8> },
    /// Every register, as `G` writes them, in its hex.
    Registers(String),
    /// A monitor command of the processor family's own, which may change the core.
    Monitor(String),
    /// A step, which holds interrupts off for its instruction.
    Stepped,
    /// A debugger's reset.
    Reset,
    /// What GDB answered a file call with, or `None` when it didn't.
    HostCall(Option<Fresult>),
    /// A stop the debugger was told of, and how the core came to be held there. What came in after
    /// it at its place comes back only once the core has stopped there again, or once it's clear it
    /// won't, so the debugger sees what it saw.
    Stopped { reason: Reason, halted: Halted },
}

/// How the core came to be held at a stop.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Halted {
    /// The debugger halted it, which a run that goes over the stop without stopping does in its
    /// place.
    By(HaltReason),
    /// A debug event of the core's own halted it, which it makes again whenever it gets there.
    Itself,
    /// A debug event of the core's own halted it at one of the debugger's watchpoints, which the
    /// debugger's halt stands in for when a run goes over the stop without stopping.
    AtWatchpoint,
}

/// Where the run stood when something came in: its position, and the instruction the core was at,
/// which tells apart the two places a core can be at one position, before an exception it's yet to
/// take and at its handler.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Place {
    position: Position,
    pc: u64,
}

impl Place {
    /// Where the run stands.
    fn of(core: &Core) -> Self {
        Self {
            position: core.machine.position(),
            pc: core.machine.pc(),
        }
    }
}

/// A checkpoint, and how much of the history had come in when it was taken.
#[derive(Debug)]
pub(super) struct Mark {
    pub(super) checkpoint: Checkpoint,
    pub(super) inputs: usize,
}

/// What a debugger has kept of the run to go back to it.
#[derive(Debug, Default)]
pub(super) struct History {
    /// Each input, in the order it came, with where the run stood.
    inputs: Vec<(Place, Input)>,
    /// Where the run stood after the last stretch, while it's at the next input's position with
    /// the core yet to get to it, which it gives up on once a stretch of nothing changes nothing.
    settling: Option<Place>,
    /// The next input a run going forward over what it did puts back.
    next: usize,
    /// What `monitor save` kept, by name.
    saved: BTreeMap<String, Arc<Mark>>,
    /// The step running is one the history puts back, whose end doesn't stop the core.
    pub(super) replaying: bool,
    /// Checkpoints taken as the run went, in the order of where they were taken.
    checkpoints: Vec<Arc<Mark>>,
    /// The count before which the history takes no checkpoint, since it has one near or one failed.
    next_checkpoint: u64,
    /// Where the debugger is taking the run back to.
    going: Option<Going>,
    /// The furthest the run has been on the way it's going, once it has gone back from there.
    furthest: Option<Position>,
    /// Where the core last stopped, told to the debugger or passed going back, which a stop the
    /// history has there is.
    stopped_at: Option<Place>,
    /// A stop that changed nothing, the run going forward over what it already did, noted only if
    /// the run goes a new way from where it is.
    unnoted: Option<(Place, Input)>,
    /// The furthest a breakpoint's print was printed from, which a run going forward over it again
    /// prints nothing up to.
    printed: Option<Position>,
    /// A halt point behind the run, which going back stops at, `monitor until-icount` with a count
    /// the run has passed.
    pub(super) behind: Option<u64>,
}

/// Where the debugger is taking the run back to, a span between checkpoints at a time.
#[derive(Clone, Copy, Debug)]
enum Going {
    /// To where the run stood just before the instruction that retired one more than `count`,
    /// stopping at nothing on the way: at `count`, once a stretch of nothing changes nothing, which
    /// takes an exception the core was yet to take.
    Back { count: u64, settled: Option<Place> },
    /// Over the span from checkpoint `mark` to `end`, counting what going forward would have
    /// stopped at.
    Looking {
        mark: usize,
        end: Position,
        stops: u32,
    },
    /// To the last of the span's stops, `left` stops on.
    Last { left: u32 },
    /// To just after the instruction a watchpoint stopped before, the instruction that retires
    /// `count`, where it stops for `reason`. GDB takes a watchpoint out and steps the instruction
    /// after a watch stop, the way it's going, so going back it steps onto the store.
    After { reason: Reason, count: u64 },
}

/// Keeps `one` at `at` among `kept`, thinning them once they're more than [`CHECKPOINTS`].
fn keep_one<T>(kept: &mut Vec<T>, at: usize, one: T) {
    kept.insert(at, one);
    if kept.len() > CHECKPOINTS {
        thin(kept);
    }
}

/// Drops every other one of the older half of `kept`.
fn thin<T>(kept: &mut Vec<T>) {
    let older = kept.len() / 2;
    let mut index = 0;
    kept.retain(|_| {
        let keep = index >= older || index % 2 == 0;
        index += 1;
        keep
    });
}

impl History {
    /// The core stopped, so it's going back no further, and a step the history put back is done.
    pub(super) fn stopped(&mut self) {
        self.going = None;
        self.replaying = false;
    }

    /// Whether a breakpoint's print `here` is printed: once the run is past where the last was.
    pub(super) fn first_print(&mut self, here: Position) -> bool {
        if self.printed.is_some_and(|printed| here <= printed) {
            return false;
        }
        self.printed = Some(here);
        true
    }
}

impl Debugger<'_> {
    /// Whether the run may go back, which its driver says.
    pub(super) fn rewinds(core: &Core) -> bool {
        core.driven.may_rewind()
    }

    /// Whether the history keeps what comes in: while a debugger is attached to a run that may go
    /// back.
    fn keeping(&self, core: &Core) -> bool {
        self.attached() && Self::rewinds(core)
    }

    /// Whether the run is going forward over what it already did.
    fn behind(&self, core: &Core) -> bool {
        let here = core.machine.position();
        self.history.next < self.history.inputs.len()
            || core.driven.retracing()
            || self
                .history
                .furthest
                .is_some_and(|furthest| here < furthest)
    }

    /// Makes `input` with `make`, noted where the run stood before it. One that's what the history
    /// has next here is that one, and anything else takes the run a new way from here before it's
    /// made, so the driver and the ports hear what it does.
    pub(super) fn note<T>(
        &mut self,
        core: &mut Core,
        input: Input,
        make: impl FnOnce(&mut Core) -> T,
    ) -> T {
        let history = &self.history;
        let next = history.inputs.get(history.next);
        if self.keeping(core) && next == Some(&(Place::of(core), input.clone())) {
            self.history.next += 1;
            return make(core);
        }
        let here = self.new_input(core);
        let made = make(core);
        self.noted(here, input);
        made
    }

    /// Before an input the history doesn't have next: where the run stands, to note it at, with
    /// the run taken a new way from here when it's going forward over what it already did. `None`
    /// while the history keeps nothing.
    pub(super) fn new_input(&mut self, core: &mut Core) -> Option<Place> {
        if !self.keeping(core) {
            return None;
        }
        if self.behind(core) {
            self.new_way(core);
        }
        Some(Place::of(core))
    }

    /// Notes `input`, made where the run stood at `here`.
    pub(super) fn noted(&mut self, here: Option<Place>, input: Input) {
        if let Some(here) = here {
            self.history.inputs.push((here, input));
            self.history.next = self.history.inputs.len();
        }
    }

    /// Notes the stop the debugger is told of, for `reason`, where the core stands, `halted` as it
    /// was, `changed` saying whether that changed what the firmware sees. Going forward over what
    /// the run already did, a stop the history has here is that one, a new one that changed
    /// something takes the run a new way from here, and one that changed nothing is noted only if
    /// the run goes a new way from here later.
    pub(super) fn note_stop(
        &mut self,
        core: &mut Core,
        reason: Reason,
        halted: Halted,
        changed: bool,
    ) {
        let here = Place::of(core);
        self.history.stopped_at = Some(here);
        let stop = Input::Stopped { reason, halted };
        if !self.keeping(core) {
            return;
        }
        let history = &mut self.history;
        if history.inputs.get(history.next) == Some(&(here, stop.clone())) {
            history.next += 1;
            return;
        }
        if !changed && self.behind(core) {
            self.history.unnoted = Some((here, stop));
            return;
        }
        let here = self.new_input(core);
        self.noted(here, stop);
    }

    /// Whether the core stops here again for `reason`, held as `halted`, before it runs on: at a
    /// breakpoint of the debugger's it hasn't passed here, at a watchpoint of the debugger's it
    /// hasn't passed here, or on a debug event of its own.
    fn stops_here(&self, core: &Core, reason: Reason, halted: Halted) -> bool {
        let (pc, count) = (core.machine.pc(), core.machine.retired());
        let watching = &core.machine.watching;
        match reason {
            _ if halted == Halted::Itself => true,
            Reason::Breakpoint(_) => {
                self.breakpoint_at(pc).is_some() && self.resumed != Some((pc, count))
            }
            Reason::Watch(watchpoint, address) => {
                watching.passing != Some((pc, count + 1))
                    && watching.debugged.iter().any(|&((first, last), kind)| {
                        kind == watchpoint && (first..=last).contains(&address)
                    })
            }
            _ => false,
        }
    }

    /// The run goes a new way from where it stands: the driver and the ports hear everything from
    /// here, and what the history had past here goes, the snapshots and checkpoints taken past here
    /// with it. The next checkpoint is taken from here.
    fn new_way(&mut self, core: &mut Core) {
        core.new_way();
        let here = core.machine.position();
        let history = &mut self.history;
        history.inputs.truncate(history.next);
        let next = history.next;
        let kept = |mark: &Arc<Mark>| mark.inputs <= next && mark.checkpoint.position <= here;
        history.saved.retain(|_, mark| kept(mark));
        history.checkpoints.retain(kept);
        history.next_checkpoint = here.count;
        history.furthest = None;
        // What's printed past here is the new way's.
        history.printed = history.printed.map(|printed| printed.min(here));
        // A stop here that changed nothing is what comes in here first.
        let place = Place::of(core);
        if let Some((at, stop)) = history.unnoted.take()
            && at == place
        {
            history.inputs.push((at, stop));
            history.next = history.inputs.len();
        }
    }

    /// Puts back what the history has here, up to a step or a file call, which the core makes
    /// itself, or a stop the core makes here again, and answers whether a step is next. A run that
    /// went past what the history has, or settled short of it, is another run from there, and goes
    /// a new way.
    pub(super) fn put_back_here(&mut self, core: &mut Core) -> bool {
        loop {
            let here = Place::of(core);
            let Some((at, input)) = self.history.inputs.get(self.history.next).cloned() else {
                return false;
            };
            if at.position < here.position {
                self.new_way(core);
                return false;
            }
            if at != here {
                return false;
            }
            match input {
                Input::Stepped => return true,
                Input::HostCall(_) => return false,
                Input::Stopped { reason, halted }
                    if self.history.stopped_at != Some(here)
                        && self.stops_here(core, reason, halted) =>
                {
                    return false;
                }
                input => put_back(core, &input),
            }
            self.history.next += 1;
        }
    }

    /// While the run is at the next input's position with the core at another instruction: notes
    /// where it stands, and once a stretch of nothing changed nothing, the core settled somewhere
    /// it never came in, so the run goes a new way from there.
    fn give_up_short_of(&mut self, core: &mut Core) {
        let here = Place::of(core);
        let history = &mut self.history;
        let short = matches!(
            history.inputs.get(history.next),
            Some((at, _)) if at.position == here.position && at.pc != here.pc
        );
        if !short {
            history.settling = None;
        } else if history.settling == Some(here) {
            history.settling = None;
            self.new_way(core);
        } else {
            history.settling = Some(here);
        }
    }

    /// After a stretch that didn't stop the core: puts back what the history has here, a step
    /// held as the debugger held it, and aims the core at the next place the history has.
    pub(super) fn replay(&mut self, core: &mut Core) {
        self.give_up_short_of(core);
        if self.put_back_here(core) {
            self.history.next += 1;
            self.history.replaying = true;
            self.core = Held::Stepping;
        }
        self.aim(core);
    }

    /// The answer GDB gave the file call the core makes here, when the run is going forward over
    /// it, with what came in before it here put back.
    #[expect(
        clippy::option_option,
        reason = "whether the history has the call apart from what GDB answered it, which may be nothing"
    )]
    pub(super) fn answered_here(&mut self, core: &mut Core) -> Option<Option<Fresult>> {
        self.put_back_here(core);
        let here = Place::of(core);
        match self.history.inputs.get(self.history.next) {
            Some(&(at, Input::HostCall(answer))) if at == here => {
                self.history.next += 1;
                Some(answer)
            }
            _ => None,
        }
    }

    /// Takes the step the history has next as the one the core is about to make.
    pub(super) fn history_step(&mut self) {
        self.history.next += 1;
    }

    /// Where the history has the core stop next to put something back, while the run is short of
    /// it: past where it stands, or where it stands with the core yet to get to the instruction. At
    /// that position the core runs stretches of nothing, which take any exception it's yet to take.
    /// What it has where the core stands is a file call or a step, which the core makes as it runs.
    pub(super) fn next_input(&self, core: &Core) -> Option<Position> {
        let here = Place::of(core);
        let (at, _) = self.history.inputs.get(self.history.next)?;
        (at.position > here.position || (at.position == here.position && at.pc != here.pc))
            .then_some(at.position)
    }

    /// `monitor save NAME`.
    pub(super) fn save(&mut self, core: &mut Core, name: &str) -> String {
        if let Err(why) = Self::can_go_back(core) {
            return why;
        }
        if name.is_empty() {
            return "save takes a name, like save before-the-fault\n".to_owned();
        }
        match core.checkpoint() {
            Ok(checkpoint) => {
                let position = checkpoint.position;
                let mark = Mark {
                    checkpoint,
                    inputs: self.history.next,
                };
                self.history.saved.insert(name.to_owned(), Arc::new(mark));
                format!(
                    "saved {name} at icount {} at {} ns\n",
                    position.count, position.at.0
                )
            }
            Err(why) => format!("can't save here: {why}\n"),
        }
    }

    /// `monitor restore NAME`.
    pub(super) fn restore(&mut self, core: &mut Core, name: &str) -> String {
        if let Err(why) = Self::can_go_back(core) {
            return why;
        }
        let Some(mark) = self.history.saved.get(name).cloned() else {
            return format!("no snapshot {name}, see monitor snapshots\n");
        };
        match self.go_to(core, &mark) {
            Ok(()) => format!(
                "restored {name} at icount {} at {} ns\n",
                mark.checkpoint.position.count, mark.checkpoint.position.at.0
            ),
            Err(why) => format!("can't restore {name}: {why}\n"),
        }
    }

    /// `monitor snapshots`.
    pub(super) fn snapshots(&self) -> String {
        if self.history.saved.is_empty() {
            return "no snapshots, monitor save NAME takes one\n".to_owned();
        }
        self.history
            .saved
            .iter()
            .fold(String::new(), |mut said, (name, mark)| {
                let at = mark.checkpoint.position;
                writeln!(said, "{name} at icount {} at {} ns", at.count, at.at.0)
                    .expect("a String takes it");
                said
            })
    }

    /// Why the run can't go back, when it can't.
    fn can_go_back(core: &Core) -> Result<(), String> {
        if Self::rewinds(core) {
            Ok(())
        } else {
            Err(
                "this run can't go back: its driver doesn't say it may, and one under --link \
                 never does, since an engine's inputs aren't kept\n"
                    .to_owned(),
            )
        }
    }

    /// Puts the run back to `mark` and holds the core there, with nothing the debugger had it stop
    /// at next. The server looks for the debugger again from there, at the next stretch.
    pub(super) fn go_to(&mut self, core: &mut Core, mark: &Mark) -> Result<(), String> {
        let left = core.machine.position();
        let furthest = self.history.furthest.get_or_insert(left);
        *furthest = left.max(*furthest);
        core.restore(&mark.checkpoint)?;
        self.history.next = mark.inputs;
        self.history.stopped_at = None;
        self.history.unnoted = None;
        self.halt_at = None;
        self.resumed = None;
        self.next_look = 0;
        self.next_warp = 0;
        self.history.replaying = false;
        self.core = Held::Halted;
        self.aim(core);
        self.threads.forget();
        self.stopped = self.threads.stopped(core, Reason::Trap);
        Ok(())
    }

    /// Drops the history, what `monitor save` kept and the checkpoints with it, as a debugger that
    /// goes takes them with it. A run it leaves going forward over what it already did goes a new
    /// way from there, since nothing puts back what came in.
    pub(super) fn forget_history(&mut self, core: &mut Core) {
        if self.behind(core) {
            core.new_way();
        }
        self.history = History::default();
    }

    /// Before the core runs on, with a debugger attached to a run that may go back: keeps a
    /// checkpoint where the run stands, at attach and then every [`CHECKPOINT_EVERY`]
    /// instructions on from the newest before it. One that can't be taken yet, with a reset
    /// pending say, is tried again before the next stretch, and one that can't be taken at all
    /// that far on.
    pub(super) fn keep_up(&mut self, core: &mut Core) {
        let here = core.machine.position();
        if here.count < self.history.next_checkpoint || !self.keeping(core) {
            return;
        }
        let at = self
            .history
            .checkpoints
            .partition_point(|mark| mark.checkpoint.position <= here);
        let near = at
            .checked_sub(1)
            .map(|newest| self.history.checkpoints[newest].checkpoint.position.count)
            .map(|count| count.saturating_add(CHECKPOINT_EVERY))
            .filter(|&next| here.count < next);
        if let Some(next) = near {
            self.history.next_checkpoint = next;
            return;
        }
        let checkpoint = match core.checkpoint() {
            Ok(checkpoint) => checkpoint,
            // Gone once the core has run on, so the next stretch tries again.
            Err(snapshot::Error::Resetting | snapshot::Error::Resuming) => return,
            Err(_) => {
                self.history.next_checkpoint = here.count.saturating_add(CHECKPOINT_EVERY);
                return;
            }
        };
        self.history.next_checkpoint = here.count.saturating_add(CHECKPOINT_EVERY);
        let checkpoints = &mut self.history.checkpoints;
        let mark = Mark {
            checkpoint,
            inputs: self.history.next,
        };
        keep_one(checkpoints, at, Arc::new(mark));
    }

    /// Whether the run can go back, which `qSupported` says.
    pub(super) fn reverses(core: &Core) -> bool {
        Self::rewinds(core)
    }

    /// `bs`: back to the instruction before, from the newest checkpoint at or before it. Answers
    /// whether the core runs to get there: `false` when it's held where the history begins, which
    /// GDB has been told.
    pub(super) fn step_back(&mut self, core: &mut Core) -> Result<bool, String> {
        let here = core.machine.position();
        let target = here.count.checked_sub(1);
        let from = target.and_then(|target| {
            self.history
                .checkpoints
                .iter()
                .rposition(|mark| mark.checkpoint.position.count <= target)
        });
        let (Some(target), Some(from)) = (target, from) else {
            self.back_to_the_beginning(core)?;
            return Ok(false);
        };
        let mark = Arc::clone(&self.history.checkpoints[from]);
        self.go_to(core, &mark)?;
        self.history.going = Some(Going::Back {
            count: target,
            settled: None,
        });
        self.travel(core);
        Ok(true)
    }

    /// `bc`: back to the last place going forward would have stopped, looking over the span from
    /// the newest checkpoint before here first.
    pub(super) fn continue_back(&mut self, core: &mut Core) -> Result<bool, String> {
        let here = core.machine.position();
        let Some(mark) = self
            .history
            .checkpoints
            .iter()
            .rposition(|mark| mark.checkpoint.position < here)
        else {
            self.back_to_the_beginning(core)?;
            return Ok(false);
        };
        self.look_over(core, mark, here)?;
        Ok(true)
    }

    /// Puts the run back to checkpoint `mark` and has it look over the span to `end`.
    fn look_over(&mut self, core: &mut Core, mark: usize, end: Position) -> Result<(), String> {
        let from = Arc::clone(&self.history.checkpoints[mark]);
        self.go_to(core, &from)?;
        self.history.going = Some(Going::Looking {
            mark,
            end,
            stops: 0,
        });
        self.travel(core);
        Ok(())
    }

    /// Puts the run back to the oldest checkpoint, where the history begins, and holds the core
    /// there with `replaylog:begin`, which GDB is told.
    fn back_to_the_beginning(&mut self, core: &mut Core) -> Result<(), String> {
        let oldest = self
            .history
            .checkpoints
            .first()
            .cloned()
            .ok_or("the history keeps no checkpoint")?;
        if oldest.checkpoint.position != core.machine.position() {
            self.go_to(core, &oldest)?;
        }
        self.stop_back(core, Reason::Begin, Halted::By(HaltReason::Requested));
        Ok(())
    }

    /// Lets the core run on the way back, with interrupts as they'd be, once what the history has
    /// where it stands is put back.
    fn travel(&mut self, core: &mut Core) {
        self.core = Held::Running;
        self.replay(core);
    }

    /// Holds the core where going back ended, held as `halted`, and tells GDB why.
    fn stop_back(&mut self, core: &mut Core, reason: Reason, halted: Halted) {
        if self.halt(core, reason, halted).is_err() {
            self.disconnect(core);
        }
    }

    /// Where the run going back has to stop next, past where it stands: where it's going, or the
    /// halt point behind the run while the core is short of it.
    pub(super) fn going_until(&self, core: &Core) -> Option<Position> {
        let going = match self.history.going? {
            Going::Back { count, .. } | Going::After { count, .. } => Some(Position {
                count,
                at: crate::time::VirtualNanos(u64::MAX),
            }),
            Going::Looking { end, .. } => Some(end),
            Going::Last { .. } => None,
        };
        let behind = self
            .history
            .behind
            .filter(|&count| count > core.machine.retired());
        going
            .into_iter()
            .chain(behind.map(|count| Position {
                count,
                at: crate::time::VirtualNanos(u64::MAX),
            }))
            .min()
    }

    /// After a stretch while the run goes back: what going forward would have stopped at here is
    /// counted, or stopped at once it's the last, and passed otherwise. Answers whether going back
    /// had the stretch, which it always does while it goes.
    pub(super) fn going_back(&mut self, core: &mut Core, exit: Exit, ran: u64) -> bool {
        let Some(going) = self.history.going else {
            return false;
        };
        // A step the history put back is done, and the core runs on.
        if self.core == Held::Stepping && (ran > 0 || exit != Exit::Breakpoint) {
            self.history.replaying = false;
            self.core = Held::Running;
        }
        let at = (core.machine.cpu().pc(), core.machine.retired());
        let hit = (exit == Exit::Breakpoint && self.resumed != Some(at))
            .then(|| self.breakpoint_at(at.0))
            .flatten();
        let stop = if let Some((address, watchpoint)) = core.machine.watching.debugger_hit.take() {
            let halted = if exit == Exit::Halted {
                core.machine.watching.passing = Some((at.0, at.1 + 1));
                Halted::AtWatchpoint
            } else {
                Halted::By(HaltReason::Watchpoint)
            };
            Some((Reason::Watch(watchpoint, address), halted))
        } else if let Some(kind) = hit
            && self.stops_at(core, at.0)
        {
            Some((Reason::Breakpoint(kind), Halted::By(HaltReason::Breakpoint)))
        } else if exit == Exit::Halted {
            Some((Reason::Trap, Halted::Itself))
        } else if self.history.behind == Some(at.1) && ran > 0 {
            Some((Reason::Trap, Halted::By(HaltReason::Requested)))
        } else {
            None
        };
        if hit.is_some() {
            self.pass_own_breakpoint(core);
        }
        // What the history has here after a stop there comes back as the run goes on.
        if stop.is_some() {
            self.history.stopped_at = Some(Place::of(core));
        }
        let here = core.machine.position();
        match going {
            Going::Back { count, .. } if here.count < count => self.replay(core),
            Going::Back { settled, .. } if settled == Some(Place::of(core)) => {
                self.stop_back(core, Reason::Trap, Halted::By(HaltReason::Requested));
            }
            // What the history has here comes in once the debugger goes on from here.
            Going::Back { count, .. } => {
                self.history.going = Some(Going::Back {
                    count,
                    settled: Some(Place::of(core)),
                });
                self.aim(core);
            }
            Going::Looking { mark, end, stops } if here >= end => self.looked(core, mark, stops),
            Going::Looking { mark, end, stops } => {
                self.history.going = Some(Going::Looking {
                    mark,
                    end,
                    stops: stops + u32::from(stop.is_some()),
                });
                self.replay(core);
            }
            Going::After { reason, count } if here.count >= count => {
                self.stop_back(core, reason, Halted::By(HaltReason::Watchpoint));
            }
            Going::After { .. } => self.replay(core),
            Going::Last { left } => match stop {
                Some((reason @ Reason::Watch(..), _)) if left <= 1 && exit == Exit::Halted => {
                    self.history.going = Some(Going::After {
                        reason,
                        count: at.1 + 1,
                    });
                    self.aim(core);
                }
                Some((reason, halted)) if left <= 1 => {
                    if self.history.behind == Some(at.1) {
                        self.history.behind = None;
                    }
                    self.stop_back(core, reason, halted);
                }
                Some(_) => {
                    self.history.going = Some(Going::Last { left: left - 1 });
                    self.replay(core);
                }
                None => self.replay(core),
            },
        }
        true
    }

    /// The span from checkpoint `mark` has been looked over, with `stops` in it: back to the last
    /// of them, or on to the span before, or to where the history begins.
    fn looked(&mut self, core: &mut Core, mark: usize, stops: u32) {
        let went = if stops > 0 {
            let from = Arc::clone(&self.history.checkpoints[mark]);
            self.go_to(core, &from).map(|()| {
                self.history.going = Some(Going::Last { left: stops });
                self.travel(core);
            })
        } else if mark > 0 {
            let end = self.history.checkpoints[mark].checkpoint.position;
            self.look_over(core, mark - 1, end)
        } else {
            self.back_to_the_beginning(core)
        };
        if went.is_err() {
            self.stop_back(core, Reason::Trap, Halted::By(HaltReason::Requested));
        }
    }
}

/// Puts `input` back as it came the first time.
fn put_back(core: &mut Core, input: &Input) {
    match input {
        Input::Write { address, bytes } => {
            core.debugger_write(*address, bytes);
        }
        Input::Flash { address, bytes } => core.debugger_flash(*address, bytes),
        Input::Read { address, length } => {
            core.debugger_read(*address, *length, super::memory::Reads::Firmware);
        }
        Input::Register { number, bytes } => {
            core.machine.cpu().set_gdb_register(*number, bytes);
        }
        Input::Registers(hex) => {
            set_registers(core.machine.cpu(), hex);
        }
        Input::Monitor(command) => {
            core.machine.cpu().monitor_command(command);
        }
        Input::Reset => reset(core),
        Input::Stopped { halted, .. } => {
            let halt = match *halted {
                Halted::By(halt) => halt,
                Halted::AtWatchpoint => HaltReason::Watchpoint,
                Halted::Itself => return,
            };
            core.machine.cpu().debugger_halted(halt);
        }
        Input::Stepped | Input::HostCall(_) => {}
    }
}

/// A debugger's reset, which holds the core at its first instruction as the debugger's halt, a
/// reset's own vector catch included.
pub(super) fn reset(core: &mut Core) {
    core.debugger_reset();
    core.machine.cpu().debugger_halted(HaltReason::Requested);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Thinning a full history keeps the newer half as it was and every other one of the older
    /// half, so the gaps grow with age: after a run kept one more checkpoint than it holds, over and
    /// over, the newest are a checkpoint apart and the oldest reach back to the first.
    #[test]
    fn thinning_keeps_recent_checkpoints_close_and_old_ones_far() {
        let mut kept: Vec<u64> = (0..=64).collect();
        thin(&mut kept);
        assert_eq!(kept.len(), 49);
        assert_eq!(&kept[..4], [0, 2, 4, 6]);
        assert_eq!(&kept[16..], (32..=64).collect::<Vec<_>>());
        let mut kept: Vec<u64> = Vec::new();
        for taken in 0..10_000 {
            let newest = kept.len();
            keep_one(&mut kept, newest, taken);
        }
        assert!(kept.len() <= CHECKPOINTS);
        assert_eq!(kept.first(), Some(&0), "the oldest stays");
        let newest: Vec<u64> = kept
            .windows(2)
            .rev()
            .take(8)
            .map(|pair| pair[1] - pair[0])
            .collect();
        assert!(newest.iter().all(|&gap| gap == 1), "{newest:?}");
        let oldest = kept[1] - kept[0];
        assert!(oldest > 64, "the oldest gap is {oldest}");
    }
}