rigless 0.3.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
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The `rigless` command, over any table of machines.
//!
//! `run` executes a firmware on one MCU of a machine with the emulator built in, and `svd generate`
//! turns a vendor's SVD into the register tables of an SoC. The `rigless` binary is [`main`] over
//! [`crate::machine::all`]. A board written outside this crate gets the whole command, `--link`,
//! `--gdb`, `--coverage` and the rest, from a binary of its own that hands [`main`] its own table, as
//! the guide's [running it](crate#running-it) shows. An engine spawns that binary wherever it would
//! spawn `rigless`, so a board with an edge is stepped in lockstep the same way the boards this crate
//! carries are.

use std::collections::BTreeMap;
use std::io::{self, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpListener};
use std::path::PathBuf;
use std::process::ExitCode;
#[cfg(unix)]
use std::sync::atomic::{AtomicBool, Ordering};

use anyhow::{Context, bail};
use clap::{Parser, Subcommand};

use crate::chip::uart::TcpPeer;
use crate::emulator::{KernelSymbol, KernelThread, WalkThreads};
use crate::machine::{Board, Constructor};
use crate::soc::{Endian, Width};
use crate::time::{NO_DEADLINE, VirtualNanos, parse_virtual_time};

#[derive(Parser)]
#[command(version = crate::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(Box<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)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each is a switch of `rigless run`, which clap reads into a bool"
)]
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 press Ctrl-C, which is what a debugger session wants. Its stop
    /// line then says where it was, with reason=interrupted.
    #[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 IP
    /// address, IPv6 in brackets. A port of 0 is any free port, and the run says which it got.
    /// Attach whenever you like.
    #[arg(long, value_name = "[HOST:]PORT", value_parser = parse_debugger_address)]
    gdb: Option<SocketAddr>,
    /// Hold the core before its first instruction, until the debugger continues.
    #[arg(long, requires = "gdb")]
    wait_for_debugger: bool,
    /// Serve the firmware's semihosting calls: its console is printed, its clock is virtual time,
    /// its exit ends the run with its status, and its files are the attached debugger's, or fail
    /// with none attached. Without it a call is the breakpoint it is on a part with nothing serving
    /// host calls.
    #[arg(long)]
    semihosting: bool,
    /// Stream the core's own trace at this address, as its trace protocol's packets, which a viewer
    /// for that protocol reads unchanged. An address is as `--gdb` takes it, and the run says where
    /// it listens. With nobody connected the trace goes, and the run never waits.
    #[arg(long, value_name = "[HOST:]PORT", value_parser = parse_debugger_address)]
    trace: Option<SocketAddr>,
    /// Stream the firmware's RTT terminal at this address, drained every virtual millisecond as a
    /// probe drains it, which makes room for more. An address is as `--gdb` takes it, and the run
    /// says where it listens. With nobody connected what's drained goes.
    #[arg(long, value_name = "[HOST:]PORT", value_parser = parse_debugger_address)]
    rtt: Option<SocketAddr>,
    /// Write a register coverage report here when the run ends: how much of each modeled 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>,
    /// Print everything but the line per access: the console, the outputs, the stop and the gaps
    /// the run ends with. What a firmware too big to read access by access wants.
    #[arg(long)]
    quiet: bool,
    /// 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",
            "quiet",
            "coverage",
            "host",
            "semihosting",
            "trace",
            "rtt"
        ]
    )]
    link: bool,
    /// Key every random draw the board makes by SEED, 0 when it's left out: the noise a condition puts
    /// on a chip, and which words a garbled serial line errs on. The same seed, runtime and firmware
    /// under the same steps is the same run on any host.
    #[arg(long, requires = "link", value_name = "SEED", default_value_t = 0)]
    seed: u64,
    /// Start from the snapshot at PATH, which an engine asked a target to write, rather than from
    /// reset. It has to be of the same machine, target, images, boot address and runtime, and the
    /// run carries on from the stop it was taken at, under the seed it was taken with. The emulator
    /// loads it as it stands, so only restore one you or your engine wrote.
    #[arg(long, requires = "link", conflicts_with = "seed", value_name = "PATH")]
    restore: Option<PathBuf>,
    /// 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>,
    /// Place another image in memory beside the firmware, such as the bootloader in front of it. It
    /// goes where the firmware would: an ELF file's sections where it stores them, and any other file
    /// at the ADDRESS after the @.
    #[arg(long = "image", value_name = "PATH[@ADDRESS]")]
    images: Vec<Placement>,
    /// Boot from ADDRESS instead of where the core boots on its own, such as an application linked to
    /// sit behind a bootloader, run without one. An image has to place something there.
    #[arg(long, value_name = "ADDRESS", value_parser = parse_address)]
    boot: Option<u64>,
    /// The firmware to run: an ELF file, whose sections go where it stores them, or any other file
    /// at the ADDRESS after the @. A fault names an instruction by its symbols.
    #[arg(value_name = "FIRMWARE[@ADDRESS]")]
    firmware: Placement,
}

/// A file to place, and where a file that isn't ELF goes.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Placement {
    path: PathBuf,
    at: Option<u64>,
}

impl Run {
    /// The listener `--gdb` asks for, bound, and where it listens said once it does, which for a
    /// port of 0 is the port the system picked.
    fn debugger(&self) -> anyhow::Result<Option<TcpListener>> {
        let Some(address) = self.gdb else {
            return Ok(None);
        };
        let listener = TcpListener::bind(address)
            .with_context(|| format!("listening for GDB on {address}"))?;
        let state = if self.wait_for_debugger {
            "waiting for a debugger"
        } else {
            "serving GDB"
        };
        writeln!(io::stderr(), "{state} on {}", listener.local_addr()?)?;
        Ok(Some(listener))
    }

    /// The listener an output port asks for at `address`, bound, and where it listens said once it
    /// does as `NAME on ADDRESS`.
    fn port(name: &str, address: Option<SocketAddr>) -> anyhow::Result<Option<TcpListener>> {
        let Some(address) = address else {
            return Ok(None);
        };
        let listener = TcpListener::bind(address)
            .with_context(|| format!("listening for the {name} on {address}"))?;
        writeln!(io::stderr(), "{name} on {}", listener.local_addr()?)?;
        Ok(Some(listener))
    }

    /// Every image the run places: the firmware first, then each `--image` in order.
    fn images(&self) -> anyhow::Result<Vec<crate::image::Image>> {
        std::iter::once(&self.firmware)
            .chain(&self.images)
            .map(|placement| {
                crate::image::Image::read(&placement.path, placement.at).map_err(Into::into)
            })
            .collect()
    }
}

/// Runs the command line this process was started with over `machines`, each a board by the name
/// `run --machine` takes with the function that builds it, and answers the process's exit. An error
/// is printed the way `main` returning one prints it, and fails the process.
#[must_use]
pub fn main(machines: &[(&'static str, Constructor)]) -> ExitCode {
    let done = match Cli::parse().command {
        Command::Svd {
            command: Svd::Generate { soc_directory },
        } => crate::svd::write_module(&soc_directory)
            .map(|()| None)
            .with_context(|| format!("generating {}", soc_directory.display())),
        Command::Run(run) => run_firmware(&run, machines),
    };
    match done {
        Ok(Some(code)) => ExitCode::from(code.to_le_bytes()[0]),
        Ok(None) => ExitCode::SUCCESS,
        Err(error) => {
            // Nothing else can be said if standard error is gone too.
            writeln!(io::stderr(), "Error: {error:?}").ok();
            ExitCode::FAILURE
        }
    }
}

/// 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.
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 = TcpPeer::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.
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(", ")
        ),
    }
}

/// 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)
}

/// An address, in hexadecimal after `0x` or in decimal.
fn parse_address(text: &str) -> Result<u64, String> {
    match text.strip_prefix("0x") {
        Some(digits) => u64::from_str_radix(digits, 16),
        None => text.parse(),
    }
    .map_err(|error| format!("{text} isn't an address like 0x8000: {error}"))
}

/// A file with the address after its last `@`, when what follows it is one. Otherwise the whole of it
/// is the file, so a path with an `@` of its own still names it.
impl std::str::FromStr for Placement {
    type Err = std::convert::Infallible;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let (path, at) = text
            .rsplit_once('@')
            .filter(|(path, _)| !path.is_empty())
            .and_then(|(path, address)| Some((path, Some(parse_address(address).ok()?))))
            .unwrap_or((text, None));
        Ok(Self {
            path: PathBuf::from(path),
            at,
        })
    }
}

/// 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. A host is an address, never a name, which
/// would resolve to whichever family the host prefers.
fn parse_debugger_address(text: &str) -> Result<SocketAddr, String> {
    if let Ok(port) = text.parse::<u16>() {
        return Ok(SocketAddr::from((Ipv4Addr::LOCALHOST, port)));
    }
    text.parse().map_err(|error| {
        format!("{text} is neither a port nor an address and port like 0.0.0.0:3333 or [::1]:3333: {error}")
    })
}

/// Builds the machine `run` names from `machines`, holding the board to the name the table gives it.
fn build(run: &Run, machines: &[(&'static str, Constructor)]) -> anyhow::Result<Box<dyn Board>> {
    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 board = build().with_context(|| format!("building {name}"))?;
    if board.name() != *name {
        bail!(
            "the machine built for {name} calls itself {}, and a run names a machine by what it calls itself",
            board.name()
        );
    }
    Ok(board)
}

/// Runs the firmware as `run` asks, and answers the status it ended the run with, if it did.
fn run_firmware(
    run: &Run,
    machines: &[(&'static str, Constructor)],
) -> anyhow::Result<Option<u32>> {
    if run.link {
        let restored = run
            .restore
            .as_deref()
            .map(crate::snapshot::Snapshot::read)
            .transpose()?;
        let images = run.images()?;
        let board = build(run, machines)?;
        let target = target_index(&*board, run.target.as_deref())?;
        let debugger = run.debugger()?;
        let kernels = kernels();
        let mut launch = crate::link::Launch::new(&images);
        launch.start.boot = run.boot;
        launch.start.debugger = debugger.as_ref();
        launch.start.wait_for_debugger = run.wait_for_debugger;
        launch.start.kernels = &kernels;
        launch.seed = run.seed;
        launch.restore = restored.as_ref();
        crate::link::serve(board, target, &launch, crate::link::Served::stdio())?;
        return Ok(None);
    }
    // Before anything listens, so a firmware it can't read follows no line saying it's listening.
    let images = run.images()?;
    let mut board = build(run, machines)?;
    let target = target_index(&*board, run.target.as_deref())?;
    let name = board.name();
    // Before anything says it listens, so a Ctrl-C after that line ends the run where it stands.
    #[cfg(unix)]
    catch_interrupt().context("catching Ctrl-C")?;
    attach_hosts(&mut *board, name, &run.host)?;
    let trace = Run::port("trace", run.trace)?;
    let rtt = Run::port("rtt", run.rtt)?;
    let debugger = run.debugger()?;
    let kernels = kernels();
    let mut start = crate::emulator::Start::new(&images);
    start.trace = trace.as_ref();
    start.rtt = rtt.as_ref();
    start.boot = run.boot;
    start.debugger = debugger.as_ref();
    start.wait_for_debugger = run.wait_for_debugger;
    start.semihosting = run.semihosting;
    start.kernels = &kernels;
    #[cfg(unix)]
    {
        start.interrupt = Some(&INTERRUPT);
    }
    let session = crate::session::Session::new(board, target, run.until.unwrap_or(NO_DEADLINE))?;
    let accesses = if run.quiet {
        crate::emulator::Accesses::Counted
    } else {
        crate::emulator::Accesses::Printed
    };
    let printed =
        crate::emulator::run_printed(session, &start, run.outputs, accesses, io::stdout())?;
    if let Some(path) = &run.coverage {
        std::fs::write(path, printed.coverage.to_string())
            .with_context(|| format!("writing {}", path.display()))?;
    }
    Ok(printed.exit_status)
}

/// Set by the first Ctrl-C of a run that prints, which ends it where it stands.
#[cfg(unix)]
static INTERRUPT: AtomicBool = AtomicBool::new(false);

/// Has the first Ctrl-C set [`INTERRUPT`] instead of ending the process, and a second end it as it
/// would without this, for a run that never gets back between two instructions to see it.
#[cfg(unix)]
#[expect(
    unsafe_code,
    reason = "a signal's handler is set through the C library"
)]
fn catch_interrupt() -> io::Result<()> {
    extern "C" fn interrupted(_signal: libc::c_int) {
        INTERRUPT.store(true, Ordering::Relaxed);
    }
    let handler: extern "C" fn(libc::c_int) = interrupted;
    // SAFETY: `sigaction` is plain data, and zero is a valid value of each of its fields.
    let mut action: libc::sigaction = unsafe { std::mem::zeroed() };
    action.sa_sigaction = handler as libc::sighandler_t;
    // A system call the signal lands in carries on, rather than failing with `EINTR`.
    action.sa_flags = libc::SA_RESETHAND | libc::SA_RESTART;
    // SAFETY: the mask is a field of `action`, which lives to the end of this function.
    unsafe { libc::sigemptyset(&raw mut action.sa_mask) };
    // SAFETY: the handler only stores to an atomic, which is safe in a signal handler, and the
    // action before it isn't asked for.
    if unsafe { libc::sigaction(libc::SIGINT, &raw const action, std::ptr::null_mut()) } == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// Every kernel `rigless-rtos` knows, in its order, for the debugger to show the threads of.
pub(crate) fn kernels() -> Vec<Box<dyn WalkThreads>> {
    rigless_rtos::Kernel::ALL
        .iter()
        .map(|&kernel| -> Box<dyn WalkThreads> {
            let symbols = kernel
                .symbols()
                .iter()
                .map(|symbol| KernelSymbol {
                    name: symbol.name,
                    required: symbol.required,
                })
                .collect();
            Box::new(Kernel { kernel, symbols })
        })
        .collect()
}

/// A kernel `rigless-rtos` walks, and the symbols it asks for.
#[derive(Debug)]
struct Kernel {
    kernel: rigless_rtos::Kernel,
    symbols: Vec<KernelSymbol>,
}

impl WalkThreads for Kernel {
    fn symbols(&self) -> &[KernelSymbol] {
        &self.symbols
    }

    fn walk(
        &self,
        found: &[Option<u64>],
        registers: &BTreeMap<&str, Vec<u8>>,
        endian: Endian,
        read: &mut dyn FnMut(u64, Width) -> Option<u64>,
    ) -> Option<Vec<KernelThread>> {
        let endian = match endian {
            Endian::Little => rigless_rtos::Endian::Little,
            Endian::Big => rigless_rtos::Endian::Big,
        };
        let threads = self
            .kernel
            .threads(found, registers, endian, &mut |address, bytes| {
                let width = [Width::W8, Width::W16, Width::W32, Width::W64]
                    .into_iter()
                    .find(|width| width.bytes() == u32::from(bytes))?;
                read(address, width)
            })?;
        let threads = threads.into_iter().map(|thread| KernelThread {
            id: thread.id,
            name: (!thread.name.is_empty()).then_some(thread.name),
            state: thread.state,
            saved: thread.saved,
        });
        Some(threads.collect())
    }
}

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

    #[test]
    fn a_debugger_port_alone_is_on_the_loopback_and_an_address_names_its_interface() {
        assert_eq!(
            parse_debugger_address("3333"),
            Ok(SocketAddr::from((Ipv4Addr::LOCALHOST, 3333)))
        );
        assert_eq!(
            parse_debugger_address("0.0.0.0:3333"),
            Ok(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 3333)))
        );
        assert_eq!(
            parse_debugger_address("[::1]:3333"),
            Ok(SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, 3333)))
        );
        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_seed_is_taken_only_with_link() {
        let run = |arguments: &[&str]| {
            let command = ["rigless", "run", "--machine", "a-board"];
            Cli::try_parse_from(command.iter().chain(arguments).chain(&["firmware.elf"])).map(
                |cli| match cli.command {
                    Command::Run(run) => run.seed,
                    Command::Svd { .. } => unreachable!("asked to run"),
                },
            )
        };
        assert_eq!(run(&["--link", "--seed", "7"]).unwrap(), 7);
        assert_eq!(run(&["--link"]).unwrap(), 0, "0 when it's left out");
        assert!(
            run(&["--seed", "7"]).is_err(),
            "a seed keys the link's draws"
        );
        assert!(run(&["--link", "--seed", "-1"]).is_err());
    }

    #[test]
    fn a_file_takes_the_address_after_its_last_at_sign_when_that_is_one() {
        let placed = |text: &str| text.parse::<Placement>().unwrap();
        let at = |path: &str, at| Placement {
            path: PathBuf::from(path),
            at,
        };
        assert_eq!(placed("app.bin@0x8000"), at("app.bin", Some(0x8000)));
        assert_eq!(placed("app.bin@32768"), at("app.bin", Some(0x8000)));
        assert_eq!(placed("app.elf"), at("app.elf", None));
        assert_eq!(placed("builds@2/app.elf"), at("builds@2/app.elf", None));
        assert_eq!(placed("me@host.bin@0x10"), at("me@host.bin", Some(0x10)));
        assert_eq!(placed("@0x10"), at("@0x10", None));
        assert!(parse_address("0x").is_err());
        assert!(parse_address("0x1_0000_0000_0000_0000").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)));
    }
}