rigless 0.2.2

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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Threads as GDB sees them, and the stop replies that name one. "Debugging with GDB" for GDB 18.1,
//! section E.3 gives a thread-id's two forms: `p<pid>.<tid>` once the debugger and the server both
//! said `multiprocess`, and `<tid>` before.
//!
//! With no kernel the run was handed, the core is the one thread, `p1.1`, in the one process. Once
//! GDB has looked up a kernel's symbols for the server with `qSymbol`, section E.5, each of the
//! kernel's threads is one GDB sees, by the id its walk gives it. The one that runs has the core's
//! registers, and every other one the registers its kernel saved when it switched away from it,
//! which GDB can read and can't write. The server walks the kernel's threads once a stop, when
//! something first asks, through peeks, so a debugger that looks at threads leaves the run the
//! same run. `p1.1` stays the thread that runs, for a debugger that picked it before it knew of the
//! kernel.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::num::NonZeroU64;

use super::super::Core;
use super::memory::peek;
use super::packet::{Negotiated, from_hex, hex, to_hex};
use super::points::{Breakpoint, Watchpoint};
use super::registers::named;
use crate::emulator::{KernelThread, WalkThreads};

/// The one process a server has.
pub(super) const PROCESS: u64 = 1;

/// Whether `process`, in hex, is the server's one process.
pub(super) fn ours(process: Option<&str>) -> bool {
    process.and_then(hex) == Some(PROCESS)
}

/// A thread as GDB names it: the core, or one of the firmware's threads, by an id that stays put
/// while it lives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ThreadId(NonZeroU64);

/// The core itself, the one thread a firmware with no kernel the server knows has.
pub(super) const CORE: ThreadId = ThreadId(NonZeroU64::MIN);

impl ThreadId {
    /// The id as this connection's debugger reads it.
    fn render(self, negotiated: Negotiated) -> String {
        if negotiated.multiprocess {
            format!("p{PROCESS:x}.{:x}", self.0)
        } else {
            format!("{:x}", self.0)
        }
    }
}

/// What a packet names, "Debugging with GDB" for GDB 18.1, section E.3's thread-id: every thread,
/// any thread, or one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Thread {
    All,
    Any,
    One(ThreadId),
}

impl Thread {
    /// The thread `text` names in either form, or `None` for text that isn't a thread-id, names
    /// another process, or names one thread of every process.
    pub(super) fn parse(text: &str) -> Option<Self> {
        let Some(process) = text.strip_prefix('p') else {
            return Self::one_of(text);
        };
        let (process, thread) = process.split_once('.').unwrap_or((process, "-1"));
        let thread = Self::one_of(thread)?;
        match (process, thread) {
            ("-1", Self::One(_)) => None,
            ("-1" | "0", _) => Some(thread),
            _ => (hex(process)? == PROCESS).then_some(thread),
        }
    }

    /// `-1`, `0` or a thread's id in hex.
    fn one_of(text: &str) -> Option<Self> {
        match text {
            "-1" => Some(Self::All),
            "0" => Some(Self::Any),
            _ => NonZeroU64::new(hex(text)?).map(|id| Self::One(ThreadId(id))),
        }
    }
}

/// Whose registers `g` and `p` read.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Picked<'a> {
    /// The thread that runs, whose registers are the core's.
    Running,
    /// A thread the kernel switched away from, and the registers it saved of it, by name.
    Switched(&'a BTreeMap<&'static str, Vec<u8>>),
    /// A thread that's gone.
    Gone,
}

/// The firmware's threads as the server knows them, and what the debugger looked up and picked.
/// Every answer that names a thread asks this.
#[derive(Debug)]
pub(super) struct Threads<'a> {
    /// The kernels the run was handed, in the order the server asks for their symbols.
    kernels: &'a [Box<dyn WalkThreads>],
    /// The address GDB gave for each symbol a kernel's walk needs, by its name.
    found: BTreeMap<&'static str, u64>,
    /// The symbol `qSymbol` asks GDB for next, as its place among every kernel's.
    asking: usize,
    /// The thread `Hg` picked, whose registers `g` and `p` read.
    picked: Thread,
    /// The kernel's threads at this stop.
    walked: Walked,
    /// The core is the one thread whatever kernel it runs, as it is in non-stop mode, since the
    /// server can't stop one of a kernel's threads and leave the rest running.
    // ceiling: a kernel's threads show in all-stop mode only; upgrade when a core can hold one
    // thread while it runs the others
    only_core: bool,
}

/// The kernel's threads at a stop, walked when something first asks.
#[derive(Debug)]
enum Walked {
    /// Nothing asked since the core last ran.
    Unasked,
    /// No kernel, or one whose walk doesn't check out, so the core is the one thread.
    Core,
    /// The kernel's threads, and the id of the one that runs.
    Kernel {
        current: NonZeroU64,
        each: Vec<KernelThread>,
    },
}

impl<'a> Threads<'a> {
    /// The threads of `kernels`, before a debugger has looked anything up.
    pub(super) fn new(kernels: &'a [Box<dyn WalkThreads>]) -> Self {
        Self {
            kernels,
            found: BTreeMap::new(),
            asking: 0,
            picked: Thread::Any,
            walked: Walked::Unasked,
            only_core: false,
        }
    }

    /// A new debugger, which has looked nothing up and picked no thread.
    pub(super) fn connected(&mut self) {
        *self = Self::new(self.kernels);
    }

    /// The core ran, or was reset, so the kernel's threads are walked again when something asks.
    pub(super) fn forget(&mut self) {
        self.walked = Walked::Unasked;
    }

    /// Has the core be the one thread, or a kernel's threads show again.
    pub(super) fn only_core(&mut self, only: bool) {
        self.only_core = only;
        self.forget();
    }

    /// The kernel's threads at this stop and the id of the one that runs, walked the first time
    /// something asks: the first kernel whose required symbols GDB found all of, if its walk checks
    /// out as [`WalkThreads::walk`] says.
    fn walk(&mut self, core: &mut Core) -> Option<(NonZeroU64, &[KernelThread])> {
        if self.only_core {
            self.walked = Walked::Core;
        }
        if matches!(self.walked, Walked::Unasked) {
            let found = &self.found;
            let kernel = self.kernels.iter().find(|kernel| {
                kernel
                    .symbols()
                    .iter()
                    .all(|symbol| !symbol.required || found.contains_key(symbol.name))
            });
            let walked = kernel.and_then(|kernel| {
                let addresses: Vec<Option<u64>> = kernel
                    .symbols()
                    .iter()
                    .map(|symbol| found.get(symbol.name).copied())
                    .collect();
                let registers = named(core.machine.cpu());
                let endian = core.machine.memory.endian();
                let each = kernel.walk(&addresses, &registers, endian, &mut |address, width| {
                    peek(core, address, width)
                })?;
                let current = running(&each)?;
                Some(Walked::Kernel { current, each })
            });
            self.walked = walked.unwrap_or(Walked::Core);
        }
        match &self.walked {
            Walked::Kernel { current, each } => Some((*current, each)),
            Walked::Unasked | Walked::Core => None,
        }
    }

    /// The thread that runs now, which a stop names.
    pub(super) fn current(&mut self, core: &mut Core) -> ThreadId {
        self.walk(core)
            .map_or(CORE, |(current, _)| ThreadId(current))
    }

    /// A stop for `reason`, in the thread that runs now.
    pub(super) fn stopped(&mut self, core: &mut Core, reason: Reason) -> Stopped {
        Stopped {
            reason,
            thread: self.current(core),
        }
    }

    /// The kernel's thread `id`.
    fn thread(&mut self, core: &mut Core, id: ThreadId) -> Option<&KernelThread> {
        let (_, each) = self.walk(core)?;
        each.iter().find(|thread| thread.id == id.0)
    }

    /// Whether a thread `thread` names is alive.
    fn has(&mut self, core: &mut Core, thread: Thread) -> bool {
        match thread {
            Thread::All | Thread::Any => true,
            Thread::One(id) => id == CORE || self.thread(core, id).is_some(),
        }
    }

    /// `H`, which picks the thread later packets act on, `c` for continuing and stepping and `g`
    /// for everything else. The core runs whichever thread the kernel runs, so `Hc` picks nothing.
    pub(super) fn select(&mut self, core: &mut Core, rest: &str) -> &'static str {
        let mut characters = rest.chars();
        let operation = characters.next();
        let Some(thread) =
            Thread::parse(characters.as_str()).filter(|&thread| self.has(core, thread))
        else {
            return "E01";
        };
        match operation {
            Some('g') => {
                self.picked = thread;
                "OK"
            }
            Some('c') => "OK",
            _ => "E01",
        }
    }

    /// `T`, whether the thread it names is alive.
    pub(super) fn alive(&mut self, core: &mut Core, rest: &str) -> &'static str {
        if Thread::parse(rest).is_some_and(|thread| self.has(core, thread)) {
            "OK"
        } else {
            "E01"
        }
    }

    /// Whose registers `g` and `p` read, for the thread `Hg` picked.
    pub(super) fn picked(&mut self, core: &mut Core) -> Picked<'_> {
        let id = match self.picked {
            Thread::One(id) if id != CORE => id,
            _ => return Picked::Running,
        };
        match self.thread(core, id) {
            None => Picked::Gone,
            Some(thread) => thread
                .saved
                .as_ref()
                .map_or(Picked::Running, Picked::Switched),
        }
    }

    /// The answer to `qC`, `qfThreadInfo` or `qsThreadInfo`, or `None` for any other query. A
    /// debugger that isn't `attached` has no threads.
    pub(super) fn query(
        &mut self,
        core: &mut Core,
        rest: &str,
        negotiated: Negotiated,
        attached: bool,
    ) -> Option<String> {
        match rest {
            "C" => Some(format!("QC{}", self.current(core).render(negotiated))),
            "fThreadInfo" if attached => {
                let ids: Vec<String> = match self.walk(core) {
                    Some((_, each)) => each
                        .iter()
                        .map(|thread| ThreadId(thread.id).render(negotiated))
                        .collect(),
                    None => vec![CORE.render(negotiated)],
                };
                Some(format!("m{}", ids.join(",")))
            }
            "fThreadInfo" | "sThreadInfo" => Some("l".to_owned()),
            _ => None,
        }
    }

    /// `qThreadExtraInfo,ID`: the kernel's name for the thread and what it's doing, in hex, or
    /// `core` for the core with no kernel. `p1.1` is the thread that runs once there's a kernel. An
    /// empty answer would tell GDB the server has no such packet, and it would ask no more.
    pub(super) fn extra_info(&mut self, core: &mut Core, id: &str) -> String {
        let Some(Thread::One(id)) = Thread::parse(id) else {
            return "E01".to_owned();
        };
        let id = if id == CORE { self.current(core) } else { id };
        match self.thread(core, id) {
            Some(KernelThread {
                name: Some(name),
                state,
                ..
            }) => to_hex(format!("{name}, {state}").as_bytes()),
            Some(thread) => to_hex(thread.state.as_bytes()),
            None if id == CORE => to_hex(b"core"),
            None => "E01".to_owned(),
        }
    }

    /// `qSymbol`, section E.5. `qSymbol::` offers to look symbols up, which starts over, and
    /// `qSymbol:VALUE:NAME` answers the one asked for, with no value when GDB doesn't know it.
    /// Each answer asks for the next symbol a kernel's walk needs, until none is left, then `OK`.
    pub(super) fn symbol(&mut self, arguments: &str) -> String {
        let kernels = self.kernels;
        let wanted = || kernels.iter().flat_map(|kernel| kernel.symbols());
        let (value, name) = arguments.split_once(':').unwrap_or((arguments, ""));
        if name.is_empty() {
            self.found.clear();
            self.asking = 0;
        } else {
            let asked = wanted().nth(self.asking);
            match asked.filter(|symbol| from_hex(name).as_deref() == Some(symbol.name.as_bytes())) {
                Some(symbol) => {
                    if let Some(address) = hex(value) {
                        self.found.insert(symbol.name, address);
                    }
                    self.asking += 1;
                }
                None => self.asking = usize::MAX,
            }
        }
        self.forget();
        match wanted().nth(self.asking) {
            Some(symbol) => format!("qSymbol:{}", to_hex(symbol.name.as_bytes())),
            None => "OK".to_owned(),
        }
    }
}

/// The id of the thread in `each` that runs, if the walk checks out: one thread has nothing saved,
/// no id repeats, and no thread its kernel switched away from has the core's id, which `p1.1` keeps
/// for the thread that runs. Otherwise an id GDB sends could name a thread the server reads as
/// another.
fn running(each: &[KernelThread]) -> Option<NonZeroU64> {
    let mut running = each.iter().filter(|thread| thread.saved.is_none());
    let current = running.next()?.id;
    let ids: BTreeSet<NonZeroU64> = each.iter().map(|thread| thread.id).collect();
    let checks_out = running.next().is_none()
        && ids.len() == each.len()
        && (current == CORE.0 || !ids.contains(&CORE.0));
    checks_out.then_some(current)
}

/// A stop, as a stop reply tells it: why the core stopped, and the thread that was running.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Stopped {
    pub(super) reason: Reason,
    pub(super) thread: ThreadId,
}

/// Why the core stopped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Reason {
    /// GDB's interrupt, signal 2, `SIGINT`.
    Interrupt,
    /// `vCont`'s `t`, which stops a thread in non-stop mode with signal 0.
    Halt,
    /// Going back reached where the history begins, `replaylog:begin`, a trap.
    Begin,
    /// A step, an attach, or a debug event the core halted on: signal 5, `SIGTRAP`.
    Trap,
    /// One of the debugger's breakpoints, `SIGTRAP` too.
    Breakpoint(Breakpoint),
    /// A watchpoint, hit at an address.
    Watch(Watchpoint, u64),
}

/// The stop reply for `stopped`, "Debugging with GDB" for GDB 18.1, section E.4: the signal, the
/// thread that stopped, and why, as this connection's debugger reads them. A breakpoint says its
/// kind only to a debugger that said it reads it.
pub(super) fn stop_reply(stopped: Stopped, negotiated: Negotiated) -> String {
    let signal = match stopped.reason {
        Reason::Interrupt => 2,
        Reason::Halt => 0,
        _ => 5,
    };
    let mut reply = format!("T{signal:02x}thread:{};", stopped.thread.render(negotiated));
    match stopped.reason {
        Reason::Watch(watchpoint, address) => {
            write!(reply, "{}:{address:x};", watchpoint.reason()).expect("a String takes it");
        }
        Reason::Breakpoint(Breakpoint::Software) if negotiated.swbreak => {
            reply.push_str("swbreak:;");
        }
        Reason::Breakpoint(Breakpoint::Hardware) if negotiated.hwbreak => {
            reply.push_str("hwbreak:;");
        }
        Reason::Begin => reply.push_str("replaylog:begin;"),
        _ => {}
    }
    reply
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::emulator::KernelSymbol;
    use crate::soc::{Endian, Width};

    /// A kernel that asks for its symbols and never finds a thread.
    #[derive(Debug)]
    struct Asks(&'static [KernelSymbol]);

    const fn required(name: &'static str) -> KernelSymbol {
        KernelSymbol {
            name,
            required: true,
        }
    }

    const FIRST: &[KernelSymbol] = &[required("first"), required("second")];
    const SECOND: &[KernelSymbol] = &[required("third"), required("fourth"), required("fifth")];

    impl WalkThreads for Asks {
        fn symbols(&self) -> &[KernelSymbol] {
            self.0
        }

        fn walk(
            &self,
            _found: &[Option<u64>],
            _registers: &BTreeMap<&str, Vec<u8>>,
            _endian: Endian,
            _read: &mut dyn FnMut(u64, Width) -> Option<u64>,
        ) -> Option<Vec<KernelThread>> {
            None
        }
    }

    /// A stop names the thread that ran when it was taken, in the form the debugger reads.
    #[test]
    fn a_stop_names_the_thread_that_was_running() {
        let stopped = Stopped {
            reason: Reason::Interrupt,
            thread: ThreadId(NonZeroU64::new(0x2000_1F00).unwrap()),
        };
        let multiprocess = Negotiated {
            multiprocess: true,
            ..Negotiated::default()
        };
        assert_eq!(stop_reply(stopped, multiprocess), "T02thread:p1.20001f00;");
        assert_eq!(
            stop_reply(stopped, Negotiated::default()),
            "T02thread:20001f00;"
        );
    }

    /// `qSymbol::` asks for each kernel's symbols in turn, an answer with no value asks for the
    /// next all the same, and once every one is asked for, or GDB answers one it wasn't asked,
    /// it's `OK`. `qSymbol::` again starts over.
    #[test]
    fn qsymbol_asks_for_each_kernels_symbols_then_answers_ok() {
        let kernels: [Box<dyn WalkThreads>; 2] = [Box::new(Asks(FIRST)), Box::new(Asks(SECOND))];
        let mut threads = Threads::new(&kernels);
        let asks = |name: &str| format!("qSymbol:{}", to_hex(name.as_bytes()));
        let wanted = ["first", "second", "third", "fourth", "fifth"];
        assert_eq!(threads.symbol(":"), asks(wanted[0]));
        for (at, name) in wanted.iter().enumerate() {
            let answer = if at % 2 == 0 {
                format!("{:x}:{}", 0x2000_0000 + at, to_hex(name.as_bytes()))
            } else {
                format!(":{}", to_hex(name.as_bytes()))
            };
            let next = wanted
                .get(at + 1)
                .map_or("OK".to_owned(), |next| asks(next));
            assert_eq!(threads.symbol(&answer), next, "{name}");
        }
        assert_eq!(threads.found.len(), wanted.len().div_ceil(2));
        assert_eq!(threads.found.get("first"), Some(&0x2000_0000));
        assert_eq!(threads.symbol(":"), asks(wanted[0]));
        assert!(threads.found.is_empty());
        let stranger = format!("8:{}", to_hex(b"main"));
        assert_eq!(threads.symbol(&stranger), "OK");
    }

    /// Both forms of a thread-id read back, and one that names another process, or one thread of
    /// every process, isn't one.
    #[test]
    fn a_thread_id_is_read_in_either_form() {
        let core = Some(Thread::One(CORE));
        for text in ["1", "p1.1", "p0.1"] {
            assert_eq!(Thread::parse(text), core, "{text}");
        }
        for (text, thread) in [
            ("-1", Thread::All),
            ("0", Thread::Any),
            ("p1", Thread::All),
            ("p1.-1", Thread::All),
            ("p-1", Thread::All),
            ("p1.0", Thread::Any),
        ] {
            assert_eq!(Thread::parse(text), Some(thread), "{text}");
        }
        for text in ["p2.1", "p-1.1", "", "p", "x", "p1.", "p1.x"] {
            assert_eq!(Thread::parse(text), None, "{text}");
        }
        assert_eq!(
            Thread::parse("2"),
            Some(Thread::One(ThreadId(NonZeroU64::new(2).unwrap())))
        );
    }
}