cverif 0.0.7

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
//! Binary-to-binary comparison (`cverif --compare old new`): the same source built in two ways
//! must come out equivalent, a changed function must be reported for exactly what it changes,
//! with and without the source.
//!
//! The tests skip themselves when the cross tools are not installed.  Nothing here depends on
//! the shape of the code a particular compiler version emits: without the source the
//! assertions are about what may never happen (a difference reported in an unchanged pure
//! function) and the measured rates are printed, not asserted.

use cverif::bindiff::{Assumptions, Comparison, Options, Route, Verdict, compare, compare_replayed};
use cverif::image::Image;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

const GCC: &str = "arm-none-eabi-gcc";
const CLANG: &str = "clang";

const CORPUS: &[&str] = &[
    "arith.c",
    "control.c",
    "memory.c",
    "calls.c",
    "cfeatures.c",
    "extcalls.c",
];

fn have(tool: &str) -> bool {
    Command::new(tool)
        .arg("--version")
        .output()
        .is_ok_and(|o| o.status.success())
}

fn corpus(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus").join(name)
}

fn tmp(name: &str) -> PathBuf {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("bindiff");
    std::fs::create_dir_all(&dir).unwrap();
    dir.join(name)
}

#[derive(Clone, Copy)]
struct Tc {
    name: &'static str,
    cc: &'static str,
    flags: &'static [&'static str],
}

const GCC_M3: Tc = Tc {
    name: "gcc-m3",
    cc: GCC,
    flags: &["-mthumb", "-mcpu=cortex-m3"],
};
const GCC_M0: Tc = Tc {
    name: "gcc-m0",
    cc: GCC,
    flags: &["-mthumb", "-mcpu=cortex-m0"],
};
const CLANG_M3: Tc = Tc {
    name: "clang-m3",
    cc: CLANG,
    flags: &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb"],
};
const CLANG_M3_RWPI: Tc = Tc {
    name: "clang-m3-rwpi",
    cc: CLANG,
    flags: &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb", "-frwpi"],
};
/// The firmware command line of the project's main target, without and with `-fropi`.
const CLANG_M0P: Tc = Tc {
    name: "clang-m0plus",
    cc: CLANG,
    flags: &[
        "-fomit-frame-pointer",
        "-momit-leaf-frame-pointer",
        "-mcpu=cortex-m0plus",
        "-mthumb",
        "-mno-unaligned-access",
        "--target=armv6m-none-eabi",
        "-fno-jump-tables",
    ],
};
const CLANG_M0P_ROPI: Tc = Tc {
    name: "clang-m0plus-ropi",
    cc: CLANG,
    flags: &[
        "-fomit-frame-pointer",
        "-momit-leaf-frame-pointer",
        "-mcpu=cortex-m0plus",
        "-mthumb",
        "-mno-unaligned-access",
        "--target=armv6m-none-eabi",
        "-fropi",
        "-fno-jump-tables",
    ],
};

impl Tc {
    fn try_build(&self, src: &Path, level: &str, extra: &[&str]) -> Result<PathBuf, String> {
        let stem = src.file_stem().unwrap().to_string_lossy();
        let tag: String = extra
            .iter()
            .flat_map(|e| e.chars())
            .filter(|c| c.is_ascii_alphanumeric())
            .collect();
        let obj = tmp(&format!("{stem}-{}{level}{tag}.o", self.name));
        // Tests run in parallel and may build the same object: write it under a unique name
        // and rename, so that nobody reads a half-written file.
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let part = obj.with_extension(format!("{}-{n}.part.o", std::process::id()));
        let out = Command::new(self.cc)
            .args(self.flags)
            .args(["-ffreestanding", "-c", level, "-I"])
            .arg(corpus("include"))
            .args(extra)
            .arg(src)
            .arg("-o")
            .arg(&part)
            .output()
            .map_err(|e| e.to_string())?;
        if out.status.success() {
            std::fs::rename(&part, &obj).map_err(|e| e.to_string())?;
            Ok(obj)
        } else {
            Err(String::from_utf8_lossy(&out.stderr).into_owned())
        }
    }

    fn build(&self, src: &Path, level: &str, extra: &[&str]) -> PathBuf {
        self.try_build(src, level, extra)
            .unwrap_or_else(|e| panic!("{} failed: {e}", self.cc))
    }

    /// Is the compiler installed and able to generate code for this target?
    fn available(&self) -> bool {
        let ok = self.try_build(&corpus("arith.c"), "-Os", &["-DCVERIF_PROBE"]).is_ok();
        if !ok {
            eprintln!("skipping: {} cannot build for {}", self.cc, self.name);
        }
        ok
    }
}

fn load(path: &Path) -> Image {
    let bytes = std::fs::read(path).unwrap();
    cverif::inputs::load(&bytes, 0, &[], &[], None).unwrap_or_else(|e| panic!("{}: {e}", path.display()))
}

/// Verification is capped: two worker threads and a deterministic work budget.
fn options(assume: Assumptions) -> Options {
    Options {
        verify: cverif::verify::Options {
            jobs: 2,
            work_limit: 30_000,
            time_limit: Duration::from_secs(900),
            ..Default::default()
        },
        assume,
        explain: false,
    }
}

fn run_images(a: Image, b: Image, src: Option<Vec<PathBuf>>, assume: Assumptions) -> Comparison {
    // Term construction recurses deeply; use a generous stack like the CLI does.
    std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let opts = options(assume);
            let progs = src.map(|files| {
                let parse = |image: &Image| {
                    let copts = cverif::c::Options {
                        include_dirs: vec![corpus("include")],
                        short_enums: image.short_enums,
                        ..Default::default()
                    };
                    cverif::c::parse_files(&files, &copts).expect("parse C")
                };
                (parse(&a), parse(&b))
            });
            let c = compare_replayed(&a, &b, progs.as_ref().map(|p| (&p.0, &p.1)), &opts);
            replays_hold(&c);
            c
        })
        .unwrap()
        .join()
        .unwrap()
}

/// Every counterexample that was run on the two functions (by an interpreter that shares
/// nothing with the comparison) shows the difference the verdict states.
fn replays_hold(c: &Comparison) {
    use cverif::bindiff::replay::Replay;
    for f in &c.funcs {
        // (Nothing in the corpus is different in a way that execution does not show.)
        assert!(
            !matches!(f.verdict, Verdict::Different(_)) || f.replay.is_some(),
            "{}: DIFFERENT without a counterexample that was run",
            f.name
        );
        match &f.replay {
            Some(Replay::NotReproduced(how)) => panic!(
                "{}: {}: running both functions on the counterexample shows no difference: {how}",
                f.name,
                f.detail()
            ),
            Some(Replay::NotModelled(how)) => eprintln!("{}: counterexample not run: {how}", f.name),
            _ => {}
        }
    }
}

fn run(a: &Path, b: &Path, src: Option<&Path>) -> Comparison {
    run_images(
        load(a),
        load(b),
        src.map(|s| vec![s.to_path_buf()]),
        Assumptions::default(),
    )
}

fn describe(c: &Comparison) -> String {
    let mut s = String::new();
    for f in &c.funcs {
        s.push_str(&format!("  {:<12} {} {}\n", f.label(), f.name, f.detail()));
    }
    for (n, what) in &c.data {
        s.push_str(&format!("  DATA {n}: {what}\n"));
    }
    s
}

fn flagged(c: &Comparison) -> Vec<&str> {
    c.funcs
        .iter()
        .filter(|f| matches!(f.verdict, Verdict::Different(_) | Verdict::MayDiffer(_)))
        .map(|f| f.name.as_str())
        .collect()
}

fn paired(c: &Comparison) -> usize {
    c.funcs
        .iter()
        .filter(|f| !matches!(f.verdict, Verdict::Added | Verdict::Removed))
        .count()
}

fn equivalent(c: &Comparison) -> usize {
    c.funcs.iter().filter(|f| f.is_equivalent()).count()
}

/// A compiler configuration and an optimisation level.
type Build = (Tc, &'static str);

/// One line of the result tables printed by the tests.
fn row(what: &str, c: &Comparison) -> String {
    let n = |l: &str| c.count(l);
    format!(
        "{what:<44} {:>3} equivalent {:>3} may-differ {:>3} different {:>3} bounded {:>3} inconclusive {:>3} unsupported  ({} paired)",
        equivalent(c),
        n("MAY-DIFFER"),
        n("DIFFERENT"),
        n("BOUNDED"),
        n("INCONCLUSIVE"),
        n("UNSUPPORTED"),
        paired(c)
    )
}

/// With the source, two builds of it never differ: every function is equivalent, or a limit
/// was hit, and most are equivalent.
fn expect_same_with_source(a: (Tc, &str), b: (Tc, &str), files: &[&str]) {
    if !a.0.available() || !b.0.available() {
        return;
    }
    for file in files {
        let src = corpus(file);
        let c = run(&a.0.build(&src, a.1, &[]), &b.0.build(&src, b.1, &[]), Some(&src));
        let what = format!("{file} {}{} / {}{}", a.0.name, a.1, b.0.name, b.1);
        eprintln!("{}", row(&format!("{what} +source"), &c));
        assert!(flagged(&c).is_empty(), "{what}: false difference\n{}", describe(&c));
        assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
        assert!(!c.differs() && !c.may_differ(), "{what}");
        assert!(
            equivalent(&c) * 5 >= paired(&c) * 4 && paired(&c) > 0,
            "{what}: too little proved\n{}",
            describe(&c)
        );
    }
}

#[test]
fn levels_with_source() {
    expect_same_with_source((GCC_M3, "-O0"), (GCC_M3, "-O2"), CORPUS);
    expect_same_with_source((GCC_M3, "-Os"), (GCC_M3, "-O3"), CORPUS);
}

#[test]
fn compilers_and_cpus_with_source() {
    expect_same_with_source((GCC_M3, "-Os"), (CLANG_M3, "-Os"), CORPUS);
    expect_same_with_source((GCC_M0, "-O2"), (GCC_M3, "-O2"), CORPUS);
}

#[test]
fn position_independence_with_source() {
    expect_same_with_source((CLANG_M0P, "-Os"), (CLANG_M0P_ROPI, "-Os"), CORPUS);
    expect_same_with_source((CLANG_M3, "-Os"), (CLANG_M3_RWPI, "-Os"), CORPUS);
}

/// Without the source: what is proved is printed (the README quotes these tables), and the
/// pure functions of arith.c, which can differ in nothing but r0, are never DIFFERENT.
#[test]
fn source_free_rates() {
    let pairs: &[(Build, Build)] = &[
        ((GCC_M3, "-O0"), (GCC_M3, "-O2")),
        ((GCC_M3, "-Os"), (GCC_M3, "-O3")),
        ((GCC_M3, "-Os"), (CLANG_M3, "-Os")),
        ((GCC_M0, "-O2"), (GCC_M3, "-O2")),
        ((CLANG_M0P, "-Os"), (CLANG_M0P_ROPI, "-Os")),
        ((CLANG_M3, "-Os"), (CLANG_M3_RWPI, "-Os")),
    ];
    for (a, b) in pairs {
        if !a.0.available() || !b.0.available() {
            continue;
        }
        for file in CORPUS {
            let src = corpus(file);
            let (oa, ob) = (a.0.build(&src, a.1, &[]), b.0.build(&src, b.1, &[]));
            let what = format!("{file} {}{} / {}{}", a.0.name, a.1, b.0.name, b.1);
            let c = run(&oa, &ob, None);
            eprintln!("{}", row(&what, &c));
            assert!(paired(&c) > 0, "{what}: nothing compared");
            if *file == "arith.c" {
                assert_eq!(c.count("DIFFERENT"), 0, "{what}\n{}", describe(&c));
                assert!(equivalent(&c) * 2 >= paired(&c), "{what}\n{}", describe(&c));
            }
            // With the registers that may be dead assumed dead.
            let lenient = Assumptions {
                ext_arity: true,
                void_r0: true,
                ..Default::default()
            };
            let c = run_images(load(&oa), load(&ob), None, lenient);
            eprintln!("{}", row(&format!("{what} +assume"), &c));
        }
    }
}

// ----- data layout, patches ----------------------------------------------------------------

fn patch_src() -> PathBuf {
    corpus("bindiff/patch.c")
}

/// The same program with its data at other addresses: everything is equivalent, without
/// the source.
#[test]
fn data_layout() {
    for tc in [GCC_M0, GCC_M3, CLANG_M3] {
        if !tc.available() {
            continue;
        }
        let src = patch_src();
        let c = run(
            &tc.build(&src, "-Os", &[]),
            &tc.build(&src, "-Os", &["-DREORDER"]),
            None,
        );
        let what = format!("reordered data, {}", tc.name);
        assert!(paired(&c) >= 14, "{what}\n{}", describe(&c));
        assert!(c.funcs.iter().all(|f| f.is_equivalent()), "{what}\n{}", describe(&c));
        assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
        assert_eq!(c.data_added, ["g_pad"], "{what}");
        assert!(!c.differs() && !c.may_differ(), "{what}");
    }
}

/// A patch: the changed function and the function that inlines the change are DIFFERENT,
/// the caller is equivalent modulo its callee, the rest is untouched.
#[test]
fn patched_function() {
    for tc in [GCC_M0, GCC_M3, CLANG_M3] {
        if !tc.available() {
            continue;
        }
        let src = patch_src();
        let c = run(&tc.build(&src, "-Os", &[]), &tc.build(&src, "-Os", &["-DPATCH"]), None);
        let what = format!("patch, {}", tc.name);
        let verdict = |n: &str| {
            &c.func(n)
                .unwrap_or_else(|| panic!("{what}: no {n}\n{}", describe(&c)))
                .verdict
        };
        assert!(
            matches!(verdict("clampv"), Verdict::Different(_)),
            "{what}\n{}",
            describe(&c)
        );
        assert!(
            matches!(verdict("store_limited"), Verdict::Different(_)),
            "{what}\n{}",
            describe(&c)
        );
        assert_eq!(flagged(&c), ["clampv", "store_limited"], "{what}\n{}", describe(&c));
        let caller = c.func("add_clamped").unwrap();
        assert!(
            caller.is_equivalent() && caller.modulo.iter().any(|m| m.0 == "clampv" && m.1 == "DIFFERENT"),
            "{what}\n{}",
            describe(&c)
        );
        assert_eq!(*verdict("added_fn"), Verdict::Added, "{what}");
        assert_eq!(*verdict("removed_fn"), Verdict::Removed, "{what}");
        for f in &c.funcs {
            let touched = ["clampv", "store_limited", "added_fn", "removed_fn"].contains(&f.name.as_str());
            assert!(touched || f.is_equivalent(), "{what}: {}\n{}", f.name, describe(&c));
        }
        assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
        assert!(c.differs(), "{what}");
    }
}

/// One immediate flipped in the object file: different exactly there.
#[test]
fn binary_patch() {
    let tc = GCC_M0;
    if !tc.available() {
        return;
    }
    let obj = tc.build(&patch_src(), "-Os", &[]);
    let image = load(&obj);
    let key = image.func("key").expect("key");
    let code = image.read(key.addr, key.size).unwrap().to_vec();
    let Some(imm) = code.iter().position(|&b| b == 0x5a) else {
        eprintln!("skipping: no 0x5a immediate in key()");
        return;
    };
    let mut bytes = std::fs::read(&obj).unwrap();
    let at: Vec<usize> = (0..bytes.len() - code.len())
        .filter(|&i| bytes[i..i + code.len()] == code[..])
        .collect();
    assert_eq!(at.len(), 1, "the code of key() occurs once in the file");
    bytes[at[0] + imm] = 0x5b;
    let patched = tmp("patch-flipped.o");
    std::fs::write(&patched, bytes).unwrap();
    let c = run(&obj, &patched, None);
    assert!(
        matches!(c.func("key").unwrap().verdict, Verdict::Different(_)),
        "{}",
        describe(&c)
    );
    assert_eq!(flagged(&c), ["key"], "{}", describe(&c));
    let user = c.func("use_key").unwrap();
    assert!(
        user.label() == "IDENTICAL" && user.modulo.iter().any(|m| m.0 == "key"),
        "{}",
        describe(&c)
    );
    for f in &c.funcs {
        assert!(f.name == "key" || f.label() == "IDENTICAL", "{}", describe(&c));
    }
    // With the source both sides are checked against it: the flipped one does not match.
    let c = run(&obj, &patched, Some(&patch_src()));
    assert!(
        matches!(c.func("key").unwrap().verdict, Verdict::Different(_)),
        "{}",
        describe(&c)
    );
    assert_eq!(flagged(&c), ["key"], "{}", describe(&c));
}

// ----- mutants ------------------------------------------------------------------------------

const MUTANTS: &[(u32, &str)] = &[
    (1, "m_add"),
    (2, "m_cmp"),
    (3, "m_const"),
    (4, "m_loop"),
    (5, "m_store"),
    (6, "m_call"),
    (7, "m_backdoor"),
    (8, "m_table"),
    (9, "m_order"),
    (10, "m_shift"),
];
const CALL_MUTANTS: &[(u32, &str)] = &[
    (1, "x_out"),
    (2, "x_which"),
    (3, "x_buf"),
    (4, "x_nested"),
    (5, "x_div64"),
    (6, "x_str"),
    (7, "x_stackarg"),
    (8, "x_strlen"),
    (9, "x_shift64"),
    (10, "x_stale_store"),
];
const CFEATURE_MUTANTS: &[(u32, &str)] = &[
    (1, "mc_fp_table"),
    (2, "mc_fp_target"),
    (3, "mc_fp_args"),
    (4, "mc_sv_ret"),
    (5, "mc_sv_stack"),
    (6, "mc_sv_big"),
    (7, "mc_bf_set"),
    (8, "mc_bf_signed"),
    (9, "mc_range"),
    (10, "mc_vol_twice"),
    (11, "mc_vol_dup"),
    (12, "mc_vol_order"),
    (13, "mc_vol_value"),
    (14, "mc_bf_global"),
    (15, "mc_vol_extra"),
];
const LOOP_MUTANTS: &[(u32, &str)] = &[
    (1, "ml_sum_bytes"),
    (2, "ml_sum_n"),
    (3, "ml_xor_ints"),
    (4, "ml_split"),
    (5, "ml_fill"),
    (6, "ml_gcd"),
    (7, "ml_find"),
    (8, "ml_call_each"),
    (9, "ml_send"),
    (10, "ml_strlen"),
    (11, "ml_copy"),
    (12, "ml_digits"),
];
const FLOAT_MUTANTS: &[(u32, &str)] = &[
    (1, "mf_lt"),
    (2, "mf_ulp"),
    (3, "mf_prec"),
    (4, "mf_sub"),
    (5, "mf_div"),
    (6, "mf_round"),
    (7, "mf_assoc"),
    (8, "mf_nan"),
    (9, "mf_conv"),
    (10, "mf_table"),
    (11, "mf_zero"),
    (12, "mf_mul_zero"),
    (13, "mf_double_const"),
    (14, "mf_call"),
    (15, "mf_recip"),
    (16, "mf_negsub"),
];

const ARITH_MUTANTS: &[(u32, &str)] = &[
    (1, "a_div10"),
    (2, "a_div7"),
    (3, "a_sdiv8"),
    (4, "a_sdiv10"),
    (5, "a_add64"),
    (6, "a_sub"),
    (7, "a_below"),
    (8, "a_divisible3"),
    (9, "a_mulhi"),
    (10, "a_rotl5"),
    (11, "a_lt64"),
    (12, "a_clamp"),
    (13, "a_smod7"),
    (14, "a_ptrdiff"),
    (15, "a_clz"),
    (16, "a_mul100"),
];

/// Every `-DMUTANT=n` build against the unmutated one, without the source: nothing but the
/// mutated function is reported, and that function is never called equivalent (it is
/// DIFFERENT or MAY-DIFFER; a limit or an unsupported construct is counted and printed).
/// A mutant that only changes initialised data is a data difference.
fn expect_mutants_found(file: &str, level: &str, mutants: &[(u32, &str)]) {
    let tc = GCC_M3;
    if !tc.available() {
        return;
    }
    let src = corpus(file);
    let base = tc.build(&src, level, &[]);
    let (mut hard, mut weak, mut data, mut other) = (0, 0, 0, 0);
    for &(n, func) in mutants {
        // A changed high word of a 64-bit result is a difference: nothing is assumed about r1.
        let strict = Assumptions {
            ret32: false,
            ..Default::default()
        };
        let mutant = tc.build(&src, level, &[&format!("-DMUTANT={n}")]);
        let c = run_images(load(&base), load(&mutant), None, strict);
        let what = format!("{file} {level} mutant {n} ({func})");
        let f = c.func(func).unwrap_or_else(|| panic!("{what}: no such function"));
        assert!(
            flagged(&c).iter().all(|&g| g == func),
            "{what}: reported elsewhere\n{}",
            describe(&c)
        );
        assert!(
            !f.is_equivalent() || !c.data.is_empty(),
            "{what}: not noticed\n{}",
            describe(&c)
        );
        match &f.verdict {
            Verdict::Different(_) => hard += 1,
            Verdict::MayDiffer(_) => weak += 1,
            _ if !c.data.is_empty() => data += 1,
            _ => other += 1,
        }
    }
    eprintln!(
        "{file} {level}: {} mutants: {hard} DIFFERENT, {weak} MAY-DIFFER, {data} data only, {other} not decided",
        mutants.len()
    );
    // Most are decided: a mutant is rarely beyond what machine code alone shows.
    assert!((hard + weak + data) * 2 > mutants.len(), "{file}: too few decided");
}

/// The same with the source: the mutated build does not match it, so the function is
/// DIFFERENT (or its data is), and nothing else is.
fn expect_mutants_different(file: &str, level: &str, mutants: &[(u32, &str)]) {
    let tc = GCC_M3;
    if !tc.available() {
        return;
    }
    let src = corpus(file);
    let base = tc.build(&src, level, &[]);
    for &(n, func) in mutants {
        let c = run(&base, &tc.build(&src, level, &[&format!("-DMUTANT={n}")]), Some(&src));
        let what = format!("{file} {level} mutant {n} ({func}) +source");
        let f = c.func(func).unwrap_or_else(|| panic!("{what}: no such function"));
        assert!(
            matches!(f.verdict, Verdict::Different(_)) || !c.data.is_empty(),
            "{what}: not reported\n{}",
            describe(&c)
        );
        assert!(
            flagged(&c).iter().all(|&g| g == func),
            "{what}: reported elsewhere\n{}",
            describe(&c)
        );
        assert!(c.differs(), "{what}");
    }
}

#[test]
fn mutants_without_source() {
    expect_mutants_found("mutants.c", "-O2", MUTANTS);
    expect_mutants_found("mutants.c", "-Os", MUTANTS);
    expect_mutants_found("mutants_x.c", "-Os", CALL_MUTANTS);
    expect_mutants_found("mutants_c.c", "-Os", CFEATURE_MUTANTS);
}

#[test]
fn loop_float_and_arithmetic_mutants_without_source() {
    expect_mutants_found("mutants_l.c", "-Os", LOOP_MUTANTS);
    expect_mutants_found("mutants_f.c", "-Os", FLOAT_MUTANTS);
    expect_mutants_found("mutants_a.c", "-Os", ARITH_MUTANTS);
}

#[test]
fn mutants_with_source() {
    expect_mutants_different("mutants.c", "-Os", MUTANTS);
    expect_mutants_different("mutants_x.c", "-Os", CALL_MUTANTS);
    expect_mutants_different("mutants_c.c", "-Os", CFEATURE_MUTANTS);
    expect_mutants_different("mutants_a.c", "-Os", ARITH_MUTANTS);
    expect_mutants_different("mutants_f.c", "-Os", FLOAT_MUTANTS);
}

// ----- linked firmware ---------------------------------------------------------------------

const UNITS: &[&str] = &["app", "crc", "ring", "startup", "uart", "strings"];

fn fw() -> PathBuf {
    corpus("link/fw")
}

/// Build the firmware project of tests/link.rs; returns the directory with fw.elf, fw.bin
/// and fw.nm.
fn build_fw(tag: &str, extra: &[&str]) -> PathBuf {
    let dir = tmp(&format!("fw-{tag}"));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let run = |cmd: &mut Command| {
        let out = cmd.output().unwrap_or_else(|e| panic!("{cmd:?}: {e}"));
        assert!(
            out.status.success(),
            "{cmd:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        out.stdout
    };
    let mut objs = Vec::new();
    for u in UNITS {
        let obj = dir.join(format!("{u}.o"));
        run(Command::new(GCC)
            .args(["-mcpu=cortex-m3", "-mthumb", "-ffreestanding"])
            .args(["-ffunction-sections", "-fdata-sections", "-c", "-Os"])
            .args(extra)
            .arg(fw().join(format!("{u}.c")))
            .arg("-o")
            .arg(&obj));
        objs.push(obj);
    }
    let elf = dir.join("fw.elf");
    run(Command::new(GCC)
        .args(["-mthumb", "-mcpu=cortex-m3", "-nostdlib", "-Wl,--gc-sections", "-T"])
        .arg(fw().join("fw.ld"))
        .args(&objs)
        .arg("-o")
        .arg(&elf)
        .arg("-lgcc"));
    run(Command::new("arm-none-eabi-objcopy")
        .args(["-O", "binary"])
        .arg(&elf)
        .arg(dir.join("fw.bin")));
    let nm = run(Command::new("arm-none-eabi-nm").arg("-S").arg(&elf));
    std::fs::write(dir.join("fw.nm"), nm).unwrap();
    dir
}

/// A linked image against a patched one: a changed function (its callers read the result),
/// a changed vector entry, changed initialised data, a changed string, a changed table.
#[test]
fn linked_firmware() {
    if !have(GCC) || !have("arm-none-eabi-objcopy") || !have("arm-none-eabi-nm") {
        eprintln!("skipping: no GNU cross toolchain");
        return;
    }
    let base = build_fw("base", &[]);
    let elf = |d: &Path| d.join("fw.elf");
    // The image against itself.
    let c = run(&elf(&base), &elf(&base), None);
    assert!(paired(&c) >= 15, "{}", describe(&c));
    assert!(flagged(&c).is_empty() && c.data.is_empty(), "{}", describe(&c));
    assert!(
        c.funcs.iter().all(|f| f.same_code),
        "identical images have identical code\n{}",
        describe(&c)
    );
    assert!(equivalent(&c) * 3 >= paired(&c) * 2, "{}", describe(&c));
    // (mutant, functions that may be reported, object that differs)
    let cases: &[(u32, &[&str], &str)] = &[
        (1, &["crc8_byte"], ""),
        (2, &[], "g_vectors"),
        (3, &[], "g_level"),
        (4, &["str_ready", "str_entry"], ""),
        (5, &["str_entry"], "entries"),
    ];
    for &(n, funcs, object) in cases {
        let dir = build_fw(&format!("m{n}"), &[&format!("-DMUTANT={n}")]);
        let c = run(&elf(&base), &elf(&dir), None);
        let what = format!("firmware mutant {n}");
        let got = flagged(&c);
        assert!(got.iter().all(|g| funcs.contains(g)), "{what}\n{}", describe(&c));
        assert_eq!(got.is_empty(), funcs.is_empty(), "{what}\n{}", describe(&c));
        if object.is_empty() {
            assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
        } else {
            assert!(
                !c.data.is_empty() && c.data.iter().all(|d| d.0.starts_with(object)),
                "{what}\n{}",
                describe(&c)
            );
        }
        assert!(c.differs() || c.may_differ(), "{what}");
        if n == 1 {
            // main() uses the result: the change is a difference, not a maybe.
            assert!(
                matches!(c.func("crc8_byte").unwrap().verdict, Verdict::Different(_)),
                "{what}\n{}",
                describe(&c)
            );
            // The same from raw binaries, each with its own symbol table and load address.
            let raw = |d: &Path| {
                let nm = std::fs::read_to_string(d.join("fw.nm")).unwrap();
                cverif::inputs::load(&std::fs::read(d.join("fw.bin")).unwrap(), 0x0800_0000, &[], &[nm], None)
                    .expect("raw image")
            };
            let r = run_images(raw(&base), raw(&dir), None, Assumptions::default());
            assert_eq!(flagged(&r), ["crc8_byte"], "{what} (raw)\n{}", describe(&r));
            assert!(r.data.is_empty(), "{what} (raw)\n{}", describe(&r));
        }
    }
}

/// A one-line patch that makes a function longer, so that the code and the constant data
/// behind it move: the patched function is DIFFERENT, nothing else is reported.
#[test]
fn layout_shift_patch() {
    if !have(GCC) || !have("arm-none-eabi-objcopy") || !have("arm-none-eabi-nm") {
        eprintln!("skipping: no GNU cross toolchain");
        return;
    }
    let (old, new) = (build_fw("shift-base", &[]), build_fw("shift-m6", &["-DMUTANT=6"]));
    let c = run(&old.join("fw.elf"), &new.join("fw.elf"), None);
    assert!(
        c.funcs
            .iter()
            .any(|f| matches!((f.old, f.new), (Some(a), Some(b)) if a.0 != b.0)),
        "the patch moves nothing\n{}",
        describe(&c)
    );
    assert_eq!(flagged(&c), ["ring_pop"], "{}", describe(&c));
    assert!(
        matches!(c.func("ring_pop").unwrap().verdict, Verdict::Different(_)),
        "{}",
        describe(&c)
    );
    assert!(c.data.is_empty(), "{}", describe(&c));
}

fn causes_src() -> PathBuf {
    corpus("bindiff/causes.c")
}

/// What made a patch of a real firmware look like more than it was: pointers to moved
/// objects (compared, stored and read back, one of two values, in a table of functions),
/// code after a call that does not return, a register shifted into another.  With the code
/// and data moved nothing differs; with the patch, the patched function and the one that
/// inlines it do, and nothing else.
#[test]
fn moved_code_and_data() {
    for tc in [GCC_M0, GCC_M3, CLANG_M3] {
        if !tc.available() {
            continue;
        }
        let src = causes_src();
        let base = tc.build(&src, "-Os", &[]);
        let c = run(&base, &tc.build(&src, "-Os", &["-DSHIFT"]), None);
        let what = format!("moved code and data, {}", tc.name);
        // Known limit: a pointer constant built by movw/movt, stored, read back byte by byte
        // (another store may have overwritten it) and told from the constant by subtraction
        // is compared by its number: MAY-DIFFER, never DIFFERENT.
        let limit: &[&str] = if tc.cc == CLANG { &["store_and_read"] } else { &[] };
        assert!(paired(&c) >= 8, "{what}\n{}", describe(&c));
        assert!(got_only(&c, limit), "{what}\n{}", describe(&c));
        assert!(
            !c.funcs.iter().any(|f| matches!(f.verdict, Verdict::Different(_))),
            "{what}\n{}",
            describe(&c)
        );
        assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
        println!("{}", row(&what, &c));

        let c = run(&base, &tc.build(&src, "-Os", &["-DSHIFT", "-DPATCH"]), None);
        let what = format!("moved and patched, {}", tc.name);
        let got = flagged(&c);
        assert!(
            got.iter()
                .all(|g| ["patched", "caller"].contains(g) || limit.contains(g)),
            "{what}\n{}",
            describe(&c)
        );
        let v = &c.func("patched").unwrap().verdict;
        assert!(matches!(v, Verdict::Different(_)), "{what}\n{}", describe(&c));
        assert!(c.data.is_empty(), "{what}\n{}", describe(&c));
    }
}

/// Two builds that order a load and a store through pointers of different types differently
/// differ only where the two overlap: never DIFFERENT, and the caller that calls the function
/// is not reported for it.
#[test]
fn load_store_order() {
    for tc in [GCC_M3, CLANG_M3] {
        if !tc.available() {
            continue;
        }
        let src = corpus("bindiff/overlap.c");
        let c = run(&tc.build(&src, "-Os", &[]), &tc.build(&src, "-O2", &[]), None);
        let what = format!("load/store order, {}", tc.name);
        for name in ["adjust", "use"] {
            let v = &c.func(name).unwrap_or_else(|| panic!("{what}: no {name}")).verdict;
            assert!(!matches!(v, Verdict::Different(_)), "{what}\n{}", describe(&c));
        }
        if let Verdict::MayDiffer(why) = &c.func("adjust").unwrap().verdict {
            assert!(why.contains("overlaps"), "{what}\n{}", describe(&c));
            assert!(!flagged(&c).contains(&"use"), "{what}\n{}", describe(&c));
        }
        println!("{}", row(&what, &c));
    }
}

/// A source for each image: the function whose definition changed is reported as changed in
/// the source and decided by its machine code; the functions that are the same in both
/// sources and match them are equivalent through the source.
#[test]
fn two_sources() {
    let tc = GCC_M3;
    if !tc.available() {
        return;
    }
    let src = causes_src();
    let (old, new) = (
        tc.build(&src, "-Os", &[]),
        tc.build(&src, "-Os", &["-DSHIFT", "-DPATCH"]),
    );
    let (a, b) = (load(&old), load(&new));
    let c = std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let parse = |image: &Image, defs: &[&str]| {
                let copts = cverif::c::Options {
                    include_dirs: vec![corpus("include")],
                    defines: defs.iter().map(|d| (d.to_string(), "1".to_string())).collect(),
                    short_enums: image.short_enums,
                    ..Default::default()
                };
                cverif::c::parse_files(&[causes_src()], &copts).expect("parse C")
            };
            let (pa, pb) = (parse(&a, &[]), parse(&b, &["SHIFT", "PATCH"]));
            compare(&a, &b, Some((&pa, &pb)), &options(Assumptions::default()))
        })
        .unwrap()
        .join()
        .unwrap();
    assert_eq!(c.source_changed, ["patched", "shift_code"], "{}", describe(&c));
    // `caller` calls the patched function: its own code is unchanged, and the report says
    // what it rests on.
    assert!(c.source_affected.is_empty(), "{}", describe(&c));
    let caller = c.func("caller").unwrap();
    assert!(
        caller.is_equivalent() && caller.modulo.iter().any(|m| m.0 == "patched" && m.1 == "DIFFERENT"),
        "{}",
        describe(&c)
    );
    let p = c.func("patched").unwrap();
    assert!(matches!(p.verdict, Verdict::Different(_)), "{}", describe(&c));
    assert!(
        p.via_source
            .as_deref()
            .is_some_and(|s| s.starts_with("CHANGED IN SOURCE")),
        "{}",
        describe(&c)
    );
    for name in ["is_empty", "pick", "checked", "shifted", "dispatch", "store_and_read"] {
        let f = c.func(name).unwrap();
        assert!(
            !matches!(f.verdict, Verdict::Different(_) | Verdict::MayDiffer(_)),
            "{name}\n{}",
            describe(&c)
        );
    }
    assert!(got_only(&c, &["patched", "caller"]), "{}", describe(&c));
}

/// A review with one source per image (tests/corpus/bindiff/review.c): what the sources say
/// differently is found exactly, and each function is decided by the cheapest means that
/// decides it.
#[test]
fn two_source_review() {
    let tc = GCC_M3;
    if !tc.available() {
        return;
    }
    // The two versions as two files, as a reviewer has them: the lines under `#ifdef NEW`
    // are in the new one only, those under its `#else` in the old one only.
    let version = |new: bool| -> PathBuf {
        let text = std::fs::read_to_string(corpus("bindiff/review.c")).unwrap();
        let mut keep = true;
        let mut o = String::new();
        for l in text.lines() {
            match l.trim() {
                "#ifdef NEW" => keep = new,
                "#else" => keep = !new,
                "#endif" => keep = true,
                _ if keep => {
                    o.push_str(l);
                    o.push('\n');
                }
                _ => {}
            }
        }
        let dir = tmp(&format!(
            "review-{}-{}",
            if new { "new" } else { "old" },
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("review.c");
        std::fs::write(&path, o).unwrap();
        path
    };
    let (src_old, src_new) = (version(false), version(true));
    for level in ["-Os", "-O2"] {
        let (old, new) = (
            tc.build(&src_old, level, &["-DOLD"]),
            tc.build(&src_new, level, &["-DNEW"]),
        );
        let (a, b) = (load(&old), load(&new));
        let (src_old, src_new) = (src_old.clone(), src_new.clone());
        let c = std::thread::Builder::new()
            .stack_size(32 << 20)
            .spawn(move || {
                let parse = |image: &Image, file: &Path| {
                    let copts = cverif::c::Options {
                        include_dirs: vec![corpus("include")],
                        short_enums: image.short_enums,
                        ..Default::default()
                    };
                    cverif::c::parse_files(&[file.to_path_buf()], &copts).expect("parse C")
                };
                let (pa, pb) = (parse(&a, &src_old), parse(&b, &src_new));
                compare(&a, &b, Some((&pa, &pb)), &options(Assumptions::default()))
            })
            .unwrap()
            .join()
            .unwrap();
        let text = format!("{level}\n{}\n{}", describe(&c), c.render());
        // White space, comments and position are no change; a line number is one, and is
        // named as such; assembly is compared as text.
        assert_eq!(
            c.source_changed,
            ["asm_changed", "lined", "patched", "quiet", "soft"],
            "{text}"
        );
        let via = |n: &str| c.func(n).unwrap().via_source.clone().unwrap_or_default();
        assert!(via("lined").contains("line numbers"), "{text}");
        assert!(!via("patched").contains("line numbers"), "{text}");
        let verdict = |n: &str| &c.func(n).unwrap().verdict;
        for n in ["asm_changed", "patched", "inliner", "reads_knob"] {
            assert!(matches!(verdict(n), Verdict::Different(_)), "{n}\n{text}");
        }
        // (The line number is an argument of a function the images do not define.)
        assert!(
            matches!(verdict("lined"), Verdict::Different(_) | Verdict::MayDiffer(_)),
            "{text}"
        );
        for n in ["moved", "asm_same", "plain"] {
            assert!(c.func(n).unwrap().is_equivalent(), "{n}\n{text}");
        }
        // The caller of a changed function is equivalent through the source, and says so:
        // it was not compared as machine code.
        let caller = c.func("caller").unwrap();
        assert!(caller.is_equivalent(), "{text}");
        assert!(caller.modulo.iter().any(|m| m.0 == "patched"), "{text}");
        assert!(caller.route != Route::Machine, "{text}");
        // ... but not where it has the changed code in place, with or without a symbol for
        // the function it came from; nor where a constant or a declaration changed.
        for n in ["inliner", "reads_knob", "uses_stop"] {
            assert!(c.source_affected.iter().any(|x| x == n), "{n}\n{text}");
            assert!(c.func(n).unwrap().route != Route::Source, "{n}\n{text}");
        }
        let sc = c.func("soft_caller").unwrap();
        let calls_soft = sc.modulo.iter().any(|m| m.0 == "soft");
        assert!(
            matches!(sc.verdict, Verdict::Different(_)) || (sc.is_equivalent() && calls_soft),
            "{text}"
        );
        if level == "-O2" {
            assert!(matches!(sc.verdict, Verdict::Different(_)), "{text}");
        }
        assert!(
            !c.source_affected.iter().any(|x| x == "caller" || x == "plain"),
            "{text}"
        );
    }
}

fn got_only(c: &Comparison, allowed: &[&str]) -> bool {
    flagged(c).iter().all(|g| allowed.contains(g))
}

/// The patch review on MicroPython itself (opt-in): `CVERIF_MICROPYTHON` is a built checkout
/// (see tests/upy.rs), `CVERIF_MICROPYTHON_PATCHED` a second one in which `list_pop` of
/// py/objlist.c tests `self->len < 2` instead of `self->len == 0`.  Exactly that function
/// differs; a function that prints the build's version banner may be reported as well.
#[test]
#[ignore]
fn micropython_patch() {
    let (Ok(old), Ok(new)) = (
        std::env::var("CVERIF_MICROPYTHON"),
        std::env::var("CVERIF_MICROPYTHON_PATCHED"),
    ) else {
        eprintln!("skipping: CVERIF_MICROPYTHON and CVERIF_MICROPYTHON_PATCHED are not both set");
        return;
    };
    let elf = |root: &str| Path::new(root).join("ports/minimal/build/firmware.elf");
    let c = run(&elf(&old), &elf(&new), None);
    println!("{}", row("MicroPython, list_pop patched", &c));
    let different: Vec<&str> = (c.funcs.iter())
        .filter(|f| matches!(f.verdict, Verdict::Different(_)))
        .map(|f| f.name.as_str())
        .collect();
    assert_eq!(different, ["list_pop"], "{}", describe(&c));
    assert!(got_only(&c, &["list_pop", "pyexec_friendly_repl"]), "{}", describe(&c));
    assert!(equivalent(&c) * 10 >= paired(&c) * 9, "{}", describe(&c));
    // Measured: 628 equivalent, 614 of the 640 pairs settled by their instructions alone.
    assert!(equivalent(&c) >= 620, "{}", row("", &c));
    let same = (c.funcs.iter()).filter(|f| f.route == Route::SameInstructions).count();
    assert!(same >= 600, "{same} pairs with the same instructions");
}

/// Several names for one piece of code.  Identical functions that the linker folds in one
/// image and not in the other are paired by name and are equivalent, not added, removed or
/// different, and so are their callers; a change in a caller is still found.  A run-time
/// routine under two ABI names is one callee.
#[test]
fn folded_functions_and_aliases() {
    let dir = tmp("alias");
    std::fs::create_dir_all(&dir).unwrap();
    let ok = |cmd: &mut Command| cmd.output().is_ok_and(|o| o.status.success());
    let alias = |f: &str| corpus("alias").join(f);
    let cc = |src: &Path, out: &Path, extra: &[&str]| {
        ok(Command::new(GCC)
            .args(GCC_M3.flags)
            .args(["-ffreestanding", "-c"])
            .args(extra)
            .arg(src)
            .arg("-o")
            .arg(out))
    };
    let uniq = std::process::id();
    if !have(GCC) {
        eprintln!("skipping: no GNU cross toolchain");
        return;
    }
    // The division routines: the same callers at two levels, then a changed one.
    let lib = dir.join(format!("divmod-{uniq}.o"));
    assert!(cc(&alias("divmod.S"), &lib, &[]));
    let div = |tag: &str, flags: &[&str]| -> PathBuf {
        let (o, all) = (
            dir.join(format!("div-{tag}-{uniq}.o")),
            dir.join(format!("divall-{tag}-{uniq}.o")),
        );
        assert!(cc(&alias("div.c"), &o, flags));
        assert!(ok(Command::new("arm-none-eabi-ld")
            .arg("-r")
            .arg(&o)
            .arg(&lib)
            .arg("-o")
            .arg(&all)));
        all
    };
    let base = div("os", &["-Os"]);
    let c = run(&base, &div("o2", &["-O2"]), None);
    assert!(
        !c.funcs
            .iter()
            .any(|f| matches!(f.verdict, Verdict::Different(_) | Verdict::Added | Verdict::Removed)),
        "division routines\n{}",
        describe(&c)
    );
    let c = run(&base, &div("m1", &["-Os", "-DMUTANT=1"]), None);
    assert_eq!(flagged(&c), ["qr"], "division routines, mutant\n{}", describe(&c));

    // Folding at link time.
    if !ok(Command::new("ld.lld").arg("--version")) {
        eprintln!("skipping the folded functions: no ld.lld");
        return;
    }
    let ext = dir.join(format!("ext-{uniq}.o"));
    assert!(cc(&alias("ext.c"), &ext, &["-Os"]));
    let link = |tag: &str, mutant: u32, fold: bool| -> Option<PathBuf> {
        let (o, elf) = (
            dir.join(format!("folded-{tag}-{uniq}.o")),
            dir.join(format!("folded-{tag}-{uniq}.elf")),
        );
        let m = format!("-DMUTANT={mutant}");
        assert!(cc(
            &alias("folded.c"),
            &o,
            &[
                "-Os",
                "-fno-inline",
                "-fno-ipa-icf",
                "-ffunction-sections",
                "-DNO_SAME",
                &m
            ]
        ));
        let mut ld = Command::new("ld.lld");
        if fold {
            ld.arg("--icf=all");
        }
        ok(ld.args(["-e", "g1"]).arg(&o).arg(&ext).arg("-o").arg(&elf)).then_some(elf)
    };
    let (Some(plain), Some(folded), Some(changed)) =
        (link("plain", 0, false), link("icf", 0, true), link("icf-m1", 1, true))
    else {
        eprintln!("skipping the folded functions: ld.lld cannot link for this target");
        return;
    };
    let at = |p: &Path, n: &str| load(p).func(n).map(|s| s.addr);
    assert_eq!(
        at(&folded, "f1"),
        at(&folded, "f2"),
        "the linker was expected to fold f1 and f2"
    );
    assert_ne!(at(&plain, "f1"), at(&plain, "f2"));
    for (old, new, what) in [
        (&plain, &folded, "folded in the new image"),
        (&folded, &plain, "folded in the old image"),
    ] {
        let c = run(old, new, None);
        assert!(flagged(&c).is_empty(), "{what}\n{}", describe(&c));
        assert!(
            !c.funcs
                .iter()
                .any(|f| matches!(f.verdict, Verdict::Added | Verdict::Removed)),
            "{what}\n{}",
            describe(&c)
        );
        for name in ["f1", "f2", "g1", "g2", "h"] {
            let f = c
                .func(name)
                .unwrap_or_else(|| panic!("{what}: no {name}\n{}", describe(&c)));
            assert!(f.is_equivalent(), "{what}: {name}\n{}", describe(&c));
        }
        let f1 = c.func("f1").unwrap();
        assert!(
            f1.via_source.as_deref().is_some_and(|s| s.starts_with("folded")),
            "{what}: {:?}\n{}",
            f1.via_source,
            describe(&c)
        );
    }
    let c = run(&plain, &changed, None);
    assert_eq!(flagged(&c), ["g2"], "folded and changed\n{}", describe(&c));
}

// ----- command line -------------------------------------------------------------------------

#[test]
fn command_line() {
    let tc = GCC_M0;
    if !tc.available() {
        return;
    }
    let src = patch_src();
    let (old, new, moved) = (
        tc.build(&src, "-Os", &[]),
        tc.build(&src, "-Os", &["-DPATCH"]),
        tc.build(&src, "-Os", &["-DREORDER"]),
    );
    let cverif = |args: &[&str], a: &Path, b: &Path| {
        Command::new(env!("CARGO_BIN_EXE_cverif"))
            .args(["--compare", "-j", "2", "--work-limit", "30000"])
            .args(args)
            .arg(a)
            .arg(b)
            .output()
            .expect("run cverif")
    };
    let json = tmp("compare.json");
    let out = cverif(&["--json", json.to_str().unwrap()], &old, &new);
    assert_eq!(out.status.code(), Some(1));
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("DIFFERENT    clampv"), "{text}");
    assert!(text.contains("assumptions:") && text.contains("sp-aligned"), "{text}");
    let doc = std::fs::read_to_string(&json).unwrap();
    assert!(
        doc.contains("\"type\": \"compare\"") && doc.contains("\"different\": true"),
        "{doc}"
    );
    assert!(
        doc.contains("{\"name\": \"clampv\", \"status\": \"DIFFERENT\""),
        "{doc}"
    );
    // --explain: the two values as expressions and the code of both versions.
    let out = cverif(&["--explain"], &old, &new);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("old code:") && text.contains("new code:"), "{text}");
    assert!(text.contains("cmp r0, #99") && text.contains("cmp r0, #100"), "{text}");
    let out = cverif(&[], &old, &moved);
    assert_eq!(out.status.code(), Some(0), "{}", String::from_utf8_lossy(&out.stdout));
    assert!(String::from_utf8_lossy(&out.stdout).contains("verdict:         EQUIVALENT"));
    let out = cverif(&["--assume", "nonsense"], &old, &moved);
    assert_eq!(out.status.code(), Some(2));
    // Three-way: the source is the remaining argument; -D selects what the source says.
    let out = Command::new(env!("CARGO_BIN_EXE_cverif"))
        .args(["--compare", "-j", "2", "--work-limit", "30000"])
        .arg(&old)
        .arg(&moved)
        .arg(&src)
        .output()
        .expect("run cverif");
    let text = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code(), Some(0), "{text}");
    assert!(text.contains("three-way"), "{text}");
}