cverif 0.0.2

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
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
//! cverif command-line interface.

use cverif::image::Image;
use cverif::verify::{Options, Report, Status, verify};
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

/// Printing that survives a closed pipe (`cverif ... | head`): the report is cut short, the
/// exit status still tells the verdict.
macro_rules! println {
    ($($t:tt)*) => {{
        use std::io::Write;
        let _ = writeln!(std::io::stdout(), $($t)*);
    }};
}
macro_rules! print {
    ($($t:tt)*) => {{
        use std::io::Write;
        let _ = write!(std::io::stdout(), $($t)*);
    }};
}

const USAGE: &str = "\
cverif - prove that compiled machine code matches its C source

USAGE:
    cverif [OPTIONS] <BINARY> <SOURCE>...
    cverif --compare [OPTIONS] <OLD-BINARY> <NEW-BINARY> [<SOURCE>...]

ARGS:
    <BINARY>       ELF file with symbols (object or executable), or a raw binary, Intel HEX or
                   S-record image (with --symbols)
    <SOURCE>...    C source files or directories (searched recursively for *.c)

OPTIONS:
    -I <DIR>               Add an include directory
    -D <NAME>[=<VALUE>]    Define a preprocessor macro
    --symbols <FILE>       Symbol table for a non-ELF image: `nm` output (any format) or a GNU ld
                           link map; may be repeated (a map also names the object files)
    --base <HEX>           Load address of a raw binary (default 0)
    --load <FILE>@<HEX>    A further memory image (raw at the address, HEX or S-record); may be repeated
    --lcov <FILE>          Write source coverage as an LCOV tracefile
    --drcov <FILE>         Write binary coverage in drcov format (for disassembler plugins)
    --json <FILE>          Write the full report, with coverage ranges, as JSON
    -fshort-enums          Enumerated types take the smallest type that fits
    -fno-short-enums       Enumerated types are at least int (default: what the ELF records)
    --mmio <HEX>-<HEX>     Peripheral address range, where the binary may access memory only as the
                           source does (may be repeated; replaces the default 40000000-5fffffff
                           and e0000000-ffffffff)
    --static-base <HEX>    Value of r9 for linked code built with -frwpi (data base address)
    --only <FUNCTION>      Verify only this function (may be repeated)
    --max-paths <N>        Maximum number of paths explored per function (default 2000)
    --max-depth <N>        Maximum number of undetermined branches per path (default 40)
    --time-limit <SECS>    Wall-clock safety net per function (default 300)
    --work-limit <UNITS>   Effort budget per function, in terms built plus thousands of
                           solver propagations: same result on any machine (default 500000)
    --timeout <SECS>       Stop everything after this long; unfinished functions are BOUNDED
    -j, --jobs <N>         Verify N functions in parallel (default: one per CPU)
    -v, --verbose          List unproved source lines (with their text), unproved machine code
                           (disassembled) and unmatched binary functions
    --explain[=FUNCTION]   Explain every function that is not PROVED (or the one named): what was
                           compared, the path, both symbolic values and where they differ, the
                           counterexample with the value of each side
    --dump <FUNCTION>      Verify only this function and print, for every path, what the source
                           and the machine code compute (may be repeated)
    --dump-all             The same for every function
    --dump-binary <WHAT>   Disassemble machine code and summarise it symbolically on its own;
                           WHAT is a symbol, an address or START-END (hex).  Needs no source.
    --full                 Do not shorten the symbolic values and lists of the three above
    --list-unsupported     Summarise why functions are unsupported, grouped by reason
    -U <NAME>              Undefine a preprocessor macro
    -include <FILE>        Process a file before each source file
    --explain-flags        Show the evidence behind every detected compiler flag
    --compare              Compare two binaries with each other: is the new machine code
                           observably equivalent to the old?  With sources, both are first
                           verified against the source (three-way)
    --old-<OPT>, --new-<OPT>
                           In --compare mode, --symbols, --map, --base, --load and --static-base
                           for one of the two binaries only (unprefixed: for both)
    --assume <NAME>        Rely on an assumption in --compare mode: sp-aligned, ret32 (on by
    --no-assume <NAME>     default), ext-arity, void-r0 (off by default); the report lists them.
                           --explain adds, for each difference, both values as expressions
                           and the code of both versions
    -h, --help             Show this help
    -V, --version          Show the version

EXIT STATUS:
    0  no difference found    1  the binary provably differs from the source    2  usage or input error
";

struct Args {
    binary: PathBuf,
    sources: Vec<PathBuf>,
    copts: cverif::c::Options,
    symbols: Vec<PathBuf>,
    loads: Vec<(PathBuf, u32)>,
    base: u32,
    static_base: Option<u32>,
    lcov: Option<PathBuf>,
    drcov: Option<PathBuf>,
    json: Option<PathBuf>,
    opts: Options,
    verbose: bool,
    explain_flags: bool,
    list_unsupported: bool,
    compare: bool,
    /// Per-side inputs of --compare: (symbols, loads, base, static base).
    sides: [Side; 2],
    assume: cverif::bindiff::Assumptions,
    /// `--explain`: None = off, empty = every function that is not proved.
    explain: Option<Vec<String>>,
    dump: Vec<String>,
    dump_all: bool,
    dump_binary: Vec<String>,
    full: bool,
}

#[derive(Default)]
struct Side {
    symbols: Vec<PathBuf>,
    loads: Vec<(PathBuf, u32)>,
    base: Option<u32>,
    static_base: Option<u32>,
}

fn hex_arg(v: Option<String>, what: &str) -> Result<u32, String> {
    v.and_then(|v| u32::from_str_radix(v.trim_start_matches("0x"), 16).ok())
        .ok_or_else(|| format!("{what} needs a hex address"))
}

fn load_arg(v: Option<String>, what: &str) -> Result<(PathBuf, u32), String> {
    let v = v.ok_or_else(|| format!("{what} needs file@address"))?;
    Ok(match v.rsplit_once('@') {
        Some((f, x)) => (
            f.into(),
            u32::from_str_radix(x.trim_start_matches("0x"), 16)
                .map_err(|_| format!("{what} needs file@address with a hex address"))?,
        ),
        None => (v.into(), 0),
    })
}

fn parse_args() -> Result<Option<Args>, String> {
    let mut it = std::env::args().skip(1).peekable();
    let mut pos: Vec<PathBuf> = Vec::new();
    let mut a = Args {
        binary: PathBuf::new(),
        sources: Vec::new(),
        copts: Default::default(),
        symbols: Vec::new(),
        loads: Vec::new(),
        base: 0,
        static_base: None,
        lcov: None,
        drcov: None,
        json: None,
        opts: Options::default(),
        verbose: false,
        explain_flags: false,
        list_unsupported: false,
        compare: false,
        sides: Default::default(),
        assume: Default::default(),
        explain: None,
        dump: Vec::new(),
        dump_all: false,
        dump_binary: Vec::new(),
        full: false,
    };
    let num = |s: Option<String>, what: &str| -> Result<u64, String> {
        s.and_then(|v| v.parse().ok())
            .ok_or_else(|| format!("{what} needs a number"))
    };
    let mut mmio_given = false;
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "-h" | "--help" => {
                print!("{USAGE}");
                return Ok(None);
            }
            "-V" | "--version" => {
                println!("cverif {}", env!("CARGO_PKG_VERSION"));
                return Ok(None);
            }
            "-v" | "--verbose" => a.verbose = true,
            "--symbols" | "--map" => a.symbols.push(it.next().ok_or("--symbols needs a file")?.into()),
            "--load" => {
                let v = it.next().ok_or("--load needs file@address")?;
                let (file, addr) = match v.rsplit_once('@') {
                    Some((f, x)) => (
                        f,
                        u32::from_str_radix(x.trim_start_matches("0x"), 16)
                            .map_err(|_| "--load needs file@address with a hex address")?,
                    ),
                    None => (v.as_str(), 0),
                };
                a.loads.push((file.into(), addr));
            }
            "--explain-flags" => a.explain_flags = true,
            "--compare" => a.compare = true,
            "--assume" => a.assume.set(&it.next().ok_or("--assume needs a name")?, true)?,
            "--no-assume" => a.assume.set(&it.next().ok_or("--no-assume needs a name")?, false)?,
            s if s.starts_with("--old-") || s.starts_with("--new-") => {
                let side = &mut a.sides[s.starts_with("--new-") as usize];
                match &s[6..] {
                    "symbols" | "map" => side
                        .symbols
                        .push(it.next().ok_or_else(|| format!("{s} needs a file"))?.into()),
                    "base" => side.base = Some(hex_arg(it.next(), s)?),
                    "static-base" => side.static_base = Some(hex_arg(it.next(), s)?),
                    "load" => side.loads.push(load_arg(it.next(), s)?),
                    _ => return Err(format!("unknown option {s}")),
                }
            }
            "--explain" => {
                let names = a.explain.get_or_insert_with(Vec::new);
                // A function name may follow; a file or a directory is the next argument proper.
                if let Some(n) = it.next_if(|n| !n.starts_with('-') && !std::path::Path::new(n).exists()) {
                    names.push(n);
                }
            }
            s if s.starts_with("--explain=") => a
                .explain
                .get_or_insert_with(Vec::new)
                .push(s["--explain=".len()..].to_string()),
            "--dump" => a.dump.push(it.next().ok_or("--dump needs a function name")?),
            "--dump-all" => a.dump_all = true,
            "--dump-binary" => a
                .dump_binary
                .push(it.next().ok_or("--dump-binary needs a symbol or an address")?),
            "--full" => a.full = true,
            "--list-unsupported" => a.list_unsupported = true,
            "--lcov" => a.lcov = Some(it.next().ok_or("--lcov needs a file name")?.into()),
            "--drcov" => a.drcov = Some(it.next().ok_or("--drcov needs a file name")?.into()),
            "--json" => a.json = Some(it.next().ok_or("--json needs a file name")?.into()),
            "--static-base" => {
                let v = it.next().ok_or("--static-base needs an address")?;
                a.static_base = Some(
                    u32::from_str_radix(v.trim_start_matches("0x"), 16)
                        .map_err(|_| "--static-base needs a hex address")?,
                );
            }
            "--mmio" => {
                let v = it.next().ok_or("--mmio needs a range")?;
                let hex = |s: &str| u32::from_str_radix(s.trim_start_matches("0x"), 16).ok();
                let range = v
                    .split_once('-')
                    .and_then(|(lo, hi)| Some((hex(lo)?, hex(hi)?)))
                    .filter(|(lo, hi)| lo <= hi)
                    .ok_or("--mmio needs a range of hex addresses: START-END")?;
                if !mmio_given {
                    a.opts.mmio.clear();
                    mmio_given = true;
                }
                a.opts.mmio.push(range);
            }
            "--base" => {
                let v = it.next().ok_or("--base needs an address")?;
                a.base =
                    u32::from_str_radix(v.trim_start_matches("0x"), 16).map_err(|_| "--base needs a hex address")?;
            }
            "--only" => a.opts.only.push(it.next().ok_or("--only needs a function name")?),
            "--max-paths" => a.opts.limits.max_paths = num(it.next(), "--max-paths")? as usize,
            "--max-depth" => a.opts.limits.max_depth = num(it.next(), "--max-depth")? as usize,
            "--work-limit" => a.opts.work_limit = num(it.next(), "--work-limit")?,
            "--timeout" => {
                a.opts.deadline = Some(std::time::Instant::now() + Duration::from_secs(num(it.next(), "--timeout")?))
            }
            "-j" | "--jobs" => a.opts.jobs = num(it.next(), "--jobs")? as usize,
            "--time-limit" => a.opts.time_limit = Duration::from_secs(num(it.next(), "--time-limit")?),
            "-I" => a
                .copts
                .include_dirs
                .push(it.next().ok_or("-I needs a directory")?.into()),
            "-D" => {
                let d = it.next().ok_or("-D needs a macro")?;
                a.copts.defines.push(split_define(&d));
            }
            "-fshort-enums" => a.copts.short_enums = Some(true),
            "-fno-short-enums" => a.copts.short_enums = Some(false),
            "-U" => a.copts.undefines.push(it.next().ok_or("-U needs a macro name")?),
            "-include" => a
                .copts
                .forced_includes
                .push(it.next().ok_or("-include needs a file")?.into()),
            s if s.starts_with("-I") => a.copts.include_dirs.push(s[2..].into()),
            s if s.starts_with("-U") => a.copts.undefines.push(s[2..].into()),
            s if s.starts_with("-D") => a.copts.defines.push(split_define(&s[2..])),
            s if s.starts_with('-') => return Err(format!("unknown option {s}")),
            _ => pos.push(arg.into()),
        }
    }
    if pos.len() == 1 && !a.dump_binary.is_empty() {
        a.binary = pos.remove(0);
        return Ok(Some(a));
    }
    if a.compare {
        if pos.len() < 2 {
            return Err("--compare expects two binaries".into());
        }
    } else if pos.len() < 2 {
        return Err("expected a binary and at least one source file or directory".into());
    }
    a.binary = pos.remove(0);
    a.sources = pos;
    Ok(Some(a))
}

fn split_define(d: &str) -> (String, String) {
    match d.split_once('=') {
        Some((k, v)) => (k.to_string(), v.to_string()),
        None => (d.to_string(), "1".to_string()),
    }
}

/// `--compare`: the first source argument is the new binary.
fn run_compare(a: Args) -> Result<ExitCode, String> {
    let paths = [a.binary.clone(), a.sources[0].clone()];
    let mut images = Vec::new();
    for (path, side) in paths.iter().zip(&a.sides) {
        let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let mut extra = Vec::new();
        for (p, addr) in a.loads.iter().chain(&side.loads) {
            extra.push((std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?, *addr));
        }
        let mut symtabs = Vec::new();
        for p in a.symbols.iter().chain(&side.symbols) {
            symtabs.push(std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?);
        }
        let image = cverif::inputs::load(
            &bytes,
            side.base.unwrap_or(a.base),
            &extra,
            &symtabs,
            side.static_base.or(a.static_base),
        )
        .map_err(|e| format!("{}: {e}", path.display()))?;
        images.push(image);
    }
    let mut files = Vec::new();
    for s in &a.sources[1..] {
        files.extend(cverif::c::collect_sources(s).map_err(|e| format!("{}: {e}", s.display()))?);
    }
    let mut progs = Vec::new();
    if !files.is_empty() {
        for image in &images {
            let mut copts = a.copts.clone();
            if copts.short_enums.is_none() {
                copts.short_enums = image.short_enums;
            }
            progs.push(cverif::c::parse_files(&files, &copts)?);
        }
    } else if a.sources.len() > 1 {
        return Err("no C source files found".into());
    }
    let opts = cverif::bindiff::Options {
        verify: a.opts.clone(),
        assume: a.assume.clone(),
        explain: a.explain.is_some(),
    };
    let src = (!progs.is_empty()).then(|| (&progs[0], &progs[1]));
    let cmp = cverif::bindiff::compare(&images[0], &images[1], src, &opts);
    print!("{}", cmp.render());
    if let Some(p) = &a.json {
        let (old, new) = (paths[0].display().to_string(), paths[1].display().to_string());
        std::fs::write(p, cmp.json(&old, &new)).map_err(|e| format!("{}: {e}", p.display()))?;
    }
    Ok(if cmp.differs() || cmp.may_differ() {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

fn run(mut a: Args) -> Result<ExitCode, String> {
    if a.compare {
        return run_compare(a);
    }
    let bytes = std::fs::read(&a.binary).map_err(|e| format!("{}: {e}", a.binary.display()))?;
    let mut extra = Vec::new();
    for (p, addr) in &a.loads {
        extra.push((std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?, *addr));
    }
    let mut symtabs = Vec::new();
    for p in &a.symbols {
        symtabs.push(std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?);
    }
    let image = cverif::inputs::load(&bytes, a.base, &extra, &symtabs, a.static_base)
        .map_err(|e| format!("{}: {e}", a.binary.display()))?;
    let style = if a.full {
        cverif::explain::Style::full()
    } else {
        cverif::explain::Style::default()
    };
    for spec in &a.dump_binary {
        let mut budget = cverif::explain::binary::Budget::default();
        if a.full {
            budget.max_paths = a.opts.limits.max_paths;
        }
        print!(
            "{}",
            cverif::explain::binary::dump_binary(&image, spec, style, &budget)?
        );
    }
    if a.sources.is_empty() {
        return Ok(ExitCode::SUCCESS);
    }
    if a.dump_all || !a.dump.is_empty() {
        a.opts.dump = if a.full { usize::MAX } else { 32 };
        if !a.dump_all {
            a.opts.only.extend(a.dump.iter().cloned());
        }
    }
    let mut files = Vec::new();
    for s in &a.sources {
        files.extend(cverif::c::collect_sources(s).map_err(|e| format!("{}: {e}", s.display()))?);
    }
    if files.is_empty() {
        return Err("no C source files found".into());
    }
    let mut copts = a.copts.clone();
    if copts.short_enums.is_none() {
        copts.short_enums = image.short_enums;
    }
    let prog = cverif::c::parse_files(&files, &copts)?;
    let report = verify(&prog, &image, &a.opts);
    print_report(&report, &image, a.verbose, a.explain_flags);
    print_details(&report, &image, &prog, &a, style);
    if a.list_unsupported {
        list_unsupported(&report);
    }
    let bin_name = a.binary.display().to_string();
    let write = |path: &Option<PathBuf>, data: Vec<u8>| -> Result<(), String> {
        match path {
            Some(p) => std::fs::write(p, data).map_err(|e| format!("{}: {e}", p.display())),
            None => Ok(()),
        }
    };
    write(&a.lcov, cverif::report::lcov(&report).into_bytes())?;
    write(&a.drcov, cverif::report::drcov(&report, &image, &bin_name))?;
    write(&a.json, cverif::report::json(&report, &image, &bin_name).into_bytes())?;
    Ok(if report.has_mismatch() {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

/// Why functions could not be verified, most frequent reason first.  Source locations are
/// dropped from the reason so that one construct used in many places is one line.
fn list_unsupported(r: &Report) {
    let mut groups: Vec<(String, Vec<&str>)> = Vec::new();
    for f in &r.funcs {
        let Status::Unsupported(why) = &f.status else { continue };
        let mut key = why.as_str();
        // "reason (file:line)" -> "reason"
        if key.ends_with(')')
            && let Some(i) = key.rfind(" (")
            && key[i..].contains(':')
        {
            key = &key[..i];
        }
        let key = match key.strip_prefix("calls ") {
            Some(rest) => match rest.split_once(": ") {
                Some((_, inner)) => format!("calls a function that is unsupported: {inner}"),
                None => key.to_string(),
            },
            None => key.to_string(),
        };
        match groups.iter_mut().find(|g| g.0 == key) {
            Some(g) => g.1.push(&f.name),
            None => groups.push((key, vec![&f.name])),
        }
    }
    groups.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(&b.0)));
    println!();
    println!(
        "unsupported:     {} functions, {} distinct reasons",
        groups.iter().map(|g| g.1.len()).sum::<usize>(),
        groups.len()
    );
    for (why, names) in &groups {
        let shown: Vec<&str> = names.iter().copied().take(4).collect();
        let more = if names.len() > shown.len() { ", ..." } else { "" };
        println!("  {:>4}  {why}  [{}{more}]", names.len(), shown.join(", "));
    }
}

fn print_report(r: &Report, image: &Image, verbose: bool, explain_flags: bool) {
    let width = r.funcs.iter().map(|f| f.name.len()).max().unwrap_or(8);
    for f in &r.funcs {
        let mut line = format!(
            "{:<12} {:<width$}  {:>5} bytes  {:>4} paths  {:>6} ms",
            f.status.label(),
            f.name,
            f.size,
            f.paths,
            f.millis
        );
        if !f.status.detail().is_empty() {
            line.push_str(&format!("  {}", f.status.detail()));
        }
        println!("{line}");
    }
    for d in &r.data_issues {
        println!("{:<12} {d}", "DATA");
    }
    let count = |p: fn(&Status) -> bool| r.funcs.iter().filter(|f| p(&f.status)).count();
    println!();
    println!(
        "functions:       {} proved, {} bounded, {} mismatched, {} inconclusive, {} unsupported",
        count(|s| matches!(s, Status::Proved)),
        count(|s| matches!(s, Status::Bounded(_))),
        count(|s| matches!(s, Status::Mismatch(_))),
        count(|s| matches!(s, Status::Inconclusive(_))),
        count(|s| matches!(s, Status::Unsupported(_))),
    );
    println!(
        "source coverage: {:5.1}%  ({} of {} statements and branches proved)",
        100.0 * r.src_coverage(),
        r.src.0,
        r.src.1
    );
    println!(
        "binary coverage: {:5.1}%  ({} of {} code bytes proved)",
        100.0 * r.bin_coverage(),
        r.bin.0,
        r.bin.1
    );
    let objects = cverif::report::object_coverage(r, image);
    if objects.len() > 1 {
        // Directories of object files and archives say nothing here.
        let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string();
        let w = objects
            .iter()
            .map(|o| short(&o.0).len().max(9))
            .max()
            .unwrap_or(9)
            .min(60);
        for (name, proved, total) in &objects {
            let name = if name.is_empty() {
                "(unknown)".to_string()
            } else {
                short(name)
            };
            println!(
                "  {name:<w$}  {:5.1}%  ({proved} of {total})",
                100.0 * *proved as f64 / (*total).max(1) as f64
            );
        }
    }
    println!(
        "initialised data: {} objects compared, {} differ",
        r.data_checked,
        r.data_issues.len()
    );
    let flags = cverif::detect::detect(image);
    print!("{}", flags.render(explain_flags));
    println!("score:           {:.1} / 100", r.score());
    println!(
        "verdict:         {}",
        if r.has_mismatch() {
            "MISMATCH - the binary does not match the source"
        } else {
            "no difference found"
        }
    );
    if verbose && !explain_flags {
        for e in &flags.evidence {
            println!("  flag evidence: {e}");
        }
    }
    if verbose {
        for (n, s) in &r.unmatched {
            println!("  unmatched binary function: {n} ({s} bytes)");
        }
        for n in &r.absent {
            println!("  source function not found in binary: {n}");
        }
    }
}

/// `--dump`, `--explain` and the detailed part of `-v`.
fn print_details(r: &Report, image: &Image, prog: &cverif::c::ast::Program, a: &Args, style: cverif::explain::Style) {
    let names = cverif::explain::Names::new(image, Some(prog));
    if a.opts.dump > 0 {
        for f in &r.funcs {
            let Some(d) = f.detail.as_ref().filter(|d| !d.paths.is_empty() || d.skipped_paths > 0) else {
                continue;
            };
            println!();
            println!("== {} at {:#x}: {} ==", f.name, f.addr, f.status.label());
            print!("{}", d.dump_text(&names, style));
        }
    }
    if let Some(only) = &a.explain {
        for f in &r.funcs {
            if f.status == Status::Proved || !(only.is_empty() || only.contains(&f.name)) {
                continue;
            }
            println!();
            println!("== {} {}: {} ==", f.status.label(), f.name, f.status.detail());
            match f.detail.as_ref().and_then(|d| d.explanation.as_ref()) {
                Some(e) => print!("{}", e.text(&names, style)),
                None => println!("  (nothing was compared: the function was not verified)"),
            }
        }
        for n in only {
            if !r.funcs.iter().any(|f| f.name == *n) {
                println!();
                println!("== {n}: not a verified function ==");
            }
        }
    }
    if !(a.verbose || a.explain.is_some()) {
        return;
    }
    // Source the proof does not reach, with its text.
    let mut texts: std::collections::HashMap<&str, Vec<String>> = std::collections::HashMap::new();
    for (f, l) in &r.uncovered_lines {
        let lines = texts.entry(f.as_str()).or_insert_with(|| {
            std::fs::read_to_string(f)
                .map(|t| t.lines().map(|l| l.to_string()).collect())
                .unwrap_or_default()
        });
        match lines.get((*l as usize).wrapping_sub(1)) {
            Some(t) => println!("  unproved source line: {f}:{l}: {}", t.trim()),
            None => println!("  unproved source line: {f}:{l}"),
        }
    }
    // Machine code the proof does not account for.
    let limit = if a.full { usize::MAX } else { 24 };
    let unproved: Vec<_> = r
        .bin_ranges
        .iter()
        .filter(|b| b.state == cverif::verify::ByteState::Unproved)
        .collect();
    for b in unproved.iter().take(limit) {
        let at = match names.locate(b.start) {
            Some(s) => format!(" <{s}>"),
            None => String::new(),
        };
        println!();
        println!(
            "  unproved machine code {:#x}-{:#x}{at} ({} bytes):",
            b.start,
            b.end,
            b.end - b.start
        );
        let text = cverif::explain::binary::listing(image, &names, b.start, b.end);
        for l in text.lines() {
            println!("  {l}");
        }
        // A whole function nothing was proved about: what it computes on its own.
        if let Some(s) = image
            .func_at(b.start)
            .filter(|s| s.addr == b.start && s.addr + s.size <= b.end + 4)
        {
            let budget = cverif::explain::binary::Budget {
                max_paths: if a.full { 64 } else { 6 },
                work_limit: 50_000,
                time_limit: std::time::Duration::from_secs(5),
                ..Default::default()
            };
            let end = s.addr + s.size.max(2);
            let text = cverif::explain::binary::summary_text(image, &names, s.addr, end, style, &budget);
            for l in text.lines() {
                println!("  {l}");
            }
        }
    }
    if unproved.len() > limit {
        println!("  ... {} more unproved ranges (--full)", unproved.len() - limit);
    }
}

fn main() -> ExitCode {
    let args = match parse_args() {
        Ok(Some(a)) => a,
        Ok(None) => return ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("cverif: {e}\n\n{USAGE}");
            return ExitCode::from(2);
        }
    };
    // Term construction and evaluation recurse deeply on long paths.
    let worker = std::thread::Builder::new()
        .stack_size(64 << 20)
        .spawn(move || run(args))
        .expect("spawn worker thread");
    match worker.join() {
        Ok(Ok(code)) => code,
        Ok(Err(e)) => {
            eprintln!("cverif: {e}");
            ExitCode::from(2)
        }
        Err(_) => {
            eprintln!("cverif: internal error");
            ExitCode::from(2)
        }
    }
}