rpi-loader 0.5.0

Host-side CLI for the rpi-loader UART command agent — upload firmware to a Raspberry Pi over serial and read/write its SD card, without touching the card
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! Host-side driver for rpi-loader: a small on-device agent reached over
//! UART. The loader stays resident and services commands, so this is a
//! subcommand CLI rather than a one-shot uploader — the Pi is
//! power-cycled only to re-flash the loader itself, not between commands.
//!
//! The handshake and terminal always run at [`BASE_BAUD`]; the bulk
//! transfers (`mem-write`, `sd-read`, `sd-write`) optionally negotiate a
//! faster rate (`--baud`) and always drop back before returning, so the
//! next invocation can handshake at the rate the loader is left listening
//! on. The wire protocol itself is documented in [`link`].

mod bundle;
mod link;

use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use anyhow::{anyhow, Context, Result};
use clap::{CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use serialport::{SerialPortInfo, SerialPortType};

use link::{Link, BASE_BAUD, DEFAULT_BAUD};

/// Exit status for a Ctrl-C, matching the shell convention of 128 plus
/// the signal number.
const EXIT_INTERRUPTED: u8 = 130;

/// The 7-bit I2C address the HAT specification assigns the ID EEPROM, as
/// the text `--help` shows and [`parse_i2c_address`] parses.
const HAT_EEPROM_ADDRESS: &str = "0x50";

/// Page size assumed when programming an EEPROM. 32 bytes is the page of
/// a 24C32 — the smallest part the HAT specification allows — and every
/// larger part's page is a multiple of it, so a 32-byte write never
/// crosses a page boundary whatever is fitted.
const DEFAULT_PAGE_SIZE: u32 = 32;

/// Header the HAT specification puts at the start of an ID EEPROM image:
/// `"R-Pi"`, a format version and a reserved byte, the atom count, then
/// the image length. Only the signature and that length are read here —
/// enough for `eeprom-read` to work out how much to read.
const HAT_HEADER_LEN: u32 = 12;
/// Magic the header starts with.
const HAT_SIGNATURE: &[u8; 4] = b"R-Pi";
/// Where the image length sits within the header.
const HAT_EEPLEN_AT: usize = 8;
/// Ceiling on an image length taken from the header, matching what the
/// device's two-byte addressing can reach — a corrupt header should be an
/// error, not a request to read 4 GiB one chunk at a time.
const HAT_MAX_IMAGE: u32 = 0x1_0000;

/// Upload firmware to a Raspberry Pi over serial, and read or write its
/// SD card, without touching the card itself.
#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    // `global` so it is accepted on either side of the subcommand:
    // `rpi-loader --device /dev/ttyUSB0 boot img` and
    // `rpi-loader boot img --device /dev/ttyUSB0` are the same command.
    // clap forbids `required` on a global argument, so it is an option
    // here and `run` rejects a missing one itself. Doc comments on these
    // fields are what `--help` prints, so this note stays a plain
    // comment.
    /// Serial device the loader is attached to (e.g. /dev/ttyUSB0).
    #[arg(short, long, global = true, value_name = "DEVICE")]
    device: Option<String>,

    /// What to ask the loader to do.
    #[command(subcommand)]
    command: Command,
}

/// The subcommands, one per loader operation.
#[derive(Subcommand)]
enum Command {
    /// Upload an image to memory, jump to it, then act as a terminal.
    Boot {
        /// Kernel image to upload.
        image: PathBuf,
        /// Load address: 0x8000 for a 32-bit kernel7.img or kernel.img,
        /// 0x80000 for a 64-bit kernel8.img.
        #[arg(long, value_parser = parse_u32)]
        load_addr: u32,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Write a file to a memory address (no jump).
    MemWrite {
        /// Destination address (e.g. 0x8000).
        #[arg(value_parser = parse_u32)]
        addr: u32,
        /// File to write.
        file: PathBuf,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Jump to an address already loaded in memory.
    Exec {
        /// Address to jump to (e.g. 0x8000).
        #[arg(value_parser = parse_u32)]
        addr: u32,
        /// Stay attached as a passthrough terminal after jumping.
        #[arg(long)]
        terminal: bool,
    },

    /// List a directory on the SD card's FAT boot partition.
    SdList {
        /// Directory path (default /).
        #[arg(default_value = "/")]
        path: String,
    },

    /// Copy a file off the SD card.
    SdRead {
        /// Path on the SD card (e.g. /config.txt).
        remote: String,
        /// Local file to write.
        local: PathBuf,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Copy a local file onto the SD card, creating or truncating it.
    SdWrite {
        /// Local file to read.
        local: PathBuf,
        /// Path on the SD card (e.g. /TEST.BIN).
        remote: String,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Delete a file from the SD card.
    SdDelete {
        /// Path on the SD card (e.g. /TEST.BIN).
        remote: String,
    },

    /// Create a directory on the SD card (a single level).
    SdMkdir {
        /// Directory path on the SD card (e.g. /LOGS).
        remote: String,
    },

    /// Copy an EEPROM's contents off the HAT ID bus (GPIO0/1) into a file.
    EepromRead {
        /// Local file to write.
        local: PathBuf,
        /// How many bytes to read. Default: the image length from the HAT
        /// EEPROM header, which requires the EEPROM to hold one.
        #[arg(long, value_parser = parse_u32)]
        length: Option<u32>,
        /// 7-bit I2C address. 0x50 is what the HAT specification assigns
        /// the ID EEPROM.
        // The default is spelled as the string `--help` should show: with
        // `default_value_t` clap prints the `u8`, and "80" is a poor way
        // to write an I2C address every datasheet gives as 0x50.
        #[arg(long, value_parser = parse_i2c_address, default_value = HAT_EEPROM_ADDRESS)]
        address: u8,
        /// Byte offset to start at.
        #[arg(long, value_parser = parse_u32, default_value_t = 0)]
        offset: u32,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Program a local image into an EEPROM on the HAT ID bus (GPIO0/1).
    EepromWrite {
        /// Local image to program — for a HAT ID EEPROM, the `.eep` file
        /// Raspberry Pi's `eepmake` produces.
        local: PathBuf,
        /// 7-bit I2C address. 0x50 is what the HAT specification assigns
        /// the ID EEPROM.
        // The default is spelled as the string `--help` should show: with
        // `default_value_t` clap prints the `u8`, and "80" is a poor way
        // to write an I2C address every datasheet gives as 0x50.
        #[arg(long, value_parser = parse_i2c_address, default_value = HAT_EEPROM_ADDRESS)]
        address: u8,
        /// Byte offset to start at.
        #[arg(long, value_parser = parse_u32, default_value_t = 0)]
        offset: u32,
        /// The part's page size in bytes. The default suits every part
        /// from the 24C32 (the HAT specification's floor) up; a 24C256's
        /// own page is 64 bytes, which programs in half the time. Too
        /// large corrupts data rather than failing, since a page write
        /// that overruns wraps to the start of the same page.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_PAGE_SIZE)]
        page_size: u32,
        /// Baud to negotiate for the transfer; the link always returns to
        /// 115200 afterward.
        #[arg(long, value_parser = parse_u32, default_value_t = DEFAULT_BAUD)]
        baud: u32,
    },

    /// Pack an over-the-air bundle from a manifest, and optionally upload
    /// it to a running board.
    ///
    /// The only subcommand that touches no serial port: a bundle reaches a
    /// board over the network, and this is here because the format has to
    /// have one implementation, shared with the firmware that installs it.
    Bundle {
        /// The manifest describing what the bundle holds.
        #[arg(default_value = "bundle.toml")]
        manifest: PathBuf,
        /// Where to write it. Defaults to `target/<name>.bundle` beside
        /// the manifest.
        #[arg(short, long)]
        output: Option<PathBuf>,
        /// Also write the bundle's contents into this directory — a
        /// mounted SD card's boot partition — for an update a board
        /// cannot be sent over the network. Writes only what the bundle
        /// carries, which is less than a card needs to boot.
        #[arg(long, value_name = "DIR")]
        sdcard: Option<PathBuf>,
        /// POST it to a running board once built, e.g.
        /// http://10.0.0.5/api/v1/ota.
        #[arg(long, value_name = "URL")]
        upload: Option<String>,
    },

    /// Passthrough serial terminal only, with no handshake.
    Terminal,

    /// Write a shell completion script to stdout.
    ///
    /// Generated from the same command tree clap builds for `--help`, so
    /// it lists whatever subcommands and flags this binary actually has.
    /// Touches no serial port.
    ///
    /// Install it where your shell looks, e.g. on Linux:
    ///
    ///     rpi-loader completions bash | sudo tee /usr/share/bash-completion/completions/rpi-loader
    ///
    /// or, without root:
    ///
    ///     rpi-loader completions bash > ~/.local/share/bash-completion/completions/rpi-loader
    Completions {
        /// Which shell to generate for.
        #[arg(value_enum, default_value_t = Shell::Bash)]
        shell: Shell,
    },

    /// List the serial ports on this machine, to find the one to pass to
    /// --device.
    List {
        /// Include non-USB ports too — the legacy /dev/ttyS* range, PCI
        /// and Bluetooth serial. A USB-to-serial cable is what the loader
        /// is reached through, so these are filtered out by default;
        /// a typical Linux machine reports thirty-odd of them.
        #[arg(long)]
        all: bool,
    },
}

impl Command {
    /// Whether this command must greet the loader before running.
    ///
    /// `terminal` is the exception among the ones that open the port: it
    /// exists to watch an already-running kernel, which doesn't speak the
    /// loader protocol, so a HELLO would never be answered.
    fn needs_handshake(&self) -> bool {
        !matches!(
            self,
            Command::Terminal
                | Command::List { .. }
                | Command::Bundle { .. }
                | Command::Completions { .. }
        )
    }
}

/// Parses an address or baud in any of the bases a user is likely to
/// type, mirroring what the shell and the datasheets use: `0x8000`,
/// `0b1010`, `0o755`, `1500000`, or `1_500_000`.
fn parse_u32(s: &str) -> Result<u32, String> {
    let text = s.trim().replace('_', "");
    let (digits, radix) = match text.get(..2).map(str::to_ascii_lowercase).as_deref() {
        Some("0x") => (&text[2..], 16),
        Some("0b") => (&text[2..], 2),
        Some("0o") => (&text[2..], 8),
        _ => (&text[..], 10),
    };
    u32::from_str_radix(digits, radix).map_err(|e| format!("{s:?} is not a number: {e}"))
}

/// Parses a 7-bit I2C address in any of the bases [`parse_u32`] takes,
/// rejecting anything the bus cannot carry. 0x00-0x07 and 0x78-0x7f are
/// reserved by the I2C specification, but a part answering there is the
/// user's business, not this tool's — only the 7-bit range is enforced.
fn parse_i2c_address(s: &str) -> Result<u8, String> {
    let value = parse_u32(s)?;
    u8::try_from(value)
        .ok()
        .filter(|&address| address <= 0x7f)
        .ok_or_else(|| format!("{s:?} is not a 7-bit I2C address (0x00-0x7f)"))
}

/// Reads a local file, naming it if that fails.
fn read_file(path: &Path) -> Result<Vec<u8>> {
    fs::read(path).with_context(|| format!("reading {}", path.display()))
}

/// Describes a port's type in one line: for USB, whatever the device
/// reports about itself, which is what distinguishes one cable from
/// another when several are plugged in.
fn describe(port_type: &SerialPortType) -> String {
    match port_type {
        SerialPortType::UsbPort(info) => {
            let mut parts = Vec::new();
            let name = [info.manufacturer.as_deref(), info.product.as_deref()]
                .into_iter()
                .flatten()
                .collect::<Vec<_>>()
                .join(" ");
            if !name.is_empty() {
                parts.push(name);
            }
            parts.push(format!("{:04x}:{:04x}", info.vid, info.pid));
            if let Some(serial) = &info.serial_number {
                parts.push(format!("serial {serial}"));
            }
            parts.join("  ")
        }
        SerialPortType::PciPort => "PCI serial".into(),
        SerialPortType::BluetoothPort => "Bluetooth serial".into(),
        _ => "unknown".into(),
    }
}

/// Works around a clap_complete bug that breaks every subcommand's
/// completion when the binary's name contains a hyphen.
///
/// Its bash generator builds the same case label twice, and mangles the
/// binary name differently each time. The dispatcher that decides which
/// subcommand you are in uses `bin_name.replace('-', "__")`, producing
/// `rpi__loader__subcmd__boot`; the branch that then supplies that
/// subcommand's options is built from the command *path* with every
/// separator replaced by `__subcmd__`, and the hyphen goes the same way,
/// producing `rpi__subcmd__loader__subcmd__boot`. No label ever matches.
///
/// The symptom is not a missing flag here and there: past the first
/// word, the script offers nothing at all. `rpi-loader sd-read --dev<TAB>`
/// completes to nothing, and so does every other subcommand. Only the
/// top level works, which is why it looks like it works at a glance.
///
/// A binary without a hyphen is unaffected, which is presumably why this
/// survives upstream. The repair is to spell the name the dispatcher's
/// way everywhere: harmless if clap_complete fixes it, since the broken
/// spelling then does not appear.
fn repair_hyphenated_bin_name(name: &str, script: String) -> String {
    if !name.contains('-') {
        return script;
    }
    script.replace(&name.replace('-', "__subcmd__"), &name.replace('-', "__"))
}

/// Bash layered over the generated script, so that `--device` completes
/// to the serial ports this machine has right now.
///
/// clap can only say that `--device` takes a string, which its bash
/// generator turns into filename completion — workable, since a port is
/// a path, but it offers every file on the system and makes you type
/// `/dev/tty` first. What the ports actually are is a runtime question,
/// and the one thing that can answer it is this binary, so the wrapper
/// asks it: `list` with no `--all`, the same USB-only filter a user would
/// get by running it themselves.
///
/// `2>/dev/null` and a bare `awk` suffice because `list` writes only port
/// lines to stdout — the "no ports found" notice goes to stderr, so an
/// empty list stays empty rather than becoming a candidate called "No".
///
/// The delegation is what makes this an addition rather than a
/// replacement: anything that is not a `--device` value falls through to
/// clap's own function, which keeps every other flag and subcommand
/// exactly as generated.
///
/// `@FN@` is that generated function, `@PREFIX@` names the two added
/// here, and `@BIN@` is the command being completed.
const BASH_DEVICE_WRAPPER: &str = r#"
# Serial ports for --device, from the binary that knows them. Everything
# else falls through to the generated completion above.
@PREFIX@_ports() {
    @BIN@ list 2>/dev/null | awk 'NF {print $1}'
}

@PREFIX@_complete() {
    case "$3" in
        -d|--device)
            COMPREPLY=( $(compgen -W "$(@PREFIX@_ports)" -- "$2") )
            return 0
            ;;
    esac
    @FN@ "$@"
}

complete -F @PREFIX@_complete -o bashdefault -o default @BIN@
"#;

/// Writes a shell completion script for this binary to stdout.
///
/// Built from the `Command` clap derives from [`Cli`] — the same one
/// behind `--help` — so the script describes the CLI that is actually
/// compiled rather than a copy of it that has to be kept in step.
///
/// The binary name is taken from the command rather than hardcoded,
/// because it is what the completion registers against: a script naming
/// `rpi-loader` does nothing for a binary the user renamed or reached
/// through a symlink, and clap already knows which name it was built
/// with.
///
/// Output goes to stdout rather than to a file this picks: where a
/// completion belongs differs by shell, distribution and whether the user
/// can write outside their home, none of which this can work out. Piping
/// it leaves that choice where it belongs — see the subcommand's `--help`
/// for the two usual destinations.
///
/// For bash, [`BASH_DEVICE_WRAPPER`] is appended. It calls clap's
/// generated function by name, which is the one thing here that depends
/// on how clap_complete spells its output, so the name is derived the way
/// that generator derives it and the result is *checked* before the
/// wrapper is added: if the function is not there to delegate to, the
/// script is emitted unchanged rather than wrapped around nothing, since
/// a wrapper whose fall-through is missing would break every completion
/// rather than just this one. `tests/completions.rs` asserts the wrapper
/// is present, so that silent degradation fails a test instead of
/// shipping.
fn write_completions(shell: Shell) -> Result<()> {
    let mut command = Cli::command();
    let name = command.get_name().to_string();

    // Into memory rather than straight to stdout, so the bash arm below
    // can look at what came out before adding to it.
    let mut buffer = Vec::new();
    clap_complete::generate(shell, &mut command, &name, &mut buffer);
    let mut script = String::from_utf8(buffer).context("completion script is not UTF-8")?;

    if shell == Shell::Bash {
        script = repair_hyphenated_bin_name(&name, script);

        // clap_complete's bash generator names its function after the
        // command, with each `-` doubled into `__`.
        let generated = format!("_{}", name.replace('-', "__"));
        if script.contains(&format!("{generated}()")) {
            script.push_str(
                &BASH_DEVICE_WRAPPER
                    .replace("@PREFIX@", &format!("_{}_device", name.replace('-', "_")))
                    .replace("@FN@", &generated)
                    .replace("@BIN@", &name),
            );
        }
    }

    print!("{script}");
    Ok(())
}

/// Lists the serial ports this machine can see.
///
/// Enumeration needs no privileges and opens nothing, so this works even
/// where the port itself would be refused for lack of group membership.
fn list_ports(all: bool) -> Result<()> {
    let mut ports = serialport::available_ports().context("enumerating serial ports")?;
    if !all {
        ports.retain(|port| matches!(port.port_type, SerialPortType::UsbPort(_)));
    }
    // USB first, then by name: with --all the handful of interesting
    // ports would otherwise be buried in the legacy range.
    ports.sort_by(|a, b| {
        let rank = |port: &SerialPortInfo| !matches!(port.port_type, SerialPortType::UsbPort(_));
        (rank(a), a.port_name.clone()).cmp(&(rank(b), b.port_name.clone()))
    });

    if ports.is_empty() {
        eprintln!(
            "{}",
            if all {
                "No serial ports found."
            } else {
                "No USB serial ports found; pass --all to list every port."
            }
        );
        return Ok(());
    }

    let width = ports
        .iter()
        .map(|port| port.port_name.len())
        .max()
        .unwrap_or(0);
    for port in &ports {
        println!(
            "{:width$}  {}",
            port.port_name,
            describe(&port.port_type),
            width = width
        );
    }
    Ok(())
}

/// Works out how much of an EEPROM to read when `--length` was not given,
/// by reading the HAT header at `offset` and taking the image length out
/// of it.
///
/// The alternative would be reading the whole address space, which for a
/// 32 KiB part means seconds of I2C traffic to recover a few hundred bytes
/// of atoms and 31 KiB of `0xff`. An EEPROM without a valid header is
/// asked for by length instead — the error says so.
fn hat_image_length(link: &mut Link, address: u8, offset: u32) -> Result<u32> {
    let header = link.eeprom_read(address, offset, HAT_HEADER_LEN)?;
    if !header.starts_with(HAT_SIGNATURE) {
        return Err(anyhow!(
            "0x{address:02x} does not hold a HAT image (no \"R-Pi\" signature at offset \
             {offset}); pass --length to read it anyway"
        ));
    }
    let eeplen = u32::from_le_bytes(
        header[HAT_EEPLEN_AT..HAT_EEPLEN_AT + 4]
            .try_into()
            .expect("the header is 12 bytes, so this slice is 4"),
    );
    if !(HAT_HEADER_LEN..=HAT_MAX_IMAGE).contains(&eeplen) {
        return Err(anyhow!(
            "the HAT header claims an image length of {eeplen} bytes, which is not \
             plausible; pass --length to read it anyway"
        ));
    }
    Ok(eeplen)
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    // Set by the Ctrl-C handler `run` installs once it is about to open the
    // serial link; see there for why it is not installed sooner.
    let interrupted = Arc::new(AtomicBool::new(false));

    match run(cli, Arc::clone(&interrupted)) {
        Ok(()) if interrupted.load(Ordering::SeqCst) => ExitCode::from(EXIT_INTERRUPTED),
        Ok(()) => ExitCode::SUCCESS,
        // The error here is whatever loop noticed the flag and unwound;
        // saying "interrupted" is more use than reporting it.
        Err(_) if interrupted.load(Ordering::SeqCst) => {
            eprintln!("\nInterrupted.");
            ExitCode::from(EXIT_INTERRUPTED)
        }
        Err(e) => {
            eprintln!("Error: {e:#}");
            ExitCode::FAILURE
        }
    }
}

/// Opens the port, greets the loader unless the command opts out, and
/// runs the command.
fn run(cli: Cli, interrupted: Arc<AtomicBool>) -> Result<()> {
    // Before anything opens a port: listing is how a user finds out what
    // to pass to --device, so it cannot require one, packing a bundle
    // never involves the serial link at all, and a completion script is
    // printed from this binary's own argument tree with no board in the
    // picture.
    if let Command::List { all } = &cli.command {
        return list_ports(*all);
    }
    if let Command::Completions { shell } = &cli.command {
        return write_completions(*shell);
    }
    if let Command::Bundle {
        manifest,
        output,
        sdcard,
        upload,
    } = &cli.command
    {
        return bundle::run(
            manifest,
            output.clone(),
            sdcard.as_deref(),
            upload.as_deref(),
        );
    }

    let device = cli.device.as_deref().ok_or_else(|| {
        anyhow!("no serial device given; pass --device (e.g. --device /dev/ttyUSB0)")
    })?;

    // From here on, Ctrl-C sets a flag rather than killing the process, so
    // the terminal can leave cleanly and a transfer can unwind instead of
    // stranding the device mid-chunk. Every loop on the link that could
    // block forever polls it.
    //
    // Not before: the commands above have nothing to unwind, and none of
    // them polls the flag, so a handler installed for them only makes
    // Ctrl-C do nothing — a bundle upload waiting on the board ignored it.
    let flag = Arc::clone(&interrupted);
    if let Err(e) = ctrlc::set_handler(move || flag.store(true, Ordering::SeqCst)) {
        eprintln!("Warning: could not install the Ctrl-C handler: {e}");
    }

    let mut link = Link::open(device, interrupted)?;
    if cli.command.needs_handshake() {
        link.handshake()?;
    }

    match cli.command {
        Command::Boot {
            image,
            load_addr,
            baud,
        } => {
            let data = read_file(&image)?;
            link.negotiate_baud(baud)?;
            link.mem_write(load_addr, &data)?;
            // Drop back to base baud before jumping so a booted kernel's
            // output lands at the rate the terminal below listens at.
            link.negotiate_baud(BASE_BAUD)?;
            link.exec(load_addr)?;
            eprintln!("Jumped to {load_addr:#x}.");
            link.terminal()?;
        }

        Command::MemWrite { addr, file, baud } => {
            let data = read_file(&file)?;
            link.negotiate_baud(baud)?;
            link.mem_write(addr, &data)?;
            link.negotiate_baud(BASE_BAUD)?;
            eprintln!("Wrote {} bytes to {addr:#x}.", data.len());
        }

        Command::Exec { addr, terminal } => {
            link.exec(addr)?;
            eprintln!("Jumped to {addr:#x}.");
            if terminal {
                link.terminal()?;
            }
        }

        Command::SdList { path } => {
            for entry in link.sd_list(&path)? {
                let marker = if entry.is_dir { "/" } else { "" };
                println!("{:>12}  {}{marker}", entry.size, entry.name);
            }
        }

        Command::SdRead {
            remote,
            local,
            baud,
        } => {
            link.negotiate_baud(baud)?;
            let data = link.sd_read(&remote)?;
            link.negotiate_baud(BASE_BAUD)?;
            fs::write(&local, &data).with_context(|| format!("writing {}", local.display()))?;
            eprintln!(
                "Read {} bytes from {remote} -> {}",
                data.len(),
                local.display()
            );
        }

        Command::SdWrite {
            local,
            remote,
            baud,
        } => {
            let data = read_file(&local)?;
            link.negotiate_baud(baud)?;
            link.sd_write(&remote, &data)?;
            link.negotiate_baud(BASE_BAUD)?;
        }

        Command::SdDelete { remote } => {
            link.sd_delete(&remote)?;
            eprintln!("Deleted {remote}");
        }

        Command::SdMkdir { remote } => {
            link.sd_mkdir(&remote)?;
            eprintln!("Created directory {remote}");
        }

        Command::EepromRead {
            local,
            length,
            address,
            offset,
            baud,
        } => {
            link.negotiate_baud(baud)?;
            let length = match length {
                Some(length) => length,
                None => hat_image_length(&mut link, address, offset)?,
            };
            let data = link.eeprom_read(address, offset, length)?;
            link.negotiate_baud(BASE_BAUD)?;
            fs::write(&local, &data).with_context(|| format!("writing {}", local.display()))?;
            eprintln!(
                "Read {} bytes from 0x{address:02x} -> {}",
                data.len(),
                local.display()
            );
        }

        Command::EepromWrite {
            local,
            address,
            offset,
            page_size,
            baud,
        } => {
            let data = read_file(&local)?;
            if data.is_empty() {
                return Err(anyhow!("{} is empty", local.display()));
            }
            // A warning rather than a refusal: this command programs an
            // EEPROM, and only the usual one on this bus holds a HAT image.
            if offset == 0 && !data.starts_with(HAT_SIGNATURE) {
                eprintln!(
                    "Warning: {} does not start with the HAT signature \"R-Pi\"; \
                     writing it anyway.",
                    local.display()
                );
            }
            link.negotiate_baud(baud)?;
            link.eeprom_write(address, offset, page_size, &data)?;
            link.negotiate_baud(BASE_BAUD)?;
            eprintln!(
                "Programmed and verified {} bytes at offset {offset} of 0x{address:02x}.",
                data.len()
            );
        }

        Command::Terminal => link.terminal()?,

        // All three returned above, before a port was ever opened.
        Command::Bundle { .. } => unreachable!(),
        Command::List { .. } => unreachable!(),
        Command::Completions { .. } => unreachable!(),
    }

    Ok(())
}