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
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
// 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::net::{Ipv4Addr, SocketAddrV4};
use std::path::PathBuf;

use anyhow::Context;
use clap::{Parser, Subcommand};
use rigless::emulator::NO_DEADLINE;
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;

const UNITS: [(&str, u64); 4] = [
    ("ns", 1),
    ("us", NANOS_PER_MICRO),
    ("ms", NANOS_PER_MILLI),
    ("s", NANOS_PER_SECOND),
];

#[derive(Parser)]
#[command(version = rigless::version::RUNTIME, 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 at this address. A port alone is on the loopback interface, and a host is an IPv4
    /// address. The run starts from reset, so attach whenever you like.
    #[arg(long, value_name = "[HOST:]PORT", value_parser = parse_debugger_address)]
    gdb: Option<SocketAddrV4>,
    /// 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, every register of one it did not, and what it reached with no model behind
    /// it. What a bench run is read for.
    #[arg(long, value_name = "PATH")]
    coverage: Option<PathBuf>,
    /// Print each of the board's outputs when it changes, read every PERIOD of virtual time, with a
    /// unit. The period has to be above zero.
    #[arg(long, value_parser = parse_period, value_name = "PERIOD")]
    outputs: Option<VirtualNanos>,
    /// Be the target of an engine on stdin and stdout: say what the board carries, reach the instants
    /// it asks for under the signals and port bytes it sends, and answer with the board's outputs, what
    /// the firmware sent and anything the models couldn't answer. The board's ports cross the link and
    /// open no socket. Nothing else is printed there.
    #[arg(long, conflicts_with_all = ["until", "outputs", "coverage", "host"])]
    link: bool,
    /// Listen for the host on this wire at PORT instead of the port the board names, as WIRE=PORT.
    /// A PORT of 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}, only {}",
                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))
}

/// A period of virtual time, above zero: at zero the outputs would be read forever at one instant, and
/// the run would never move on.
fn parse_period(text: &str) -> Result<VirtualNanos, String> {
    let period = parse_virtual_time(text)?;
    if period.0 == 0 {
        return Err(format!(
            "{text} would read the outputs forever at one instant. Give a period above zero"
        ));
    }
    Ok(period)
}

/// Where to serve the debugger. A port alone is on the loopback interface, so serving another is
/// something the command line says, never a default. The host is IPv4 because the emulator's stub
/// takes no other.
fn parse_debugger_address(text: &str) -> Result<SocketAddrV4, String> {
    if let Ok(port) = text.parse::<u16>() {
        return Ok(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port));
    }
    text.parse().map_err(|error| {
        format!("{text} is neither a port nor an IPv4 address and port like 0.0.0.0:3333: {error}")
    })
}

#[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, Write};

    use anyhow::{Context, bail};
    use rigless::emulator::{NO_DEADLINE, Start, run_printed};
    use rigless::session::Session;

    use super::{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(address) = run.gdb {
            let state = if run.wait_for_debugger {
                "waiting for a debugger"
            } else {
                "serving GDB"
            };
            writeln!(io::stderr(), "{state} on {address}")?;
        }
        let start = Start {
            firmware: &run.image,
            debugger: run.gdb,
            wait_for_debugger: run.wait_for_debugger,
        };
        let session = Session::new(board, target, run.until.unwrap_or(NO_DEADLINE))?;
        let printed = run_printed(session, &start, run.outputs, io::stdout())?;
        if let Some(path) = &run.coverage {
            fs::write(path, printed.coverage.to_string())
                .with_context(|| format!("writing {}", path.display()))?;
        }
        Ok(())
    }
}

/// `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::emulator::{Driver, Finished, Start, Stop};
    use rigless::link::{
        Frame, Gaps, LinkError, Manifest, Reached, Report, Served, VERSION, attach_engine_ports,
        deliver, report, sent, values_of,
    };
    use rigless::machine::Board;
    use rigless::session::Session;
    use rigless::time::VirtualNanos;

    use super::{Run, 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 Some(edge) = board.edge() else {
            bail!("{name} has no edge a plant couples to, so it can't be an engine's target");
        };
        let (inputs, outputs) = (edge.fields(), edge.output_fields());
        let rest = values_of(inputs, &edge.rest_wire())?;
        let target = target_index(&*board, run.target.as_deref())?;
        let ports = attach_engine_ports(&mut *board)?;
        let manifest = Manifest {
            version: VERSION,
            machine: (*name).to_owned(),
            runtime: rigless::version::RUNTIME.to_owned(),
            inputs: inputs.to_vec(),
            rest: rest.clone(),
            outputs: outputs.to_vec(),
            ports: ports.iter().map(ToString::to_string).collect(),
        };
        let mut served = Served::stdio();
        served.open(&manifest)?;
        // The engine says where to reach first, before anything runs.
        let Frame::Advance(first) = served.receive()? else {
            served.report(Report::default())?;
            return Ok(());
        };
        let mut inputs = rest;
        deliver(&mut *board, &mut inputs, &ports, &first, VirtualNanos(0))?;
        let session = Session::new(board, target, first.until)?;
        let start = Start {
            firmware: &run.image,
            debugger: run.gdb,
            wait_for_debugger: run.wait_for_debugger,
        };
        let driver = Linked {
            served,
            inputs,
            ports,
            gaps: Gaps::default(),
            resets_told: 0,
            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(&session))?;
        Ok(())
    }

    struct Linked {
        served: Served<Stdin, Stdout>,
        inputs: Vec<i64>,
        ports: Vec<&'static str>,
        gaps: Gaps,
        resets_told: usize,
        failed: Option<LinkError>,
    }

    impl Linked {
        fn answer(
            &mut self,
            session: &mut Session<dyn Board>,
            stop: Stop,
        ) -> Result<Option<VirtualNanos>, LinkError> {
            let edge = session.board_mut().edge().ok_or_else(|| {
                LinkError::Board("lost its edge in the middle of a run".to_owned())
            })?;
            let outputs = values_of(edge.output_fields(), &edge.drive_wire())?;
            let ports = sent(session.board_mut(), &self.ports)?;
            let resets = session.resets()[self.resets_told..]
                .iter()
                .map(|reset| reset.at)
                .collect::<Vec<_>>();
            self.resets_told = session.resets().len();
            let gaps = self.gaps.fresh(session);
            self.served.reached(Reached {
                stop,
                outputs,
                ports,
                resets,
                gaps,
            })?;
            match self.served.receive()? {
                Frame::Advance(advance) => {
                    deliver(
                        session.board_mut(),
                        &mut self.inputs,
                        &self.ports,
                        &advance,
                        stop.at,
                    )?;
                    Ok(Some(advance.until))
                }
                _ => Ok(None),
            }
        }
    }

    impl Driver<dyn Board> for Linked {
        fn on_stop(
            &mut self,
            session: &mut Session<dyn Board>,
            stop: Stop,
        ) -> Option<VirtualNanos> {
            self.answer(session, stop).unwrap_or_else(|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"
        );
    }

    #[test]
    fn a_debugger_port_alone_is_on_the_loopback_and_an_address_names_its_interface() {
        assert_eq!(
            parse_debugger_address("3333"),
            Ok(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 3333))
        );
        assert_eq!(
            parse_debugger_address("0.0.0.0:3333"),
            Ok(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 3333))
        );
        assert!(
            parse_debugger_address("[::1]:3333").is_err(),
            "the emulator's stub takes no IPv6 host"
        );
        assert!(
            parse_debugger_address("localhost:3333").is_err(),
            "a name would resolve to whichever family the host prefers"
        );
        assert!(parse_debugger_address("70000").is_err());
    }

    #[test]
    fn a_period_of_zero_is_refused_since_the_run_would_never_move_on() {
        assert!(parse_period("0ns").is_err());
        assert!(parse_period("0s").is_err());
        assert_eq!(parse_period("1ns"), Ok(VirtualNanos(1)));
    }
}