rigless 0.0.5

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; a fork of QEMU is built in and executes 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
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The link between an engine and a target: one process steps a plant, the other runs a firmware,
//! and they meet once per plant step.
//!
//! The engine spawns the target, `rigless run --link`, with the target's stdin and stdout as the two
//! halves of the link, and speaks frames to it: [`Frame::Advance`] asks the target to reach an instant
//! and carries what the world does to the board from now on, as the board's own signals encoded by
//! [`Wire`]; the target answers [`Frame::Reached`] with where it stopped and the board's outputs as they
//! stand, each as its index in the board's list and its pulse; [`Frame::Shutdown`] ends the run and is
//! answered with [`Frame::Report`], what the run recorded. Strict alternation: one frame in flight,
//! ever, so there are no sequence numbers. The first `Advance` carries no signals, since no plant has
//! stepped yet; every later one does.
//!
//! A frame is a length, a kind and the fields, little-endian integers with nothing padded and nothing
//! aligned, decoded by a reader that refuses a short frame, an unknown kind, an invalid value and a
//! trailing byte alike, never a panic. Both sides are this crate, so there is no header for another
//! language and no version to negotiate: the engine pins the crate, and the binary it spawns is built
//! from the same one.
//!
//! [`Target`] is the engine's side; [`Served`] is the target's.

use std::ffi::OsStr;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Stdio};

use crate::edge::Pulse;
use crate::emulator::{Stop, StopReason};
use crate::time::VirtualNanos;

/// ceiling: the largest frame either side accepts; upgrade when a board's signals outgrow it.
const LARGEST_FRAME: usize = 1 << 20;

const KIND_ADVANCE: u8 = 1;
const KIND_REACHED: u8 = 2;
const KIND_SHUTDOWN: u8 = 3;
const KIND_REPORT: u8 = 4;

/// A value that crosses the link as bytes.
pub trait Wire: Sized {
    /// Appends the value's bytes.
    fn encode(&self, out: &mut Vec<u8>);

    /// Takes the value's bytes from the front of `bytes`.
    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError>;
}

/// Why bytes are not a value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum WireError {
    /// The frame ends before the value does.
    #[error("the frame ends after {have} of the {need} bytes a value needs")]
    Short {
        /// What is left.
        have: usize,
        /// What the value needs.
        need: usize,
    },
    /// A byte or a word names nothing.
    #[error("{value} is no {what}")]
    Invalid {
        /// What it should have been.
        what: &'static str,
        /// What it was.
        value: u64,
    },
    /// Bytes follow the last value of the frame.
    #[error("{0} bytes follow the last value of the frame")]
    Trailing(usize),
}

fn take<'a>(bytes: &mut &'a [u8], need: usize) -> Result<&'a [u8], WireError> {
    if bytes.len() < need {
        return Err(WireError::Short {
            have: bytes.len(),
            need,
        });
    }
    let (taken, rest) = bytes.split_at(need);
    *bytes = rest;
    Ok(taken)
}

macro_rules! integer_wire {
    ($($int:ty),*) => {$(
        impl Wire for $int {
            fn encode(&self, out: &mut Vec<u8>) {
                out.extend_from_slice(&self.to_le_bytes());
            }

            fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
                let taken = take(bytes, size_of::<$int>())?;
                Ok(<$int>::from_le_bytes(taken.try_into().expect("taken that many")))
            }
        }
    )*};
}

integer_wire!(u8, u16, u32, u64, i32, i64);

impl Wire for bool {
    fn encode(&self, out: &mut Vec<u8>) {
        u8::from(*self).encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        match u8::decode(bytes)? {
            0 => Ok(false),
            1 => Ok(true),
            value => Err(WireError::Invalid {
                what: "bool",
                value: u64::from(value),
            }),
        }
    }
}

impl Wire for VirtualNanos {
    fn encode(&self, out: &mut Vec<u8>) {
        self.0.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        u64::decode(bytes).map(Self)
    }
}

impl<T: Wire, const N: usize> Wire for [T; N] {
    fn encode(&self, out: &mut Vec<u8>) {
        for value in self {
            value.encode(out);
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let mut values = Vec::with_capacity(N);
        for _ in 0..N {
            values.push(T::decode(bytes)?);
        }
        Ok(values
            .try_into()
            .unwrap_or_else(|_| unreachable!("decoded N values")))
    }
}

impl<T: Wire> Wire for Option<T> {
    fn encode(&self, out: &mut Vec<u8>) {
        match self {
            None => false.encode(out),
            Some(value) => {
                true.encode(out);
                value.encode(out);
            }
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        if bool::decode(bytes)? {
            T::decode(bytes).map(Some)
        } else {
            Ok(None)
        }
    }
}

impl<T: Wire> Wire for Vec<T> {
    fn encode(&self, out: &mut Vec<u8>) {
        u32::try_from(self.len())
            .expect("fewer values than a word counts")
            .encode(out);
        for value in self {
            value.encode(out);
        }
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let count = u32::decode(bytes)?;
        let mut values = Vec::new();
        for _ in 0..count {
            values.push(T::decode(bytes)?);
        }
        Ok(values)
    }
}

impl Wire for Pulse {
    fn encode(&self, out: &mut Vec<u8>) {
        self.width.encode(out);
        self.period.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            width: Wire::decode(bytes)?,
            period: Wire::decode(bytes)?,
        })
    }
}

impl Wire for StopReason {
    fn encode(&self, out: &mut Vec<u8>) {
        let code: u8 = match self {
            Self::Deadline => 0,
            Self::Idle => 1,
            Self::Reset => 2,
        };
        code.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let code = u8::decode(bytes)?;
        Self::from_code(u32::from(code)).ok_or(WireError::Invalid {
            what: "stop reason",
            value: u64::from(code),
        })
    }
}

impl Wire for Stop {
    fn encode(&self, out: &mut Vec<u8>) {
        self.at.encode(out);
        self.instruction_count.encode(out);
        self.reason.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            at: Wire::decode(bytes)?,
            instruction_count: Wire::decode(bytes)?,
            reason: Wire::decode(bytes)?,
        })
    }
}

/// One output of the board as it stands, without its name: the engine has the names from the board's
/// edge, in the same order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Output {
    /// The pulse on the pin, or `None` while the pin is not driven or carries no pulse.
    pub pulse: Option<Pulse>,
    /// The command in thousandths of the whole, for a pulse on the board's curve.
    pub command: Option<u32>,
}

impl Wire for Output {
    fn encode(&self, out: &mut Vec<u8>) {
        self.pulse.encode(out);
        self.command.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            pulse: Wire::decode(bytes)?,
            command: Wire::decode(bytes)?,
        })
    }
}

/// What a run recorded, as the target reports it when it is shut down.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Report {
    /// The instants the firmware requested a reset, in order.
    pub resets: Vec<VirtualNanos>,
    /// How many addresses the bus refused for want of a register.
    pub unmodeled: u64,
    /// How many accesses the bus refused with the register there.
    pub refused: u64,
    /// How many registers were answered with no model behind them.
    pub unbacked: u64,
    /// How many interrupts had no line.
    pub unrouted: u64,
}

impl Wire for Report {
    fn encode(&self, out: &mut Vec<u8>) {
        self.resets.encode(out);
        self.unmodeled.encode(out);
        self.refused.encode(out);
        self.unbacked.encode(out);
        self.unrouted.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        Ok(Self {
            resets: Wire::decode(bytes)?,
            unmodeled: Wire::decode(bytes)?,
            refused: Wire::decode(bytes)?,
            unbacked: Wire::decode(bytes)?,
            unrouted: Wire::decode(bytes)?,
        })
    }
}

/// One frame of the link.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
    /// Engine to target: reach `until`, with what the world does to the board from now on, or nothing
    /// yet before the first step.
    Advance {
        /// The instant to reach.
        until: VirtualNanos,
        /// The board's signals, as [`Wire`] encodes them, or `None` before the plant's first step.
        signals: Option<Vec<u8>>,
    },
    /// Target to engine: the run reached the instant it was asked to.
    Reached {
        /// Where and why it stopped.
        stop: Stop,
        /// The board's outputs as they stand, in the board's order.
        outputs: Vec<Output>,
    },
    /// Engine to target: end the run.
    Shutdown,
    /// Target to engine: what the run recorded, and the last thing it says.
    Report(Report),
}

impl Frame {
    fn kind(&self) -> &'static str {
        match self {
            Self::Advance { .. } => "Advance",
            Self::Reached { .. } => "Reached",
            Self::Shutdown => "Shutdown",
            Self::Report(_) => "Report",
        }
    }

    /// Writes the frame whole: its length, its kind, and its fields.
    pub fn write_to(&self, output: &mut impl Write) -> io::Result<()> {
        let mut body = Vec::new();
        match self {
            Self::Advance { until, signals } => {
                KIND_ADVANCE.encode(&mut body);
                until.encode(&mut body);
                signals.encode(&mut body);
            }
            Self::Reached { stop, outputs } => {
                KIND_REACHED.encode(&mut body);
                stop.encode(&mut body);
                outputs.encode(&mut body);
            }
            Self::Shutdown => KIND_SHUTDOWN.encode(&mut body),
            Self::Report(report) => {
                KIND_REPORT.encode(&mut body);
                report.encode(&mut body);
            }
        }
        let length = u32::try_from(body.len()).expect("a frame is shorter than a word counts");
        output.write_all(&length.to_le_bytes())?;
        output.write_all(&body)?;
        output.flush()
    }

    /// Reads one frame, or says why the bytes are not one.
    pub fn read_from(input: &mut impl Read) -> Result<Self, LinkError> {
        let mut length = [0; 4];
        match input.read_exact(&mut length) {
            Ok(()) => {}
            Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => {
                return Err(LinkError::Closed);
            }
            Err(error) => return Err(LinkError::Io(error)),
        }
        let length = usize::try_from(u32::from_le_bytes(length)).expect("a word fits");
        if length > LARGEST_FRAME {
            return Err(LinkError::Wire(WireError::Invalid {
                what: "frame length",
                value: length as u64,
            }));
        }
        let mut body = vec![0; length];
        input.read_exact(&mut body)?;
        let mut bytes = &body[..];
        let frame = match u8::decode(&mut bytes)? {
            KIND_ADVANCE => Self::Advance {
                until: Wire::decode(&mut bytes)?,
                signals: Wire::decode(&mut bytes)?,
            },
            KIND_REACHED => Self::Reached {
                stop: Wire::decode(&mut bytes)?,
                outputs: Wire::decode(&mut bytes)?,
            },
            KIND_SHUTDOWN => Self::Shutdown,
            KIND_REPORT => Self::Report(Wire::decode(&mut bytes)?),
            kind => {
                return Err(LinkError::Wire(WireError::Invalid {
                    what: "frame kind",
                    value: u64::from(kind),
                }));
            }
        };
        if !bytes.is_empty() {
            return Err(LinkError::Wire(WireError::Trailing(bytes.len())));
        }
        Ok(frame)
    }
}

/// What can go wrong on the link.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum LinkError {
    /// The other side went away.
    #[error("the other side of the link closed it")]
    Closed,
    /// The pipe failed.
    #[error(transparent)]
    Io(#[from] io::Error),
    /// The bytes are not a frame.
    #[error(transparent)]
    Wire(#[from] WireError),
    /// A frame the protocol does not allow here.
    #[error("the link carried {got} where {wanted} was expected")]
    Unexpected {
        /// What came.
        got: &'static str,
        /// What the protocol allows.
        wanted: &'static str,
    },
    /// The target could not be started.
    #[error("starting {binary}: {source}", binary = binary.display())]
    Spawn {
        /// The binary.
        binary: PathBuf,
        /// Why.
        #[source]
        source: io::Error,
    },
    /// The target ended, and not well.
    #[error("the target exited with {0}")]
    Exited(ExitStatus),
}

/// The engine's side of the link: a target it spawned and speaks to.
#[derive(Debug)]
pub struct Target {
    child: Child,
    input: ChildStdout,
    output: ChildStdin,
}

impl Target {
    /// Spawns `binary` as `run --link --machine <machine> <arguments...> <firmware>`, its stdin and
    /// stdout as the link and its stderr inherited, so what it says about itself reaches the terminal.
    pub fn spawn(
        binary: &Path,
        machine: &str,
        firmware: &Path,
        arguments: &[impl AsRef<OsStr>],
    ) -> Result<Self, LinkError> {
        let mut child = Command::new(binary)
            .args(["run", "--link", "--machine", machine])
            .args(arguments)
            .arg(firmware)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .map_err(|source| LinkError::Spawn {
                binary: binary.to_path_buf(),
                source,
            })?;
        let output = child.stdin.take().expect("piped");
        let input = child.stdout.take().expect("piped");
        Ok(Self {
            child,
            input,
            output,
        })
    }

    /// Asks the target to reach `until` under `signals`, and answers where it stopped and the board's
    /// outputs as they stood.
    pub fn advance(
        &mut self,
        until: VirtualNanos,
        signals: Option<&impl Wire>,
    ) -> Result<(Stop, Vec<Output>), LinkError> {
        let signals = signals.map(|signals| {
            let mut bytes = Vec::new();
            signals.encode(&mut bytes);
            bytes
        });
        Frame::Advance { until, signals }.write_to(&mut self.output)?;
        match Frame::read_from(&mut self.input)? {
            Frame::Reached { stop, outputs } => Ok((stop, outputs)),
            other => Err(LinkError::Unexpected {
                got: other.kind(),
                wanted: "Reached",
            }),
        }
    }

    /// Ends the run and takes its report; the target exits after.
    pub fn shutdown(mut self) -> Result<Report, LinkError> {
        Frame::Shutdown.write_to(&mut self.output)?;
        let report = match Frame::read_from(&mut self.input)? {
            Frame::Report(report) => report,
            other => {
                return Err(LinkError::Unexpected {
                    got: other.kind(),
                    wanted: "Report",
                });
            }
        };
        let status = self.child.wait()?;
        if !status.success() {
            return Err(LinkError::Exited(status));
        }
        Ok(report)
    }
}

impl Drop for Target {
    fn drop(&mut self) {
        // A target whose link closes ends itself; this is for one that did not get the chance.
        if matches!(self.child.try_wait(), Ok(None)) {
            self.child.kill().ok();
            self.child.wait().ok();
        }
    }
}

/// The target's side of the link: the engine on its stdin and stdout.
#[derive(Debug)]
pub struct Served<R: Read, W: Write> {
    input: R,
    output: W,
}

impl Served<io::Stdin, io::Stdout> {
    /// The link on this process's own stdin and stdout.
    #[must_use]
    pub fn stdio() -> Self {
        Self {
            input: io::stdin(),
            output: io::stdout(),
        }
    }
}

impl<R: Read, W: Write> Served<R, W> {
    /// The link over any two streams.
    pub fn over(input: R, output: W) -> Self {
        Self { input, output }
    }

    /// The engine's next word: where to reach and under what, or that the run is over.
    pub fn receive(&mut self) -> Result<Frame, LinkError> {
        match Frame::read_from(&mut self.input)? {
            frame @ (Frame::Advance { .. } | Frame::Shutdown) => Ok(frame),
            other => Err(LinkError::Unexpected {
                got: other.kind(),
                wanted: "Advance or Shutdown",
            }),
        }
    }

    /// Tells the engine the run reached the instant it asked for.
    pub fn reached(&mut self, stop: Stop, outputs: Vec<Output>) -> Result<(), LinkError> {
        Ok(Frame::Reached { stop, outputs }.write_to(&mut self.output)?)
    }

    /// The last word: what the run recorded.
    pub fn report(&mut self, report: Report) -> Result<(), LinkError> {
        Ok(Frame::Report(report).write_to(&mut self.output)?)
    }
}

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

    fn round_trip(frame: &Frame) -> Frame {
        let mut bytes = Vec::new();
        frame.write_to(&mut bytes).unwrap();
        Frame::read_from(&mut &bytes[..]).unwrap()
    }

    #[test]
    fn every_frame_reads_back_as_it_was_written() {
        let stop = Stop {
            at: VirtualNanos(5_000_000),
            instruction_count: 1234,
            reason: StopReason::Idle,
        };
        let frames = [
            Frame::Advance {
                until: VirtualNanos(5_000_000),
                signals: None,
            },
            Frame::Advance {
                until: VirtualNanos(10_000_000),
                signals: Some(vec![1, 2, 3]),
            },
            Frame::Reached {
                stop,
                outputs: vec![
                    Output {
                        pulse: Some(Pulse {
                            width: VirtualNanos(1_500_000),
                            period: VirtualNanos(2_500_000),
                        }),
                        command: Some(500),
                    },
                    Output {
                        pulse: None,
                        command: None,
                    },
                ],
            },
            Frame::Shutdown,
            Frame::Report(Report {
                resets: vec![VirtualNanos(7)],
                unmodeled: 1,
                refused: 2,
                unbacked: 3,
                unrouted: 4,
            }),
        ];
        for frame in &frames {
            assert_eq!(&round_trip(frame), frame);
        }
    }

    #[test]
    fn a_short_frame_an_unknown_kind_and_a_trailing_byte_are_refused_and_a_closed_link_is_named() {
        assert!(matches!(
            Frame::read_from(&mut &[][..]),
            Err(LinkError::Closed)
        ));
        let short = [3u8, 0, 0, 0, KIND_ADVANCE, 1, 2];
        assert!(matches!(
            Frame::read_from(&mut &short[..]),
            Err(LinkError::Wire(WireError::Short { .. }))
        ));
        let unknown = [1u8, 0, 0, 0, 9];
        assert!(matches!(
            Frame::read_from(&mut &unknown[..]),
            Err(LinkError::Wire(WireError::Invalid {
                what: "frame kind",
                value: 9
            }))
        ));
        let trailing = [2u8, 0, 0, 0, KIND_SHUTDOWN, 0];
        assert!(matches!(
            Frame::read_from(&mut &trailing[..]),
            Err(LinkError::Wire(WireError::Trailing(1)))
        ));
    }

    #[test]
    fn the_served_side_takes_only_what_the_engine_may_send() {
        let mut bytes = Vec::new();
        Frame::Report(Report::default())
            .write_to(&mut bytes)
            .unwrap();
        let mut served = Served::over(&bytes[..], Vec::new());
        assert!(matches!(
            served.receive(),
            Err(LinkError::Unexpected { got: "Report", .. })
        ));
    }
}