rigless 0.0.6

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 fork of QEMU built in to execute the instructions
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The target's side of a link beyond its frames: a port whose far end is the engine, what an
//! `Advance` hands the board, which gaps the engine hasn't been told yet, and the run's report.

use std::any::Any;
use std::collections::{BTreeMap, BTreeSet, VecDeque};

use super::{Advance, Gap, LinkError, Report, bytes_of};
use crate::chip::uart;
use crate::device::DeviceContext;
use crate::emulator::NO_DEADLINE;
use crate::machine::Board;
use crate::session::{Session, Unimplemented, Unmapped};
use crate::soc::Fault;
use crate::time::VirtualNanos;

/// A serial port whose far end is the engine. What the engine delivered waits here for the controller to
/// take, and what the firmware sent waits for the next `Reached`. A word wider than a byte crosses as its
/// low byte, as it does to a host on a socket.
#[derive(Debug, Default)]
pub struct EnginePort {
    toward_firmware: VecDeque<u8>,
    from_firmware: Vec<u8>,
}

impl EnginePort {
    /// Queues `bytes` for the controller to take, after anything still waiting.
    pub fn deliver(&mut self, bytes: &[u8]) {
        self.toward_firmware.extend(bytes);
    }

    /// What the firmware sent since the last call.
    pub fn take_sent(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.from_firmware)
    }
}

impl uart::Peer for EnginePort {
    fn receive(&mut self, word: u16, _context: &DeviceContext<'_>) {
        self.from_firmware.push(word.to_le_bytes()[0]);
    }

    fn transmit(&mut self, _now: VirtualNanos) -> Option<u16> {
        self.toward_firmware.pop_front().map(u16::from)
    }
}

/// The engine's port on the wire called `name`, or why there isn't one.
fn engine_port<'a>(board: &'a mut dyn Board, name: &str) -> Result<&'a mut EnginePort, LinkError> {
    let peer: &mut dyn Any = board.host_mut(name).ok_or_else(|| {
        LinkError::Misfit(format!("names a port {name} the board has no host on"))
    })?;
    peer.downcast_mut::<EnginePort>().ok_or_else(|| {
        LinkError::Misfit(format!(
            "names a port {name} whose far end isn't the engine"
        ))
    })
}

/// Hangs a port whose far end is the engine on every wire of the board a host may sit on, and answers
/// their names in the board's order. A board that won't take one, or won't hand it back, is refused here,
/// before `Manifest`, since the engine couldn't reach that port once the run started.
pub fn attach_engine_ports(board: &mut dyn Board) -> Result<Vec<&'static str>, LinkError> {
    let ports: Vec<&'static str> = board.hosts().into_iter().map(|wire| wire.name).collect();
    for &port in &ports {
        if !board.attach_host(port, Box::new(EnginePort::default())) {
            return Err(LinkError::Board(format!(
                "names a port {port} it won't take"
            )));
        }
        let handed_back = board.host_mut(port).is_some_and(|peer| {
            let peer: &dyn Any = peer;
            peer.is::<EnginePort>()
        });
        if !handed_back {
            return Err(LinkError::Board(format!(
                "takes a port on {port} and doesn't hand it back from host_mut"
            )));
        }
    }
    Ok(ports)
}

/// Hands the board what `advance` carries: the inputs it changes, sensed whole, and each port's bytes to
/// that port's queue. `inputs` holds every input's value as it stands, `ports` names the ports in the
/// order `Manifest` gave them, and `now` is the instant the run stands at.
///
/// An instant the run can't reach from `now` is refused, since the run would never answer it: one behind
/// `now`, or one the virtual clock never gets to.
pub fn deliver(
    board: &mut dyn Board,
    inputs: &mut [i64],
    ports: &[&str],
    advance: &Advance,
    now: VirtualNanos,
) -> Result<(), LinkError> {
    if advance.until >= NO_DEADLINE {
        return Err(LinkError::Misfit(format!(
            "asked to reach {} ns, and the virtual clock stops short of {} ns",
            advance.until.0, NO_DEADLINE.0
        )));
    }
    if advance.until < now {
        return Err(LinkError::Misfit(format!(
            "asked to reach {} ns when the run already stands at {} ns",
            advance.until.0, now.0
        )));
    }
    if advance.ports.len() != ports.len() {
        return Err(LinkError::Misfit(format!(
            "sent bytes for {} ports and the board has {}",
            advance.ports.len(),
            ports.len()
        )));
    }
    for set in &advance.inputs {
        let count = inputs.len();
        let input = inputs.get_mut(usize::from(set.input)).ok_or_else(|| {
            LinkError::Misfit(format!("set input {} and the board has {count}", set.input))
        })?;
        *input = set.value;
    }
    if !advance.inputs.is_empty() {
        let edge = board
            .edge()
            .ok_or_else(|| LinkError::Board("has no edge to sense the inputs on".to_owned()))?;
        edge.sense_wire(&bytes_of(edge.fields(), inputs)?)?;
    }
    for (name, bytes) in ports.iter().zip(&advance.ports) {
        if !bytes.is_empty() {
            engine_port(board, name)?.deliver(bytes);
        }
    }
    Ok(())
}

/// What the firmware sent on each of `ports` since the last call, in their order.
pub fn sent(board: &mut dyn Board, ports: &[&str]) -> Result<Vec<Vec<u8>>, LinkError> {
    ports
        .iter()
        .map(|name| Ok(engine_port(board, name)?.take_sent()))
        .collect()
}

/// The gaps already told, so each is told once, the first time the run meets it.
#[derive(Debug, Default)]
pub struct Gaps {
    unmapped: BTreeSet<u64>,
    refused: BTreeSet<u64>,
    unimplemented: BTreeSet<u64>,
    unrouted: BTreeSet<(&'static str, u16)>,
}

impl Gaps {
    /// Every gap `session` holds that hasn't been told yet.
    pub fn fresh<D: Board + ?Sized>(&mut self, session: &Session<D>) -> Vec<Gap> {
        self.fresh_in(
            &session.unmapped(),
            session.refused(),
            session.unimplemented(),
            session.unrouted(),
        )
    }

    fn fresh_in(
        &mut self,
        unmapped: &[Unmapped],
        refused: &BTreeMap<u64, Fault>,
        unimplemented: &BTreeMap<u64, Unimplemented>,
        unrouted: &BTreeSet<(&'static str, u16)>,
    ) -> Vec<Gap> {
        let mut gaps = Vec::new();
        for entry in unmapped {
            if self.unmapped.insert(entry.address) {
                gaps.push(Gap::Unmapped {
                    address: entry.address,
                    program_counter: entry.program_counter,
                });
            }
        }
        // A shut gate is the part saying no, as the silicon does, so it's the model and not a gap.
        let outstanding = refused.iter().filter(|(_, fault)| !fault.is_shut_gate());
        for (&address, fault) in outstanding {
            if self.refused.insert(address) {
                gaps.push(Gap::Refused {
                    address,
                    why: fault.to_string(),
                });
            }
        }
        for (&address, entry) in unimplemented {
            if self.unimplemented.insert(address) {
                gaps.push(Gap::Unimplemented {
                    instance: entry.instance.to_owned(),
                    register: entry.register.to_owned(),
                    address,
                    program_counter: entry.program_counter,
                });
            }
        }
        for &(instance, line) in unrouted {
            if self.unrouted.insert((instance, line)) {
                gaps.push(Gap::Unrouted {
                    instance: instance.to_owned(),
                    line,
                });
            }
        }
        gaps
    }
}

/// What the run recorded, as `Report` carries it: every reset, and how many of each kind of gap the run
/// met. A shut gate is told nowhere, so it's counted nowhere.
#[must_use]
pub fn report<D: Board + ?Sized>(session: &Session<D>) -> Report {
    let count = |entries: usize| u64::try_from(entries).expect("a count fits");
    Report {
        resets: session.resets().iter().map(|reset| reset.at).collect(),
        unmapped: count(session.unmapped().len()),
        refused: count(
            session
                .refused()
                .values()
                .filter(|fault| !fault.is_shut_gate())
                .count(),
        ),
        unimplemented: count(session.unimplemented().len()),
        unrouted: count(session.unrouted().len()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chip::uart::Peer;
    use crate::machine::{HostWire, Target};
    use crate::mcu::Mcu;
    use crate::soc::Gate;

    /// A board with one wire a host sits on, which gives the host back only if it `hands_back`.
    #[derive(Debug)]
    struct Wired {
        peer: Option<Box<dyn Peer>>,
        hands_back: bool,
    }

    impl Wired {
        fn handing_back(hands_back: bool) -> Self {
            Self {
                peer: None,
                hands_back,
            }
        }
    }

    impl Board for Wired {
        fn name(&self) -> &'static str {
            "wired"
        }

        fn targets(&mut self) -> Vec<Target<'_>> {
            Vec::new()
        }

        fn target_names(&self) -> Vec<&'static str> {
            Vec::new()
        }

        fn mcu(&mut self, _target: usize) -> Option<&mut dyn Mcu> {
            None
        }

        fn hosts(&self) -> Vec<HostWire> {
            vec![HostWire {
                name: "wire1",
                port: 0,
            }]
        }

        fn attach_host(&mut self, name: &str, peer: Box<dyn Peer>) -> bool {
            self.peer = Some(peer);
            name == "wire1"
        }

        fn host_mut(&mut self, name: &str) -> Option<&mut dyn Peer> {
            match &mut self.peer {
                Some(peer) if self.hands_back && name == "wire1" => Some(peer.as_mut()),
                _ => None,
            }
        }
    }

    fn quiet(until: u64) -> Advance {
        Advance {
            until: VirtualNanos(until),
            inputs: Vec::new(),
            ports: vec![Vec::new()],
        }
    }

    #[test]
    fn a_board_that_does_not_hand_its_port_back_is_refused_before_the_manifest() {
        let mut board = Wired::handing_back(true);
        assert_eq!(attach_engine_ports(&mut board).unwrap(), ["wire1"]);
        let mut board = Wired::handing_back(false);
        assert!(matches!(
            attach_engine_ports(&mut board),
            Err(LinkError::Board(why)) if why.contains("wire1")
        ));
    }

    #[test]
    fn an_instant_behind_the_run_or_past_the_clock_is_refused_and_the_one_it_stands_at_is_not() {
        let mut board = Wired::handing_back(true);
        let ports = attach_engine_ports(&mut board).unwrap();
        let now = VirtualNanos(10);
        let mut deliver_at = |until| deliver(&mut board, &mut [], &ports, &quiet(until), now);
        assert!(matches!(deliver_at(9), Err(LinkError::Misfit(_))));
        assert!(matches!(
            deliver_at(NO_DEADLINE.0),
            Err(LinkError::Misfit(_))
        ));
        assert!(matches!(deliver_at(u64::MAX), Err(LinkError::Misfit(_))));
        assert!(
            deliver_at(10).is_ok(),
            "a step of no length is still a step"
        );
        assert!(deliver_at(NO_DEADLINE.0 - 1).is_ok());
    }

    #[test]
    fn an_engine_port_hands_the_controller_its_bytes_in_order_and_keeps_what_the_firmware_sent() {
        let mut port = EnginePort::default();
        port.deliver(b"ab");
        port.deliver(b"c");
        let taken: Vec<Option<u16>> = (0..4).map(|_| port.transmit(VirtualNanos(0))).collect();
        assert_eq!(
            taken,
            [
                Some(u16::from(b'a')),
                Some(u16::from(b'b')),
                Some(u16::from(b'c')),
                None
            ]
        );
        port.from_firmware.extend([1, 2]);
        assert_eq!(port.take_sent(), [1, 2]);
        assert!(port.take_sent().is_empty(), "each byte is told once");
    }

    #[test]
    fn each_gap_is_told_once_the_first_time_it_is_met_and_a_shut_gate_is_none() {
        let mut gaps = Gaps::default();
        let unmapped = [Unmapped {
            address: 0x1000,
            program_counter: 0x20,
        }];
        let refused = BTreeMap::from([
            (0x2000, Fault::Unmapped { address: 0x2000 }),
            (
                0x2400,
                Fault::Gated {
                    instance: "TIMER",
                    register: "CONTROL",
                    by: Gate {
                        instance: "CLOCKS",
                        register: "ENABLE",
                        field: "TIMEREN",
                    },
                },
            ),
        ]);
        let unimplemented = BTreeMap::from([(
            0x3000,
            Unimplemented {
                instance: "TIMER",
                register: "CONTROL",
                program_counter: 0x30,
                reads: 1,
                writes: 0,
                written: None,
            },
        )]);
        let unrouted = BTreeSet::from([("TIMER", 7)]);
        let first = gaps.fresh_in(&unmapped, &refused, &unimplemented, &unrouted);
        assert_eq!(
            first,
            [
                Gap::Unmapped {
                    address: 0x1000,
                    program_counter: 0x20
                },
                Gap::Refused {
                    address: 0x2000,
                    why: "no register at 0x2000".to_owned()
                },
                Gap::Unimplemented {
                    instance: "TIMER".to_owned(),
                    register: "CONTROL".to_owned(),
                    address: 0x3000,
                    program_counter: 0x30
                },
                Gap::Unrouted {
                    instance: "TIMER".to_owned(),
                    line: 7
                },
            ]
        );
        assert!(
            gaps.fresh_in(&unmapped, &refused, &unimplemented, &unrouted)
                .is_empty(),
            "nothing new the second time"
        );
    }
}