cverif 0.0.3

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
//! Naming discovered functions after the source, by proof.
//!
//! Cheap signatures (constants, strings, addresses of objects, calls to known helpers) only
//! *rank* the candidates for a source function.  A name is assigned when the equivalence proof
//! of the source function against the candidate succeeds: PROVED, or BOUNDED with at least one
//! path and no mismatch ("bounded match").  Objects without a symbol are located the same way:
//! an address the candidate uses is tried for each object the source function uses, and kept
//! if the proof goes through.
//!
//! Run-time helpers of the compiler (division, 64-bit arithmetic) have no source here.  They
//! are *recognised* by running them on test vectors, which is evidence and not proof; the
//! report says so.

use super::{Analysis, Discovery, Finding, Func, Match, Provenance};
use crate::c::ast::{Body, EK, Expr, OpKind, Program, Term, Type};
use crate::c::exec::CEnv;
use crate::image::{Image, SymKind, Symbol};
use crate::sym::{Ctx, Limits, Stop};
use crate::thumb::exec::{Callee, Exit, Machine};
use crate::verify::{Options as VerifyOptions, Preset, Status, run_jobs, trial};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};

// ----- running machine code on its own ----------------------------------------------------

fn new_ctx(limits: Limits, work: u64, time: Duration, image: &Image) -> Ctx {
    let mut ctx = Ctx::new(limits);
    ctx.set_budget(work, 4_000_000, Some(Instant::now() + time));
    ctx.prover.rom = image
        .segments
        .iter()
        .filter(|s| !s.writable)
        .map(|s| (s.addr, s.data.clone()))
        .collect();
    ctx
}

/// Symbolically execute the code at `entry` with every input unknown and report the
/// instructions executed and the read-only data read on any explored path, restricted to
/// nothing; the last value says whether every path was explored to its end.
#[allow(clippy::type_complexity)]
pub(super) fn trace(image: &Image, entry: u32, limit: u32) -> (BTreeSet<(u32, u8)>, BTreeSet<(u32, u8)>, bool) {
    let limits = Limits {
        max_depth: 24,
        max_paths: 600,
        max_steps: 4000,
        ..Limits::default()
    };
    let mut ctx = new_ctx(limits, 150_000, Duration::from_secs(5), image);
    let mut regs = [0; 16];
    for (i, r) in regs.iter_mut().enumerate().take(13) {
        *r = ctx.named_sym(&format!("r{i}"), 32);
    }
    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 classify = |addr: u32| -> Callee {
        let a = addr & !1;
        if a >= entry && a < limit {
            return Callee::Internal;
        }
        match image.func_at(a) {
            Some(s) => Callee::External(s.name.clone()),
            None => Callee::Internal,
        }
    };
    let (mut insns, mut data) = (BTreeSet::new(), BTreeSet::new());
    let mut complete = true;
    let mut explored = 0usize;
    loop {
        ctx.restart(&[]);
        explored += 1;
        let mut m = Machine::new(&mut ctx, entry, regs);
        let mut k = 0usize;
        loop {
            match m.run(&mut ctx, image, lr0, &classify) {
                Ok(Exit::Call { name }) => {
                    m.mem.world.clear();
                    m.mem.epoch += 1;
                    let ret = ctx.named_sym(&format!("ret{k}:{name}"), 32);
                    m.finish_call(&mut ctx, k, Some(ret), None);
                    k += 1;
                    if k > 32 {
                        complete = false;
                        break;
                    }
                }
                Ok(_) | Err(Stop::Undefined) | Err(Stop::Halt) => break,
                Err(_) => {
                    complete = false;
                    break;
                }
            }
        }
        insns.extend(m.covered.iter().copied());
        data.extend(m.data_covered.iter().copied());
        if ctx.check_deadline().is_err() || explored >= limits.max_paths {
            complete = false;
            break;
        }
        if !ctx.next_path() {
            break;
        }
    }
    (insns, data, complete)
}

/// Run the code at `entry` on concrete register values; r0-r3 at its return, if it returns
/// without touching anything unknown.
fn concrete(image: &Image, entry: u32, args: [u32; 4]) -> Option<[u32; 4]> {
    let limits = Limits {
        max_depth: 2,
        max_paths: 1,
        max_steps: 3000,
        ..Limits::default()
    };
    let mut ctx = new_ctx(limits, 60_000, Duration::from_millis(500), image);
    let mut regs = [0; 16];
    for (i, r) in regs.iter_mut().enumerate().take(13) {
        *r = match args.get(i) {
            Some(v) => ctx.tm.konst(32, *v as u64),
            None => ctx.tm.konst(32, 0xa5a5_0000 + i 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 classify = |_: u32| Callee::Internal;
    ctx.restart(&[]);
    let mut m = Machine::new(&mut ctx, entry, regs);
    match m.run(&mut ctx, image, lr0, &classify) {
        Ok(Exit::Return) => {}
        _ => return None,
    }
    if !ctx.decisions.is_empty() || !m.mem.world.is_empty() {
        return None; // depended on something unknown, or wrote memory that is not its stack
    }
    let mut out = [0u32; 4];
    for (i, o) in out.iter_mut().enumerate() {
        *o = ctx.tm.as_const(m.regs[i])? as u32;
    }
    Some(out)
}

/// Run-time helpers that can be told apart by their results: (name, arguments -> expected
/// r0..r3 with a mask of the registers that count).
type Reference = fn([u32; 4]) -> Option<([u32; 4], u8)>;

fn u64of(lo: u32, hi: u32) -> u64 {
    (lo as u64) | ((hi as u64) << 32)
}

const HELPERS: &[(&str, Reference)] = &[
    ("__aeabi_uidivmod", |a| {
        (a[1] != 0).then(|| ([a[0] / a[1], a[0] % a[1], 0, 0], 0b11))
    }),
    ("__aeabi_idivmod", |a| {
        let (x, y) = (a[0] as i32, a[1] as i32);
        (y != 0 && !(x == i32::MIN && y == -1)).then(|| ([(x / y) as u32, (x % y) as u32, 0, 0], 0b11))
    }),
    ("__aeabi_uidiv", |a| (a[1] != 0).then(|| ([a[0] / a[1], 0, 0, 0], 0b1))),
    ("__aeabi_idiv", |a| {
        let (x, y) = (a[0] as i32, a[1] as i32);
        (y != 0 && !(x == i32::MIN && y == -1)).then(|| ([(x / y) as u32, 0, 0, 0], 0b1))
    }),
    ("__aeabi_lmul", |a| {
        let p = u64of(a[0], a[1]).wrapping_mul(u64of(a[2], a[3]));
        Some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
    }),
    ("__aeabi_llsl", |a| {
        let p = u64of(a[0], a[1]) << (a[2] & 63);
        (a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
    }),
    ("__aeabi_llsr", |a| {
        let p = u64of(a[0], a[1]) >> (a[2] & 63);
        (a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
    }),
    ("__aeabi_lasr", |a| {
        let p = ((u64of(a[0], a[1]) as i64) >> (a[2] & 63)) as u64;
        (a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
    }),
    ("__aeabi_uldivmod", |a| {
        let (x, y) = (u64of(a[0], a[1]), u64of(a[2], a[3]));
        (y != 0).then(|| {
            let (q, r) = (x / y, x % y);
            ([q as u32, (q >> 32) as u32, r as u32, (r >> 32) as u32], 0b1111)
        })
    }),
    ("__aeabi_ldivmod", |a| {
        let (x, y) = (u64of(a[0], a[1]) as i64, u64of(a[2], a[3]) as i64);
        (y != 0 && !(x == i64::MIN && y == -1)).then(|| {
            let (q, r) = ((x / y) as u64, (x % y) as u64);
            ([q as u32, (q >> 32) as u32, r as u32, (r >> 32) as u32], 0b1111)
        })
    }),
];

const VECTORS: &[[u32; 4]] = &[
    [1_000_003, 97, 12, 5],
    [0xffff_fff9, 7, 3, 0],
    [0x8000_0001, 0xffff_fffd, 33, 0xffff_ffff],
    [5, 0x7fff_ffff, 63, 1],
    [0, 3, 0, 9],
    [0xdead_beef, 0x0001_0000, 17, 0],
    [123_456_789, 1, 1, 0],
    [0x7fff_ffff, 2, 31, 0x8000_0000],
    [0xffff_ffff, 0xffff_ffff, 32, 0],
    [99, 100, 8, 0],
    [0x0012_3456, 0x0000_0123, 60, 0x10],
    [0xfedc_ba98, 0x7654_3210, 4, 2],
];

/// Functions that behave like a run-time helper on every test vector: (address, name, vectors).
pub fn recognise(image: &Image, funcs: &[Func]) -> Vec<(u32, &'static str, usize)> {
    let mut out = Vec::new();
    for f in funcs {
        if f.size > 4096 || !f.notes.is_empty() {
            continue;
        }
        // A helper computes on registers: no object, no peripheral.
        if f.consts.iter().any(|c| (0x1000_0000..=0xffff_ffff).contains(c)) {
            continue;
        }
        'helper: for (name, reference) in HELPERS {
            let mut agreed = 0usize;
            for v in VECTORS {
                let Some((want, mask)) = reference(*v) else { continue };
                let Some(got) = concrete(image, f.addr, *v) else {
                    continue 'helper;
                };
                if (0..4).any(|i| mask & (1 << i) != 0 && got[i] != want[i]) {
                    continue 'helper;
                }
                agreed += 1;
            }
            if agreed >= 8 {
                out.push((f.addr, *name, agreed));
                break;
            }
        }
    }
    out
}

// ----- signatures -------------------------------------------------------------------------

/// What a source function refers to (with the functions it calls, to a small depth).
#[derive(Default, Clone)]
struct SrcSig {
    consts: BTreeSet<u32>,
    strings: BTreeSet<u32>,
    globals: BTreeSet<u32>,
    callees: BTreeSet<u32>,
}

fn walk_expr(e: &Expr, sig: &mut SrcSig) {
    match &e.kind {
        EK::Const(c) => {
            if *c >= 0x100 {
                sig.consts.insert(*c as u32);
            }
        }
        EK::Str(s) => {
            sig.strings.insert(*s);
        }
        EK::Global(g) => {
            sig.globals.insert(*g);
        }
        EK::Func(f) => {
            sig.callees.insert(*f);
        }
        EK::FConst(_) | EK::Local(_) | EK::Prev | EK::VlaLive(_) => {}
        EK::Asm(a) => {
            if let Some(x) = &a.input {
                walk_expr(x, sig);
            }
        }
        EK::Alloca(a, ..) => walk_expr(a, sig),
        EK::Deref(a)
        | EK::Member(a, _)
        | EK::BitField(a, ..)
        | EK::Bits(a, ..)
        | EK::Addr(a)
        | EK::Load(a)
        | EK::Cast(a)
        | EK::Neg(a)
        | EK::BitNot(a)
        | EK::LogNot(a)
        | EK::VaStart(a)
        | EK::VaArg(a) => walk_expr(a, sig),
        EK::Bin(_, a, b)
        | EK::PtrAdd(a, b, _)
        | EK::PtrDiff(a, b, _)
        | EK::LogAnd(a, b)
        | EK::LogOr(a, b)
        | EK::Comma(a, b)
        | EK::Assign(a, b)
        | EK::AssignOp(a, b, _) => {
            walk_expr(a, sig);
            walk_expr(b, sig);
        }
        EK::Cond(a, b, c) => {
            walk_expr(a, sig);
            walk_expr(b, sig);
            walk_expr(c, sig);
        }
        EK::Compound { items, .. } => items.iter().for_each(|(_, x)| walk_expr(x, sig)),
        EK::Call(f, args) => {
            walk_expr(f, sig);
            args.iter().for_each(|x| walk_expr(x, sig));
        }
    }
}

fn walk_body(b: &Body, sig: &mut SrcSig) {
    for blk in &b.blocks {
        for op in &blk.ops {
            match &op.kind {
                OpKind::Eval(e) => walk_expr(e, sig),
                OpKind::Init { items, .. } => items.iter().for_each(|(_, x)| walk_expr(x, sig)),
            }
        }
        match &blk.term {
            Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk_expr(e, sig),
            _ => {}
        }
    }
}

fn src_sig(prog: &Program, fid: u32) -> SrcSig {
    let mut sig = SrcSig::default();
    let mut seen: HashSet<u32> = HashSet::new();
    let mut work = vec![(fid, 0)];
    while let Some((f, depth)) = work.pop() {
        if !seen.insert(f) {
            continue;
        }
        let Some(body) = &prog.funcs[f as usize].body else {
            continue;
        };
        let mut one = SrcSig::default();
        walk_body(body, &mut one);
        if depth < 4 {
            work.extend(one.callees.iter().map(|c| (*c, depth + 1)));
        }
        sig.consts.extend(one.consts);
        sig.strings.extend(one.strings);
        sig.globals.extend(one.globals);
        sig.callees.extend(one.callees);
    }
    sig
}

/// Constants a function of the binary forms, with those of the anonymous functions it calls.
fn bin_consts(
    funcs: &BTreeMap<u32, &Func>,
    named: &HashMap<u32, String>,
    addr: u32,
) -> (BTreeSet<u32>, BTreeSet<String>) {
    let mut consts = BTreeSet::new();
    let mut calls = BTreeSet::new();
    let mut seen: HashSet<u32> = HashSet::new();
    let mut work = vec![(addr, 0)];
    while let Some((a, depth)) = work.pop() {
        if !seen.insert(a) {
            continue;
        }
        let Some(f) = funcs.get(&a) else { continue };
        consts.extend(f.consts.iter().copied());
        for c in &f.calls {
            match named.get(c) {
                Some(n) => {
                    calls.insert(n.clone());
                }
                None if depth < 3 => work.push((*c, depth + 1)),
                None => {}
            }
        }
    }
    (consts, calls)
}

// ----- the matcher ------------------------------------------------------------------------

/// What matching decides.
#[derive(Default)]
pub struct Outcome {
    pub matches: Vec<Match>,
    /// Objects located for the source: (name, address, size).
    pub objects: Vec<(String, u32, u32)>,
    /// Candidates each unmatched source function was tried against without success.
    pub tried: HashMap<u32, BTreeSet<u32>>,
    /// What the attempt at the best-ranked candidate ended in, for each of them.
    pub last: HashMap<u32, String>,
    pub findings: Vec<Finding>,
    /// Source functions no code was matched to, and what the attempts ended in.
    pub not_found: Vec<(String, String)>,
    /// How verification has to place the source's functions and objects.
    pub preset: Preset,
    /// Entry points that the proofs establish and discovery did not have: (address, name).
    pub new_entries: Vec<(u32, String)>,
    /// Given function symbols that are wrong: (name, given address).
    pub dropped: Vec<(String, u32)>,
}

/// Result of trying one source function.
struct Try {
    fid: u32,
    /// (address, proved?, paths, objects placed for it)
    #[allow(clippy::type_complexity)]
    hit: Option<(u32, bool, usize, Vec<(u32, u32)>)>,
    /// Candidates tried.
    tried: BTreeSet<u32>,
    /// Further candidates the proof succeeds for.
    also: Vec<u32>,
    trials: usize,
    last: String,
}

fn is_good(status: &Status, paths: usize) -> Option<bool> {
    match status {
        Status::Proved => Some(true),
        Status::Bounded(_) if paths > 0 => Some(false),
        _ => None,
    }
}

/// The image trial proofs run on: every discovered function has a symbol, so that calls
/// between them are followed (anonymous functions) or matched by name (helpers, externals).
fn trial_image(base: &Image, d: &Discovery, helpers: &[(u32, &'static str, usize)], extra: &[(u32, u32)]) -> Image {
    let mut img = Image {
        segments: base
            .segments
            .iter()
            .map(|s| crate::image::Segment {
                exec: s.exec || (base.soft_bounds && !s.writable),
                ..s.clone()
            })
            .collect(),
        externals: base.externals.clone(),
        static_base: base.static_base,
        short_enums: base.short_enums,
        hard_float: base.hard_float,
        soft_bounds: base.soft_bounds,
        ..Default::default()
    };
    let mut at: BTreeSet<u32> = BTreeSet::new();
    for &(a, name, _) in helpers {
        let size = d.funcs.iter().find(|f| f.addr == a).map_or(2, |f| f.size.max(2));
        img.symbols.push(Symbol {
            name: name.to_string(),
            addr: a,
            size,
            kind: SymKind::Func,
            global: true,
            file: None,
        });
        at.insert(a);
    }
    for f in &d.funcs {
        if !at.insert(f.addr) {
            continue;
        }
        // Given names are not relied upon here: whether they are right is what is being tested.
        img.symbols.push(Symbol {
            name: if super::is_helper_name(&f.name) {
                f.name.clone()
            } else {
                format!("fn_{:08x}", f.addr)
            },
            addr: f.addr,
            size: f.size.max(2),
            kind: SymKind::Func,
            global: true,
            file: None,
        });
        img.data_ranges.extend(f.pools.iter().copied());
    }
    for &(a, size) in extra {
        if at.insert(a) {
            img.symbols.push(Symbol {
                name: format!("sub_{a:08x}"),
                addr: a,
                size,
                kind: SymKind::Func,
                global: true,
                file: None,
            });
        }
    }
    img.symbols
        .extend(base.symbols.iter().filter(|s| s.kind != SymKind::Func).cloned());
    img.symbols.sort_by_key(|s| (s.addr, s.kind != SymKind::Func));
    img.data_ranges.sort();
    img
}

/// Name the functions of `a` after the source `prog`.  `given` is the image as the user gave
/// it (its function symbols are tested, not trusted).
///
/// `prior`: candidates that an earlier run already tried in vain for a source function.
pub fn run(
    prog: &Program,
    given: &Image,
    a: &Analysis,
    vopts: &VerifyOptions,
    prior: &HashMap<u32, BTreeSet<u32>>,
    prior_last: &HashMap<u32, String>,
) -> Outcome {
    let d = &a.discovery;
    let mut out = Outcome::default();
    let funcs: BTreeMap<u32, &Func> = d.funcs.iter().map(|f| (f.addr, f)).collect();

    // Helpers of the compiler's run-time library, by test vectors.
    let probe = trial_image(given, d, &[], &[]);
    let anonymous: Vec<Func> = d
        .funcs
        .iter()
        .filter(|f| super::is_anonymous(&f.name))
        .cloned()
        .collect();
    let helpers = recognise(&probe, &anonymous);
    for &(addr, name, n) in &helpers {
        out.matches.push(Match {
            source: name.to_string(),
            addr,
            how: "recognised",
            also: Vec::new(),
            detail: format!("agrees with {name} on {n} test vectors; not proved"),
        });
    }
    let mut named: HashMap<u32, String> = helpers.iter().map(|h| (h.0, h.1.to_string())).collect();
    for f in &d.funcs {
        if super::is_helper_name(&f.name) {
            named.entry(f.addr).or_insert(f.name.clone());
        }
    }

    // Speculative neighbours of given symbols: an address that is off by an instruction or two.
    let mut extra: Vec<(u32, u32)> = Vec::new();
    for s in given.symbols.iter().filter(|s| s.kind == SymKind::Func) {
        for delta in [-4i32, -2, 2, 4] {
            let c = s.addr.wrapping_add(delta as u32);
            if !funcs.contains_key(&c) && given.read_const(c, 2).is_some() {
                let end = funcs
                    .range(c + 1..)
                    .next()
                    .map_or(c + 2, |(e, f)| if *e <= s.addr { e + f.size } else { *e });
                extra.push((c, end.saturating_sub(c).max(2)));
            }
        }
    }
    extra.sort();
    extra.dedup_by_key(|e| e.0);
    let image = trial_image(given, d, &helpers, &extra);

    let mut env = CEnv::new(prog, &image);
    // Functions: nothing is placed by name.
    let todo: Vec<u32> = (0..prog.funcs.len() as u32)
        .filter(|&f| prog.funcs[f as usize].body.is_some())
        .collect();
    for &f in &todo {
        env.set_func(f, None);
    }
    let given_addr = |fid: u32| -> Option<u32> {
        let f = &prog.funcs[fid as usize];
        let mut it = given
            .symbols
            .iter()
            .filter(|s| s.kind == SymKind::Func && s.name == *f.name);
        match (it.next(), it.next()) {
            (Some(s), None) => Some(s.addr),
            _ => None,
        }
    };
    let sigs: HashMap<u32, SrcSig> = todo.iter().map(|&f| (f, src_sig(prog, f))).collect();
    let bsig: BTreeMap<u32, (BTreeSet<u32>, BTreeSet<String>)> = d
        .funcs
        .iter()
        .map(|f| (f.addr, bin_consts(&funcs, &named, f.addr)))
        .collect();
    let trial_opts = {
        let mut o = vopts.clone();
        o.only = Vec::new();
        o.dump = 0;
        o.work_limit = o.work_limit.min(30_000);
        o.time_limit = o.time_limit.min(Duration::from_secs(5));
        o.limits.max_paths = o.limits.max_paths.min(300);
        o
    };
    let big = d.funcs.len() > 400;

    let mut claimed: BTreeMap<u32, Vec<u32>> = BTreeMap::new(); // address -> source functions
    let mut done: HashMap<u32, Try> = HashMap::new();
    let mut pending: Vec<u32> = todo.clone();
    let mut bound_objs: BTreeMap<u32, u32> = BTreeMap::new(); // global -> address, placed by a proof
    for round in 0..6 {
        if pending.is_empty() {
            break;
        }
        // Fewest unknown objects first within a round (they are placed for the others).
        let unknown = |env: &CEnv, f: u32| {
            sigs[&f]
                .globals
                .iter()
                .filter(|g| env.global_addr[**g as usize].is_none())
                .count()
        };
        pending.sort_by_key(|&f| (unknown(&env, f), f));
        let results = run_jobs(&pending, vopts.jobs, |fid| {
            try_function(
                prog,
                &image,
                &env,
                fid,
                &sigs[&fid],
                &funcs,
                &bsig,
                &claimed,
                given_addr(fid),
                prior.get(&fid),
                &extra,
                &trial_opts,
                big,
                round,
            )
        });
        let mut next = Vec::new();
        let mut progress = false;
        for t in results {
            let fid = t.fid;
            match &t.hit {
                Some((addr, _, _, objs)) => {
                    // Two functions of this round may want the same code or the same object.
                    let clash_obj = objs.iter().any(|(g, a)| {
                        bound_objs.get(g).is_some_and(|x| x != a)
                            || bound_objs.iter().any(|(g2, a2)| g2 != g && a2 == a)
                    });
                    let clash_fn = claimed.get(addr).is_some_and(|c| !c.is_empty()) && round < 4 && !t.also.is_empty();
                    if clash_obj || clash_fn {
                        next.push(fid);
                        continue;
                    }
                    for &(g, at) in objs {
                        if bound_objs.insert(g, at).is_none() {
                            env.set_global(&image, g, at);
                        }
                    }
                    claimed.entry(*addr).or_default().push(fid);
                    env.set_func(fid, Some(*addr));
                    progress = true;
                    done.insert(fid, t);
                }
                None => {
                    next.push(fid);
                    done.insert(fid, t);
                }
            }
        }
        pending = next;
        if !progress {
            break;
        }
    }

    // Results.
    for &fid in &todo {
        let f = &prog.funcs[fid as usize];
        let ga = given_addr(fid);
        let Some(t) = done.get_mut(&fid) else { continue };
        if t.last.is_empty()
            && let Some(l) = prior_last.get(&fid)
        {
            t.last = l.clone();
        }
        let t = &*t;
        match &t.hit {
            Some((addr, proved, paths, _)) => {
                out.preset.funcs.push((fid, *addr));
                let how = if *proved { "proved" } else { "bounded" };
                out.matches.push(Match {
                    source: f.name.to_string(),
                    addr: *addr,
                    how,
                    also: t.also.clone(),
                    detail: if *proved {
                        format!("{paths} path(s)")
                    } else {
                        format!("no difference on the {paths} path(s) explored")
                    },
                });
                if !funcs.contains_key(addr) {
                    out.new_entries.push((*addr, f.name.to_string()));
                }
                match ga {
                    Some(g) if g != *addr => {
                        let other = given
                            .symbols
                            .iter()
                            .find(|s| s.kind == SymKind::Func && s.addr == *addr && s.name != *f.name);
                        let (kind, text) = match other {
                            Some(o) => (
                                "swapped",
                                format!(
                                    "symbol {} is given at {g:#x}, where the proof against its source fails; the proof succeeds at {addr:#x}, which the table calls {}: corrected",
                                    f.name, o.name
                                ),
                            ),
                            None => (
                                "wrong-address",
                                format!(
                                    "symbol {} is given at {g:#x}, where the proof against its source fails; the proof succeeds at {addr:#x}: corrected",
                                    f.name
                                ),
                            ),
                        };
                        out.findings.push(Finding {
                            addr: g,
                            name: f.name.to_string(),
                            kind,
                            text,
                        });
                        out.dropped.push((f.name.to_string(), g));
                    }
                    _ => {}
                }
            }
            None => {
                match ga {
                    Some(g) if funcs.contains_key(&g) => {
                        // Not confirmed, not refuted elsewhere: the given name stays, and
                        // verification will say what is wrong with it.
                        out.preset.funcs.push((fid, g));
                        out.matches.push(Match {
                            source: f.name.to_string(),
                            addr: g,
                            how: "given",
                            also: Vec::new(),
                            detail: format!("not confirmed by proof: {}", t.last),
                        });
                        if t.last.starts_with("MISMATCH") {
                            out.findings.push(Finding {
                                addr: g,
                                name: f.name.to_string(),
                                kind: "proof-fails",
                                text: format!(
                                    "symbol {} at {g:#x}: the proof against its source fails ({}), and no other function of the image fits",
                                    f.name, t.last
                                ),
                            });
                        }
                    }
                    _ => {
                        let tried = t.trials + prior.get(&fid).map_or(0, |p| p.len());
                        let why = match (tried, t.last.is_empty()) {
                            (0, false) => t.last.clone(),
                            (0, true) => "no candidate".to_string(),
                            (n, true) => format!("{n} candidate(s) tried"),
                            (n, false) => format!("{n} candidate(s) tried; the best-ranked one: {}", t.last),
                        };
                        out.not_found.push((f.name.to_string(), why))
                    }
                }
            }
        }
    }
    let obj_size = |g: usize| prog.size_of(prog.globals[g].ty).unwrap_or(0);
    for (g, at) in &bound_objs {
        out.preset.globals.push((*g, *at));
        out.objects
            .push((prog.globals[*g as usize].name.to_string(), *at, obj_size(*g as usize)));
    }
    for (fid, t) in &done {
        if t.hit.is_none() {
            let mut all = prior.get(fid).cloned().unwrap_or_default();
            all.extend(t.tried.iter().copied());
            out.tried.insert(*fid, all);
            out.last.insert(*fid, t.last.clone());
        }
    }
    by_data(prog, given, d, &funcs, &mut env, &mut out);
    // Constant objects nothing placed yet: by their contents, now that the functions they
    // point to have addresses.
    for (i, g) in prog.globals.iter().enumerate() {
        if env.global_addr[i].is_some() || !g.defined || !g.is_const {
            continue;
        }
        let Some(bytes) = env.init_bytes(i as u32) else {
            continue;
        };
        if bytes.len() < 8 {
            continue;
        }
        let align = prog.align_of(g.ty).max(1);
        let mut hits = Vec::new();
        for seg in given.segments.iter().filter(|s| !s.writable) {
            let mut from = 0usize;
            while from + bytes.len() <= seg.data.len() && hits.len() < 2 {
                match seg.data[from..].windows(bytes.len()).position(|w| w == bytes) {
                    Some(o) => {
                        let at = seg.addr + (from + o) as u32;
                        if at.is_multiple_of(align) {
                            hits.push(at);
                        }
                        from += o + 1;
                    }
                    None => break,
                }
            }
        }
        if let [at] = hits[..] {
            env.set_global(given, i as u32, at);
            out.preset.globals.push((i as u32, at));
            out.objects.push((g.name.to_string(), at, obj_size(i)));
        }
    }
    out
}

#[allow(clippy::too_many_arguments)]
fn try_function(
    prog: &Program,
    image: &Image,
    env: &CEnv,
    fid: u32,
    sig: &SrcSig,
    funcs: &BTreeMap<u32, &Func>,
    bsig: &BTreeMap<u32, (BTreeSet<u32>, BTreeSet<String>)>,
    claimed: &BTreeMap<u32, Vec<u32>>,
    given: Option<u32>,
    skip: Option<&BTreeSet<u32>>,
    extra: &[(u32, u32)],
    opts: &VerifyOptions,
    big: bool,
    round: usize,
) -> Try {
    let f = &prog.funcs[fid as usize];
    let mut t = Try {
        fid,
        hit: None,
        tried: BTreeSet::new(),
        also: Vec::new(),
        trials: 0,
        last: String::new(),
    };
    if f.unsupported.is_some() {
        t.last = "the source function uses something this tool does not model".into();
        return t;
    }
    // Objects the function needs that have no address yet.
    let unbound: Vec<u32> = sig
        .globals
        .iter()
        .copied()
        .filter(|g| env.global_addr[*g as usize].is_none())
        .collect();
    if unbound.len() > 3 {
        t.last = format!("uses {} objects that have not been located", unbound.len());
        return t;
    }
    // Addresses that hold another object of the source (a declaration without a definition,
    // such as a linker-script symbol, owns no storage and may share its address).
    let taken: BTreeSet<u32> = env
        .global_addr
        .iter()
        .enumerate()
        .filter(|(g, _)| prog.globals[*g].defined)
        .filter_map(|(_, a)| *a)
        .collect();
    let externs: BTreeSet<&str> = sig
        .callees
        .iter()
        .filter(|c| prog.funcs[**c as usize].body.is_none())
        .map(|c| &*prog.funcs[*c as usize].name)
        .collect();

    // Rank the candidates.
    let mut ranked: Vec<(bool, i32, u32)> = Vec::new();
    for (&addr, func) in funcs {
        if func.provenance == Provenance::Speculative && !big && given.is_none() && round == 0 {
            // Guesses are tried after everything certain.
        }
        if super::is_helper_name(&func.name) {
            continue;
        }
        let (consts, calls) = &bsig[&addr];
        let mut score = 0i32;
        for s in &sig.strings {
            let lit = &prog.strings[*s as usize];
            if lit.len() < 2 {
                continue;
            }
            let hit = consts
                .iter()
                .any(|c| image.read_const(*c, lit.len() as u32) == Some(&lit[..]));
            score += if hit { 6 } else { -3 };
        }
        for c in &sig.consts {
            if consts.contains(c) {
                score += if *c >= 0x4000_0000 { 6 } else { 3 };
            } else if *c >= 0x4000_0000 {
                score -= 2;
            }
        }
        for g in &sig.globals {
            match env.global_addr[*g as usize] {
                Some(a) => {
                    let size = prog.size_of(prog.globals[*g as usize].ty).unwrap_or(1).max(1);
                    let hit = consts.range(a..a.saturating_add(size)).next().is_some();
                    score += if hit { 5 } else { -2 };
                }
                None => {
                    if !consts.iter().any(|c| !taken.contains(c)) {
                        score -= 6;
                    }
                }
            }
        }
        for e in &externs {
            score += if calls.contains(*e) { 5 } else { -4 };
        }
        if given == Some(addr) {
            score += 100;
        }
        if func.provenance == Provenance::Speculative {
            score -= 4;
        }
        ranked.push((claimed.get(&addr).is_some_and(|c| !c.is_empty()), -score, addr));
    }
    if let Some(g) = given {
        for &(a, _) in extra {
            if a.abs_diff(g) <= 4 {
                ranked.push((false, -50, a));
            }
        }
    }
    ranked.sort();
    let keep = if big { 8 } else { 48 };
    ranked.truncate(keep);

    let deadline = Instant::now() + Duration::from_secs(if big { 20 } else { 60 });
    for &(_, _, addr) in &ranked {
        if Instant::now() > deadline {
            break;
        }
        if skip.is_some_and(|s| s.contains(&addr)) {
            continue;
        }
        t.tried.insert(addr);
        let consts: Vec<u32> = match bsig.get(&addr) {
            Some(b) => b.0.iter().copied().collect(),
            None => {
                // A neighbour of a given symbol: the constants of the function it is next to.
                bsig.range(..addr)
                    .next_back()
                    .map(|b| b.1.0.iter().copied().collect())
                    .unwrap_or_default()
            }
        };
        // Constant objects that have no address of their own yet (the source's copy stands in
        // for them): where the candidate uses an address that holds exactly their contents,
        // that is the object.
        let mut fixed: Vec<(u32, u32)> = Vec::new();
        for &g in &sig.globals {
            if let Some(a) = env.global_addr[g as usize]
                && env.is_synthetic(a)
                && prog.size_of(prog.globals[g as usize].ty).is_some_and(|n| n >= 2)
                && let Some(at) = consts
                    .iter()
                    .copied()
                    .find(|c| !taken.contains(c) && env.matches_at(image, g, *c))
            {
                fixed.push((g, at));
            }
        }
        // Candidate addresses for each unlocated object.
        let mut choices: Vec<Vec<u32>> = Vec::new();
        for &g in &unbound {
            let gl = &prog.globals[g as usize];
            let mut c: Vec<u32> = Vec::new();
            if gl.is_const && gl.defined {
                // By content, among the addresses the candidate uses.
                c.extend(consts.iter().copied().filter(|a| env.matches_at(image, g, *a)));
            } else {
                let ram =
                    |a: u32| image.segment_at(a).is_none_or(|s| s.writable) && (0x1000_0000..0x4000_0000).contains(&a);
                let mut offs: Vec<u32> = vec![0];
                if let Type::Record(r) = prog.ty(prog.unqual(gl.ty)) {
                    offs.extend(
                        prog.records[*r as usize]
                            .fields
                            .iter()
                            .map(|f| f.offset)
                            .filter(|o| *o > 0),
                    );
                }
                offs.dedup();
                for off in offs {
                    for a in consts.iter().copied().filter(|a| ram(*a)) {
                        let at = a.wrapping_sub(off);
                        if !taken.contains(&at) && !c.contains(&at) && at.is_multiple_of(prog.align_of(gl.ty).max(1)) {
                            c.push(at);
                        }
                    }
                }
            }
            c.truncate(6);
            choices.push(c);
        }
        if choices.iter().any(|c| c.is_empty()) {
            continue;
        }
        // Enumerate assignments (distinct addresses), a bounded number of them.
        let mut idx = vec![0usize; choices.len()];
        let mut tried = 0usize;
        'assign: loop {
            let mut pick: Vec<(u32, u32)> = unbound
                .iter()
                .zip(&idx)
                .enumerate()
                .map(|(i, (g, k))| (*g, choices[i][*k]))
                .collect();
            pick.extend(fixed.iter().copied());
            let distinct = pick.iter().map(|p| p.1).collect::<BTreeSet<_>>().len() == pick.len();
            if distinct {
                let mut e = env.clone();
                for &(g, at) in &pick {
                    e.set_global(image, g, at);
                }
                e.set_func(fid, Some(addr));
                let (status, paths) = trial(prog, image, &e, fid, opts);
                t.trials += 1;
                tried += 1;
                match is_good(&status, paths) {
                    Some(proved) => {
                        match &t.hit {
                            None => t.hit = Some((addr, proved, paths, pick.clone())),
                            Some((first, was_proved, ..)) => {
                                if proved && !*was_proved {
                                    let old = *first;
                                    t.hit = Some((addr, proved, paths, pick.clone()));
                                    t.also.push(old);
                                } else if *first != addr && !t.also.contains(&addr) {
                                    t.also.push(addr);
                                }
                            }
                        }
                        break 'assign;
                    }
                    None => {
                        if given == Some(addr) || t.last.is_empty() {
                            t.last = format!("{}: {}", status.label(), status.detail());
                        }
                    }
                }
            }
            // Next assignment.
            let mut i = 0;
            loop {
                if i == idx.len() || tried >= 16 {
                    break 'assign;
                }
                idx[i] += 1;
                if idx[i] < choices[i].len() {
                    break;
                }
                idx[i] = 0;
                i += 1;
            }
        }
        // A proof at the address the table gives settles it.  Otherwise one more candidate
        // that fits is looked for, to report the ambiguity (not to change the choice).
        if let Some((at, true, ..)) = t.hit
            && (given == Some(at) || !t.also.is_empty() || big)
        {
            break;
        }
    }
    t
}

/// Apply what matching decided to the discovery: names, provenance, findings.
pub fn apply(d: &mut Discovery, out: &Outcome) {
    d.matches = out.matches.clone();
    d.objects = out.objects.clone();
    d.findings.extend(out.findings.iter().cloned());
    d.not_found = out.not_found.iter().map(|n| n.0.clone()).collect();
    d.not_found_why = out.not_found.iter().map(|n| n.1.clone()).collect();
    for m in &out.matches {
        let Some(f) = d.funcs.iter_mut().find(|f| f.addr == m.addr) else {
            continue;
        };
        let wrong_name = out.dropped.iter().any(|(n, _)| *n == f.name);
        if super::is_anonymous(&f.name)
            || wrong_name
            || (m.how != "given"
                && f.provenance == Provenance::Given
                && f.name != m.source
                && out.dropped.iter().any(|(n, _)| *n == m.source))
        {
            if wrong_name || f.provenance == Provenance::Given {
                f.provenance = Provenance::Corrected;
            } else if f.provenance == Provenance::Speculative && m.how == "recognised" {
                continue;
            }
            f.name = m.source.clone();
        }
    }
    let matched: BTreeSet<u32> = d.matches.iter().map(|m| m.addr).collect();
    d.binary_only = d
        .funcs
        .iter()
        .filter(|f| f.provenance != Provenance::Speculative && !matched.contains(&f.addr))
        .map(|f| f.addr)
        .collect();
}

/// Functions named by the source's data: a constant object of the source that holds function
/// addresses (a vector table, a table of handlers) and is found in the image with every
/// address a function entry, the ones already matched in their places.  The functions in the
/// other places get their names from the table: evidence, not proof.
fn by_data(
    prog: &Program,
    given: &Image,
    d: &Discovery,
    funcs: &BTreeMap<u32, &Func>,
    env: &mut CEnv,
    out: &mut Outcome,
) {
    use crate::c::ast::SymRef;
    let read = |a: u32| {
        given
            .read_const(a, 4)
            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    };
    for (gi, g) in prog.globals.iter().enumerate() {
        let Some(init) = g.init.as_ref().filter(|_| g.defined && g.is_const) else {
            continue;
        };
        let nfuncs = init.relocs.iter().filter(|r| matches!(r.1, SymRef::Func(_))).count();
        let Some(size) = prog.size_of(g.ty).filter(|_| nfuncs >= 2) else {
            continue;
        };
        let fits = |env: &CEnv, at: u32| -> Option<usize> {
            let have = given.read_const(at, size)?;
            let mut agree = 0usize;
            let mut covered = vec![false; size as usize];
            for (off, target, add) in &init.relocs {
                let w = read(at + off)?.wrapping_sub(*add as u32);
                covered.get_mut(*off as usize..*off as usize + 4)?.fill(true);
                match target {
                    SymRef::Func(f) => {
                        if w & 1 == 0 || !funcs.contains_key(&(w & !1)) {
                            return None;
                        }
                        match env.func_addr[*f as usize] {
                            Some(a) if a == w & !1 => agree += 1,
                            Some(_) => return None,
                            None => {}
                        }
                    }
                    SymRef::Global(o) => {
                        if env.global_addr[*o as usize].is_some_and(|a| a != w) {
                            return None;
                        }
                    }
                    SymRef::Str(_) => {}
                }
            }
            let same = (0..size as usize).all(|i| covered[i] || init.bytes.get(i).copied().unwrap_or(0) == have[i]);
            same.then_some(agree)
        };
        let mut places: Vec<(u32, usize)> = Vec::new();
        match env.global_addr[gi].filter(|a| !env.is_synthetic(*a)) {
            Some(at) => places.extend(fits(env, at).map(|n| (at, n))),
            None => {
                for seg in given.segments.iter().filter(|s| !s.writable) {
                    let mut at = seg.addr.next_multiple_of(4);
                    while at + size <= seg.addr + seg.data.len() as u32 && places.len() < 2 {
                        if let Some(n) = fits(env, at)
                            && (n >= 1 || d.vectors.is_some_and(|v| v.0 == at))
                        {
                            places.push((at, n));
                        }
                        at += 4;
                    }
                }
            }
        }
        let [(at, _)] = places[..] else { continue };
        if env.global_addr[gi] != Some(at) {
            env.set_global(given, gi as u32, at);
            out.preset.globals.push((gi as u32, at));
            out.objects.push((g.name.to_string(), at, size));
        }
        for (off, target, add) in &init.relocs {
            let Some(w) = read(at + off).map(|w| w.wrapping_sub(*add as u32)) else {
                continue;
            };
            match target {
                SymRef::Func(f) if env.func_addr[*f as usize].is_none() => {
                    let name = prog.funcs[*f as usize].name.to_string();
                    env.set_func(*f, Some(w & !1));
                    if prog.funcs[*f as usize].body.is_some() {
                        out.preset.funcs.push((*f, w & !1));
                        out.not_found.retain(|n| n.0 != name);
                    }
                    out.matches.push(Match {
                        source: name,
                        addr: w & !1,
                        how: "by-data",
                        also: Vec::new(),
                        detail: format!(
                            "the source stores its address at {}+{off}, found at {:#x}; not proved",
                            g.name,
                            at + off
                        ),
                    });
                }
                SymRef::Global(o) if env.global_addr[*o as usize].is_none() => {
                    env.set_global(given, *o, w);
                    out.preset.globals.push((*o, w));
                    let size = prog.size_of(prog.globals[*o as usize].ty).unwrap_or(0);
                    out.objects.push((prog.globals[*o as usize].name.to_string(), w, size));
                }
                _ => {}
            }
        }
    }
}