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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! SEGGER RTT as a probe reads it. SEGGER's RTT documentation, kb.segger.com/RTT, says how it
//! works: a control block in RAM that starts with an ID a probe finds it by, then a descriptor for
//! each up-channel, whose write offset the target moves and whose read offset the probe moves, the
//! buffer empty when they meet. The layout is the one SEGGER's published `SEGGER_RTT.h` gives
//! `SEGGER_RTT_CB` and `SEGGER_RTT_BUFFER_UP`, with pointers as wide as the core family's data model
//! has them and 32-bit offsets.
//!
//! The block is the firmware's `_SEGGER_RTT`, or with no symbols to say where, found by its ID in
//! RAM. Only up-channel 0, the terminal, is drained. Down-channels are input to the firmware, and
//! a run takes no input that isn't in its record.
// ceiling: up-channel 0; upgrade when a firmware logs on a second channel someone reads

use std::ops::Range;

use crate::emulator::Memory;
use crate::soc::Width;
use crate::time::VirtualNanos;

/// How often a probe drains the terminal, in virtual nanoseconds: a millisecond.
pub(crate) const PERIOD: u64 = 1_000_000;

/// The drain after `at`: the next whole period, so drains land on the same instants however the run
/// got to `at`.
pub(crate) fn next_drain(at: VirtualNanos) -> VirtualNanos {
    VirtualNanos((at.0 / PERIOD + 1) * PERIOD)
}

/// The symbol the block is, and the ID it starts with, padded with NULs to `acID`'s 16 bytes.
pub(crate) const SYMBOL: &str = "_SEGGER_RTT";
const ID: &[u8; 16] = b"SEGGER RTT\0\0\0\0\0\0";

/// Where each field the probe reads is in the block, and where up-channel 0's descriptor is, which
/// follows `acID` and the two `int`s `MaxNumUpBuffers` and `MaxNumDownBuffers`.
const UP_CHANNELS: u64 = 16;
const UP: u64 = 24;

/// Where up-channel 0's descriptor keeps each field the probe reads: after its `sName` and its
/// `pBuffer`, both pointers, its `unsigned` `SizeOfBuffer`, `WrOff` and `RdOff`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Fields {
    /// The width of a pointer in the firmware.
    pointer: Width,
}

impl Fields {
    fn pointer_bytes(self) -> u64 {
        u64::from(self.pointer.bytes())
    }

    /// `pBuffer`.
    fn buffer(self) -> u64 {
        self.pointer_bytes()
    }

    /// `SizeOfBuffer`.
    fn size(self) -> u64 {
        2 * self.pointer_bytes()
    }

    /// `WrOff`.
    fn write(self) -> u64 {
        self.size() + 4
    }

    /// `RdOff`.
    fn read(self) -> u64 {
        self.size() + 8
    }
}

/// The firmware's block, and the RAM its terminal's buffer has to be in.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Rtt {
    block: Block,
    ram: Vec<Range<u64>>,
    fields: Fields,
    /// The block is found by its ID, the firmware having no symbols to say where it is.
    by_id: bool,
    /// Bytes the next drain leaves out, which the run a snapshot was taken from drained at its end.
    skip: u64,
}

/// How the block is found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Block {
    /// It's here.
    At(u64),
    /// It's somewhere in RAM, which each drain looks through for its ID until it shows up.
    // ceiling: a firmware with no symbols is looked for at every drain until its block shows up;
    // upgrade when a firmware brings its block up late enough for that to cost
    Somewhere,
    /// The firmware's symbols say it has none.
    Nowhere,
}

impl Rtt {
    /// How a firmware's block is found: at `symbol`, the firmware's `_SEGGER_RTT`, nowhere when the
    /// firmware has symbols and that isn't one, or by its ID in `ram` when it has no symbols. The
    /// firmware's pointers are `pointer` wide.
    pub(crate) fn new(
        symbol: Option<u64>,
        has_symbols: bool,
        ram: Vec<Range<u64>>,
        pointer: Width,
    ) -> Self {
        let block = match symbol {
            Some(at) => Block::At(at),
            None if has_symbols => Block::Nowhere,
            None => Block::Somewhere,
        };
        Self {
            block,
            ram,
            fields: Fields { pointer },
            by_id: block == Block::Somewhere,
            skip: 0,
        }
    }

    /// Where its ID search found the block, for a snapshot to keep, so a run started from it
    /// drains the same block rather than looking again.
    pub(crate) fn found(&self) -> Option<u64> {
        match self.block {
            Block::At(at) if self.by_id => Some(at),
            _ => None,
        }
    }

    /// How many bytes the terminal holds that no drain has taken yet, which a drain at the end of
    /// the run takes past a snapshot taken here.
    pub(crate) fn waiting(&self, memory: &mut dyn Memory) -> u64 {
        let Block::At(block) = self.block else {
            return 0;
        };
        channel(memory, block, &self.ram, self.fields).map_or(0, |channel| channel.waiting())
    }

    /// Puts back what a snapshot kept: where an ID search found the block, and how many bytes
    /// the run it was taken from drained past it at its end, which the next drain leaves out.
    pub(crate) fn put_back(&mut self, found: Option<u64>, skip: u64) {
        if self.by_id {
            self.block = found.map_or(Block::Somewhere, Block::At);
        }
        self.skip = skip;
    }

    /// Whether the firmware's symbols say it has no block, so there's never anything to drain.
    pub(crate) fn has_none(&self) -> bool {
        self.block == Block::Nowhere
    }

    /// Drains the terminal, as a probe does: the bytes from its read offset round to its write
    /// offset, with the read offset then written where the write offset is. Nothing when there's
    /// no block yet, or its ID or its descriptor doesn't check out.
    pub(crate) fn drain(&mut self, memory: &mut dyn Memory) -> Vec<u8> {
        if self.block == Block::Somewhere
            && let Some(at) = find(memory, &self.ram)
        {
            self.block = Block::At(at);
        }
        let Block::At(block) = self.block else {
            return Vec::new();
        };
        let mut bytes = terminal(memory, block, &self.ram, self.fields).unwrap_or_default();
        let skipped = bytes
            .len()
            .min(usize::try_from(self.skip).unwrap_or(usize::MAX));
        bytes.drain(..skipped);
        self.skip -= skipped as u64;
        bytes
    }
}

/// The value of `width` at `offset` past `base`, or `None` where nothing answers.
fn at(memory: &mut dyn Memory, base: u64, offset: u64, width: Width) -> Option<u64> {
    memory.read(base.checked_add(offset)?, width).ok()
}

/// Whether the block's ID is at `address`.
fn has_id(memory: &mut dyn Memory, address: u64) -> bool {
    (0..)
        .zip(ID)
        .all(|(offset, &byte)| at(memory, address, offset, Width::W8) == Some(u64::from(byte)))
}

/// The first word-aligned place in `ram` that starts with the ID.
fn find(memory: &mut dyn Memory, ram: &[Range<u64>]) -> Option<u64> {
    ram.iter()
        .flat_map(|range| (range.start..range.end).step_by(4))
        .find(|&address| has_id(memory, address))
}

/// Up-channel 0's descriptor as the block at `block` holds it.
struct Channel {
    /// Where its read offset is.
    up: u64,
    buffer: u64,
    size: u64,
    write: u64,
    read: u64,
}

impl Channel {
    /// How many bytes it holds, from its read offset round to its write offset.
    fn waiting(&self) -> u64 {
        (self.write + self.size - self.read) % self.size
    }
}

/// Up-channel 0's descriptor at the block at `block`, when it checks out. A buffer that isn't all
/// inside one of the `ram` ranges doesn't, so a descriptor the firmware hasn't set up, or has
/// spoiled, can't have the probe read anywhere else, or forever.
fn channel(
    memory: &mut dyn Memory,
    block: u64,
    ram: &[Range<u64>],
    fields: Fields,
) -> Option<Channel> {
    if !has_id(memory, block) || at(memory, block, UP_CHANNELS, Width::W32)? == 0 {
        return None;
    }
    let up = block.checked_add(UP)?;
    let word = |memory: &mut dyn Memory, offset| at(memory, up, offset, Width::W32);
    let buffer = at(memory, up, fields.buffer(), fields.pointer)?;
    let size = word(memory, fields.size())?;
    let write = word(memory, fields.write())?;
    let read = word(memory, fields.read())?;
    let end = buffer.checked_add(size)?;
    let in_ram = ram
        .iter()
        .any(|range| range.start <= buffer && end <= range.end);
    (in_ram && write < size && read < size).then_some(Channel {
        up,
        buffer,
        size,
        write,
        read,
    })
}

/// The terminal's bytes at the block at `block`, with its read offset moved past them, when its
/// descriptor checks out.
fn terminal(
    memory: &mut dyn Memory,
    block: u64,
    ram: &[Range<u64>],
    fields: Fields,
) -> Option<Vec<u8>> {
    let Channel {
        up,
        buffer,
        size,
        write,
        read,
    } = channel(memory, block, ram, fields)?;
    let (first, second) = if read <= write {
        (read..write, 0..0)
    } else {
        (read..size, 0..write)
    };
    let bytes = first
        .chain(second)
        .map(|offset| {
            at(memory, buffer, offset, Width::W8).and_then(|byte| u8::try_from(byte).ok())
        })
        .collect::<Option<Vec<u8>>>()?;
    memory.write(up + fields.read(), Width::W32, write).ok()?;
    Some(bytes)
}

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

    const RAM: Range<u64> = 0x2000_0000..0x2000_1000;
    const BLOCK: u64 = 0x2000_0100;
    const BUFFER: u64 = 0x2000_0400;
    const SIZE: u32 = 16;
    /// The descriptor of a firmware with 32-bit pointers.
    const ILP32: Fields = Fields {
        pointer: Width::W32,
    };

    /// A block at `BLOCK` with one up-channel of `SIZE` bytes holding `text` from offset `from`,
    /// round the end when it has to.
    fn laid(text: &[u8], from: u32) -> Laid {
        let mut memory = Laid::default();
        memory.bytes(BUFFER, &[b'.'; SIZE as usize]);
        for (offset, &byte) in (from..).zip(text) {
            memory.bytes(BUFFER + u64::from(offset % SIZE), &[byte]);
        }
        memory.bytes(BLOCK, ID);
        let write = (from + u32::try_from(text.len()).unwrap()) % SIZE;
        memory.word(BLOCK + UP_CHANNELS, 1);
        memory.word(BLOCK + 20, 1);
        for (offset, value) in [
            (0, 0),
            (ILP32.buffer(), u32::try_from(BUFFER).unwrap()),
            (ILP32.size(), SIZE),
            (ILP32.write(), write),
            (ILP32.read(), from),
            (20, 2),
        ] {
            memory.word(BLOCK + UP + offset, value);
        }
        memory
    }

    fn read_offset(memory: &mut Laid) -> u64 {
        memory.read(BLOCK + UP + ILP32.read(), Width::W32).unwrap()
    }

    #[test]
    fn the_control_block_is_found_by_symbol_or_by_its_id() {
        let ram: Vec<Range<u64>> = [RAM].into();
        let mut memory = laid(b"hi", 0);
        let mut by_symbol = Rtt::new(Some(BLOCK), true, ram.clone(), Width::W32);
        assert_eq!(by_symbol.drain(&mut memory), b"hi");
        let mut memory = laid(b"hi", 0);
        let mut by_id = Rtt::new(None, false, ram.clone(), Width::W32);
        assert_eq!(by_id.drain(&mut memory), b"hi");
        assert_eq!(by_id.block, Block::At(BLOCK), "found once, kept");
        let mut nowhere = Rtt::new(None, true, ram, Width::W32);
        assert!(nowhere.has_none(), "symbols without the block's");
        assert!(nowhere.drain(&mut memory).is_empty());

        let mut empty = Laid::default();
        empty.bytes(0x2000_0000, &[0; 0x1000]);
        let mut waiting = Rtt::new(None, false, [RAM].into(), Width::W32);
        assert!(waiting.drain(&mut empty).is_empty(), "not there yet");
        assert_eq!(waiting.block, Block::Somewhere);
    }

    #[test]
    fn a_drain_takes_from_rdoff_to_wroff_across_the_wrap_and_writes_rdoff_back() {
        let mut rtt = Rtt::new(Some(BLOCK), true, [RAM].into(), Width::W32);
        let mut memory = laid(b"0123456789", 3);
        assert_eq!(rtt.drain(&mut memory), b"0123456789");
        assert_eq!(read_offset(&mut memory), 13);
        assert!(rtt.drain(&mut memory).is_empty(), "nothing new");

        let mut memory = laid(b"round the end", 10);
        assert_eq!(rtt.drain(&mut memory), b"round the end", "past the wrap");
        assert_eq!(read_offset(&mut memory), 7);

        let mut spoiled = laid(b"x", 0);
        spoiled.bytes(BLOCK, b"SEGGER RTX");
        assert!(
            rtt.drain(&mut spoiled).is_empty(),
            "an ID that doesn't check out"
        );
        let mut spoiled = laid(b"x", 0);
        spoiled.word(BLOCK + UP + ILP32.write(), SIZE);
        assert!(
            rtt.drain(&mut spoiled).is_empty(),
            "an offset past the buffer"
        );
        assert_eq!(read_offset(&mut spoiled), 0, "left as it was");
    }

    /// A firmware with 64-bit pointers keeps `pBuffer` in eight bytes after an eight-byte `sName`,
    /// and its offsets after them, so the probe reads each where that layout puts it.
    #[test]
    fn a_firmware_with_64_bit_pointers_is_drained_where_its_layout_puts_each_field() {
        const LP64: Fields = Fields {
            pointer: Width::W64,
        };
        let mut memory = Laid::default();
        memory.bytes(BUFFER, b"wide");
        memory.bytes(BLOCK, ID);
        memory.word(BLOCK + UP_CHANNELS, 1);
        memory.bytes(BLOCK + UP + LP64.buffer(), &BUFFER.to_le_bytes());
        for (offset, value) in [(LP64.size(), SIZE), (LP64.write(), 4), (LP64.read(), 0)] {
            memory.word(BLOCK + UP + offset, value);
        }
        let mut rtt = Rtt::new(Some(BLOCK), true, [RAM].into(), Width::W64);
        assert_eq!(rtt.drain(&mut memory), b"wide");
        assert_eq!(memory.read(BLOCK + UP + 24, Width::W32), Some(4), "RdOff");
    }

    /// A buffer that isn't all in one RAM range doesn't check out, however big its descriptor says
    /// it is, and its read offset stays where it was.
    #[test]
    fn a_buffer_outside_ram_is_never_read() {
        let mut rtt = Rtt::new(Some(BLOCK), true, [RAM].into(), Width::W32);
        let mut huge = laid(b"x", 0);
        for (offset, value) in [
            (ILP32.size(), u32::MAX),
            (ILP32.write(), 0xFFFF_FFF0),
            (ILP32.read(), 0),
        ] {
            huge.word(BLOCK + UP + offset, value);
        }
        assert!(rtt.drain(&mut huge).is_empty(), "a buffer of 4 GiB");
        assert_eq!(read_offset(&mut huge), 0);

        // Memory answers past RAM's end here, as another region's would.
        let mut past = laid(b"x", 0);
        let near_the_end = u32::try_from(RAM.end).unwrap() - SIZE / 2;
        past.bytes(u64::from(near_the_end), &[b'x'; SIZE as usize]);
        past.word(BLOCK + UP + ILP32.buffer(), near_the_end);
        assert!(rtt.drain(&mut past).is_empty(), "running past RAM's end");
        assert_eq!(read_offset(&mut past), 0);
    }
}