cverif 0.0.1

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
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
//! Equivalence driver: for every source function present in the binary, explores
//! all paths of the C function and of the machine code under the same symbolic
//! inputs and proves that every observable effect is identical.

use crate::c::ast::{Program, Type, VOID};
use crate::c::exec::{CEnv, CExec};
use crate::image::{Image, SymKind};
use crate::sym::{ArgLoc, Ctx, Event, Limits, R, Stop, WordLoc, Write, arg_locs, arg_words};
use crate::term::{Env, T};
use crate::thumb::exec::{Callee, Exit, Machine, image_init};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};

#[derive(Clone, Debug)]
pub struct Options {
    pub limits: Limits,
    /// Verify only these functions (all when empty).
    pub only: Vec<String>,
    /// Wall-clock budget per function.
    pub time_limit: Duration,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            limits: Limits::default(),
            only: Vec::new(),
            time_limit: Duration::from_secs(60),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
    /// Every path of the function was explored and proved equivalent.
    Proved,
    /// No difference found, but exploration hit a limit (e.g. an unbounded loop).
    Bounded(String),
    /// The machine code provably behaves differently from the source.
    Mismatch(String),
    /// The prover gave up on some obligation.
    Inconclusive(String),
    /// The function uses something the tool does not model yet.
    Unsupported(String),
}

impl Status {
    pub fn label(&self) -> &'static str {
        match self {
            Status::Proved => "PROVED",
            Status::Bounded(_) => "BOUNDED",
            Status::Mismatch(_) => "MISMATCH",
            Status::Inconclusive(_) => "INCONCLUSIVE",
            Status::Unsupported(_) => "UNSUPPORTED",
        }
    }

    pub fn detail(&self) -> &str {
        match self {
            Status::Proved => "",
            Status::Bounded(s) | Status::Mismatch(s) | Status::Inconclusive(s) | Status::Unsupported(s) => s,
        }
    }
}

#[derive(Clone, Debug)]
pub struct FuncReport {
    pub name: String,
    pub addr: u32,
    pub size: u32,
    pub status: Status,
    /// Paths proved equivalent.
    pub paths: usize,
    /// Paths on which the source has undefined behaviour (nothing to prove).
    pub undefined_paths: usize,
    pub millis: u128,
}

#[derive(Clone, Debug, Default)]
pub struct Report {
    pub funcs: Vec<FuncReport>,
    /// Source coverage points: (proved, total).
    pub src: (usize, usize),
    /// Code bytes of the binary: (proved, total).
    pub bin: (usize, usize),
    /// Binary functions that no verified path reaches: (name, size).
    pub unmatched: Vec<(String, u32)>,
    /// Source functions that have no symbol in the binary and were not reached through a caller.
    pub absent: Vec<String>,
    /// Initialised data that differs between source and binary.
    pub data_issues: Vec<String>,
    /// Number of source-defined objects whose initial contents were compared.
    pub data_checked: usize,
    /// Source lines never reached by a proved path: (file, line).
    pub uncovered_lines: Vec<(String, u32)>,
    /// Every source coverage point (a statement or a branch condition), in source order.
    pub src_points: Vec<SrcPoint>,
    /// The executable segments as maximal address ranges of one state, in address order.
    pub bin_ranges: Vec<BinRange>,
}

/// One source coverage point and whether a proved path goes through it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SrcPoint {
    pub file: String,
    pub line: u32,
    pub func: String,
    pub proved: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ByteState {
    /// On a proved path (instructions executed, literal-pool and table data read).
    Proved,
    /// Code or data in code that no proved path accounts for.
    Unproved,
    /// Alignment padding between functions; not counted in the coverage.
    Padding,
}

impl ByteState {
    pub fn label(self) -> &'static str {
        match self {
            ByteState::Proved => "proved",
            ByteState::Unproved => "unproved",
            ByteState::Padding => "padding",
        }
    }
}

/// Addresses `start..end` of the binary, all in the same state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BinRange {
    pub start: u32,
    pub end: u32,
    pub state: ByteState,
}

impl Report {
    pub fn src_coverage(&self) -> f64 {
        if self.src.1 == 0 {
            0.0
        } else {
            self.src.0 as f64 / self.src.1 as f64
        }
    }

    pub fn bin_coverage(&self) -> f64 {
        if self.bin.1 == 0 {
            0.0
        } else {
            self.bin.0 as f64 / self.bin.1 as f64
        }
    }

    pub fn has_mismatch(&self) -> bool {
        !self.data_issues.is_empty() || self.funcs.iter().any(|f| matches!(f.status, Status::Mismatch(_)))
    }

    /// 0..=100: how much of the source and of the binary is accounted for by proofs.
    /// Zero as soon as anything provably differs.
    pub fn score(&self) -> f64 {
        if self.has_mismatch() {
            return 0.0;
        }
        50.0 * (self.src_coverage() + self.bin_coverage())
    }
}

/// Strip GCC's function-clone suffixes (`.constprop.0`, `.isra.0`, `.part.0`, `.cold`).
fn base_name(name: &str) -> &str {
    match name.find('.') {
        Some(i) if i > 0 => &name[..i],
        _ => name,
    }
}

struct PathResult {
    cov: Vec<u32>,
    insns: Vec<(u32, u8)>,
    data: Vec<(u32, u8)>,
}

struct Job<'a> {
    prog: &'a Program,
    image: &'a Image,
    env: &'a CEnv<'a>,
    fid: u32,
    entry: u32,
    regs: [T; 16],
    args: Vec<T>,
    stack_args: Vec<(u32, T)>,
    /// Structure arguments: (the C-side object, the words the caller passed).
    struct_args: Vec<(T, Vec<T>)>,
    /// Caller-provided memory for a structure result.
    ret_slot: Option<T>,
    lr0: T,
}

fn witness(ctx: &Ctx, env: &Env) -> String {
    let mut items: Vec<(String, u64)> = env
        .syms
        .iter()
        .map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
        .filter(|(n, _)| {
            let b = n.as_bytes();
            (b.len() == 2 && b[0] == b'r' && b[1] <= b'3') || n.starts_with("stk") || n.starts_with("ret")
        })
        .collect();
    items.sort();
    let mut parts: Vec<String> = items.iter().map(|(n, v)| format!("{n}={v:#x}")).collect();
    let mut mem: Vec<(u64, u8)> = env
        .mem
        .iter()
        .filter(|((m, _), _)| *m < 0x8000_0000)
        .map(|((_, a), v)| (*a, *v))
        .collect();
    mem.sort();
    for (a, v) in mem.iter().take(8) {
        parts.push(format!("mem[{a:#x}]={v:#04x}"));
    }
    if parts.is_empty() {
        "any input".into()
    } else {
        parts.join(" ")
    }
}

fn prove_eq(ctx: &mut Ctx, c: T, b: T, what: &str) -> R<()> {
    if c == b {
        return Ok(());
    }
    let e = ctx.tm.eq(c, b);
    match ctx.check(e) {
        Ok(()) => Ok(()),
        Err(Some(env)) => {
            if ctx.mentions_unspecified(c) || ctx.mentions_unspecified(b) {
                return Err(Stop::Unsupported(format!(
                    "{what}: depends on the unspecified magnitude of a string comparison result"
                )));
            }
            if ctx.mentions_private(c) || ctx.mentions_private(b) {
                return Err(Stop::Unsupported(format!(
                    "{what}: the address of a local object escapes"
                )));
            }
            let mut memo = Default::default();
            let (cv, bv) = (ctx.tm.eval(c, &env, &mut memo), ctx.tm.eval(b, &env, &mut memo));
            Err(Stop::Mismatch(
                format!(
                    "{what}: source gives {cv:#x}, binary gives {bv:#x} for {}",
                    witness(ctx, &env)
                ),
                Some(env),
            ))
        }
        Err(None) => {
            if std::env::var_os("CVERIF_DEBUG").is_some() {
                eprintln!(
                    "inconclusive {what}:\n  source: {}\n  binary: {}",
                    ctx.tm.show(c),
                    ctx.tm.show(b)
                );
            }
            Err(Stop::Inconclusive(format!("{what}: prover gave up")))
        }
    }
}

/// Prove that world memory is the same on both sides for every location either side wrote.
fn compare_world(ctx: &mut Ctx, job: &Job, c_log: &[Write], c_epoch: u32, m: &Machine, what: &str) -> R<()> {
    let mut seen: HashSet<(T, u8)> = HashSet::new();
    let entries: Vec<(T, u8)> = c_log
        .iter()
        .chain(m.mem.world.iter())
        .map(|w| (w.addr, w.size))
        .collect();
    for (addr, size) in entries {
        if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
            continue;
        }
        let env = job.env;
        let mut c_init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, c_epoch);
        let cv = ctx.read_world(c_log, addr, size, &mut c_init);
        let mut b_init = image_init(job.image, m.mem.epoch, None);
        let bv = ctx.mem_read(&m.mem, addr, size, &mut b_init);
        let at = ctx.tm.show(addr);
        prove_eq(ctx, cv, bv, &format!("{what}: {size}-byte value stored at {at}"))?;
    }
    Ok(())
}

/// Where the binary keeps the C locals whose address is visible to external functions.
#[derive(Default)]
struct Escapes {
    /// C object base -> (address in the binary's frame, its offset from the initial SP, size).
    map: HashMap<T, (T, i64, u32)>,
}

/// The bytes of the string literal a constant C-side pointer points into, from that pointer on.
fn literal_at<'a>(env: &'a CEnv<'a>, addr: u32) -> Option<&'a [u8]> {
    env.prog.strings.iter().zip(&env.str_addr).find_map(|(s, a)| {
        let o = addr.checked_sub((*a)?)? as usize;
        s.get(o..).filter(|r| !r.is_empty())
    })
}

/// Compare a value the source hands to the outside world with the binary's.  Besides plain
/// equality this accepts pointers that correspond: the address of a C local against its slot in
/// the binary's stack frame (the correspondence is fixed the first time it is seen), and string
/// literals against any read-only copy of the same bytes.
fn match_value(
    ctx: &mut Ctx,
    job: &Job,
    cx: &CExec,
    esc: &mut Escapes,
    ev: &Event,
    (c, b): (T, T),
    what: &str,
) -> R<()> {
    if c == b {
        return Ok(());
    }
    if ctx.tm.width(c) != 32 {
        return prove_eq(ctx, c, b, what);
    }
    // Two different constant addresses of identical read-only string contents.
    if let (Some(ca), Some(ba)) = (ctx.tm.as_const(c), ctx.unique_value(b))
        && ca != ba
        && let Some(lit) = literal_at(job.env, ca as u32)
        && job.image.read_const(ba as u32, lit.len() as u32) == Some(lit)
    {
        return Ok(());
    }
    let Some((base, off)) = ctx.private_split(c) else {
        return prove_eq(ctx, c, b, what);
    };
    if let Some(&sid) = cx.str_bases.get(&base) {
        // A literal that was not located in the image by content search.
        let lit = &job.env.prog.strings[sid as usize];
        if let (Some(o), Some(ba)) = (ctx.tm.as_const(off), ctx.unique_value(b))
            && let Some(rest) = lit.get(o as usize..)
        {
            if job.image.read_const(ba as u32, rest.len() as u32) == Some(rest) {
                return Ok(());
            }
            return Err(Stop::Mismatch(
                format!("{what}: binary passes {ba:#x}, which does not hold the source's string literal"),
                None,
            ));
        }
        return prove_eq(ctx, c, b, what);
    }
    let Some(obj) = ev.escaped.iter().find(|e| e.base == base) else {
        return prove_eq(ctx, c, b, what);
    };
    let name = obj.name.trim_start_matches('&');
    let bb = match esc.map.get(&base) {
        Some(e) => e.0,
        None => {
            let bb = ctx.tm.sub(b, off);
            let sp0 = job.regs[13];
            let Some(d) = ctx.tm.const_diff(bb, sp0) else {
                return Err(Stop::Unsupported(format!(
                    "{what}: source passes the address of local {name}, binary passes {} which is not a fixed stack slot",
                    ctx.tm.show(b)
                )));
            };
            let d = d as u32 as i32 as i64;
            let top = job.stack_args.iter().map(|a| a.0 as i64 + 4).max().unwrap_or(0);
            if d + obj.size as i64 > top {
                return Err(Stop::Mismatch(
                    format!(
                        "{what}: source passes the address of local {name}, binary passes a stack address outside its frame"
                    ),
                    None,
                ));
            }
            // Objects the callee can reach at the same time must not share storage.
            let live = |b: &T| ev.escaped.iter().any(|e| e.base == *b);
            if esc
                .map
                .iter()
                .any(|(b2, &(_, d2, s2))| live(b2) && d < d2 + s2 as i64 && d2 < d + obj.size as i64)
            {
                return Err(Stop::Mismatch(
                    format!("{what}: binary places local {name} over another local visible to the callee"),
                    None,
                ));
            }
            esc.map.insert(base, (bb, d, obj.size));
            bb
        }
    };
    let expect = ctx.tm.add(bb, off);
    if expect == b {
        return Ok(());
    }
    let e = ctx.tm.eq(expect, b);
    match ctx.check(e) {
        Ok(()) => Ok(()),
        Err(Some(_)) => Err(Stop::Mismatch(
            format!(
                "{what}: source passes the address of local {name}, binary passes {} instead of {}",
                ctx.tm.show(b),
                ctx.tm.show(expect)
            ),
            None,
        )),
        Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
    }
}

fn match_call(ctx: &mut Ctx, job: &Job, cx: &CExec, esc: &mut Escapes, m: &mut Machine, ev: &Event, k: usize) -> R<()> {
    let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
    let sp = m.regs[13];
    for (i, (&(val, signed), loc)) in ev.args.iter().zip(arg_locs(&widths)).enumerate() {
        let (expect, got) = match loc {
            ArgLoc::Reg(n) => (ctx.tm.resize(val, 32, signed), m.regs[n as usize]),
            ArgLoc::RegPair(n) => (val, ctx.tm.concat(m.regs[n as usize + 1], m.regs[n as usize])),
            ArgLoc::Stack(off) => {
                let a = ctx.tm.add_const(sp, off as u64);
                (ctx.tm.resize(val, 32, signed), m.read32(ctx, job.image, a))
            }
            ArgLoc::Stack64(off) => {
                let a = ctx.tm.add_const(sp, off as u64);
                let lo = m.read32(ctx, job.image, a);
                let a = ctx.tm.add_const(sp, off as u64 + 4);
                let hi = m.read32(ctx, job.image, a);
                (val, ctx.tm.concat(hi, lo))
            }
        };
        let what = format!("argument {} of call #{} to {}", i + 1, k + 1, ev.name);
        match_value(ctx, job, cx, esc, ev, (expect, got), &what)?;
    }
    // Locals the callee can reach must hold the same contents on both sides.
    for obj in &ev.escaped {
        let name = obj.name.trim_start_matches('&');
        let Some(&(bb, d, _)) = esc.map.get(&obj.base) else {
            return Err(Stop::Unsupported(format!(
                "call #{} to {}: local {name} is reachable by the callee but its place in the binary's frame is unknown",
                k + 1,
                ev.name
            )));
        };
        // The object must still be inside the live part of the frame.
        if let Some(s) = ctx.tm.const_diff(sp, job.regs[13])
            && d < s as u32 as i32 as i64
        {
            return Err(Stop::Mismatch(
                format!(
                    "call #{} to {}: local {name} lies below the stack pointer",
                    k + 1,
                    ev.name
                ),
                None,
            ));
        }
        for &(off, size, v) in &obj.pre {
            let Some(v) = v else { continue };
            let a = ctx.tm.add_const(bb, off as u64);
            let mut init = image_init(job.image, m.mem.epoch, None);
            let bv = ctx.mem_read(&m.mem, a, size, &mut init);
            let what = format!("local {name} (offset {off}) at call #{} to {}", k + 1, ev.name);
            match_value(ctx, job, cx, esc, ev, (v, bv), &what)?;
        }
    }
    compare_world(
        ctx,
        job,
        &ev.writes,
        ev.epoch,
        m,
        &format!("memory at call #{} to {}", k + 1, ev.name),
    )
}

/// Effects of an external call that returned, on the binary's private memory: the callee may have
/// written to every local it can reach (both sides continue with the same fresh contents) and to
/// its own stack arguments.
fn after_call(ctx: &mut Ctx, esc: &Escapes, m: &mut Machine, ev: &Event, k: usize) {
    for obj in &ev.escaped {
        let Some(&(bb, _, _)) = esc.map.get(&obj.base) else {
            continue;
        };
        for &(off, size, v) in &obj.post {
            let a = ctx.tm.add_const(bb, off as u64);
            ctx.mem_write(&mut m.mem, a, size, v);
        }
    }
    let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
    let sp = m.regs[13];
    for loc in arg_locs(&widths) {
        let (off, n) = match loc {
            ArgLoc::Stack(off) => (off, 1),
            ArgLoc::Stack64(off) => (off, 2),
            _ => continue,
        };
        for i in 0..n {
            let off = off + 4 * i;
            let v = ctx.named_sym(&format!("clob{k}.stk{off}"), 32);
            let a = ctx.tm.add_const(sp, off as u64);
            ctx.mem_write(&mut m.mem, a, 4, v);
        }
    }
}

/// The binary calls a memory helper the source does not call at this point (the compiler
/// turned a loop or an aggregate copy into a library call).  With a known length it is a
/// plain memory effect; apply it to the machine state.  Returns false if it cannot be modelled.
fn model_mem_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{MAX_MEM_INLINE, mem_fill};
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let zero = ctx.tm.konst(32, 0);
    // (destination, source or fill value, length, is a fill)
    let (dst, arg, len, fill) = match name {
        "memset" => (r0, r1, r2, true),
        "__aeabi_memset" | "__aeabi_memset4" | "__aeabi_memset8" => (r0, r2, r1, true),
        "__aeabi_memclr" | "__aeabi_memclr4" | "__aeabi_memclr8" => (r0, zero, r1, true),
        "memcpy" | "memmove" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" | "__aeabi_memmove"
        | "__aeabi_memmove4" | "__aeabi_memmove8" => (r0, r1, r2, false),
        _ => return false,
    };
    let Some(n) = ctx.unique_value(len).filter(|&n| n <= MAX_MEM_INLINE) else {
        return false;
    };
    let n = n as u32;
    if fill {
        let byte = ctx.tm.trunc(arg, 8);
        mem_fill(ctx, &mut m.mem, dst, byte, n);
    } else {
        let mut chunks = Vec::new();
        let mut off = 0;
        while off < n {
            let sz = if n - off >= 4 { 4u8 } else { 1 };
            let a = ctx.tm.add_const(arg, off as u64);
            let mut init = image_init(job.image, m.mem.epoch, None);
            chunks.push((off, sz, ctx.mem_read(&m.mem, a, sz, &mut init)));
            off += sz as u32;
        }
        for (off, sz, v) in chunks {
            let a = ctx.tm.add_const(dst, off as u64);
            ctx.mem_write(&mut m.mem, a, sz, v);
        }
    }
    *count += 1;
    // mem* return the destination; the __aeabi_ variants return nothing.
    let ret = if name.starts_with("__aeabi") { None } else { Some(dst) };
    m.finish_call(ctx, 1000 + *count, ret, None);
    true
}

/// libgcc's Thumb-1 switch dispatchers: the jump table follows the call instruction and the
/// routine continues at the selected entry, preserving every register but LR.
fn model_switch_helper(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> R<bool> {
    let (esize, signed) = match name {
        "__gnu_thumb1_case_sqi" => (1u32, true),
        "__gnu_thumb1_case_uqi" => (1, false),
        "__gnu_thumb1_case_shi" => (2, true),
        "__gnu_thumb1_case_uhi" => (2, false),
        "__gnu_thumb1_case_si" => (4, true),
        _ => return Ok(false),
    };
    let ret = m.resume_pc();
    let idx = m.regs[0];
    let mut found = None;
    for i in 0..1024u32 {
        let k = ctx.tm.konst(32, i as u64);
        let e = ctx.tm.eq(idx, k);
        if ctx.branch(e)? {
            found = Some(i);
            break;
        }
    }
    let Some(i) = found else {
        return Err(Stop::Unsupported(format!(
            "switch table with more than 1024 entries at {ret:#x}"
        )));
    };
    // Word tables are aligned and hold offsets from the table; the others hold half the offset from the return address.
    let base = if esize == 4 { (ret + 3) & !3 } else { ret };
    let eaddr = base + esize * i;
    let Some(bytes) = job.image.read_const(eaddr, esize) else {
        return Err(Stop::Unsupported(format!(
            "switch table entry outside the image at {eaddr:#x}"
        )));
    };
    let mut v = 0u32;
    for (j, &b) in bytes.iter().enumerate() {
        v |= (b as u32) << (8 * j);
    }
    let target = match (esize, signed) {
        (4, _) => base.wrapping_add(v),
        (1, true) => ret.wrapping_add((v as u8 as i8 as i32 as u32) << 1),
        (2, true) => ret.wrapping_add((v as u16 as i16 as i32 as u32) << 1),
        _ => ret.wrapping_add(v << 1),
    };
    m.data_covered.push((eaddr, esize as u8));
    *count += 1;
    m.resume_at(ctx, 1000 + *count, target);
    Ok(true)
}

/// The binary calls a library string function on read-only constants where the source side
/// evaluated the call itself (the compiler may fold such calls, or not).
fn model_string_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    use crate::c::exec::{c_str, compare_result};
    // The read-only bytes from a constant address to the end of its segment.
    let rom = |ctx: &mut Ctx, t: T| -> Option<&[u8]> {
        let a = ctx.unique_value(t)? as u32;
        let s = job.image.segment_at(a).filter(|s| !s.writable)?;
        s.data.get((a - s.addr) as usize..)
    };
    let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
    let v = match name {
        "strlen" => {
            let Some(s) = rom(ctx, r0).and_then(c_str) else {
                return false;
            };
            ctx.tm.konst(32, s.len() as u64)
        }
        "strcmp" => {
            let (Some(a), Some(b)) = (rom(ctx, r0).and_then(c_str), rom(ctx, r1).and_then(c_str)) else {
                return false;
            };
            compare_result(ctx, a, b)
        }
        "memcmp" => {
            let Some(n) = ctx.unique_value(r2) else { return false };
            let (Some(a), Some(b)) = (
                rom(ctx, r0).and_then(|s| s.get(..n as usize)),
                rom(ctx, r1).and_then(|s| s.get(..n as usize)),
            ) else {
                return false;
            };
            compare_result(ctx, a, b)
        }
        _ => return false,
    };
    *count += 1;
    m.finish_call(ctx, 1000 + *count, Some(v), None);
    true
}

/// The binary calls a compiler runtime routine (libgcc / AEABI) where the source has an operator:
/// apply the routine's defined result to the machine state.  Division by zero follows the term
/// convention; the source's own no-undefined-behaviour conditions exclude it.
fn model_runtime_call(ctx: &mut Ctx, m: &mut Machine, name: &str, count: &mut usize) -> bool {
    let r = m.regs;
    let tm = &mut ctx.tm;
    let a64 = tm.concat(r[1], r[0]);
    let b64 = tm.concat(r[3], r[2]);
    let halves = |tm: &mut crate::term::Terms, v: T| (tm.extract(v, 0, 32), tm.extract(v, 32, 32));
    // Results for r0..r3; None leaves the register clobbered.
    let mut out: [Option<T>; 4] = [None; 4];
    match name {
        "__aeabi_uidiv" | "__udivsi3" => out[0] = Some(tm.udiv(r[0], r[1])),
        "__aeabi_idiv" | "__divsi3" => out[0] = Some(tm.sdiv(r[0], r[1])),
        "__umodsi3" => out[0] = Some(tm.urem(r[0], r[1])),
        "__modsi3" => out[0] = Some(tm.srem(r[0], r[1])),
        "__aeabi_uidivmod" => {
            out[0] = Some(tm.udiv(r[0], r[1]));
            out[1] = Some(tm.urem(r[0], r[1]));
        }
        "__aeabi_idivmod" => {
            out[0] = Some(tm.sdiv(r[0], r[1]));
            out[1] = Some(tm.srem(r[0], r[1]));
        }
        "__aeabi_uldivmod" | "__aeabi_ldivmod" => {
            let signed = name == "__aeabi_ldivmod";
            let q = if signed { tm.sdiv(a64, b64) } else { tm.udiv(a64, b64) };
            let rem = if signed { tm.srem(a64, b64) } else { tm.urem(a64, b64) };
            let (q0, q1) = halves(tm, q);
            let (r0, r1) = halves(tm, rem);
            out = [Some(q0), Some(q1), Some(r0), Some(r1)];
        }
        "__udivdi3" | "__divdi3" | "__umoddi3" | "__moddi3" | "__aeabi_lmul" | "__muldi3" => {
            let v = match name {
                "__udivdi3" => tm.udiv(a64, b64),
                "__divdi3" => tm.sdiv(a64, b64),
                "__umoddi3" => tm.urem(a64, b64),
                "__moddi3" => tm.srem(a64, b64),
                _ => crate::sym::mul64(tm, a64, b64),
            };
            let (lo, hi) = halves(tm, v);
            out[0] = Some(lo);
            out[1] = Some(hi);
        }
        "__aeabi_llsl" | "__aeabi_llsr" | "__aeabi_lasr" | "__ashldi3" | "__lshrdi3" | "__ashrdi3" => {
            let amt = tm.zext(r[2], 64);
            let v = match name {
                "__aeabi_llsl" | "__ashldi3" => tm.shl(a64, amt),
                "__aeabi_llsr" | "__lshrdi3" => tm.lshr(a64, amt),
                _ => tm.ashr(a64, amt),
            };
            let (lo, hi) = halves(tm, v);
            out[0] = Some(lo);
            out[1] = Some(hi);
        }
        "__aeabi_lcmp" | "__aeabi_ulcmp" => {
            let signed = name == "__aeabi_lcmp";
            let lt = if signed { tm.slt(a64, b64) } else { tm.ult(a64, b64) };
            let gt = if signed { tm.slt(b64, a64) } else { tm.ult(b64, a64) };
            let g = tm.zext(gt, 32);
            let m1 = tm.konst(32, 0xffff_ffff);
            out[0] = Some(tm.ite(lt, m1, g));
        }
        "__clzsi2" => out[0] = Some(tm.clz(r[0])),
        "__ctzsi2" => {
            // Count of trailing zeros: 31 - clz(lowest set bit).
            let n = tm.neg(r[0]);
            let low = tm.and(r[0], n);
            let c = tm.clz(low);
            let k = tm.konst(32, 31);
            out[0] = Some(tm.sub(k, c));
        }
        "__popcountsi2" => {
            let mut acc = tm.konst(32, 0);
            for i in 0..32 {
                let b = tm.extract(r[0], i, 1);
                let z = tm.zext(b, 32);
                acc = tm.add(acc, z);
            }
            out[0] = Some(acc);
        }
        "__bswapsi2" => {
            let mut acc = tm.extract(r[0], 0, 8);
            for i in 1..4 {
                let b = tm.extract(r[0], i * 8, 8);
                acc = tm.concat(acc, b);
            }
            out[0] = Some(acc);
        }
        _ => return false,
    }
    *count += 1;
    m.finish_call(ctx, 1000 + *count, out[0], out[1]);
    for i in 2..4 {
        if let Some(v) = out[i] {
            m.regs[i] = v;
        }
    }
    true
}

/// The machine code must have made exactly the volatile accesses the source makes before its
/// event number `k` (all of them when the path ends).
fn check_volatile(ctx: &Ctx, cx: &CExec, m: &Machine, k: usize) -> R<()> {
    let due = cx.volatile.iter().filter(|a| a.event <= k).count();
    if m.vol_pos == due {
        return Ok(());
    }
    let a = &cx.volatile[m.vol_pos.min(due)];
    let what = if a.write { "write to" } else { "read of" };
    let at = ctx.tm.show(a.addr);
    Err(Stop::Mismatch(
        if m.vol_pos < due {
            format!(
                "binary omits the source's {}-byte {what} the volatile object at {at}",
                a.size
            )
        } else {
            format!(
                "binary performs the {}-byte {what} the volatile object at {at} too early",
                a.size
            )
        },
        None,
    ))
}

fn run_path(ctx: &mut Ctx, job: &Job) -> R<PathResult> {
    let p = job.prog;
    let f = &p.funcs[job.fid as usize];
    // --- source side ---
    let mut cx = CExec::new(job.env);
    for (base, words) in &job.struct_args {
        for (i, &w) in words.iter().enumerate() {
            let a = ctx.tm.add_const(*base, 4 * i as u64);
            ctx.mem_write(&mut cx.mem, a, 4, w);
        }
    }
    let (ret, halted) = match cx.run_function(ctx, job.fid, &job.args) {
        Ok(r) => (r, false),
        Err(Stop::Halt) => (None, true),
        Err(e) => return Err(e),
    };
    // --- binary side ---
    let classify = |addr: u32| -> Callee {
        if let Some(name) = job.image.externals.get(&addr) {
            return Callee::External(name.clone());
        }
        match job.image.func_at(addr) {
            Some(s) => {
                let has_body = p
                    .funcs
                    .iter()
                    .any(|f| f.body.is_some() && *f.name == *base_name(&s.name));
                // Code the compiler factored out of several functions (machine outliner) has
                // no counterpart in the source: follow it like any other part of the caller.
                if has_body || s.name.starts_with("OUTLINED_FUNCTION_") {
                    Callee::Internal
                } else {
                    Callee::External(s.name.clone())
                }
            }
            None => Callee::Internal,
        }
    };
    let mut m = Machine::new(ctx, job.entry, job.regs);
    m.targets = job.env.targets.iter().map(|t| t.0).collect();
    m.known_indirect = cx.indirect.iter().map(|t| t.1).collect();
    m.vol = cx.volatile.clone();
    for &(off, v) in &job.stack_args {
        let a = ctx.tm.add_const(job.regs[13], off as u64);
        ctx.mem_write(&mut m.mem, a, 4, v);
    }
    let mut k = 0usize;
    let mut helper_calls = 0usize;
    let mut esc = Escapes::default();
    loop {
        match m.run(ctx, job.image, job.lr0, &classify)? {
            Exit::Call { name } => {
                if model_switch_helper(ctx, job, &mut m, &name, &mut helper_calls)? {
                    continue;
                }
                if cx.events.get(k).is_none_or(|ev| ev.name != name)
                    && (model_mem_call(ctx, job, &mut m, &name, &mut helper_calls)
                        || model_runtime_call(ctx, &mut m, &name, &mut helper_calls)
                        || model_string_call(ctx, job, &mut m, &name, &mut helper_calls))
                {
                    continue;
                }
                let Some(ev) = cx.events.get(k) else {
                    return Err(Stop::Mismatch(
                        format!("binary calls {name}, which the source does not call at this point"),
                        None,
                    ));
                };
                if ev.name != name {
                    return Err(Stop::Mismatch(
                        format!("binary calls {name} where the source calls {}", ev.name),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                if let Some(got) = m.indirect.take() {
                    let want = cx
                        .indirect
                        .iter()
                        .find(|t| t.0 == k)
                        .expect("indirect event has a target")
                        .1;
                    prove_eq(ctx, want, got, &format!("target of call #{} through a pointer", k + 1))?;
                }
                match_call(ctx, job, &cx, &mut esc, &mut m, ev, k)?;
                m.mem.world.clear();
                m.mem.epoch = ev.epoch + 1;
                k += 1;
                if ev.noreturn {
                    break;
                }
                let (lo, hi) = match ev.ret {
                    None => (None, None),
                    Some((sym, signed)) => {
                        if ctx.tm.width(sym) == 64 {
                            (Some(ctx.tm.extract(sym, 0, 32)), Some(ctx.tm.extract(sym, 32, 32)))
                        } else {
                            (Some(ctx.tm.resize(sym, 32, signed)), None)
                        }
                    }
                };
                after_call(ctx, &esc, &mut m, ev, k - 1);
                m.finish_call(ctx, k - 1, lo, hi);
            }
            Exit::Trap => {
                let Some(ev) = cx.events.get(k) else {
                    return Err(Stop::Mismatch(
                        "binary traps (udf) where the source does not".into(),
                        None,
                    ));
                };
                if ev.name != "<trap>" {
                    return Err(Stop::Mismatch(
                        format!("binary traps (udf) where the source calls {}", ev.name),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, k)?;
                compare_world(ctx, job, &ev.writes, ev.epoch, &m, "memory at trap")?;
                k += 1;
                break;
            }
            Exit::Return => {
                if let Some(ev) = cx.events.get(k) {
                    return Err(Stop::Mismatch(
                        format!("binary returns without calling {}", ev.name),
                        None,
                    ));
                }
                if halted {
                    return Err(Stop::Mismatch(
                        "binary returns where the source does not return".into(),
                        None,
                    ));
                }
                check_volatile(ctx, &cx, &m, usize::MAX)?;
                if let Some(v) = ret
                    && matches!(p.ty(f.ty.ret), Type::Record(_))
                {
                    // `v` is the address of the C-side result.  Compare the bits that hold values
                    // (padding is unspecified) with r0, or with the memory the caller provided.
                    let size = p.size_of(f.ty.ret).unwrap_or(0);
                    let mask = p.value_mask(f.ty.ret);
                    let mut off = 0;
                    while off < size {
                        let n = (size - off).min(4);
                        let bits = (0..n).fold(0u64, |b, i| b | (mask[(off + i) as usize] as u64) << (8 * i));
                        let a = ctx.tm.add_const(v, off as u64);
                        let want = cx.read_bytes(ctx, a, n as u8);
                        let got = match job.ret_slot {
                            Some(slot) => {
                                let a = ctx.tm.add_const(slot, off as u64);
                                let mut init = image_init(job.image, m.mem.epoch, None);
                                ctx.mem_read(&m.mem, a, n as u8, &mut init)
                            }
                            None => ctx.tm.trunc(m.regs[0], n as u8 * 8),
                        };
                        let k = ctx.tm.konst(n as u8 * 8, bits);
                        let (want, got) = (ctx.tm.and(want, k), ctx.tm.and(got, k));
                        prove_eq(
                            ctx,
                            want,
                            got,
                            &format!("bytes {off}..{} of the returned structure", off + n),
                        )?;
                        off += n;
                    }
                    // The AAPCS does not require the callee to hand the result address back in r0
                    // (GCC does, clang does not), so r0 is not compared here.
                } else if let Some(v) = ret {
                    let w = ctx.tm.width(v);
                    if w == 64 {
                        let got = ctx.tm.concat(m.regs[1], m.regs[0]);
                        prove_eq(ctx, v, got, "return value")?;
                    } else {
                        let expect = ctx.tm.resize(v, 32, p.is_signed(f.ty.ret));
                        prove_eq(ctx, expect, m.regs[0], "return value")?;
                    }
                }
                compare_world(ctx, job, &cx.mem.world, cx.mem.epoch, &m, "memory at return")?;
                for r in (4..=11).chain([13]) {
                    let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
                    prove_eq(
                        ctx,
                        job.regs[r],
                        m.regs[r],
                        &format!("callee-saved register {name} at return"),
                    )?;
                }
                return Ok(PathResult {
                    cov: cx.cov,
                    insns: m.covered,
                    data: m.data_covered,
                });
            }
        }
    }
    // The path ended in a call that does not return.
    if k != cx.events.len() {
        return Err(Stop::Mismatch(
            "binary stops before the source's remaining calls".into(),
            None,
        ));
    }
    Ok(PathResult {
        cov: cx.cov,
        insns: m.covered,
        data: m.data_covered,
    })
}

struct FuncOutcome {
    report: FuncReport,
    cov: BTreeSet<u32>,
    bytes: BTreeSet<u32>,
}

fn verify_function(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
    let f = &prog.funcs[fid as usize];
    let sym = image.func(&f.name).expect("entry has a symbol");
    let start = Instant::now();
    let mut out = FuncOutcome {
        report: FuncReport {
            name: f.name.to_string(),
            addr: sym.addr,
            size: sym.size,
            status: Status::Proved,
            paths: 0,
            undefined_paths: 0,
            millis: 0,
        },
        cov: BTreeSet::new(),
        bytes: BTreeSet::new(),
    };
    let mut ctx = Ctx::new(opts.limits);
    ctx.deadline = Some(start + opts.time_limit);
    ctx.prover.rom = image
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    // Signature check.
    let scalar = |t| prog.is_scalar(t) && !prog.is_float(t);
    let record = |t| matches!(prog.ty(t), Type::Record(_)) && prog.size_of(t).is_some_and(|s| s > 0);
    let passable = |t| scalar(t) || record(t);
    if !(f.ty.ret == VOID || passable(f.ty.ret)) || !f.ty.params.iter().all(|&t| passable(t)) || f.ty.variadic {
        out.report.status = Status::Unsupported("non-integer parameter or return type".into());
        return out;
    }
    // Shared symbolic inputs.
    let mut regs = [0 as T; 16];
    for (i, r) in regs.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
    }
    if let Some(sb) = image.static_base {
        // Read-write position independence: r9 holds the base of the data area.
        regs[9] = ctx.tm.konst(32, sb as u64);
    }
    regs[13] = ctx.private_base("SP0");
    regs[14] = ctx.named_sym("LR0", 32);
    regs[15] = ctx.tm.konst(32, 0);
    let lr0 = regs[14];
    let mut pre = Vec::new();
    // The public interface keeps the stack 8-byte aligned.
    let low = ctx.tm.extract(regs[13], 0, 3);
    let z3 = ctx.tm.konst(3, 0);
    pre.push(ctx.tm.eq(low, z3));
    // A structure larger than four bytes is returned in memory the caller provides: r0 holds
    // its address.  The caller guarantees that nothing else designates that memory, so it is
    // modelled as a private object.
    let ret_slot = if record(f.ty.ret) && prog.size_of(f.ty.ret).unwrap_or(0) > 4 {
        let slot = ctx.private_base("RET0");
        regs[0] = slot;
        let low = ctx.tm.extract(slot, 0, 2);
        let z2 = ctx.tm.konst(2, 0);
        pre.push(ctx.tm.eq(low, z2));
        Some(slot)
    } else {
        None
    };
    let shapes: Vec<(u32, bool)> =
        f.ty.params
            .iter()
            .map(|&t| (prog.size_of(t).unwrap_or(4), prog.align_of(t) == 8))
            .collect();
    let mut args = Vec::new();
    let mut stack_args = Vec::new();
    let mut struct_args = Vec::new();
    for (i, (&ty, locs)) in
        f.ty.params
            .iter()
            .zip(arg_words(&shapes, ret_slot.is_some() as u8))
            .enumerate()
    {
        let words: Vec<T> = locs
            .iter()
            .map(|loc| match *loc {
                WordLoc::Reg(n) => regs[n as usize],
                WordLoc::Stack(off) => {
                    let s = ctx.named_sym(&format!("stk{off}"), 32);
                    stack_args.push((off, s));
                    s
                }
            })
            .collect();
        if record(ty) {
            // Passed by value: the C side sees an object holding the words the caller passed.
            let base = ctx.private_base(&format!("&arg{i}"));
            struct_args.push((base, words));
            args.push(base);
            continue;
        }
        let raw = if words.len() == 2 {
            ctx.tm.concat(words[1], words[0])
        } else {
            words[0]
        };
        let w = prog.bits(ty);
        let v = ctx.tm.trunc(raw, w);
        if w < 32 {
            // The caller passes narrow arguments already extended to a full register.
            let ext = ctx.tm.resize(v, 32, prog.is_signed(ty));
            pre.push(ctx.tm.eq(raw, ext));
            if ty == crate::c::ast::BOOL {
                let two = ctx.tm.konst(8, 2);
                pre.push(ctx.tm.ult(v, two));
            }
        }
        args.push(v);
    }
    let job = Job {
        prog,
        image,
        env,
        fid,
        entry: sym.addr,
        regs,
        args,
        stack_args,
        struct_args,
        ret_slot,
        lr0,
    };
    let mut bounded: Option<String> = None;
    let mut inconclusive: Option<String> = None;
    let mut explored = 0usize;
    // Iterative deepening on the number of undetermined branches per path, so that loops with an
    // input-dependent trip count are proved for small counts first.
    let max_depth = opts.limits.max_depth;
    let mut schedule: Vec<usize> = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32]
        .into_iter()
        .filter(|&d| d < max_depth)
        .collect();
    schedule.push(max_depth);
    let mut best_paths = 0usize;
    'rounds: for (round, &depth) in schedule.iter().enumerate() {
        ctx.limits.max_depth = depth;
        ctx.decisions.clear();
        let mut depth_hit = false;
        inconclusive = None;
        out.report.paths = 0;
        out.report.undefined_paths = 0;
        loop {
            ctx.restart(&pre);
            explored += 1;
            match run_path(&mut ctx, &job) {
                Ok(r) => {
                    out.report.paths += 1;
                    out.cov.extend(r.cov);
                    for (a, n) in r.insns.into_iter().chain(r.data) {
                        out.bytes.extend(a..a + n as u32);
                    }
                }
                Err(Stop::Undefined) => out.report.undefined_paths += 1,
                Err(Stop::Halt) => unreachable!("Halt is handled by run_path"),
                Err(Stop::Truncated(why)) => {
                    if why == "branch depth limit" {
                        depth_hit = true;
                    } else {
                        bounded.get_or_insert(why);
                    }
                }
                Err(Stop::Inconclusive(why)) => {
                    inconclusive.get_or_insert(why);
                }
                Err(Stop::Mismatch(why, _)) => {
                    out.report.status = Status::Mismatch(why);
                    break 'rounds;
                }
                Err(Stop::Unsupported(why)) => {
                    out.report.status = Status::Unsupported(why);
                    break 'rounds;
                }
            }
            best_paths = best_paths.max(out.report.paths);
            if start.elapsed() > opts.time_limit {
                bounded.get_or_insert_with(|| "time limit".into());
                break 'rounds;
            }
            if explored >= opts.limits.max_paths {
                bounded.get_or_insert_with(|| "path limit".into());
                break 'rounds;
            }
            if !ctx.next_path() {
                break;
            }
        }
        if !depth_hit {
            break;
        }
        if round + 1 == schedule.len() {
            bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
        }
    }
    out.report.paths = out.report.paths.max(best_paths);
    if out.report.status == Status::Proved {
        if let Some(why) = inconclusive {
            out.report.status = Status::Inconclusive(why);
        } else if let Some(why) = bounded {
            out.report.status = Status::Bounded(format!("{why}; {} paths proved", out.report.paths));
        }
    }
    if matches!(out.report.status, Status::Mismatch(_) | Status::Unsupported(_)) {
        // Nothing about this function counts as verified.
        out.cov.clear();
        out.bytes.clear();
    }
    out.report.millis = start.elapsed().as_millis();
    out
}

/// Compare the initial contents of every source-defined object with the binary.
fn check_data(prog: &Program, image: &Image, env: &CEnv, report: &mut Report) {
    for (i, g) in prog.globals.iter().enumerate() {
        if !g.defined {
            continue;
        }
        let Some(addr) = env.global_addr[i] else { continue };
        let Some(expect) = env.init_bytes(i as u32) else {
            continue;
        };
        let Some(got) = image.read(addr, expect.len() as u32) else {
            if image.segments.iter().all(|s| !s.writable) {
                // Raw image: RAM contents are not part of the file.
                continue;
            }
            report
                .data_issues
                .push(format!("{}: object at {addr:#x} is outside the image", g.name));
            continue;
        };
        report.data_checked += 1;
        if let Some(off) = expect.iter().zip(got).position(|(a, b)| a != b) {
            report.data_issues.push(format!(
                "{}: initial value differs at offset {off}: source has {:#04x}, binary has {:#04x}",
                g.name, expect[off], got[off]
            ));
        }
    }
}

pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
    let env = CEnv::new(prog, image);
    let mut report = Report::default();
    let mut cov: BTreeSet<u32> = BTreeSet::new();
    let mut bytes: BTreeSet<u32> = BTreeSet::new();
    for (fid, f) in prog.funcs.iter().enumerate() {
        if f.body.is_none() || image.func(&f.name).is_none() {
            continue;
        }
        if !opts.only.is_empty() && !opts.only.iter().any(|n| **n == *f.name) {
            continue;
        }
        let o = verify_function(prog, image, &env, fid as u32, opts);
        cov.extend(o.cov);
        bytes.extend(o.bytes);
        report.funcs.push(o.report);
    }
    check_data(prog, image, &env, &mut report);

    // Source coverage.
    report.src = (cov.len(), prog.ncov as usize);
    let mut lines: BTreeSet<(String, u32)> = BTreeSet::new();
    let mut hit: HashSet<(u16, u32)> = HashSet::new();
    for &c in &cov {
        let loc = prog.cov_info[c as usize].1;
        hit.insert((loc.file, loc.line));
    }
    for (c, (_, loc)) in prog.cov_info.iter().enumerate() {
        if !cov.contains(&(c as u32)) && !hit.contains(&(loc.file, loc.line)) {
            lines.insert((prog.files.get(loc.file as usize).cloned().unwrap_or_default(), loc.line));
        }
    }
    report.uncovered_lines = lines.into_iter().collect();
    for (c, (fid, loc)) in prog.cov_info.iter().enumerate() {
        // Only functions that were candidates for verification have meaningful points.
        report.src_points.push(SrcPoint {
            file: prog.files.get(loc.file as usize).cloned().unwrap_or_default(),
            line: loc.line,
            func: prog.funcs[*fid as usize].name.to_string(),
            proved: cov.contains(&(c as u32)),
        });
    }
    let reached_funcs: HashSet<u32> = cov.iter().map(|&c| prog.cov_info[c as usize].0).collect();
    for (fid, f) in prog.funcs.iter().enumerate() {
        if f.body.is_some() && image.func(&f.name).is_none() && !reached_funcs.contains(&(fid as u32)) {
            report.absent.push(f.name.to_string());
        }
    }

    // Binary coverage: code bytes are everything in executable segments except alignment padding.
    let mut total = 0usize;
    let mut proved = 0usize;
    for seg in image.segments.iter().filter(|s| s.exec) {
        let in_func = |a: u32| {
            image
                .symbols
                .iter()
                .any(|s| s.kind == SymKind::Func && a >= s.addr && a - s.addr < s.size)
        };
        let mut o = 0usize;
        while o < seg.data.len() {
            let a = seg.addr + o as u32;
            let n = if o + 1 < seg.data.len() { 2 } else { 1 };
            let hw = if n == 2 {
                u16::from_le_bytes([seg.data[o], seg.data[o + 1]])
            } else {
                seg.data[o] as u16
            };
            let covered = (0..n as u32).filter(|i| bytes.contains(&(a + i))).count();
            let padding = covered == 0 && !in_func(a) && matches!(hw, 0 | 0xbf00 | 0x46c0);
            if !padding {
                total += n;
                proved += covered;
            }
            for i in 0..n as u32 {
                let state = if padding {
                    ByteState::Padding
                } else if bytes.contains(&(a + i)) {
                    ByteState::Proved
                } else {
                    ByteState::Unproved
                };
                match report.bin_ranges.last_mut() {
                    Some(r) if r.end == a + i && r.state == state => r.end += 1,
                    _ => report.bin_ranges.push(BinRange {
                        start: a + i,
                        end: a + i + 1,
                        state,
                    }),
                }
            }
            o += n;
        }
    }
    report.bin = (proved, total);
    for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size > 0) {
        if image.segment_at(s.addr).is_some() && !(s.addr..s.addr + s.size).any(|a| bytes.contains(&a)) {
            let verified = report.funcs.iter().any(|f| f.name == s.name);
            if !verified {
                report.unmatched.push((s.name.clone(), s.size));
            }
        }
    }
    report
}