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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The `rigless` command: `run` executes a firmware on one MCU of a machine with the emulator built
//! in, `svd generate` turns a vendor's SVD into the register tables of an SoC.

use std::path::PathBuf;

use anyhow::Context;
use clap::{Parser, Subcommand};
use rigless::time::VirtualNanos;

// The rest of the command is the emulator's half, and a build that has none compiles without it.
#[cfg(not(emulator_absent))]
use anyhow::bail;
#[cfg(not(emulator_absent))]
use rigless::chip::uart::Host;
#[cfg(not(emulator_absent))]
use rigless::machine::Board;
#[cfg(not(emulator_absent))]
use std::io::{self, Write};

const NANOS_PER_MICRO: u64 = 1_000;
const NANOS_PER_MILLI: u64 = 1_000_000;
const NANOS_PER_SECOND: u64 = 1_000_000_000;

/// What `--until` means when it is not given: 292 years of virtual time, which no run reaches.
///
/// The emulator's deadline is signed on its side, and a value past this one is read as no deadline
/// at all. `parse_virtual_time` refuses anything larger.
const NO_DEADLINE: VirtualNanos = VirtualNanos(i64::MAX as u64);
const UNITS: [(&str, u64); 4] = [
    ("ns", 1),
    ("us", NANOS_PER_MICRO),
    ("ms", NANOS_PER_MILLI),
    ("s", NANOS_PER_SECOND),
];

#[derive(Parser)]
#[command(version, about)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Turn a vendor's SVD into the register tables of an SoC.
    Svd {
        #[command(subcommand)]
        command: Svd,
    },
    /// Run a firmware image on one MCU of a machine and print every peripheral access.
    Run(Run),
}

#[derive(Subcommand)]
enum Svd {
    /// Regenerate `generated.rs` and `generated/` beside the one SVD file in an SoC's directory.
    Generate {
        /// The SoC's directory under `src/soc`, holding its one SVD file.
        soc_directory: PathBuf,
    },
}

#[derive(clap::Args)]
struct Run {
    /// The machine to run on, by name.
    #[arg(long)]
    machine: String,
    /// The MCU to run, on a machine that has several; a machine with one needs no name.
    #[arg(long, value_name = "MCU")]
    target: Option<String>,
    /// How much virtual time to run, with a unit: ns, us, ms, or s. Without it the run has no
    /// deadline and ends when you interrupt it, which is what a debugger session wants.
    #[arg(long, value_parser = parse_virtual_time)]
    until: Option<VirtualNanos>,
    /// Serve GDB on this TCP port. The run starts from reset; attach whenever you like.
    #[arg(long, value_name = "PORT")]
    gdb: Option<u16>,
    /// Hold the core before its first instruction, until the debugger continues.
    #[arg(long, requires = "gdb")]
    wait_for_debugger: bool,
    /// Write a register coverage report here when the run ends: how much of each modelled instance the
    /// firmware reached, and every register of one it did not. What a bench run is read for.
    #[arg(long, value_name = "PATH")]
    coverage: Option<PathBuf>,
    /// Print the board's outputs whenever one changes, read every PERIOD of virtual time, with a unit.
    #[arg(long, value_parser = parse_virtual_time, value_name = "PERIOD")]
    actuators: Option<VirtualNanos>,
    /// Be the target of an engine on stdin and stdout: reach the instants it asks for, under the
    /// signals it sends, and answer with the board's outputs. Nothing else is printed there.
    #[arg(long, conflicts_with_all = ["until", "actuators", "coverage"])]
    link: bool,
    /// Listen for the host on this wire at PORT instead of the port the board names, as WIRE=PORT;
    /// 0 is any free port, and the run says which it got.
    #[arg(long, value_name = "WIRE=PORT")]
    host: Vec<String>,
    /// The firmware image to run.
    image: PathBuf,
}

fn main() -> anyhow::Result<()> {
    match Cli::parse().command {
        Command::Svd {
            command: Svd::Generate { soc_directory },
        } => rigless::svd::write_module(&soc_directory)
            .with_context(|| format!("generating {}", soc_directory.display())),
        Command::Run(run) => run_firmware(&run),
    }
}

/// Opens a socket for every wire the board says a host may sit on, at the port the board names unless
/// `--host` names another, and says where each listens.
#[cfg(not(emulator_absent))]
fn attach_hosts(machine: &mut dyn Board, name: &str, ports: &[String]) -> anyhow::Result<()> {
    let mut chosen: Vec<(&str, u16)> = Vec::with_capacity(ports.len());
    for override_ in ports {
        let (wire, port) = override_
            .split_once('=')
            .with_context(|| format!("{override_} is not WIRE=PORT"))?;
        let port = port
            .parse()
            .with_context(|| format!("{port} is not a port"))?;
        chosen.push((wire, port));
    }
    for wire in machine.hosts() {
        let port = chosen
            .iter()
            .find(|(named, _)| *named == wire.name)
            .map_or(wire.port, |(_, port)| *port);
        let host = Host::listen(port)
            .with_context(|| format!("listening for {} on :{port}", wire.name))?;
        let port = host.port()?;
        if !machine.attach_host(wire.name, Box::new(host)) {
            bail!("{name} names no wire called {}", wire.name);
        }
        writeln!(io::stderr(), "{} on :{port}", wire.name)?;
    }
    Ok(())
}

/// The index of the target to run: the one named, or the only one.
#[cfg(not(emulator_absent))]
fn target_index(machine: &dyn Board, named: Option<&str>) -> anyhow::Result<usize> {
    let names = machine.target_names();
    match (named, &names[..]) {
        (Some(name), _) => machine.target(name).with_context(|| {
            format!(
                "{} has no MCU named {name}; it has {}",
                machine.name(),
                names.join(", ")
            )
        }),
        (None, [_only]) => Ok(0),
        (None, _) => bail!(
            "{} has the MCUs {}, so name the one to run with --target",
            machine.name(),
            names.join(", ")
        ),
    }
}

fn parse_virtual_time(text: &str) -> Result<VirtualNanos, String> {
    let (digits, scale) = UNITS
        .iter()
        .find_map(|(unit, scale)| text.strip_suffix(unit).map(|digits| (digits, *scale)))
        .ok_or_else(|| format!("{text} has no unit; use ns, us, ms, or s"))?;
    let count: u64 = digits
        .parse()
        .map_err(|error| format!("{digits} is not a whole number: {error}"))?;
    let nanos = count
        .checked_mul(scale)
        .ok_or_else(|| format!("{text} does not fit the virtual clock"))?;
    // Past this the emulator reads its deadline as none at all.
    if nanos > NO_DEADLINE.0 {
        return Err(format!(
            "{text} is longer than the virtual clock runs; the most is {} ns",
            NO_DEADLINE.0
        ));
    }
    Ok(VirtualNanos(nanos))
}

#[cfg(emulator_absent)]
fn run_firmware(_run: &Run) -> anyhow::Result<()> {
    Err(rigless::emulator::Error::NoEmulator.into())
}

#[cfg(not(emulator_absent))]
fn run_firmware(run: &Run) -> anyhow::Result<()> {
    if run.link {
        linked::run(run)
    } else {
        standalone::run(run)
    }
}

/// `rigless run` on its own: every access printed, the outputs on request, the report at the end.
#[cfg(not(emulator_absent))]
mod standalone {
    use std::fs;
    use std::io::{self, BufWriter, Write};

    use anyhow::{Context, bail};
    use rigless::coverage::Coverage;
    use rigless::edge::Actuator;
    use rigless::emulator::{Access, AccessKind, Driver, Finished, Start, Stop, StopReason};
    use rigless::machine::Board;
    use rigless::session::Session;
    use rigless::time::VirtualNanos;

    use super::{NO_DEADLINE, Run, attach_hosts, target_index};

    pub(super) fn run(run: &Run) -> anyhow::Result<()> {
        let machines = rigless::machine::all();
        let Some((name, build)) = machines.iter().find(|(name, _)| *name == run.machine) else {
            let names: Vec<&str> = machines.iter().map(|(name, _)| *name).collect();
            bail!(
                "no machine named {}; this build has {}",
                run.machine,
                names.join(", ")
            );
        };
        let mut board = build().with_context(|| format!("building {name}"))?;
        let target = target_index(&*board, run.target.as_deref())?;
        attach_hosts(&mut *board, name, &run.host)?;
        if let Some(port) = run.gdb {
            let state = if run.wait_for_debugger {
                "waiting for a debugger"
            } else {
                "serving GDB"
            };
            writeln!(io::stderr(), "{state} on :{port}")?;
        }
        let coverage = Coverage::of(board.mcu(target).expect("the index was checked"));
        // No `--until` is no deadline: the run ends when a signal ends it, which is what a person at
        // a terminal is for.
        let until = run.until.unwrap_or(NO_DEADLINE);
        let first = run.actuators.map_or(until, |period| period.min(until));
        let session = Session::new(board, target, first)?;
        let start = Start {
            firmware: &run.image,
            debugger_port: run.gdb,
            wait_for_debugger: run.wait_for_debugger,
        };
        let driver = Printing {
            output: BufWriter::new(io::stdout()),
            coverage,
            until,
            period: run.actuators,
            actuators: Vec::new(),
            failed: None,
        };
        let Finished {
            mut session,
            mut driver,
            stop,
        } = rigless::emulator::run(session, &start, driver)?;
        if let Some(error) = driver.failed.take() {
            return Err(error.into());
        }
        if let Some(error) = session.take_error() {
            return Err(error.into());
        }
        let output = &mut driver.output;
        if let Some(stop) = stop {
            writeln!(
                output,
                "stop t={} n={} reason={}",
                stop.at.0,
                stop.instruction_count,
                stop_reason(stop.reason)
            )?;
        }
        for reset in session.resets() {
            writeln!(output, "reset t={}", reset.0)?;
        }
        for (address, program_counter) in session.unmodeled() {
            writeln!(
                output,
                "unmodeled at={address:#010x} pc={program_counter:#010x}"
            )?;
        }
        for (address, seen) in session.unbacked() {
            let wrote = seen
                .written
                .map_or_else(String::new, |value| format!(" wrote={value:#010x}"));
            writeln!(
                output,
                "unbacked instance={} register={} at={address:#010x} pc={:#010x} reads={} \
                 writes={}{wrote}",
                seen.instance, seen.register, seen.program_counter, seen.reads, seen.writes
            )?;
        }
        for (instance, interrupt) in session.unrouted() {
            writeln!(output, "unrouted instance={instance} interrupt={interrupt}")?;
        }
        if let Some(path) = &run.coverage {
            fs::write(path, driver.coverage.to_string())
                .with_context(|| format!("writing {}", path.display()))?;
        }
        output.flush()?;
        Ok(())
    }

    /// Prints every access as it happens and the outputs as they change.
    struct Printing<W: Write + Send> {
        output: BufWriter<W>,
        coverage: Coverage,
        until: VirtualNanos,
        period: Option<VirtualNanos>,
        actuators: Vec<Actuator>,
        failed: Option<io::Error>,
    }

    impl<W: Write + Send> Driver<dyn Board> for Printing<W> {
        fn on_access(&mut self, access: &Access, value: u64) {
            self.coverage.saw(access);
            if self.failed.is_none() {
                self.failed = write_access(&mut self.output, access, value).err();
            }
        }

        fn on_stop(
            &mut self,
            session: &mut Session<dyn Board>,
            stop: Stop,
        ) -> Option<VirtualNanos> {
            let period = self.period?;
            let read = session.board_mut().actuators();
            if read != self.actuators {
                for actuator in &read {
                    if self.failed.is_none() {
                        self.failed = write_actuator(&mut self.output, stop.at, actuator).err();
                    }
                }
                self.actuators = read;
            }
            if stop.at >= self.until {
                return None;
            }
            Some(VirtualNanos(
                stop.at.0.saturating_add(period.0).min(self.until.0),
            ))
        }
    }

    fn write_actuator(
        output: &mut impl Write,
        at: VirtualNanos,
        actuator: &Actuator,
    ) -> io::Result<()> {
        match (actuator.pulse, actuator.command) {
            (Some(pulse), Some(command)) => writeln!(
                output,
                "actuator t={} name={} width={} period={} command={command}",
                at.0, actuator.name, pulse.width.0, pulse.period.0
            ),
            _ => writeln!(output, "actuator t={} name={} none", at.0, actuator.name),
        }
    }

    fn write_access(output: &mut impl Write, access: &Access, value: u64) -> io::Result<()> {
        let kind = match access.kind {
            AccessKind::Read => "read ",
            AccessKind::Write => "write",
        };
        writeln!(
            output,
            "{kind} t={} n={} pc={:#010x} at={:#010x} w={} v={value:#010x}",
            access.virtual_time.0,
            access.instruction_count,
            access.program_counter,
            access.address,
            access.width.bits(),
        )
    }

    fn stop_reason(reason: StopReason) -> &'static str {
        match reason {
            StopReason::Deadline => "deadline",
            StopReason::Idle => "idle",
            StopReason::Reset => "reset",
        }
    }
}

/// `rigless run --link`: an engine's target, stepped over stdin and stdout.
#[cfg(not(emulator_absent))]
mod linked {
    use std::io::{Stdin, Stdout};

    use anyhow::{Context, bail};
    use rigless::edge::Coupled;
    use rigless::emulator::{Driver, Finished, Start, Stop};
    use rigless::link::{Frame, LinkError, Output, Report, Served};
    use rigless::session::Session;
    use rigless::time::VirtualNanos;

    use super::{Run, attach_hosts, target_index};

    pub(super) fn run(run: &Run) -> anyhow::Result<()> {
        let machines = rigless::machine::coupled();
        let Some((name, build)) = machines.iter().find(|(name, _)| *name == run.machine) else {
            let names: Vec<&str> = machines.iter().map(|(name, _)| *name).collect();
            bail!(
                "no machine named {} has an edge a plant couples to; this build has {}",
                run.machine,
                names.join(", ")
            );
        };
        let mut board = build().with_context(|| format!("building {name}"))?;
        let target = target_index(&*board, run.target.as_deref())?;
        attach_hosts(&mut *board, name, &run.host)?;
        let mut served = Served::stdio();
        // The engine says where to reach first before anything runs; it has no signals yet.
        let Frame::Advance { until, signals } = served.receive()? else {
            served.report(Report::default())?;
            return Ok(());
        };
        if let Some(bytes) = signals {
            board.sense_wire(&bytes)?;
        }
        let first = until;
        let session = Session::new(board, target, first)?;
        let start = Start {
            firmware: &run.image,
            debugger_port: run.gdb,
            wait_for_debugger: run.wait_for_debugger,
        };
        let driver = Linked {
            served,
            failed: None,
        };
        let Finished {
            mut session,
            mut driver,
            ..
        } = rigless::emulator::run(session, &start, driver)?;
        if let Some(error) = driver.failed.take() {
            return Err(error.into());
        }
        if let Some(error) = session.take_error() {
            return Err(error.into());
        }
        driver.served.report(Report {
            resets: session.resets().to_vec(),
            unmodeled: count(session.unmodeled().len()),
            refused: count(session.refused().len()),
            unbacked: count(session.unbacked().len()),
            unrouted: count(session.unrouted().len()),
        })?;
        Ok(())
    }

    fn count(entries: usize) -> u64 {
        u64::try_from(entries).expect("a count fits")
    }

    /// Answers the engine at every instant it asked for, and takes its next word.
    struct Linked {
        served: Served<Stdin, Stdout>,
        failed: Option<LinkError>,
    }

    impl Driver<dyn Coupled> for Linked {
        fn on_stop(
            &mut self,
            session: &mut Session<dyn Coupled>,
            stop: Stop,
        ) -> Option<VirtualNanos> {
            let outputs = session
                .board_mut()
                .actuators()
                .into_iter()
                .map(|actuator| Output {
                    pulse: actuator.pulse,
                    command: actuator.command,
                })
                .collect();
            if let Err(error) = self.served.reached(stop, outputs) {
                self.failed = Some(error);
                return None;
            }
            match self.served.receive() {
                Ok(Frame::Advance { until, signals }) => {
                    if let Some(bytes) = signals
                        && let Err(error) = session.board_mut().sense_wire(&bytes)
                    {
                        self.failed = Some(error.into());
                        return None;
                    }
                    Some(until)
                }
                Ok(_) => None,
                Err(error) => {
                    self.failed = Some(error);
                    None
                }
            }
        }
    }
}

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

    #[test]
    fn a_duration_parses_with_each_unit_and_refuses_the_rest() {
        assert_eq!(parse_virtual_time("5ns"), Ok(VirtualNanos(5)));
        assert_eq!(parse_virtual_time("5us"), Ok(VirtualNanos(5_000)));
        assert_eq!(parse_virtual_time("5ms"), Ok(VirtualNanos(5_000_000)));
        assert_eq!(parse_virtual_time("5s"), Ok(VirtualNanos(5_000_000_000)));
        assert!(parse_virtual_time("5").is_err());
        assert!(parse_virtual_time("fives").is_err());
        assert!(parse_virtual_time("99999999999999999999s").is_err());
        assert!(
            parse_virtual_time("9223372036854775808ns").is_err(),
            "past the emulator's signed deadline"
        );
    }
}