cverif 0.0.6

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
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! cverif command-line interface.

use cverif::image::Image;
use cverif::verify::{Options, Report, Status};
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 --discover [OPTIONS] <IMAGE> [<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
    --old-source <PATH>, --new-source <PATH>
                           With --compare: a source of one image only (may be repeated)
    --old-root <DIR>, --new-root <DIR>
                           With --compare: the source tree of each image; relative <SOURCE>
                           and -I paths are taken from it.  With a source per image, a function
                           whose definition is the same in both and that is proved against it
                           in both is equivalent through the source; one that changed (or calls
                           one that did) is reported as changed in the source, with what each
                           image is against its own source, and compared as machine code
    --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)
    --discover             The image has no symbol table, or an incomplete or wrong one: find its
                           functions from the vector table (and the symbols given, which are
                           audited), classify the rest, and with sources name the functions by
                           proof; then verify with the recovered table.  -v lists everything
    --vectors <HEX>        Address of the vector table for --discover (default: start of the image)
    --no-vectors           The image has no vector table: entry points come from --symbols only
    --emit-symbols <FILE>  Write the symbol table --discover recovers (nm format, provenance
                           after each name; readable back with --symbols)
    --data <HEX>-<HEX>     Declare an address range (end exclusive) of a raw image to be data.
                           Without a link map nothing says what the bytes outside the functions
                           are: they count as unproved unless a proved path reads them or they
                           match the source's data.  Declared ranges are listed, not counted
    --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)
    --cache <DIR>          Keep results in DIR and reuse those for which nothing a proof can
                           depend on has changed (tool, options, source, image); such lines
                           are marked (cached)
    --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)
    --no-modular           Follow every callee on both sides instead of comparing calls to
                           functions that are verified on their own as calls
    --no-merge             Explore one path per way through every conditional instead of
                           merging small regions without calls into if-then-else values
    -fno-strict-aliasing   The code was built with -fno-strict-aliasing: assume nothing
                           about which types may share memory
    --standard-aliasing    Hold the source to the C rules on effective types only, not to
                           what GCC and clang assume under -fstrict-aliasing (the default:
                           accesses through incompatible types do not overlap if one is a
                           store; a proof that needs this says so)
    --strict-stack         Report an access below the stack pointer as a mismatch (by default
                           it is a hazard noted next to the verdict: the code is right
                           unless an exception is taken at that instruction)
    --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,
    --no-assume <NAME>     caller-stack (on by 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,
    data: Vec<(u32, u32)>,
    discover: bool,
    dopts: cverif::discover::Options,
    emit_symbols: Option<PathBuf>,
}

#[derive(Default)]
struct Side {
    /// Sources of this image only, and the directory its relative sources and include
    /// directories are taken from.
    sources: Vec<PathBuf>,
    root: Option<PathBuf>,
    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,
        data: Vec::new(),
        discover: false,
        dopts: Default::default(),
        emit_symbols: None,
    };
    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..] {
                    "source" => side.sources.push(
                        it.next()
                            .ok_or_else(|| format!("{s} needs a file or directory"))?
                            .into(),
                    ),
                    "root" => side.root = Some(it.next().ok_or_else(|| format!("{s} needs a directory"))?.into()),
                    "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);
            }
            "--discover" => a.discover = true,
            "--no-vectors" => a.dopts.no_vectors = true,
            "--vectors" => a.dopts.vectors = Some(hex_arg(it.next(), "--vectors")?),
            "--emit-symbols" => a.emit_symbols = Some(it.next().ok_or("--emit-symbols needs a file name")?.into()),
            "--data" => {
                let v = it.next().ok_or("--data 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("--data needs a range of hex addresses: START-END")?;
                a.data.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,
            "--no-modular" => a.opts.modular = false,
            "--no-merge" => a.opts.merge = false,
            // The former opt-in name of what is now the default.
            "--typed-memory" | "-fstrict-aliasing" => a.opts.aliasing = cverif::c::exec::Aliasing::Compiler,
            "-fno-strict-aliasing" => a.opts.aliasing = cverif::c::exec::Aliasing::Off,
            "--standard-aliasing" => a.opts.aliasing = cverif::c::exec::Aliasing::Standard,
            "--strict-stack" => a.opts.limits.strict_stack = true,
            "--work-limit" => a.opts.work_limit = num(it.next(), "--work-limit")?,
            "--cache" => a.opts.cache = Some(it.next().ok_or("--cache needs a directory")?.into()),
            "--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.discover) {
        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);
    }
    // The sources of each image: those given for both, taken from the image's own tree when
    // it has one, and its own.
    let mut progs = Vec::new();
    let any = a.sources.len() > 1 || a.sides.iter().any(|s| !s.sources.is_empty());
    if any {
        for (image, side) in images.iter().zip(&a.sides) {
            let at = |p: &PathBuf| match &side.root {
                Some(r) if p.is_relative() => r.join(p),
                _ => p.clone(),
            };
            let mut files = Vec::new();
            for s in a.sources[1..].iter().map(at).chain(side.sources.iter().cloned()) {
                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();
            copts.include_dirs = copts.include_dirs.iter().map(at).collect();
            if copts.short_enums.is_none() {
                copts.short_enums = image.short_enums;
            }
            copts.target = cverif::c::target::Target::for_image(image);
            progs.push(cverif::c::parse_files(&files, &copts)?);
        }
    }
    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);
    }
    cverif::timing::mark("start");
    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 mut image = if a.discover {
        let mut image = cverif::discover::open(&bytes, a.base, &extra, &symtabs, &mut a.dopts)
            .map_err(|e| format!("{}: {e}", a.binary.display()))?;
        if a.static_base.is_some() {
            image.static_base = a.static_base;
        }
        image
    } else {
        cverif::inputs::load(&bytes, a.base, &extra, &symtabs, a.static_base)
            .map_err(|e| format!("{}: {e}", a.binary.display()))?
    };
    for &(lo, hi) in &a.data {
        image.set_aside.push((lo, hi, "declared by the user (--data)".into()));
    }
    let mut discovery: Option<cverif::discover::Discovery> = None;
    if a.discover && a.sources.is_empty() {
        let found = cverif::discover::discover(&image, &a.dopts);
        print!("{}", found.discovery.render(a.verbose));
        if let Some(p) = &a.emit_symbols {
            cverif::discover::write_atomic(p, found.discovery.symbols_text(&found.image).as_bytes())
                .map_err(|e| format!("{}: {e}", p.display()))?;
        }
        if let Some(p) = &a.json {
            let text = format!("{{\n  \"discovery\": {}\n}}\n", found.discovery.json());
            std::fs::write(p, text).map_err(|e| format!("{}: {e}", p.display()))?;
        }
        image = found.image;
        discovery = Some(found.discovery);
    }
    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());
        }
    }
    cverif::timing::mark("load image");
    let mut files = Vec::new();
    for s in &a.sources {
        files.extend(cverif::c::collect_sources(s).map_err(|e| format!("{}: {e}", s.display()))?);
    }
    // Assembly sources (`.S`, `.s`) named on the command line are compared with the binary
    // instruction by instruction; they are not C.
    let is_asm = |f: &std::path::PathBuf| f.extension().is_some_and(|e| e == "S" || e == "s");
    for f in files.iter().filter(|f| is_asm(f)) {
        let text = std::fs::read_to_string(f).map_err(|e| format!("{}: {e}", f.display()))?;
        a.opts.asm_sources.push((f.display().to_string(), text));
    }
    files.retain(|f| !is_asm(f));
    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;
    }
    copts.target = cverif::c::target::Target::for_image(&image);
    let (prog, skipped) = cverif::c::parse_files_lenient(&files, &copts)?;
    for (file, why) in &skipped {
        eprintln!("cverif: warning: skipping {}: {why}", file.display());
    }
    if skipped.len() == files.len() {
        return Err("none of the C source files could be parsed".into());
    }
    cverif::timing::mark("parse sources");
    let mut preset = cverif::verify::Preset::default();
    // (An explanation is not kept in the cache: with --explain everything is established afresh.)
    if a.explain.is_some() {
        a.opts.cache = None;
    }
    let mut settled: Option<cverif::verify::Report> = None;
    if a.discover {
        let (mut found, mut p) = cverif::discover::discover_with_source(&image, &prog, &a.dopts, &a.opts);
        let emit = |found: &cverif::discover::Analysis| -> Result<(), String> {
            match &a.emit_symbols {
                Some(path) => {
                    cverif::discover::write_atomic(path, found.discovery.symbols_text(&found.image).as_bytes())
                        .map_err(|e| format!("{}: {e}", path.display()))
                }
                None => Ok(()),
            }
        };
        // The table as matching leaves it is on disk before verification starts: what an
        // interrupted run leaves behind is whole.
        emit(&found)?;
        cverif::timing::mark("discover");
        let (report, retracted) = cverif::discover::settle(&prog, &mut found, &mut p, &a.opts);
        if !retracted.is_empty() {
            emit(&found)?;
        }
        print!("{}", found.discovery.render(a.verbose));
        for (name, addr, why) in &retracted {
            println!("  name taken back: {name} at {addr:#x} ({why})");
        }
        println!();
        image = found.image;
        discovery = Some(found.discovery);
        preset = p;
        settled = Some(report);
    }
    let image = image;
    cverif::timing::mark("discover");
    let mut report = match settled {
        Some(r) => r,
        None => cverif::verify::verify_with(&prog, &image, &a.opts, &preset),
    };
    cverif::timing::mark("coverage accounting");
    report.skipped_sources = skipped
        .iter()
        .map(|(f, e)| (f.display().to_string(), e.clone()))
        .collect();
    cverif::timing::mark("report: start");
    print_report(&report, &image, a.verbose, a.explain_flags);
    cverif::timing::mark("report: text");
    if let Some(d) = &discovery {
        // A name that discovery chose is a hypothesis unless a symbol table gave it.
        let guessed = |f: &cverif::verify::FuncReport| {
            d.matches
                .iter()
                .any(|m| m.source == f.name && m.addr == f.addr && m.how != "given")
        };
        let n = (report.funcs.iter())
            .filter(|f| matches!(f.status, cverif::verify::Status::Mismatch(_)) && guessed(f))
            .count();
        let weak = |how: &str| {
            matches!(
                how,
                "conditional" | "ambiguous" | "bounded" | "by-data" | "by-calls" | "recognised"
            )
        };
        let hyp = d.matches.iter().filter(|m| weak(m.how)).count();
        if hyp > 0 {
            println!(
                "note: the results above hold for the recovered symbol table, in which {hyp} name(s) are not proved \
                 (conditional, ambiguous, bounded, by-data, by-calls, recognised: see the discovery above); a result that \
                 calls such a function rests on its name"
            );
        }
        if n > 0 {
            println!(
                "note: {n} of the mismatches are in functions that discovery named (no symbol table gave the name): \
                 either the code differs from the source, or it is another function"
            );
        }
    }
    // A table that `--discover --emit-symbols` wrote is not a symbol table from the build:
    // each name in it is as good as the provenance written after it, with or without the
    // header line of the file.  (A table without that column is the user's own statement.)
    if discovery.is_none() {
        let mut prov: Vec<(u32, String, String)> = Vec::new();
        for p in &a.symbols {
            if let Ok(t) = std::fs::read_to_string(p) {
                prov.extend(cverif::discover::provenance(&t));
            }
        }
        if !prov.is_empty() {
            let r = cverif::discover::rests_on(&report, &prov);
            let pct = |x: (usize, usize)| if x.1 == 0 { 0.0 } else { 100.0 * x.0 as f64 / x.1 as f64 };
            println!(
                "note: the symbol table carries the provenance column of --discover: {} of the {} proved functions \
                 rest on names that the user did not give, {} of them ({} code bytes) on names that are not proved \
                 either (conditional, bounded, by-data, by-calls, ambiguous, speculative): those results hold if the \
                 names are right.  Binary coverage without the code under such names: {:.1}% ({} of {} bytes), \
                 against {:.1}% as counted above",
                r.found,
                r.proved,
                r.soft,
                r.soft_bytes,
                pct(r.bin_firm),
                r.bin_firm.0,
                r.bin_firm.1,
                pct(r.bin)
            );
        }
    }
    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))?;
    cverif::timing::mark("report: details, lcov, drcov");
    let mut json = cverif::report::json(&report, &image, &bin_name);
    if let Some(d) = &discovery
        && let Some(i) = json.rfind('}')
    {
        json.truncate(i);
        json = format!("{},\n  \"discovery\": {}\n}}\n", json.trim_end(), d.json());
    }
    write(&a.json, json.into_bytes())?;
    cverif::timing::mark("reports");
    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.cached {
            line.push_str("  (cached)");
        }
        if !f.status.detail().is_empty() {
            line.push_str(&format!("  {}", f.status.detail()));
        }
        // What the result rests on that is not itself proved.
        let open: Vec<String> = (f.modulo.iter())
            .filter(|m| m.1 != "PROVED")
            .map(|m| format!("{}: {}", m.0, m.1))
            .collect();
        if !open.is_empty() && matches!(f.status, Status::Proved | Status::Bounded(_)) {
            line.push_str(&format!("  (modulo {})", open.join(", ")));
        }
        if f.assembly && matches!(f.status, Status::Proved) {
            line.push_str("  (assembly: every instruction is the source's)");
        }
        if matches!(f.status, Status::Proved | Status::Bounded(_)) {
            if let Some(g) = &f.given {
                line.push_str(&format!("  ({g})"));
            }
            if !f.assumes.is_empty() {
                line.push_str(&format!("  (assuming {})", f.assumes.join(", ")));
            }
        }
        if !f.hazards.is_empty() {
            let kind = match (f.hazards.iter().any(|h| !h.write), f.hazards.iter().any(|h| h.write)) {
                (true, true) => "read and store",
                (false, true) => "store",
                _ => "read",
            };
            line.push_str(&format!("  (hazard: {kind} below the stack pointer)"));
        }
        println!("{line}");
        if verbose {
            for h in &f.hazards {
                println!(
                    "{:<12} {} {} byte(s) below the stack pointer at {:#x}: unsafe if an exception is taken there",
                    "",
                    if h.write { "stores" } else { "reads" },
                    h.size,
                    h.pc
                );
            }
        }
    }
    for d in &r.data_issues {
        println!("{:<12} {d}", "DATA");
    }
    for (file, why) in &r.skipped_sources {
        println!("{:<12} {file}: {why}", "SKIPPED");
    }
    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(_))),
    );
    let hazards = r.funcs.iter().filter(|f| !f.hazards.is_empty()).count();
    if hazards > 0 {
        println!(
            "hazards:         {hazards} function(s) access memory below the stack pointer: unsafe if an exception is taken there (-v lists them, --strict-stack makes them mismatches)"
        );
    }
    let proved = count(|s| matches!(s, Status::Proved));
    let solid = r.funcs.iter().filter(|f| f.unconditional).count();
    if r.funcs.iter().any(|f| !f.modulo.is_empty()) {
        println!(
            "                 of the proved, {solid} rest only on proved functions; {} call a function that is not",
            proved - solid
        );
    }
    let aliasing = (r.funcs.iter())
        .filter(|f| {
            matches!(f.status, Status::Proved | Status::Bounded(_)) && f.assumes.iter().any(|a| a == "strict-aliasing")
        })
        .count();
    if aliasing > 0 {
        println!(
            "                 {aliasing} results assume strict aliasing as compilers implement it (-fno-strict-aliasing, --standard-aliasing: see --help)"
        );
    }
    println!(
        "source coverage: {:5.1}%  ({} of {} statements and branches proved)",
        100.0 * r.src_coverage(),
        r.src.0,
        r.src.1
    );
    if !r.src_no_code.is_empty() {
        println!(
            "  {} more statements have no code: a constant condition rules them out (-v lists them)",
            r.src_no_code.len()
        );
    }
    if !r.skipped_sources.is_empty() {
        println!(
            "  {} source file(s) could not be read: what they define is not in these figures",
            r.skipped_sources.len()
        );
    }
    println!(
        "binary coverage: {:5.1}%  ({} of {} code bytes proved)",
        100.0 * r.bin_coverage(),
        r.bin.0,
        r.bin.1
    );
    if r.bin_constants > 0 {
        println!(
            "  {} of the proved bytes are constants among the code, equal to the source's",
            r.bin_constants
        );
    }
    if r.unexplained > 0 {
        println!(
            "  {} bytes outside the known code are unaccounted for (no proved path reads them, no source \
             object has their value): counted as unproved (-v lists them; see --data and --discover)",
            r.unexplained
        );
    }
    // Per declared or classified range: the bytes of it that nothing else accounts for.
    for (lo, hi, why) in &image.set_aside {
        let n: u32 = r
            .set_aside
            .iter()
            .map(|x| x.1.min(*hi).saturating_sub(x.0.max(*lo)))
            .sum();
        if n > 0 {
            println!(
                "  not counted: {n} of the {} bytes at {lo:#x}-{hi:#x}, taken to be data: {why}",
                hi - lo
            );
        }
    }
    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
            );
        }
    }
    if objects.len() > 20 {
        // At this size: where the unproved code is.
        let (objects, dirs) = cverif::report::coverage_tables(r, image);
        let pct = |p: usize, t: usize| 100.0 * p as f64 / t.max(1) as f64;
        println!("code by source directory:");
        for (d, proved, total, n) in &dirs {
            let d = if d.is_empty() { "." } else { d };
            println!(
                "  {d:<28} {:5.1}%  ({proved} of {total} bytes, {n} object(s))",
                pct(*proved, *total)
            );
        }
        let mut worst: Vec<&cverif::report::ObjectCoverage> = objects.iter().filter(|o| o.has_source).collect();
        worst.sort_by_key(|o| std::cmp::Reverse(o.total - o.proved));
        println!("most unproved code, by object with source:");
        for o in worst.iter().take(12) {
            println!(
                "  {:<28} {:>6} bytes unproved  ({:.1}% proved)",
                o.name,
                o.total - o.proved,
                pct(o.proved, o.total)
            );
        }
        let none: Vec<&cverif::report::ObjectCoverage> = objects.iter().filter(|o| !o.has_source).collect();
        if !none.is_empty() {
            let bytes: usize = none.iter().map(|o| o.total).sum();
            let mut names: Vec<String> = (none.iter())
                .map(|o| {
                    format!(
                        "{} ({})",
                        if o.name.is_empty() { "(unknown)" } else { &o.name },
                        o.total
                    )
                })
                .collect();
            names.truncate(12);
            println!(
                "no source function (not verified): {} object(s), {bytes} bytes: {}{}",
                none.len(),
                names.join(", "),
                if none.len() > 12 { ", ..." } else { "" }
            );
        }
    }
    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!(
        "source read as:  {} (taken from the image's records; -D and -U override)",
        cverif::c::target::Target::for_image(image).describe()
    );
    println!(
        "aliasing:        {}",
        match r.aliasing {
            "standard" => "ISO C effective types only (--standard-aliasing)",
            "off" => "no type-based assumption (-fno-strict-aliasing)",
            _ => "strict, as GCC and clang implement it (default; -fno-strict-aliasing if the code was built so)",
        }
    );
    for d in &r.library_differs {
        println!("library:         {d}: callers were compiled to rely on the library's meaning");
    }
    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 !r.absent.is_empty() && !verbose {
        println!(
            "not in binary:   {} source functions ({} statements and branches) have no code in this image: not verified, not counted (-v lists them)",
            r.absent.len(),
            r.absent_points
        );
    }
    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}");
        }
        for (f, l, func) in &r.src_no_code {
            println!("  no code (constant condition): {f}:{l} in {func}");
        }
    }
}

/// `--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!(
            "  {} {:#x}-{:#x}{at} ({} bytes):",
            if image.segment_at(b.start).is_none_or(|s| s.exec) {
                "unproved machine code"
            } else {
                "unaccounted bytes (code or data, shown as code)"
            },
            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)
        }
    }
}