cverif 0.0.4

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
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
//! 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)]
pub(crate) struct SrcSig {
    pub(crate) consts: BTreeSet<u32>,
    pub(crate) strings: BTreeSet<u32>,
    pub(crate) globals: BTreeSet<u32>,
    /// Functions it names (calls, or takes the address of).
    pub(crate) callees: BTreeSet<u32>,
    /// It calls through a pointer.
    pub(crate) indirect: bool,
}

/// What the body of function `fid` itself refers to.
pub(crate) fn refs(prog: &Program, fid: u32) -> SrcSig {
    let mut one = SrcSig::default();
    if let Some(body) = &prog.funcs[fid as usize].body {
        walk_body(body, &mut one);
    }
    one
}

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) => {
            let direct = match &f.kind {
                EK::Func(_) => true,
                EK::Addr(x) => matches!(x.kind, EK::Func(_)),
                _ => false,
            };
            sig.indirect |= !direct;
            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,
    /// The callees the successful proof compared as calls.
    modulo: Vec<String>,
    /// Unnamed functions the successful proof took for functions of the source.
    bound: Vec<(String, u32)>,
}

/// The functions `fid` refers to directly (calls, or takes the address of).
fn direct_callees(prog: &Program, fid: u32) -> BTreeSet<u32> {
    let mut one = SrcSig::default();
    if let Some(body) = &prog.funcs[fid as usize].body {
        walk_body(body, &mut one);
    }
    one.callees
}

/// The functions whose calls a trial proof compares as calls: those placed at an address no
/// other source function is placed at.
///
/// `unplaced`: also those that have no address yet.  The source then calls them by name, and
/// the proof takes the unnamed function the binary calls at that point for them (see
/// `verify::trial_unifying`).
fn callable_of(prog: &Program, env: &CEnv, unplaced: bool) -> Vec<bool> {
    let mut count: HashMap<u32, u32> = HashMap::new();
    for (fid, f) in prog.funcs.iter().enumerate() {
        if let (true, Some(a)) = (f.body.is_some(), env.func_addr[fid]) {
            *count.entry(a).or_default() += 1;
        }
    }
    (prog.funcs.iter().enumerate())
        .map(|(fid, f)| f.body.is_some() && f.ty.proto && env.func_addr[fid].map_or(unplaced, |a| count[&a] == 1))
        .collect()
}

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.
    // (A function defined in a header is one function here, however many units include it.)
    let mut seen_defs: HashSet<(&str, &str, u32)> = HashSet::new();
    let todo: Vec<u32> = (0..prog.funcs.len() as u32)
        .filter(|&f| prog.funcs[f as usize].body.is_some())
        .filter(|&f| {
            let func = &prog.funcs[f as usize];
            let file = prog.files.get(func.loc.file as usize).map_or("", |s| s.as_str());
            !func.is_static || seen_defs.insert((&*func.name, file, func.loc.line))
        })
        .collect();
    for f in 0..prog.funcs.len() as u32 {
        if prog.funcs[f as usize].body.is_some() {
            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 big = d.funcs.len() > 400;
    // (A trial only has to tell the right candidate from the wrong ones; the verification
    // that follows has the full budget.)
    let trial_opts = {
        let mut o = vopts.clone();
        o.only = Vec::new();
        o.dump = 0;
        o.work_limit = o.work_limit.min(if big { 8_000 } else { 30_000 });
        o.time_limit = o.time_limit.min(Duration::from_secs(if big { 3 } else { 5 }));
        o.limits.max_paths = o.limits.max_paths.min(if big { 120 } else { 300 });
        o
    };

    let full_opts = {
        let mut o = vopts.clone();
        o.only = Vec::new();
        o.dump = 0;
        o.cache = None;
        o.work_limit = o.work_limit.min(60_000);
        o.time_limit = o.time_limit.min(Duration::from_secs(10));
        o
    };
    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

    // Anchors: what the constant data of the source says, before any proof.  The functions
    // named this way are hypotheses; each is then put to the proof like any candidate.
    let starts: BTreeSet<u32> = (d.funcs.iter())
        .filter(|f| f.provenance != Provenance::Speculative && !super::is_helper_name(&f.name))
        .map(|f| f.addr)
        .collect();
    let mut code: Vec<(u32, u32)> = (d.funcs.iter())
        .flat_map(|f| f.code.iter().chain(&f.pools).copied())
        .collect();
    code.sort();
    let anchors = super::anchor::anchor(prog, given, &starts, &code);
    let mut hyp: HashMap<u32, (u32, String)> = HashMap::new();
    // Functions no proof can name, placed by the calls of the functions around them.
    let mut by_calls: BTreeMap<u32, (u32, String)> = BTreeMap::new();
    let mut hyp_calls: HashSet<u32> = HashSet::new();
    for (&g, &at) in &anchors.globals {
        env.set_global(&image, g, at);
        bound_objs.insert(g, at);
    }
    for (&f, (at, why)) in &anchors.funcs {
        if given_addr(f).is_some_and(|g| g != *at) {
            continue; // the given table is tested by proof, below
        }
        env.set_func(f, Some(*at));
        if prog.funcs[f as usize].body.is_some() {
            hyp.insert(f, (*at, why.clone()));
            claimed.entry(*at).or_default().push(f);
        }
    }
    crate::timing::mark("discover: anchors");
    if std::env::var_os("CVERIF_TIMING").is_some() {
        eprintln!(
            "discover: {} objects and {} functions located by the source's constant data",
            anchors.globals.len(),
            hyp.len()
        );
    }
    // The call graphs of both sides: a matched function narrows down what it calls and what
    // calls it.
    let direct: HashMap<u32, BTreeSet<u32>> = todo.iter().map(|&f| (f, direct_callees(prog, f))).collect();
    let mut src_callers: HashMap<u32, Vec<u32>> = HashMap::new();
    for (&f, cs) in &direct {
        for &c in cs {
            src_callers.entry(c).or_default().push(f);
        }
    }
    let mut bin_callers: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::new();
    for f in &d.funcs {
        for &c in &f.calls {
            bin_callers.entry(c).or_default().insert(f.addr);
        }
    }
    // What a function was last tried with: it is tried again only when that changed.
    let mut tried_with: HashMap<u32, (usize, Vec<u32>)> = HashMap::new();
    let mut attempts: HashMap<u32, usize> = HashMap::new();
    let mut fallback = false;
    for round in 0..if big { 48 } else { 6 } {
        if pending.is_empty() {
            break;
        }
        // Functions that no proof can name (no body in the source, written in assembly, or
        // using something that is not modelled): where the functions placed so far agree on
        // what they call.  Evidence only; the proofs of their callers then rest on it.
        loop {
            let mut placed = false;
            for g in 0..prog.funcs.len() as u32 {
                let fg = &prog.funcs[g as usize];
                if env.func_addr[g as usize].is_some()
                    || (fg.body.is_some() && !fg.opaque && fg.unsupported.is_none())
                    || (fg.body.is_some() && !todo.contains(&g))
                {
                    continue;
                }
                let free = |a: &u32| funcs.contains_key(a) && claimed.get(a).is_none_or(|c| c.is_empty());
                let mut votes: BTreeMap<u32, usize> = BTreeMap::new();
                let mut callers = 0usize;
                let mut pinned: Option<u32> = None;
                for c in src_callers.get(&g).into_iter().flatten().filter(|c| **c != g) {
                    let Some(bf) = env.func_addr[*c as usize].and_then(|a| funcs.get(&a)) else {
                        continue;
                    };
                    callers += 1;
                    let targets: BTreeSet<u32> = bf.calls.iter().copied().filter(|t| free(t)).collect();
                    for t in &targets {
                        *votes.entry(*t).or_default() += 1;
                    }
                    // The one callee of this caller that has no address, and the one call
                    // target that has no name.
                    let unplaced = direct[c]
                        .iter()
                        .filter(|x| env.func_addr[**x as usize].is_none())
                        .count();
                    if unplaced == 1 && targets.len() == 1 {
                        pinned = targets.first().copied();
                    }
                }
                let mut order: Vec<(usize, u32)> = votes.iter().map(|(a, n)| (*n, *a)).collect();
                order.sort_by(|a, b| b.cmp(a));
                let pick = match order[..] {
                    [] => None,
                    [(n, a)] if n >= 2 || pinned == Some(a) => Some((a, n)),
                    [(n, a), (m, _), ..] if (n >= 2 && n > m && 2 * n >= callers) || pinned == Some(a) => Some((a, n)),
                    _ => None,
                };
                if let Some((addr, n)) = pick {
                    env.set_func(g, Some(addr));
                    claimed.entry(addr).or_default().push(g);
                    by_calls.insert(
                        g,
                        (
                            addr,
                            format!("called where the source calls it by {n} of the {callers} functions placed so far that call it; not proved"),
                        ),
                    );
                    placed = true;
                }
            }
            if !placed {
                break;
            }
        }
        env.callable = callable_of(prog, &env, big);
        let mut plan: HashMap<u32, Vec<(u32, i32)>> = HashMap::new();
        for &f in &pending {
            if let Some((a, _)) = hyp.get(&f) {
                plan.insert(f, vec![(*a, 1000)]);
                continue;
            }
            let mut votes: BTreeMap<u32, i32> = BTreeMap::new();
            let free = |a: &u32| funcs.contains_key(a) && claimed.get(a).is_none_or(|c| c.is_empty());
            for c in src_callers.get(&f).into_iter().flatten().filter(|c| **c != f) {
                if let Some(f) = env.func_addr[*c as usize].and_then(|a| funcs.get(&a)) {
                    for t in f.calls.iter().filter(|t| free(t)).collect::<BTreeSet<_>>() {
                        *votes.entry(*t).or_default() += 1;
                    }
                }
            }
            for g in direct[&f].iter().filter(|g| **g != f) {
                if let Some(cs) = env.func_addr[*g as usize].and_then(|a| bin_callers.get(&a)) {
                    for c in cs.iter().filter(|c| free(c)) {
                        *votes.entry(*c).or_default() += 1;
                    }
                }
            }
            if !votes.is_empty() {
                plan.insert(f, votes.into_iter().collect());
            }
        }
        let known = |env: &CEnv, f: u32| {
            direct[&f]
                .iter()
                .filter(|g| env.func_addr[**g as usize].is_some())
                .count()
        };
        let key = |env: &CEnv, f: u32| {
            let mut c: Vec<u32> = plan
                .get(&f)
                .map(|v| v.iter().map(|x| x.0).collect())
                .unwrap_or_default();
            c.sort();
            (known(env, f), c)
        };
        let mut batch: Vec<u32> = (pending.iter().copied())
            .filter(|f| !big || plan.contains_key(f))
            .filter(|f| !big || tried_with.get(f) != Some(&key(&env, *f)))
            .filter(|f| !big || attempts.get(f).is_none_or(|n| *n < 3))
            .collect();
        if batch.is_empty() && big && !fallback {
            // Nothing the data or the call graph points at is left: by resemblance alone.
            fallback = true;
            batch = pending.iter().copied().filter(|f| !plan.contains_key(f)).collect();
        }
        if batch.is_empty() {
            break;
        }
        for &f in &batch {
            tried_with.insert(f, key(&env, f));
            *attempts.entry(f).or_default() += 1;
        }
        if std::env::var_os("CVERIF_TIMING").is_some() {
            eprintln!(
                "discover: round {round}: {} of {} unmatched functions tried",
                batch.len(),
                pending.len()
            );
        }
        let waiting: Vec<u32> = pending.iter().copied().filter(|f| !batch.contains(f)).collect();
        pending = batch;
        // 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, &full_opts),
                big,
                round,
                plan.get(&fid).map(|v| &v[..]),
            )
        });
        let mut next = waiting;
        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);
                        }
                    }
                    let c = claimed.entry(*addr).or_default();
                    if !c.contains(&fid) {
                        c.push(fid);
                    }
                    env.set_func(fid, Some(*addr));
                    progress = true;
                    // What the proof took the unnamed functions it calls for: hypotheses,
                    // put to the proof in their turn where the source has a body for them.
                    for (name, at) in &t.bound {
                        if claimed.get(at).is_some_and(|c| !c.is_empty()) {
                            continue;
                        }
                        let why = format!(
                            "called by {} where the source calls it (the proof of {} at {addr:#x} goes through on that assumption); not proved",
                            prog.funcs[fid as usize].name, prog.funcs[fid as usize].name
                        );
                        for g in 0..prog.funcs.len() as u32 {
                            let fg = &prog.funcs[g as usize];
                            if *fg.name != **name || env.func_addr[g as usize].is_some() {
                                continue;
                            }
                            env.set_func(g, Some(*at));
                            claimed.entry(*at).or_default().push(g);
                            if fg.body.is_some() && !fg.opaque && fg.unsupported.is_none() && todo.contains(&g) {
                                hyp.insert(g, (*at, why.clone()));
                                hyp_calls.insert(g);
                            } else if fg.body.is_none() || todo.contains(&g) {
                                by_calls.insert(g, (*at, why.clone()));
                            }
                        }
                    }
                    done.insert(fid, t);
                }
                None => {
                    // A hypothesis from the calls of another function that the proof refutes.
                    if hyp_calls.contains(&fid)
                        && t.last.starts_with("MISMATCH")
                        && let Some((at, _)) = hyp.remove(&fid)
                    {
                        hyp_calls.remove(&fid);
                        env.set_func(fid, None);
                        if let Some(c) = claimed.get_mut(&at) {
                            c.retain(|x| *x != fid);
                        }
                    }
                    next.push(fid);
                    done.insert(fid, t);
                }
            }
        }
        pending = next;
        crate::timing::mark("discover: round");
        if !progress && !big {
            break;
        }
    }
    // Proofs that compared calls as calls rest on the names of the callees.  Those that
    // rest only on functions that are themselves proved are proved outright (the greatest
    // such set: a recursive function rests on itself).
    let name_of = |fid: u32| prog.funcs[fid as usize].name.to_string();
    let mut solid: BTreeSet<String> = (done.iter())
        .filter(|(_, t)| matches!(t.hit, Some((_, true, ..))))
        .map(|(f, _)| name_of(*f))
        .collect();
    loop {
        let drop: Vec<String> = (done.iter())
            .filter(|(f, t)| solid.contains(&name_of(**f)) && t.modulo.iter().any(|m| !solid.contains(m)))
            .map(|(f, _)| name_of(*f))
            .collect();
        if drop.is_empty() {
            break;
        }
        for d in drop {
            solid.remove(&d);
        }
    }

    // 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 rests: Vec<&str> = (t.modulo.iter())
                    .filter(|m| !solid.contains(*m))
                    .map(|m| m.as_str())
                    .collect();
                let how = match (*proved, rests.is_empty()) {
                    (true, true) => "proved",
                    (true, false) => "conditional",
                    (false, _) => "bounded",
                };
                out.matches.push(Match {
                    source: f.name.to_string(),
                    addr: *addr,
                    how,
                    also: t.also.clone(),
                    detail: match how {
                        "proved" => format!("{paths} path(s)"),
                        "conditional" => format!(
                            "{paths} path(s), taking the functions it calls to be what the data or the call graph suggests, which is not proved for: {}",
                            rests.join(", ")
                        ),
                        _ => 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
                                ),
                            });
                        }
                    }
                    _ if by_calls.contains_key(&fid) => {
                        let (at, why) = &by_calls[&fid];
                        out.preset.funcs.push((fid, *at));
                        out.matches.push(Match {
                            source: f.name.to_string(),
                            addr: *at,
                            how: "by-calls",
                            also: Vec::new(),
                            detail: why.clone(),
                        });
                    }
                    _ if hyp.contains_key(&fid) => {
                        let (at, why) = &hyp[&fid];
                        out.preset.funcs.push((fid, *at));
                        out.matches.push(Match {
                            source: f.name.to_string(),
                            addr: *at,
                            how: if hyp_calls.contains(&fid) {
                                "by-calls"
                            } else {
                                "by-data"
                            },
                            also: Vec::new(),
                            detail: format!(
                                "{why}; not proved{}{}",
                                if t.last.is_empty() { "" } else { ": " },
                                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))
                    }
                }
            }
        }
    }
    for (g, (at, why)) in &by_calls {
        if prog.funcs[*g as usize].body.is_none() {
            out.matches.push(Match {
                source: prog.funcs[*g as usize].name.to_string(),
                addr: *at,
                how: "by-calls",
                also: Vec::new(),
                detail: why.clone(),
            });
        }
    }
    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, full): (&VerifyOptions, &VerifyOptions),
    big: bool,
    round: usize,
    plan: Option<&[(u32, i32)]>,
) -> 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(),
        modulo: Vec::new(),
        bound: Vec::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();
    let _ = round;
    for (&addr, func) in funcs {
        if super::is_helper_name(&func.name) {
            continue;
        }
        // What the data or the call graph points at, where they point at anything.
        let vote = plan.and_then(|p| p.iter().find(|x| x.0 == addr)).map(|x| x.1);
        if big && plan.is_some() && vote.is_none() && given != Some(addr) {
            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;
        }
        score += 8 * vote.unwrap_or(0);
        if func.provenance == Provenance::Speculative {
            score -= 4;
        }
        ranked.push((
            claimed.get(&addr).is_some_and(|c| c.iter().any(|x| *x != fid)),
            -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 = match (big, plan.is_some()) {
        (true, true) => 5,
        (true, false) => 3,
        _ => 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, mut modulo, bound) = if big {
                    crate::verify::trial_unifying(prog, image, &e, fid, opts)
                } else {
                    let (s, p, m) = trial(prog, image, &e, fid, opts);
                    (s, p, m, Vec::new())
                };
                modulo.extend(bound.iter().map(|b| b.0.clone()));
                // A trial that ran out of its small budget says little: such a candidate is
                // kept only if the full budget finds no difference either.
                let (status, paths) = match (&status, big) {
                    (Status::Bounded(_), true) if paths > 0 => {
                        let (s, p, ..) = crate::verify::trial_unifying(prog, image, &e, fid, full);
                        (s, p)
                    }
                    _ => (status, paths),
                };
                t.trials += 1;
                tried += 1;
                match is_good(&status, paths) {
                    Some(proved) => {
                        match &t.hit {
                            None => {
                                t.hit = Some((addr, proved, paths, pick.clone()));
                                t.modulo = modulo;
                                t.bound = bound;
                            }
                            Some((first, was_proved, ..)) => {
                                if proved && !*was_proved {
                                    let old = *first;
                                    t.hit = Some((addr, proved, paths, pick.clone()));
                                    t.modulo = modulo;
                                    t.bound = bound;
                                    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));
                }
                _ => {}
            }
        }
    }
}