rigless 0.2.0

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
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The GDB remote protocol, served from the core's own thread.
//!
//! A run with a debugger's listener takes one debugger at a time from it, and closes any other
//! that connects meanwhile. The server answers it between stretches of the core, so the core never
//! runs while a packet is answered, and virtual time stands still while the debugger holds the
//! core. A debugger that connects finds the core held where it was. While the core runs, the server
//! looks for a debugger and for GDB's interrupt once every [`SERVING_STRETCH`] instructions or so,
//! which is milliseconds, once the clock has warped that many instructions' time while the core
//! waits, and every [`WAITS_BETWEEN_LOOKS`] stretches while it waits without warping. Between
//! looks the core runs as it would with no debugger, carrying on after an access by itself. A run
//! that waits for a debugger holds the core until one continues, steps, detaches or kills it. A
//! debugger that goes without `D`, `k` or `vKill`, by GDB's `disconnect` or by crashing, leaves the
//! core as it was, held or running, with its breakpoints and watchpoints taken out and its halting
//! debug on, and a core left held waits for the next debugger. A connection that closes without
//! sending a packet, a port probe's, leaves everything as it found it.
//!
//! The registers and their description are the family's. Memory is answered the way the core's own
//! accesses are, by the family's space, the memory the core maps, a bit alias the family remaps, or
//! the models, with no program counter, so the models know the access is the person's. A write to
//! memory the guest can't write lands all the same, which is how a debugger loads a firmware, and a
//! snapshot of the run is refused from then on, since it keeps that memory only as the images
//! placed it.
//!
//! A debugger that stops the core and reads memory or the core's registers leaves the run the same
//! run. A step holds interrupts off, so one that comes due while the debugger steps is taken only
//! once it lets the core run. A read of a peripheral is a peek, what the firmware's read would
//! answer with nothing changed and nobody told, until `monitor peek off` makes it the firmware's
//! read, side effects and all. A write to a register or memory changes the run at whichever stop
//! it's at, and the run's output doesn't show it unless it reaches a model. The history keeps it,
//! to put it back there when the run goes back.
//!
//! While a debugger is attached the core's halting debug is on, as a probe turns it on: the
//! firmware can see a debugger is there, and a breakpoint instruction halts the core at itself and
//! the debugger hears it. Which register says so and which instruction it is are the family's.
//!
//! What's served: the registers, as the core has them, memory, with an error where nothing answers,
//! and a CRC of it, the memory map, with flash erased and written a block at a time through
//! `vFlashErase` and `vFlashWrite`, breakpoints, write, read and access watchpoints, which stop the
//! core before the access they watch, continuing, stepping one instruction with interrupts held
//! off, the interrupt, a stop at an exact instruction count or instant with the count as `$icount`,
//! the monitor's commands, thread-ids and stop reasons in whichever form the debugger said it
//! reads, a kernel's threads, a breakpoint's conditions and commands as agent expressions, which
//! is `dprintf` in the target, non-stop mode, the firmware's file calls on the debugger's host,
//! going back with `bs` and `bc`, `monitor save` and `monitor restore`, `QStartNoAckMode`, and
//! detaching, which closes the connection under `target remote` and
//! keeps it under `target extended-remote`, where `vAttach`, GDB's `attach 1`, takes the core
//! again. `k` detaches as well and closes the connection, with no reply, since "Debugging with GDB"
//! for GDB 18.1, section E.3 gives it none. Under `target extended-remote`, `run` resets the
//! machine as `monitor reset` does and stops at the first instruction, and `kill` leaves the core
//! held for the next `run`, until the debugger detaches or goes, when it runs on.

mod agent;
#[cfg(fuzzing)]
mod fuzzed;
mod history;
mod hosted;
mod live;
mod memory;
mod monitor;
mod packet;
mod points;
mod query;
mod registers;
mod threads;

use std::collections::BTreeMap;
use std::io::{self, ErrorKind};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use super::{Core, Stretch, nanos};
use crate::emulator::{Error, Exit, HaltReason, WalkThreads};
use crate::time::VirtualNanos;
#[cfg(fuzzing)]
pub(crate) use fuzzed::Fuzzed;
use history::{Halted, History, Input};
pub(super) use hosted::Fresult;
use memory::{Reads, binary_write, hex_write, read_memory, span};
use packet::{Carry, Connection, Framed, Negotiated, PACKET_SIZE, hex};
use points::Breakpoint;
pub(super) use points::Watchpoint;
pub(super) use query::Map;
use registers::{
    pc_number, register, register_bytes, register_values, register_write, registers, set_registers,
};
use threads::{CORE, PROCESS, Picked, Reason, Stopped, Threads, ours, stop_reply};

/// The most instructions a stretch runs while a run serves a debugger, so a debugger that connects
/// or interrupts is answered within milliseconds.
const SERVING_STRETCH: u32 = 1 << 20;

/// The stretches that run nothing, a waiting core's, between two looks for a debugger or its
/// interrupt while the core runs. The count stands still while the core waits, and a look after
/// every one cost a firmware that waits often a third of its speed.
const WAITS_BETWEEN_LOOKS: u32 = 1 << 8;

/// The longest the server waits on a debugger that holds the core before it closes any other that's
/// connecting, since it serves one at a time, and how long a run that waits for a debugger pauses
/// before it tries to accept one again: after a failed accept, or after finding none when the run
/// can be interrupted.
const WAIT_ON_PACKET: Duration = Duration::from_millis(100);

/// A run's debugger: where it listens, the one connected, and what it asked for.
pub(super) struct Debugger<'a> {
    listener: TcpListener,
    connection: Option<Connection>,
    core: Held,
    /// The core's halting debug is on, which the server turns on for a debugger and leaves on when
    /// one goes without letting the core go.
    halting: bool,
    /// The core's interrupt input is held low for the debugger's steps.
    holding: bool,
    /// Each breakpoint the debugger set, by its address and the kind that set it.
    breakpoints: BTreeMap<(u64, Breakpoint), points::Agent>,
    /// Why the core last stopped, which `?` asks again.
    stopped: Stopped,
    /// Where the core was, and after how many instructions, when the debugger last let it run.
    resumed: Option<(u64, u64)>,
    /// The instructions retired when the server next looks for a debugger or its interrupt while
    /// the core runs.
    next_look: u64,
    /// The clock's warps, in nanoseconds, past which the server looks again, so a core that sleeps
    /// a long way at a time is looked at after each long sleep.
    next_warp: u64,
    /// The stretches that ran nothing since the server last looked.
    waits: u32,
    /// The threads a stop and the thread packets name.
    threads: Threads<'a>,
    /// Where the debugger has the core stop next on its own.
    halt_at: Option<HaltAt>,
    /// What the debugger's reads of memory are, peeks until `monitor peek off`.
    reads: Reads,
    /// The memory map the debugger reads, and where flash erases.
    map: Map,
    /// A debugger that connected as the one served closed its end, served once what that one sent
    /// is answered.
    next: Option<TcpStream>,
    /// GDB sent Ctrl-C back with the file call it just answered.
    interrupted_call: bool,
    /// What the debugger has kept of the run to go back to it.
    history: History,
    /// The run's interrupt, which ends a wait for a debugger or for a held core's next packet.
    interrupt: Option<&'a AtomicBool>,
}

/// Where the debugger has the core stop next on its own: after an exact number of instructions, or
/// at an instant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HaltAt {
    Count(u64),
    Instant(VirtualNanos),
}

/// Where the debugger has the core.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Held {
    /// Running, as it would with no debugger.
    Running,
    /// Held, while the debugger asks what it likes, or until one connects.
    Halted,
    /// Running one instruction, after which the debugger hears it's done.
    Stepping,
}

/// What a packet asks of the core.
#[derive(Debug, PartialEq, Eq)]
enum Asked {
    /// An answer, and the core stays as it is.
    Reply(String),
    /// Run until something stops the core.
    Continue,
    /// Run one instruction.
    Step,
    /// The core is on its way back, or there already, and GDB hears when it gets there.
    Back,
    /// Stop a core that runs in non-stop mode, for a reason.
    Stop(Reason),
    /// Say `OK` and close the connection.
    Detach,
    /// Close the connection, with no reply.
    Kill,
}

impl<'a> Debugger<'a> {
    /// Takes debuggers from `listener`, telling each of the memory in `map` and of the threads of
    /// `kernels`. With `wait`, the core is held until a debugger lets it go.
    pub(super) fn listen(
        listener: &TcpListener,
        wait: bool,
        map: Map,
        kernels: &'a [Box<dyn WalkThreads>],
        interrupt: Option<&'a AtomicBool>,
    ) -> Result<Self, Error> {
        let listener = listener.try_clone().map_err(Error::Debugger)?;
        listener.set_nonblocking(true).map_err(Error::Debugger)?;
        Ok(Self {
            listener,
            connection: None,
            core: if wait { Held::Halted } else { Held::Running },
            halting: false,
            holding: false,
            breakpoints: BTreeMap::new(),
            stopped: Stopped {
                reason: Reason::Trap,
                thread: CORE,
            },
            resumed: None,
            next_look: 0,
            next_warp: 0,
            waits: 0,
            threads: Threads::new(kernels),
            halt_at: None,
            reads: Reads::Peeks,
            map,
            next: None,
            interrupted_call: false,
            history: History::default(),
            interrupt,
        })
    }

    /// Whether the run's interrupt is set, which ends the run at the next stretch.
    fn interrupted(&self) -> bool {
        self.interrupt
            .is_some_and(|flag| flag.load(Ordering::Relaxed))
    }

    /// Before a stretch: holds interrupts off for a step and lets them go
    /// once the debugger lets the core run. Letting them go only then keeps the interrupt a step's
    /// end raises from cutting the next step short.
    pub(super) fn hold_interrupts(&mut self, core: &mut Core) {
        let stepping = self.core == Held::Stepping;
        if self.holding != stepping {
            self.holding = stepping;
            core.machine.cpu().hold_interrupts(stepping);
        }
    }

    /// The stretch to run instead of `stretch`: one instruction for a step, and never more than a
    /// debugger can wait on, or past the count the core halts at.
    pub(super) fn limit(&self, core: &Core, stretch: Stretch) -> Stretch {
        match stretch {
            Stretch::Run(_) if self.core == Held::Stepping => Stretch::Run(1),
            Stretch::Run(instructions) => {
                let left = self.until(core).saturating_sub(core.machine.retired());
                Stretch::Run(instructions.min(u32::try_from(left).unwrap_or(u32::MAX)))
            }
            Stretch::Over(address) => Stretch::Over(address),
        }
    }

    /// The instruction count the core may carry on to after an access without coming back first,
    /// which is as far as the stretch [`Debugger::limit`] gives it, or `None` for a step, which
    /// comes back after its one instruction.
    pub(super) fn carry_until(&self, core: &Core) -> Option<u64> {
        (self.core != Held::Stepping).then(|| self.until(core))
    }

    /// The instruction count the end of this stretch is at most, which is the halt point's when
    /// that's nearer, or where the history puts something back.
    fn until(&self, core: &Core) -> u64 {
        let look = core.machine.retired() + u64::from(SERVING_STRETCH);
        let halt = match self.halt_at {
            Some(HaltAt::Count(count)) => count,
            _ => u64::MAX,
        };
        let input = self.next_input(core).map_or(u64::MAX, |at| at.count);
        let back = self.going_until(core).map_or(u64::MAX, |at| at.count);
        look.min(halt).min(input).min(back)
    }

    /// Before a stretch: answers the connected debugger, its interrupt while the core runs, and
    /// every packet while it holds the core or has detached from it. Then closes any other debugger
    /// that's connecting, or takes one when none is connected and serves it the same way. A
    /// connection that fails is noticed before another is taken, so a debugger can reconnect at
    /// once.
    pub(super) fn serve(&mut self, core: &mut Core) {
        self.keep_up(core);
        if self.core == Held::Running {
            let (retired, warped) = (core.machine.retired(), core.machine.warped);
            if retired < self.next_look
                && warped < self.next_warp
                && self.waits < WAITS_BETWEEN_LOOKS
            {
                return;
            }
            let stretch = u64::from(SERVING_STRETCH);
            self.next_look = retired + stretch;
            self.next_warp = warped.saturating_add(nanos(core.machine.rate, stretch));
            self.waits = 0;
        }
        if self.connection.is_some() && self.converse(core).is_err() {
            self.disconnect(core);
        }
        if self.connection.is_some() {
            self.refuse_others();
        }
        while self.connection.is_none() && self.accept() {
            if self.converse(core).is_err() {
                self.disconnect(core);
            }
        }
    }

    fn converse(&mut self, core: &mut Core) -> io::Result<()> {
        if self.core == Held::Running {
            if self.attached() && !self.non_stop() {
                if self.connection()?.interrupted()? {
                    self.halt_core(core, Reason::Interrupt)?;
                }
            } else {
                // Detached, or in non-stop mode, where GDB doesn't wait on the core.
                for framed in self.connection()?.poll()? {
                    // What came after a `k` or a `D` that closed the connection is nobody's.
                    if self.connection.is_none() {
                        break;
                    }
                    match framed {
                        Framed::Packet(packet) => self.act(core, &packet)?,
                        Framed::Interrupt if self.attached() && self.core != Held::Halted => {
                            self.halt_core(core, Reason::Interrupt)?;
                        }
                        _ => {}
                    }
                }
            }
        }
        while self.core == Held::Halted && self.connection.is_some() && !self.interrupted() {
            let packet = match self.connection()?.next_packet() {
                // Quiet for the read timeout `connecting` set, `WAIT_ON_PACKET`.
                Err(error)
                    if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) =>
                {
                    self.refuse_others();
                    continue;
                }
                packet => packet?,
            };
            self.act(core, &packet)?;
        }
        Ok(())
    }

    /// Answers `packet` and does what it asks. A debugger's first packet takes the core.
    fn act(&mut self, core: &mut Core, packet: &str) -> io::Result<()> {
        if !self.connection()?.taken {
            self.take_core(core);
        }
        match self.answer(core, packet) {
            Asked::Reply(text) => self.connection()?.send(&text)?,
            // In non-stop mode a resume answers at once, and one of a core that runs is ignored, as
            // `vCont` has it, the core counting as running until GDB takes its stop.
            asked @ (Asked::Continue | Asked::Step) if self.non_stop() => {
                if self.core == Held::Halted && !self.telling() {
                    self.go(core, asked == Asked::Step);
                }
                self.connection()?.send("OK")?;
            }
            Asked::Continue | Asked::Step if std::mem::take(&mut self.connection()?.interrupt) => {
                self.halt_core(core, Reason::Interrupt)?;
            }
            Asked::Continue => self.go(core, false),
            Asked::Step => self.go(core, true),
            Asked::Stop(reason) => self.stop(core, reason)?,
            Asked::Back if self.non_stop() => self.connection()?.send("OK")?,
            Asked::Back => {}
            Asked::Detach => {
                self.connection()?.send("OK")?;
                self.connection = None;
            }
            Asked::Kill => self.connection = None,
        }
        Ok(())
    }

    fn connection(&mut self) -> io::Result<&mut Connection> {
        self.connection
            .as_mut()
            .ok_or_else(|| io::Error::from(ErrorKind::NotConnected))
    }

    /// Whether a debugger is connected and has the core.
    fn attached(&self) -> bool {
        self.connection
            .as_ref()
            .is_some_and(|connection| connection.attached)
    }

    /// After a stretch that ended with `exit` having run `ran` instructions: a breakpoint, a
    /// watchpoint, a step the debugger asked for or the halt point it set holds the core and tells
    /// it so, the halt point as a step's end. A step that ran nothing because it stopped at an
    /// instruction the run watches goes on, and one that ran nothing for any other reason, an
    /// exception taken or a core that waits, is done. With no debugger attached, a debug event that
    /// halting debug left on halts the core for the next one.
    pub(super) fn after(&mut self, core: &mut Core, exit: Exit, ran: u64) {
        if ran == 0 {
            self.waits = self.waits.saturating_add(1);
        }
        if !self.attached() {
            if exit == Exit::Halted {
                self.core = Held::Halted;
                self.stopped = Stopped {
                    reason: Reason::Trap,
                    thread: CORE,
                };
            } else {
                self.replay(core);
            }
            return;
        }
        // Stopped already, by a Ctrl-C GDB sent with a file call's answer, which a halt point due
        // at the same instant is the same stop as.
        if self.core == Held::Halted {
            self.reached(core);
            return;
        }
        if self.going_back(core, exit, ran) {
            return;
        }
        let stepped = ran > 0 || exit != Exit::Breakpoint;
        let reached = self.reached(core);
        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 (reason, halted) =
            if let Some((address, watchpoint)) = core.machine.watching.debugger_hit.take() {
                // A core that stopped before the access runs the instruction again from its start,
                // and it gets past the watchpoint that once, even if the debugger leaves it in. It's
                // known by its count, so a client that continues with the watchpoint still in while an
                // interrupt is due at this instant runs the handler first and stops a second time when
                // the instruction comes round again. GDB never does: it takes the watchpoint out and
                // steps first.
                let halted = if exit == Exit::Halted {
                    core.machine.watching.passing = Some((at.0, at.1 + 1));
                    Halted::AtWatchpoint
                } else {
                    Halted::By(HaltReason::Watchpoint)
                };
                (Reason::Watch(watchpoint, address), halted)
            } else if let Some(kind) = hit
                && self.stops_at(core, at.0)
            {
                (Reason::Breakpoint(kind), Halted::By(HaltReason::Breakpoint))
            } else if hit.is_some() && !reached {
                // A hit its conditions say doesn't stand, or a dprintf's, runs on past the breakpoint
                // with no stop reply, unless the halt point is here too.
                self.pass_own_breakpoint(core);
                self.replay(core);
                return;
            } else if exit == Exit::Halted {
                // A debug event of the core's own, a breakpoint instruction in the firmware among them,
                // is a plain trap. GDB takes `swbreak` where it planted nothing for a breakpoint it has
                // taken out, and resumes, and the instruction stops the core again at once.
                (Reason::Trap, Halted::Itself)
            } else if self.core == Held::Stepping && stepped && self.history.replaying && !reached {
                // A step the history put back is done, and the core runs on.
                self.history.replaying = false;
                self.core = Held::Running;
                self.replay(core);
                return;
            } else if (self.core == Held::Stepping && stepped) || reached {
                (Reason::Trap, Halted::By(HaltReason::Requested))
            } else {
                self.replay(core);
                return;
            };
        if self.halt(core, reason, halted).is_err() {
            self.disconnect(core);
        }
    }

    /// The run is over: an attached debugger hears that the target exited, "Debugging with GDB" for
    /// GDB 18.1, section E.4, and which process did once it said it reads that.
    pub(super) fn exited(mut self) {
        self.exit_reply(0);
    }

    /// Tells an attached debugger the target exited with `code`, a byte.
    fn exit_reply(&mut self, code: u32) {
        if !self.attached() {
            return;
        }
        let exited = if self.negotiated().multiprocess {
            format!("W{code:02x};process:{PROCESS:x}")
        } else {
            format!("W{code:02x}")
        };
        if self.non_stop() {
            self.tell(&exited).ok();
            self.exit_taken();
        } else if self.core != Held::Halted
            && let Ok(connection) = self.connection()
        {
            // A debugger holding the core in all-stop mode waits on no reply, so it hears the close.
            connection.send(&exited).ok();
        }
        if let Ok(connection) = self.connection() {
            connection.hear_out();
        }
    }

    /// Takes a debugger that's connecting and holds the core for it, which its first packet takes,
    /// and answers whether there was one. While the core is held with nobody connected, this
    /// blocks until one does, past any connection that fails, or until the run is interrupted.
    #[expect(
        clippy::disallowed_methods,
        reason = "the run waits on a person here, before its core runs again"
    )]
    fn accept(&mut self) -> bool {
        loop {
            match self.connecting() {
                Some(stream) => {
                    self.attach(Box::new(stream));
                    return true;
                }
                // A failure that lasts, like running out of descriptors, comes back at once.
                None if self.core == Held::Halted && !self.interrupted() => {
                    std::thread::sleep(WAIT_ON_PACKET);
                }
                None => return false,
            }
        }
    }

    /// Serves the debugger at the far end of `stream`, minding how it found the core, which it
    /// finds held, and takes with its first packet.
    fn attach(&mut self, stream: Box<dyn Carry>) {
        self.connection = Some(Connection::new(stream, (self.core, self.halting)));
        self.threads.connected();
        self.core = Held::Halted;
    }

    /// Holds the core for the connected debugger, with its halting debug on: the debugger has it
    /// now, and GDB asks why it stopped with `?`.
    fn take_core(&mut self, core: &mut Core) {
        self.core = Held::Halted;
        self.history.stopped();
        self.threads.forget();
        self.stopped = self.threads.stopped(core, Reason::Trap);
        self.set_halting(core, true);
        core.machine.cpu().debugger_halted(HaltReason::Requested);
        if let Some(connection) = self.connection.as_mut() {
            let had = connection.attached && connection.taken;
            connection.attached = true;
            connection.taken = true;
            if !had {
                Self::tell_the_run(core, true);
            }
        }
        self.keep_up(core);
    }

    /// The next debugger that's connecting, ready to serve, or `None` when there's none or its
    /// connection failed. While the core is held with nobody connected, this blocks for one.
    fn connecting(&mut self) -> Option<TcpStream> {
        if let Some(stream) = self.next.take() {
            return Self::served(stream);
        }
        // A blocking accept would never hear the interrupt, so a run that has one looks instead.
        self.listener
            .set_nonblocking(self.core != Held::Halted || self.interrupt.is_some())
            .ok()?;
        let accepted = self.listener.accept();
        // A clone shares its mode with the caller's listener, which the run leaves non-blocking.
        self.listener.set_nonblocking(true).ok()?;
        let (stream, _) = accepted.ok()?;
        Self::served(stream)
    }

    /// `stream`, ready to serve.
    fn served(stream: TcpStream) -> Option<TcpStream> {
        // Some systems hand over the listener's non-blocking mode with the connection.
        stream.set_nonblocking(false).ok()?;
        stream.set_nodelay(true).ok()?;
        stream.set_read_timeout(Some(WAIT_ON_PACKET)).ok()?;
        Some(stream)
    }

    /// Closes every other debugger that's connecting, as it's taken, so it hears at once that the
    /// run is served to another. One that connects once the debugger served has closed its end, as
    /// GDB does when it reconnects at once, is kept to serve next, once the next look finds the
    /// served one closed. The served one's end is looked at after the other is taken. On loopback
    /// that sees a close sent before the other connected, and across a network the close can come
    /// later, when the other is refused as a second debugger.
    fn refuse_others(&mut self) {
        if self.listener.set_nonblocking(true).is_err() {
            return;
        }
        while let Ok((stream, _)) = self.listener.accept() {
            let closed = self.connection.as_mut().is_some_and(Connection::closed);
            if closed && self.next.is_none() {
                self.next = Some(stream);
            }
        }
    }

    /// Holds the core where the debugger stopped it between instructions itself, and tells the
    /// debugger why.
    fn halt_core(&mut self, core: &mut Core, reason: Reason) -> io::Result<()> {
        self.halt(core, reason, Halted::By(HaltReason::Requested))
    }

    /// Holds the core where it stopped for `reason`, held as `halted`, and notes the stop.
    fn hold(&mut self, core: &mut Core, reason: Reason, halted: Halted) {
        self.history.stopped();
        let changed = match halted {
            Halted::By(halt) => core.machine.cpu().debugger_halted(halt),
            Halted::Itself | Halted::AtWatchpoint => true,
        };
        self.note_stop(core, reason, halted, changed);
        self.core = Held::Halted;
        self.stopped = self.threads.stopped(core, reason);
    }

    /// Holds the core and tells the debugger why it stopped, and in which thread, with a
    /// notification in non-stop mode.
    fn halt(&mut self, core: &mut Core, reason: Reason, halted: Halted) -> io::Result<()> {
        self.hold(core, reason, halted);
        let reply = stop_reply(self.stopped, self.negotiated());
        if self.non_stop() {
            return self.tell(&reply);
        }
        self.connection()?.send(&reply)
    }

    /// What this connection's debugger said it supports.
    fn negotiated(&self) -> Negotiated {
        self.connection
            .as_ref()
            .map_or_else(Negotiated::default, |connection| connection.negotiated)
    }

    /// What `packet` asks for, with anything it changes done. A debugger that detached under
    /// `target extended-remote` is still connected, with no core to ask about until it attaches or
    /// runs again.
    fn answer(&mut self, core: &mut Core, packet: &str) -> Asked {
        let reply = |text: &str| Asked::Reply(text.to_owned());
        let (command, rest) = packet.split_at(packet.chars().next().map_or(0, char::len_utf8));
        let endian = core.machine.memory.endian();
        let negotiated = self.negotiated();
        let attached = self.attached();
        if !attached
            && !ANSWERED_DETACHED
                .iter()
                .any(|start| packet.starts_with(start))
        {
            return reply("E01");
        }
        if self.refused_running(packet) {
            return reply("E01");
        }
        match command {
            "?" if negotiated.non_stop => self.stops_again(),
            "?" => reply(&stop_reply(self.stopped, negotiated)),
            "g" => {
                let picked = self.threads.picked(core);
                reply(&registers(core, picked, endian))
            }
            // Another thread's registers are what its kernel saved, which a write wouldn't change.
            "G" | "P" if self.threads.picked(core) != Picked::Running => reply("E01"),
            "G" | "P" => self.write_registers(core, command == "G", rest),
            "p" => {
                let picked = self.threads.picked(core);
                reply(&register(core, picked, rest, endian).unwrap_or_else(|| "E01".to_owned()))
            }
            "m" => self.read(core, rest),
            "M" | "X" => self.write(core, command == "M", rest),
            "c" | "s" => self.resume_at(core, rest, command == "s"),
            // A signal to deliver, which the core has nowhere to put, then the address.
            "C" | "S" => self.resume_at(
                core,
                rest.split_once(';').map_or("", |(_, address)| address),
                command == "S",
            ),
            "Z" | "z" => reply(self.point(core, command == "Z", rest)),
            // `D;1` once the debugger said `multiprocess`.
            // With nothing attached, a core `vKill` held for the next `run` runs on.
            "D" if rest.is_empty() || ours(rest.strip_prefix(';')) => {
                self.release(core, Held::Running);
                if negotiated.extended {
                    reply("OK")
                } else {
                    Asked::Detach
                }
            }
            "D" => reply("E01"),
            // "Debugging with GDB" for GDB 18.1, section E.3 gives `k` no reply, so a debugger that
            // goes away leaves the run going.
            "k" => {
                self.release(core, Held::Running);
                Asked::Kill
            }
            "H" => reply(self.threads.select(core, rest)),
            "T" => reply(self.threads.alive(core, rest)),
            "!" => {
                if let Some(connection) = self.connection.as_mut() {
                    connection.negotiated.extended = true;
                }
                reply("OK")
            }
            "v" if rest == "Run" || rest.starts_with("Run;") => {
                self.note(core, Input::Reset, history::reset);
                self.disarm(core);
                self.take_core(core);
                reply(&stop_reply(self.stopped, negotiated))
            }
            // In non-stop mode GDB takes the core as running once it's attached, and stops it
            // itself, so it's stopped here as `vCont;t` stops it, which tells GDB with a
            // notification after the `OK`.
            "v" if ours(rest.strip_prefix("Attach;")) && negotiated.non_stop => {
                self.take_core(core);
                self.core = Held::Running;
                Asked::Stop(Reason::Halt)
            }
            "v" if ours(rest.strip_prefix("Attach;")) => {
                self.take_core(core);
                reply(&stop_reply(self.stopped, negotiated))
            }
            "v" if rest.starts_with("Attach;") => reply("E01"),
            // A debugger that doesn't say `multiprocess` names a process of its own making. Under
            // `target extended-remote` the core stays held for the next `run`.
            "v" if rest.starts_with("Kill;")
                && (!negotiated.multiprocess || ours(rest.strip_prefix("Kill;"))) =>
            {
                if attached {
                    let then = if negotiated.extended {
                        Held::Halted
                    } else {
                        Held::Running
                    };
                    self.release(core, then);
                }
                reply("OK")
            }
            "v" if rest.starts_with("Kill;") => reply("E01"),
            "v" if rest.starts_with("Flash") => {
                self.threads.forget();
                reply(self.flash(core, rest))
            }
            "v" if rest == "Stopped" => self.told(),
            "b" if (rest == "s" || rest == "c") && Self::reverses(core) => {
                self.threads.forget();
                let went = if rest == "s" {
                    self.step_back(core)
                } else {
                    self.continue_back(core)
                };
                match went {
                    Ok(_) => Asked::Back,
                    Err(_) => reply("E01"),
                }
            }
            "v" if rest == "CtrlC" => Asked::Stop(Reason::Interrupt),
            "v" => vee(rest),
            "q" => self.query(core, rest),
            "Q" if rest == "NonStop:1" || rest == "NonStop:0" => {
                self.set_non_stop(core, rest == "NonStop:1")
            }
            "Q" => self.general_set(rest),
            _ => reply(""),
        }
    }

    /// `m`. A read while the core runs is a peek, whatever `monitor peek` says, and a firmware's
    /// read of anything but the memory the core maps is something the run hears, which the history
    /// keeps.
    fn read(&mut self, core: &mut Core, rest: &str) -> Asked {
        let reads = if self.core == Held::Halted {
            self.reads
        } else {
            Reads::Peeks
        };
        let heard = span(rest)
            .map(|(address, length)| (address, length.min(PACKET_SIZE as u64 / 2)))
            .filter(|&(address, length)| {
                reads == Reads::Firmware
                    && !(address..address + length).all(|at| core.machine.mapped_byte(at))
            });
        let read = match heard {
            Some((address, length)) => {
                let input = Input::Read { address, length };
                self.note(core, input, |core| read_memory(core, rest, reads))
            }
            None => read_memory(core, rest, reads),
        };
        Asked::Reply(read.unwrap_or_else(|| "E01".to_owned()))
    }

    /// `M`, or `X` when it isn't `hex`. A write may change a kernel's lists, so they're walked
    /// again.
    fn write(&mut self, core: &mut Core, hex: bool, rest: &str) -> Asked {
        self.threads.forget();
        let write = if hex {
            hex_write(rest)
        } else {
            binary_write(rest)
        };
        let Some((address, bytes)) = write else {
            return Asked::Reply("E01".to_owned());
        };
        let input = Input::Write {
            address,
            bytes: bytes.clone(),
        };
        let written = self.note(core, input, |core| core.debugger_write(address, &bytes));
        Asked::Reply(if written { "OK" } else { "E01" }.to_owned())
    }

    /// `G`, every register, or `P`, one.
    fn write_registers(&mut self, core: &mut Core, every: bool, rest: &str) -> Asked {
        // A walk is handed the core's registers, so it's walked again with the new ones.
        self.threads.forget();
        let cpu = core.machine.cpu();
        if every {
            if register_values(cpu, rest).is_none() {
                return Asked::Reply("E01".to_owned());
            }
            let input = Input::Registers(rest.to_owned());
            self.note(core, input, |core| {
                set_registers(core.machine.cpu(), rest);
            });
        } else {
            let Some((number, bytes)) = register_write(cpu, rest) else {
                return Asked::Reply("E01".to_owned());
            };
            let input = Input::Register {
                number,
                bytes: bytes.clone(),
            };
            self.note(core, input, |core| {
                core.machine.cpu().set_gdb_register(number, &bytes);
            });
        }
        Asked::Reply("OK".to_owned())
    }

    /// `c`, `s`, `C` and `S`, from `address` when it's given, "Debugging with GDB" for GDB 18.1,
    /// section E.3. The program counter is written as `P` writes it, which keeps the rest of the
    /// core's state as it is.
    fn resume_at(&mut self, core: &mut Core, address: &str, step: bool) -> Asked {
        if !address.is_empty() {
            let endian = core.machine.memory.endian();
            let cpu = core.machine.cpu();
            let Some((number, bytes)) =
                hex(address)
                    .zip(pc_number(cpu.target_xml()))
                    .and_then(|(value, number)| {
                        Some((number, register_bytes(cpu, number, value, endian)?))
                    })
            else {
                return Asked::Reply("E01".to_owned());
            };
            let input = Input::Register {
                number,
                bytes: bytes.clone(),
            };
            if !self.note(core, input, |core| {
                core.machine.cpu().set_gdb_register(number, &bytes)
            }) {
                return Asked::Reply("E01".to_owned());
            }
        }
        if step { Asked::Step } else { Asked::Continue }
    }

    /// Lets the core run, or with `step` run one instruction, once what the history has here is
    /// put back. A step the history has next here is that step, and one it doesn't takes the run a
    /// new way. A run that goes on where the history stepped steps there as it did.
    fn go(&mut self, core: &mut Core, step: bool) {
        let stepped_here = self.put_back_here(core);
        if step {
            if stepped_here {
                self.history_step();
            } else {
                self.note(core, Input::Stepped, |_| ());
            }
        } else if stepped_here {
            self.history_step();
            self.history.replaying = true;
        }
        self.resume(core, step || self.history.replaying);
        self.aim(core);
    }

    /// Lets the core run, or with `step` run one instruction.
    fn resume(&mut self, core: &mut Core, step: bool) {
        self.pass_own_breakpoint(core);
        self.threads.forget();
        self.core = if step { Held::Stepping } else { Held::Running };
    }

    /// Before the core runs on from where the debugger holds it: an instruction with the
    /// debugger's own breakpoint on it runs rather than stopping the core again. The run's own
    /// watch on it still sees the core arrive first, and that stop isn't the debugger's.
    fn pass_own_breakpoint(&mut self, core: &mut Core) {
        let pc = core.machine.cpu().pc();
        self.resumed = Some((pc, core.machine.retired()));
        if self.breakpoint_at(pc).is_some() && !core.machine.watching.instructions.contains(&pc) {
            core.machine.cpu().pass_breakpoint(pc);
        }
    }

    /// The debugger lets the core go, by `D`, `k` or `vKill`: its breakpoints and watchpoints come
    /// out, the core's halting debug goes off, and the core is `then`, held or running.
    fn release(&mut self, core: &mut Core, then: Held) {
        // A core that runs, in non-stop mode, is held first, so it's let go at a stop, as GDB
        // halts it to let it go in all-stop mode.
        if self.core != Held::Halted && self.attached() {
            self.hold(core, Reason::Halt, Halted::By(HaltReason::Requested));
        }
        self.take_points_out(core);
        self.forget_history(core);
        self.set_halting(core, false);
        self.core = then;
        if let Some(connection) = self.connection.as_mut()
            && std::mem::take(&mut connection.attached)
        {
            Self::tell_the_run(core, false);
        }
        self.hold_interrupts(core);
    }

    /// Tells the run a debugger took the core where it stands, or with `attached` false let it go.
    fn tell_the_run(core: &mut Core, attached: bool) {
        let (at, count) = (core.machine.now(), core.machine.retired());
        core.driven.debugger_attached(at, count, attached);
    }

    /// The connection closed, or failed. One that had the core went with no `D`, `k` or `vKill`:
    /// "Debugging with GDB" for GDB 18.1, section 20.1's `disconnect`, or a debugger that crashed.
    /// Its breakpoints and watchpoints come out and the core stays as it was, held or running, with
    /// its halting debug on for the next debugger, as a probe that lost its host leaves it. One
    /// that never sent a packet, a port probe, changes nothing. One that had already let the core
    /// go took its points with it then, and a core it held for its own next `run` runs on, since
    /// that `run` won't come.
    fn disconnect(&mut self, core: &mut Core) {
        let Some(connection) = self.connection.take() else {
            return;
        };
        self.forget_history(core);
        if let Some((held, halting)) = connection.unspoken {
            self.core = held;
            self.set_halting(core, halting);
        } else if connection.attached {
            self.take_points_out(core);
            Self::tell_the_run(core, false);
        } else {
            self.core = Held::Running;
        }
        // A step the debugger went in the middle of, in a file call, has nobody to hear it's done,
        // so the core runs as it would with no debugger.
        if self.core == Held::Stepping {
            self.core = Held::Running;
        }
        self.hold_interrupts(core);
    }

    /// Takes out every breakpoint, watchpoint and halt point the debugger set.
    fn take_points_out(&mut self, core: &mut Core) {
        for (address, _) in std::mem::take(&mut self.breakpoints).into_keys() {
            core.machine.cpu().remove_breakpoint(address);
        }
        core.machine.debugger_unwatch_all();
        self.disarm(core);
    }

    /// Takes the halt point out, which a reset or a new run takes with it as well.
    fn disarm(&mut self, core: &mut Core) {
        self.halt_at = None;
        self.aim(core);
    }

    /// Has the core halt at `at` the next time it runs, in place of any halt point set before.
    fn arm(&mut self, core: &mut Core, at: HaltAt) {
        self.halt_at = Some(at);
        self.aim(core);
    }

    /// The instant the core goes no further than, without coming back: the halt point's, or where
    /// the history puts something back, whichever is first.
    fn aim(&self, core: &mut Core) {
        let halt = match self.halt_at {
            Some(HaltAt::Instant(instant)) => Some(instant),
            _ => None,
        };
        let input = self.next_input(core).map(|at| at.at);
        let back = self
            .going_until(core)
            .map(|at| at.at)
            .filter(|&at| at != VirtualNanos(u64::MAX));
        core.machine.horizon = halt.into_iter().chain(input).chain(back).min();
    }

    /// Whether the core has reached the halt point, which goes once it has.
    fn reached(&mut self, core: &mut Core) -> bool {
        let reached = match self.halt_at {
            None => false,
            Some(HaltAt::Count(count)) => core.machine.retired() >= count,
            Some(HaltAt::Instant(instant)) => core.machine.now() >= instant,
        };
        if reached {
            self.disarm(core);
        }
        reached
    }

    /// Turns the core's halting debug on or off, as a probe does.
    fn set_halting(&mut self, core: &mut Core, on: bool) {
        self.halting = on;
        core.machine.cpu().attach_debugger(on);
    }
}

/// What a debugger that detached under `target extended-remote`, and has no core to ask about, may
/// send, as the start of each packet: "Debugging with GDB" for GDB 18.1, section 20.1.1's attach
/// and run, the thread list, which is empty, the end of the session, and what asks nothing of the
/// core. Anything else is `E01` until it attaches. A packet that asks nothing of the core opts in
/// with a row.
const ANSWERED_DETACHED: &[&str] = &[
    "vAttach;",
    "vRun",
    "qfThreadInfo",
    "qsThreadInfo",
    "!",
    "D",
    "k",
    "vKill;",
    "qSupported",
    "QStartNoAckMode",
    "qXfer:features:read:",
    "qXfer:memory-map:read:",
    "qSymbol:",
    "vCont?",
    "vMustReplyEmpty",
    // Each monitor command says whether it needs the core.
    "qRcmd,",
];

/// A `v` packet.
fn vee(rest: &str) -> Asked {
    if rest == "Cont?" {
        return Asked::Reply("vCont;c;C;s;S;t".to_owned());
    }
    let Some(actions) = rest.strip_prefix("Cont;") else {
        return Asked::Reply(String::new());
    };
    // The core runs whichever thread its kernel runs, so the first action is the core's, whichever
    // thread it names.
    match actions.chars().next() {
        Some('s' | 'S') => Asked::Step,
        Some('c' | 'C') => Asked::Continue,
        Some('t') => Asked::Stop(Reason::Halt),
        _ => Asked::Reply("E01".to_owned()),
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};
    use std::net::Ipv4Addr;

    use super::*;

    /// A debugger's end of a connection, which has sent nothing more and either waits or has
    /// closed.
    struct Quiet {
        closed: bool,
    }

    impl Read for Quiet {
        fn read(&mut self, _bytes: &mut [u8]) -> io::Result<usize> {
            if self.closed {
                Ok(0)
            } else {
                Err(io::Error::from(ErrorKind::WouldBlock))
            }
        }
    }

    impl Write for Quiet {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            Ok(bytes.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl Carry for Quiet {
        fn set_nonblocking(&self, _nonblocking: bool) -> io::Result<()> {
            Ok(())
        }
    }

    /// A debugger that connects while the one served has closed its end, but before the server
    /// has read that it has, as GDB does when it closes and reconnects at once, is kept and served
    /// next rather than refused. One that connects while the served one is still open is closed at
    /// once, and hears so.
    #[test]
    fn a_debugger_reconnecting_at_once_is_served_and_a_second_one_refused() {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let address = listener.local_addr().unwrap();
        let mut debugger = Debugger::listen(&listener, false, Map::default(), &[], None).unwrap();
        let served = |closed| {
            Some(Connection::new(
                Box::new(Quiet { closed }),
                (Held::Running, false),
            ))
        };
        debugger.connection = served(true);
        let again = TcpStream::connect(address).unwrap();
        debugger.refuse_others();
        let kept = debugger.connecting().expect("the one that reconnected");
        assert_eq!(kept.peer_addr().unwrap(), again.local_addr().unwrap());

        debugger.connection = served(false);
        let mut second = TcpStream::connect(address).unwrap();
        debugger.refuse_others();
        assert!(debugger.next.is_none());
        second
            .set_read_timeout(Some(Duration::from_secs(5)))
            .unwrap();
        let refused = match second.read(&mut [0]) {
            Ok(read) => read == 0,
            Err(error) => error.kind() == ErrorKind::ConnectionReset,
        };
        assert!(refused, "closed at once");
    }

    #[test]
    fn continuing_and_stepping_are_read_from_either_form() {
        assert_eq!(vee("Cont;c"), Asked::Continue);
        assert_eq!(vee("Cont;s:1;c"), Asked::Step);
        assert_eq!(vee("Cont;t:p1.-1"), Asked::Stop(Reason::Halt));
        assert_eq!(vee("Cont?"), Asked::Reply("vCont;c;C;s;S;t".to_owned()));
        assert_eq!(vee("MustReplyEmpty"), Asked::Reply(String::new()));
    }
}