cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
//! Optimisation-level identification against real GCC output.
//!
//! Each embedded program is compiled with `arm-none-eabi-gcc -mthumb -mcpu=cortex-m3`
//! at -O0, -O1, -O2, -O3, -Os and -Og, and `cverif::detect` is asked to recover the
//! level.  The test passes silently when the cross compiler is not installed.
//!
//! What is asserted (and why not more):
//! * -O0 is always identified exactly, and never reported for optimised code;
//! * for every level, the true level is among the top candidates: its confidence
//!   is at least `TIE` times the best one.  Several levels legitimately produce
//!   near-identical code (-O2/-O3 without transformable loops, -O1/-Og on
//!   straight-line code), so demanding a unique winner would be wrong;
//! * the assertions hold for the programs below, which contain loops, helpers,
//!   divisions by constants and switches.  Code without such structure carries
//!   less evidence; see the loop-free program, for which only -O0 is asserted.
//!
//! The weights were tuned against GCC 16.  With an older compiler (CI installs the
//! distribution's GCC 13) the tie rule is relaxed to "the true level is among the
//! three best candidates", because some fingerprints (function alignment, how far
//! the scheduler moves compares) may differ between GCC versions; the -O0 checks
//! stay strict.
//!
//! `cargo test --test detect -- --nocapture` prints the confusion matrix.

#[path = "support/cc_cache.rs"]
mod cc_cache;

use cverif::detect::{Compiler, FlagReport, OptLevel, Verdict, detect, features};
use cverif::image::Image;
use std::path::PathBuf;
use std::process::Command;

/// The true level must score at least this fraction of the best candidate.
const TIE: f32 = 0.5;

const KERNELS: &str = r#"
extern int ext(int);
extern int tab[64];
static int helper(int a, int b) { return a * 3 + b; }
static int once(int a) { int s = 0; for (int i = 0; i < a; i++) s += ext(i); return s; }
int sum(const int *p, int n) { int s = 0; for (int i = 0; i < n; i++) s += p[i]; return s; }
void fill(int *p, int n, int v) { for (int i = 0; i < n; i++) p[i] = v; }
void copy(char *d, const char *s, unsigned n) { for (unsigned i = 0; i < n; i++) d[i] = s[i]; }
unsigned div10(unsigned a) { return a / 10; }
int sdiv7(int a) { return a / 7; }
unsigned mod10(unsigned a) { return a % 10; }
int sw(int x) {
    switch (x) { case 0: return 11; case 1: return 22; case 2: return 37; case 3: return 41;
                 case 4: return 5; case 5: return 77; default: return -1; }
}
int use(int a, int b) { return helper(a, b) + helper(b, a) + once(a); }
int fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
long long mul64(long long a, long long b) { return a * b + 1; }
int nested(int n) { int s = 0; for (int i = 0; i < n; i++) for (int j = 0; j < 8; j++) s += tab[j] * i; return s; }
struct S { int a; short b; char c; int d[4]; };
int st(struct S *s) { return s->a + s->b + s->c + s->d[2]; }
int clampi(int x) { if (x < 0) return 0; if (x > 255) return 255; return x; }
"#;

const STRINGS: &str = r#"
typedef unsigned char u8;
typedef unsigned int u32;
extern void emit(int);
u32 length(const char *s) { u32 n = 0; while (s[n]) n++; return n; }
int compare(const u8 *a, const u8 *b, u32 n) {
    for (u32 i = 0; i < n; i++) { if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1; }
    return 0;
}
u32 checksum(const u8 *p, u32 n) {
    u32 a = 1, b = 0;
    for (u32 i = 0; i < n; i++) { a = (a + p[i]) % 65521; b = (b + a) % 65521; }
    return (b << 16) | a;
}
void reverse(u8 *p, u32 n) {
    for (u32 i = 0, j = n; i + 1 < j; i++) { j--; u8 t = p[i]; p[i] = p[j]; p[j] = t; }
}
int to_decimal(char *out, u32 v) {
    char tmp[12]; int n = 0, k = 0;
    do { tmp[n++] = '0' + v % 10; v /= 10; } while (v);
    while (n) out[k++] = tmp[--n];
    out[k] = 0;
    return k;
}
void scale(short *dst, const short *src, int n, int num) {
    for (int i = 0; i < n; i++) dst[i] = (short)(src[i] * num / 100);
}
int count_bits(u32 x) { int n = 0; while (x) { n += x & 1; x >>= 1; } return n; }
void report(const int *v, int n) { for (int i = 0; i < n; i++) if (v[i] > 0) emit(v[i]); }
int classify(int c) {
    switch (c) { case ' ': case '\t': return 1; case '\n': return 2; case '0': return 3;
                 case 'a': return 4; case 'z': return 5; default: return c > 127 ? 6 : 0; }
}
"#;

const STATE: &str = r#"
enum state { IDLE, HEADER, BODY, TRAILER, DONE, FAIL };
struct parser { enum state st; unsigned len, pos, sum; unsigned char buf[32]; };
extern unsigned read_reg(unsigned);
extern void write_reg(unsigned, unsigned);
static unsigned mix(unsigned h, unsigned v) { h ^= v; h *= 16777619u; return h ^ (h >> 13); }
void init(struct parser *p) { p->st = IDLE; p->len = p->pos = p->sum = 0; for (int i = 0; i < 32; i++) p->buf[i] = 0; }
int feed(struct parser *p, unsigned char c) {
    switch (p->st) {
    case IDLE: if (c == 0x7e) p->st = HEADER; break;
    case HEADER: if (c > 32) p->st = FAIL; else { p->len = c; p->pos = 0; p->st = c ? BODY : TRAILER; } break;
    case BODY: p->buf[p->pos++] = c; p->sum = mix(p->sum, c); if (p->pos == p->len) p->st = TRAILER; break;
    case TRAILER: p->st = ((p->sum & 0xff) == c) ? DONE : FAIL; break;
    default: break;
    }
    return p->st == DONE;
}
unsigned hash(const unsigned char *d, unsigned n) { unsigned h = 2166136261u; for (unsigned i = 0; i < n; i++) h = mix(h, d[i]); return h; }
void poll(unsigned base, unsigned count) {
    for (unsigned i = 0; i < count; i++) { unsigned v = read_reg(base + 4 * i); if (v & 1) write_reg(base + 4 * i, v / 3); }
}
int average(const int *v, int n) { long long s = 0; for (int i = 0; i < n; i++) s += v[i]; return n ? (int)(s / n) : 0; }
void matmul(int *c, const int *a, const int *b) {
    for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { int s = 0; for (int k = 0; k < 4; k++) s += a[i * 4 + k] * b[k * 4 + j]; c[i * 4 + j] = s; }
}
unsigned gcd(unsigned a, unsigned b) { while (b) { unsigned t = a % b; a = b; b = t; } return a; }
"#;

/// Straight-line code: several levels produce (nearly) the same bytes, so only -O0 can be told apart.
const LOOP_FREE: &str = r#"
int add(int a, int b) { return a + b; }
int max(int a, int b) { return a > b ? a : b; }
unsigned bits(unsigned a, unsigned b) { return (a & b) | (a ^ ~b); }
int neg(int a) { return -a; }
unsigned field(unsigned x) { return (x >> 5) & 0x3f; }
int pick(int c, int a, int b) { if (c) return a + 1; return b - 1; }
"#;

const LEVELS: [(&str, OptLevel); 6] = [
    ("-O0", OptLevel::O0),
    ("-O1", OptLevel::O1),
    ("-O2", OptLevel::O2),
    ("-O3", OptLevel::O3),
    ("-Os", OptLevel::Os),
    ("-Og", OptLevel::Og),
];

fn have_gcc() -> bool {
    Command::new("arm-none-eabi-gcc")
        .arg("--version")
        .output()
        .is_ok_and(|o| o.status.success())
}

/// Major version of the installed cross compiler.
fn gcc_major() -> u32 {
    let out = Command::new("arm-none-eabi-gcc").arg("-dumpversion").output().unwrap();
    String::from_utf8_lossy(&out.stdout)
        .trim()
        .split('.')
        .next()
        .and_then(|v| v.parse().ok())
        .unwrap_or(0)
}

fn compile(name: &str, src: &str, flag: &str, extra: &[&str]) -> Image {
    let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("detect");
    std::fs::create_dir_all(&dir).unwrap();
    let c = dir.join(format!("{name}.c"));
    std::fs::write(&c, src).unwrap();
    let o = dir.join(format!("{name}{flag}{}.o", extra.join("")));
    let out = cc_cache::output(
        Command::new("arm-none-eabi-gcc")
            .args(["-mthumb", "-mcpu=cortex-m3", "-std=gnu11", "-c", flag])
            .args(extra)
            .arg(&c)
            .arg("-o")
            .arg(&o),
    )
    .unwrap();
    assert!(
        out.status.success(),
        "gcc failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    Image::from_elf(&std::fs::read(&o).unwrap()).unwrap()
}

fn idx(l: OptLevel) -> usize {
    LEVELS.iter().position(|x| x.1 == l).unwrap()
}

#[test]
fn identifies_optimisation_level() {
    if !have_gcc() {
        return;
    }
    let verbose = std::env::var_os("DETECT_VERBOSE").is_some();
    let strict = gcc_major() >= 14;
    let programs = [("kernels", KERNELS), ("strings", STRINGS), ("state", STATE)];
    // confusion[true][best guess]
    let mut confusion = [[0u32; 6]; 6];
    let mut failures = Vec::new();
    for (name, src) in programs {
        for (flag, level) in LEVELS {
            let img = compile(name, src, flag, &[]);
            let r = detect(&img);
            let best = r.best().expect("candidates");
            confusion[idx(level)][idx(best)] += 1;
            let top = r.candidates[0].1;
            let own = r.candidates.iter().find(|c| c.0 == level).unwrap().1;
            if verbose {
                println!("--- {name} {flag}: {:?}", r.candidates);
                println!("    {:?}", features(&img));
                for e in &r.evidence {
                    println!("    {e}");
                }
            }
            if level == OptLevel::O0 && best != OptLevel::O0 {
                failures.push(format!("{name} {flag}: -O0 not identified (got {best})"));
            }
            if level != OptLevel::O0 && best == OptLevel::O0 {
                failures.push(format!("{name} {flag}: optimised code reported as -O0"));
            }
            let rank = r.candidates.iter().position(|c| c.0 == level).unwrap();
            if (strict && own < top * TIE) || (!strict && rank > 2) {
                failures.push(format!(
                    "{name} {flag}: true level scored {own:.2}, best is {best} at {top:.2}"
                ));
            }
            assert!(
                r.compiler.as_deref().is_some_and(|c| c.contains("GCC")),
                "compiler identification missing"
            );
        }
    }
    println!("confusion matrix (rows: true level, columns: best guess)");
    println!("      {}", LEVELS.map(|l| format!("{:>4}", l.0)).join(""));
    for (i, row) in confusion.iter().enumerate() {
        println!("{:>4}  {}", LEVELS[i].0, row.map(|n| format!("{n:>4}")).join(""));
    }
    assert!(failures.is_empty(), "\n{}", failures.join("\n"));
}

#[test]
fn loop_free_code_only_separates_o0() {
    if !have_gcc() {
        return;
    }
    for (flag, level) in LEVELS {
        let r = detect(&compile("loopfree", LOOP_FREE, flag, &[]));
        let best = r.best().expect("candidates");
        assert_eq!(
            best == OptLevel::O0,
            level == OptLevel::O0,
            "{flag}: got {:?}",
            r.candidates
        );
    }
}

#[test]
fn declared_flags_are_reported_but_not_trusted() {
    if !have_gcc() {
        return;
    }
    // Debug info records the command line; the structural guess must still be made independently.
    let img = compile("kernels_g", KERNELS, "-O0", &["-g"]);
    let r = detect(&img);
    assert!(
        r.declared.as_deref().is_some_and(|d| d.contains("GNU C")),
        "producer not found: {:?}",
        r.declared
    );
    assert_eq!(r.best(), Some(OptLevel::O0));
    let img = compile("kernels_g", KERNELS, "-Os", &["-g"]);
    let r = detect(&img);
    assert!(
        r.declared.as_deref().is_some_and(|d| d.contains("-Os")),
        "declared flags: {:?}",
        r.declared
    );
    assert!(r.evidence.iter().any(|e| e.contains("declares -Os")));
}

/// Development aid: `DETECT_FILES="a.o b.elf" cargo test --test detect inspect_files -- --ignored --nocapture`
/// prints the ranking (and, with DETECT_VERBOSE, the evidence) for arbitrary ELF files.
#[test]
#[ignore]
fn inspect_files() {
    let Some(files) = std::env::var_os("DETECT_FILES") else {
        return;
    };
    for p in files.to_string_lossy().split_whitespace() {
        let img = Image::from_elf(&std::fs::read(p).unwrap()).unwrap();
        let r = detect(&img);
        let c: Vec<String> = r
            .candidates
            .iter()
            .take(3)
            .map(|c| format!("{} {:.2}", c.0, c.1))
            .collect();
        println!("{p}: {}", c.join(", "));
        if std::env::var_os("DETECT_VERBOSE").is_some() {
            for e in &r.evidence {
                println!("    {e}");
            }
        }
    }
}

// ----- build-configuration matrix ----------------------------------------------------------------
//
// The verification corpus (`tests/corpus/*.c`, about 270 functions) is compiled with GCC and
// clang for the supported targets at every optimisation level, and with individual flags
// toggled.  The assertions are deliberately coarse, so that they hold across compiler versions:
//
// * always: the compiler family, -O0 against optimised code, the architecture, -fropi and
//   -frwpi, section/symbol-based flags, and "unknown" for what a stripped file cannot show;
// * only with the compiler versions the weights were tuned against (GCC >= 14, clang >= 18):
//   the family from code style alone, speed against size levels, the true level being among
//   the tied candidates, and the absence of contradictions on honest builds.
//
// `cargo test --release --test detect -- --nocapture` prints the accuracy table.

#[derive(Clone, Copy, PartialEq, Debug)]
enum Cc {
    Gcc,
    Clang,
}

struct Config {
    name: &'static str,
    cc: Cc,
    flags: &'static [&'static str],
    v6m: bool,
    ropi: bool,
    rwpi: bool,
    no_jump_tables: bool,
}

const fn cfg(name: &'static str, cc: Cc, flags: &'static [&'static str], v6m: bool) -> Config {
    Config {
        name,
        cc,
        flags,
        v6m,
        ropi: false,
        rwpi: false,
        no_jump_tables: false,
    }
}

const CONFIGS: &[Config] = &[
    cfg("gcc-m0plus", Cc::Gcc, &["-mthumb", "-mcpu=cortex-m0plus"], true),
    cfg("gcc-m3", Cc::Gcc, &["-mthumb", "-mcpu=cortex-m3"], false),
    cfg(
        "gcc-m35p",
        Cc::Gcc,
        &["-mthumb", "-mcpu=cortex-m35p+nodsp", "-msoft-float"],
        false,
    ),
    Config {
        no_jump_tables: true,
        ..cfg(
            "gcc-firmware",
            Cc::Gcc,
            &[
                "-fomit-frame-pointer",
                "-mcpu=cortex-m0plus",
                "-mthumb",
                "-mtune=cortex-m0plus",
                "-mlittle-endian",
                "-mno-unaligned-access",
                "-fno-jump-tables",
            ],
            true,
        )
    },
    // The production command line of the firmware this tool is written for.
    Config {
        ropi: true,
        no_jump_tables: true,
        ..cfg(
            "clang-firmware",
            Cc::Clang,
            &[
                "-fomit-frame-pointer",
                "-momit-leaf-frame-pointer",
                "-mcpu=cortex-m0plus",
                "-mthumb",
                "-mtune=cortex-m0plus",
                "-mlittle-endian",
                "-mno-unaligned-access",
                "--target=armv6m-none-eabi",
                "-fropi",
                "-fno-jump-tables",
            ],
            true,
        )
    },
    cfg(
        "clang-m0plus",
        Cc::Clang,
        &["--target=armv6m-none-eabi", "-mcpu=cortex-m0plus", "-mthumb"],
        true,
    ),
    cfg(
        "clang-m3",
        Cc::Clang,
        &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb"],
        false,
    ),
    Config {
        rwpi: true,
        ..cfg(
            "clang-m3-rwpi",
            Cc::Clang,
            &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb", "-frwpi"],
            false,
        )
    },
    Config {
        rwpi: true,
        ..cfg(
            "clang-m35p-rwpi",
            Cc::Clang,
            &[
                "--target=armv8m.main-none-eabi",
                "-mcpu=cortex-m35p+nodsp",
                "-mthumb",
                "-msoft-float",
                "-frwpi",
            ],
            false,
        )
    },
];

fn config(name: &str) -> &'static Config {
    CONFIGS.iter().find(|c| c.name == name).unwrap()
}

fn run_ok(cmd: &mut Command) -> bool {
    cc_cache::output(cmd).is_ok_and(|o| o.status.success())
}

fn have_binutils() -> bool {
    ["arm-none-eabi-ld", "arm-none-eabi-objcopy", "arm-none-eabi-nm"]
        .iter()
        .all(|t| run_ok(Command::new(t).arg("--version")))
}

fn matrix_dir() -> PathBuf {
    let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("detect-matrix");
    std::fs::create_dir_all(&d).unwrap();
    d
}

/// Can this compiler produce ARM objects at all?  (clang may be built without the ARM backend.)
fn have(cc: Cc) -> bool {
    if !have_binutils() {
        return false;
    }
    let d = matrix_dir();
    let c = d.join(format!("probe-{cc:?}.c"));
    std::fs::write(&c, "int probe(int a) { return a + 1; }\n").unwrap();
    let o = d.join(format!("probe-{cc:?}.o"));
    match cc {
        Cc::Gcc => run_ok(
            Command::new("arm-none-eabi-gcc")
                .args(["-mthumb", "-mcpu=cortex-m3", "-c"])
                .arg(&c)
                .arg("-o")
                .arg(&o),
        ),
        Cc::Clang => run_ok(
            Command::new("clang")
                .args(["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb", "-c"])
                .arg(&c)
                .arg("-o")
                .arg(&o),
        ),
    }
}

fn major(cc: Cc) -> u32 {
    match cc {
        Cc::Gcc => gcc_major(),
        Cc::Clang => {
            let out = Command::new("clang").arg("--version").output().unwrap();
            let text = String::from_utf8_lossy(&out.stdout).to_string();
            text.split("version ")
                .nth(1)
                .and_then(|v| v.split('.').next())
                .and_then(|v| v.parse().ok())
                .unwrap_or(0)
        }
    }
}

/// The weights were tuned against these compiler generations.
fn calibrated(cc: Cc) -> bool {
    match cc {
        Cc::Gcc => major(cc) >= 14,
        Cc::Clang => major(cc) >= 18,
    }
}

fn corpus() -> Vec<PathBuf> {
    let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/corpus");
    let mut v: Vec<PathBuf> = std::fs::read_dir(&dir)
        .unwrap()
        .map(|e| e.unwrap().path())
        .filter(|p| p.extension().is_some_and(|e| e == "c"))
        .collect();
    v.sort();
    v
}

type Built = Option<(Vec<PathBuf>, PathBuf)>;

/// Compile the corpus with one configuration: the objects, and all of them as one relocatable
/// object.  `None` when this compiler rejects the flags.  Tests run in parallel and share
/// builds, so each one is made exactly once.
fn built(c: &Config, level: &str, extra: &[&str]) -> Built {
    use std::collections::HashMap;
    use std::sync::{Arc, Mutex, OnceLock};
    static CACHE: Mutex<Option<HashMap<String, Arc<OnceLock<Built>>>>> = Mutex::new(None);
    let key = format!("{}{level}{}", c.name, extra.join(""));
    let cell = CACHE
        .lock()
        .unwrap()
        .get_or_insert_with(HashMap::new)
        .entry(key.clone())
        .or_default()
        .clone();
    cell.get_or_init(|| {
        let dir = matrix_dir().join(&key);
        std::fs::create_dir_all(&dir).unwrap();
        let include = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/include");
        let mut objs = Vec::new();
        for src in corpus() {
            let o = dir.join(src.file_stem().unwrap()).with_extension("o");
            let mut cmd = Command::new(if c.cc == Cc::Gcc { "arm-none-eabi-gcc" } else { "clang" });
            cmd.args(c.flags)
                .arg(level)
                .args(extra)
                .args(["-ffreestanding", "-w", "-c", "-I"])
                .arg(&include)
                .arg(&src)
                .arg("-o")
                .arg(&o);
            if !run_ok(&mut cmd) {
                return None;
            }
            objs.push(o);
        }
        let all = dir.join("all.o");
        run_ok(
            Command::new("arm-none-eabi-ld")
                .args(["-r", "-z", "muldefs"])
                .args(&objs)
                .arg("-o")
                .arg(&all),
        )
        .then_some((objs, all))
    })
    .clone()
}

fn objects(c: &Config, level: &str, extra: &[&str]) -> Option<Vec<PathBuf>> {
    built(c, level, extra).map(|b| b.0)
}

/// The corpus as one relocatable object.
fn build(c: &Config, level: &str, extra: &[&str]) -> Option<PathBuf> {
    built(c, level, extra).map(|b| b.1)
}

fn load(p: &PathBuf) -> Image {
    Image::from_elf(&std::fs::read(p).unwrap()).unwrap()
}

/// Remove everything the toolchain recorded about itself.
fn strip(p: &PathBuf) -> PathBuf {
    let out = p.with_extension("stripped");
    assert!(run_ok(
        Command::new("arm-none-eabi-objcopy")
            .args([
                "--remove-section",
                ".comment",
                "--remove-section",
                ".ARM.attributes",
                "-g"
            ])
            .arg(p)
            .arg(&out)
    ));
    out
}

fn levels(cc: Cc) -> &'static [(&'static str, OptLevel)] {
    const GCC: &[(&str, OptLevel)] = &[
        ("-O0", OptLevel::O0),
        ("-O1", OptLevel::O1),
        ("-O2", OptLevel::O2),
        ("-O3", OptLevel::O3),
        ("-Os", OptLevel::Os),
        ("-Oz", OptLevel::Oz),
        ("-Og", OptLevel::Og),
    ];
    match cc {
        Cc::Gcc => GCC,
        Cc::Clang => &GCC[..6],
    }
}

fn family(cc: Cc) -> Compiler {
    match cc {
        Cc::Gcc => Compiler::Gcc,
        Cc::Clang => Compiler::Clang,
    }
}

fn verdict(r: &FlagReport, flag: &str) -> Verdict {
    r.finding(flag).map_or(Verdict::Unknown, |f| f.verdict)
}

fn yes_no(b: bool) -> Verdict {
    if b { Verdict::Yes } else { Verdict::No }
}

fn is_speed(l: OptLevel) -> bool {
    matches!(l, OptLevel::O2 | OptLevel::O3)
}

fn is_size(l: OptLevel) -> bool {
    matches!(l, OptLevel::Os | OptLevel::Oz)
}

#[test]
fn build_matrix() {
    let mut failures: Vec<String> = Vec::new();
    // (compiler, what) -> (right, total)
    let mut table: std::collections::BTreeMap<(String, &'static str), (u32, u32)> = Default::default();
    for cc in [Cc::Gcc, Cc::Clang] {
        if !have(cc) {
            println!("{cc:?}: toolchain not available, skipped");
            continue;
        }
        let strict = calibrated(cc);
        let configs: Vec<&Config> = CONFIGS.iter().filter(|c| c.cc == cc).collect();
        // One thread per configuration: the compilers dominate the running time.
        let reports: Vec<Vec<(&str, OptLevel, FlagReport)>> = std::thread::scope(|s| {
            let handles: Vec<_> = configs
                .iter()
                .map(|c| {
                    s.spawn(move || {
                        levels(cc)
                            .iter()
                            .filter_map(|&(flag, level)| {
                                let o = build(c, flag, &[])?;
                                Some((flag, level, detect(&load(&o))))
                            })
                            .collect()
                    })
                })
                .collect();
            handles.into_iter().map(|h| h.join().unwrap()).collect()
        });
        for (c, rows) in configs.iter().zip(&reports) {
            for (flag, level, r) in rows {
                let id = format!("{} {flag}", c.name);
                let table = std::cell::RefCell::new(&mut table);
                let tally = |what: &'static str, ok: bool| {
                    let mut t = table.borrow_mut();
                    let e = t.entry((format!("{cc:?}"), what)).or_default();
                    e.0 += ok as u32;
                    e.1 += 1;
                    ok
                };
                let mut check = |what: &'static str, ok: bool, always: bool| {
                    if !tally(what, ok) && (always || strict) {
                        failures.push(format!("{id}: {what} wrong\n{}", r.render(false)));
                    }
                };
                let best = r.best().expect("candidates");
                check("compiler (recorded)", r.family == Some(family(cc)), true);
                // Unoptimised Thumb-1 code may show no habit of either compiler: "unknown" is fine,
                // the other family is not.
                let code = r.family_from_code.map(|f| f.0);
                tally("compiler (code style)", code == Some(family(cc)));
                check(
                    "compiler (code style) not wrong",
                    code.is_none_or(|f| f == family(cc)),
                    false,
                );
                check(
                    "-O0 against optimised",
                    (best == OptLevel::O0) == (*level == OptLevel::O0),
                    true,
                );
                if is_speed(*level) || is_size(*level) {
                    let wrong = (is_speed(*level) && is_size(best)) || (is_size(*level) && is_speed(best));
                    check("speed against size", !wrong, false);
                }
                // GCC emits the same code for -Os and -Oz here: either answer is the true one.
                let same = |a: OptLevel, b: OptLevel| a == b || (cc == Cc::Gcc && is_size(a) && is_size(b));
                tally("level: best guess", same(best, *level));
                check("level: among tied", r.tied().iter().any(|&t| same(t, *level)), false);
                if cc == Cc::Gcc && is_size(best) {
                    let t = r.tied();
                    check(
                        "-Os/-Oz reported as a tie",
                        t.contains(&OptLevel::Os) && t.contains(&OptLevel::Oz),
                        true,
                    );
                }
                check(
                    "recorded goal",
                    r.declared_levels.contains(level) || r.declared_levels.is_empty(),
                    false,
                );
                let arch = r.arch.unwrap_or("");
                check(
                    "architecture",
                    if c.v6m {
                        arch == "ARMv6-M"
                    } else {
                        arch.contains("Mainline")
                    },
                    true,
                );
                check("-fropi", verdict(r, "-fropi") == yes_no(c.ropi), true);
                check("-frwpi", verdict(r, "-frwpi") == yes_no(c.rwpi), true);
                // Never the opposite; "unknown" is acceptable (GCC -O0 lowers switches to chains anyway).
                let jt = verdict(r, "-fno-jump-tables");
                check(
                    "-fno-jump-tables",
                    jt == Verdict::Unknown || jt == yes_no(c.no_jump_tables),
                    false,
                );
                check("-g", verdict(r, "-g") == Verdict::No, true);
                check("-flto", verdict(r, "-flto") == Verdict::No, true);
                check(
                    "-ffunction-sections",
                    verdict(r, "-ffunction-sections") == Verdict::No,
                    true,
                );
                check(
                    "-fstack-protector",
                    verdict(r, "-fstack-protector") == Verdict::No,
                    true,
                );
                check("-mlong-calls", verdict(r, "-mlong-calls") != Verdict::Yes, false);
                check("-fpic", verdict(r, "-fpic") != Verdict::Yes, true);
                check("no contradictions", r.contradictions.is_empty(), false);
                let line = &r.command_line;
                let starts = if cc == Cc::Gcc { "arm-none-eabi-gcc " } else { "clang " };
                check(
                    "command line",
                    line.starts_with(starts)
                        && line.contains("-mthumb")
                        && line.contains("-fropi") == c.ropi
                        && line.contains("-frwpi") == c.rwpi,
                    true,
                );
                if c.name == "clang-firmware" {
                    check(
                        "command line",
                        line.contains("--target=armv6m-none-eabi") && line.contains("-mcpu=cortex-m0plus"),
                        true,
                    );
                }
            }
        }
    }
    println!("{:<8} {:<28} right/total", "compiler", "fact");
    for ((cc, what), (ok, n)) in &table {
        println!("{cc:<8} {what:<28} {ok}/{n}");
    }
    assert!(failures.is_empty(), "\n{}", failures.join("\n"));
}

/// Individual flags switched on, one at a time, on optimised Cortex-M3 code.
#[test]
fn flag_toggles() {
    let mut failures: Vec<String> = Vec::new();
    for cc in [Cc::Gcc, Cc::Clang] {
        if !have(cc) {
            continue;
        }
        let strict = calibrated(cc);
        let c = config(if cc == Cc::Gcc { "gcc-m3" } else { "clang-m3" });
        // (extra flags, finding, expected verdict, asserted for every compiler version)
        let cases: &[(&[&str], &str, Verdict, bool)] = &[
            (
                &["-ffunction-sections", "-fdata-sections"],
                "-ffunction-sections",
                Verdict::Yes,
                true,
            ),
            (
                &["-ffunction-sections", "-fdata-sections"],
                "-fdata-sections",
                Verdict::Yes,
                true,
            ),
            (&["-fstack-protector-all"], "-fstack-protector", Verdict::Yes, true),
            (&["-g"], "-g", Verdict::Yes, true),
            (&["-flto"], "-flto", Verdict::Yes, true),
            (&["-fno-omit-frame-pointer"], "-fomit-frame-pointer", Verdict::No, true),
            (&["-mlong-calls"], "-mlong-calls", Verdict::Yes, false),
            (&["-fno-jump-tables"], "-fno-jump-tables", Verdict::Yes, false),
            (&[], "-fomit-frame-pointer", Verdict::Yes, false),
            (&[], "-fno-jump-tables", Verdict::No, false),
            (&[], "-fdata-sections", Verdict::No, true),
        ];
        for level in ["-Os", "-O2"] {
            for &(extra, flag, want, always) in cases {
                let Some(o) = build(c, level, extra) else {
                    println!("{} {level} {extra:?}: not supported by this compiler", c.name);
                    continue;
                };
                let r = detect(&load(&o));
                let got = verdict(&r, flag);
                // A wrong answer is never acceptable; "unknown" only with untuned compiler versions.
                if got != want && (always || strict || got != Verdict::Unknown) {
                    failures.push(format!(
                        "{} {level} {extra:?}: {flag} is {}, expected {}\n{}",
                        c.name,
                        got.label(),
                        want.label(),
                        r.render(false)
                    ));
                }
                if strict && !r.contradictions.is_empty() {
                    failures.push(format!("{} {level} {extra:?}: {:?}", c.name, r.contradictions));
                }
            }
        }
        // Enumeration size is only ever a declared fact.
        let (extra, on) = if cc == Cc::Gcc {
            ("-fno-short-enums", false)
        } else {
            ("-fshort-enums", true)
        };
        if let Some(o) = build(c, "-Os", &[extra]) {
            let r = detect(&load(&o));
            let f = r.finding("-fshort-enums").unwrap();
            assert_eq!(f.verdict, Verdict::Unknown);
            assert_eq!(f.declared.as_ref().map(|d| d.0), Some(on), "{}", r.render(true));
            assert!(r.command_line.contains(extra), "{}", r.command_line);
        }
    }
    assert!(failures.is_empty(), "\n{}", failures.join("\n"));
}

/// Without `.comment`, build attributes and debug information only the code is left: what it
/// shows is still found, and everything else is "unknown" rather than a guess.
#[test]
fn stripped_metadata_leaves_code_evidence_only() {
    for (name, flag, level) in [
        ("clang-firmware", "-Os", OptLevel::Os),
        ("clang-m3-rwpi", "-O2", OptLevel::O2),
        ("clang-m0plus", "-O0", OptLevel::O0),
        ("gcc-m3", "-O0", OptLevel::O0),
        ("gcc-firmware", "-Os", OptLevel::Os),
    ] {
        let c = config(name);
        if !have(c.cc) {
            continue;
        }
        let Some(o) = build(c, flag, &[]) else { continue };
        let r = detect(&load(&strip(&o)));
        let text = r.render(true);
        assert!(
            r.compiler.is_none() && r.declared.is_none() && r.version.is_none(),
            "{text}"
        );
        assert!(r.attributes.is_empty() && r.declared_levels.is_empty(), "{text}");
        assert!(r.findings.iter().all(|f| f.declared.is_none()), "{text}");
        assert!(r.contradictions.is_empty(), "{text}");
        // The family now rests on code style alone: never the wrong one.
        assert_eq!(r.family, r.family_from_code.map(|f| f.0), "{text}");
        assert_ne!(
            r.family,
            Some(family(if c.cc == Cc::Gcc { Cc::Clang } else { Cc::Gcc })),
            "{text}"
        );
        if calibrated(c.cc) {
            assert_eq!(r.family, Some(family(c.cc)), "{text}");
            assert!(text.contains("from code style"), "{text}");
        }
        assert_eq!(r.best() == Some(OptLevel::O0), level == OptLevel::O0, "{text}");
        assert_eq!(verdict(&r, "-fropi"), yes_no(c.ropi), "{text}");
        assert_eq!(verdict(&r, "-frwpi"), yes_no(c.rwpi), "{text}");
        assert_eq!(verdict(&r, "-fshort-enums"), Verdict::Unknown, "{text}");
        // The corpus has floating-point code and these cores have no FPU.
        assert_ne!(verdict(&r, "-mfloat-abi=soft"), Verdict::No, "{text}");
        if c.v6m {
            // No unaligned access exists on ARMv6-M, so the flag cannot show.
            assert_eq!(verdict(&r, "-mno-unaligned-access"), Verdict::Unknown, "{text}");
        }
    }
}

/// A raw binary with an `nm` symbol table: no sections, relocations or attributes at all.
#[test]
fn raw_binary_reports_unknown_for_what_it_cannot_see() {
    for (name, flag, level) in [
        ("clang-firmware", "-Os", OptLevel::Os),
        ("gcc-m3", "-O2", OptLevel::O2),
        ("gcc-m0plus", "-O0", OptLevel::O0),
    ] {
        let c = config(name);
        if !have(c.cc) {
            continue;
        }
        let Some(objs) = objects(c, flag, &[]) else { continue };
        let dir = objs[0].parent().unwrap().to_path_buf();
        // Define every undefined symbol so that the corpus links.
        let all = build(c, flag, &[]).unwrap();
        let undefined = Command::new("arm-none-eabi-nm").arg("-u").arg(&all).output().unwrap();
        let stubs: String = String::from_utf8_lossy(&undefined.stdout)
            .lines()
            .filter_map(|l| l.split_whitespace().last())
            .map(|s| format!("void {s}(void) {{}}\n"))
            .collect();
        let stub_c = dir.join("stubs.c");
        std::fs::write(&stub_c, stubs).unwrap();
        let stub_o = dir.join("stubs.o");
        let cc = if c.cc == Cc::Gcc { "arm-none-eabi-gcc" } else { "clang" };
        assert!(run_ok(
            Command::new(cc)
                .args(c.flags)
                .args(["-Os", "-ffreestanding", "-fno-builtin", "-w", "-c"])
                .arg(&stub_c)
                .arg("-o")
                .arg(&stub_o)
        ));
        let elf = dir.join("linked.elf");
        let linked = run_ok(
            Command::new("arm-none-eabi-ld")
                .args(["-Ttext=0x8000", "-e", "0", "-z", "muldefs"])
                .args(&objs)
                .arg(&stub_o)
                .arg("-o")
                .arg(&elf),
        );
        if !linked {
            println!("{name} {flag}: the corpus does not link with this toolchain, skipped");
            continue;
        }
        // The linked ELF keeps its metadata.
        let r = detect(&load(&elf));
        assert_eq!(r.family, Some(family(c.cc)), "{}", r.render(true));
        assert_eq!(verdict(&r, "-fropi"), yes_no(c.ropi), "{}", r.render(true));
        assert_eq!(
            verdict(&r, "-ffunction-sections"),
            Verdict::Unknown,
            "{}",
            r.render(true)
        );

        let bin = dir.join("linked.bin");
        assert!(run_ok(
            Command::new("arm-none-eabi-objcopy")
                .args(["-O", "binary"])
                .arg(&elf)
                .arg(&bin)
        ));
        let nm = Command::new("arm-none-eabi-nm").arg("-S").arg(&elf).output().unwrap();
        let symbols = String::from_utf8_lossy(&nm.stdout).to_string();
        let img = Image::from_raw(&std::fs::read(&bin).unwrap(), 0x8000, &symbols).unwrap();
        let r = detect(&img);
        let text = r.render(true);
        assert!(
            r.compiler.is_none() && r.declared.is_none() && r.attributes.is_empty(),
            "{text}"
        );
        assert!(r.contradictions.is_empty(), "{text}");
        for flag in [
            "-ffunction-sections",
            "-fdata-sections",
            "-g",
            "-flto",
            "-fshort-enums",
            "-fpic",
        ] {
            assert_eq!(verdict(&r, flag), Verdict::Unknown, "{flag}\n{text}");
        }
        assert_eq!(r.best() == Some(OptLevel::O0), level == OptLevel::O0, "{text}");
        let arch = r.arch.unwrap_or("");
        assert!(
            if c.v6m {
                arch == "ARMv6-M"
            } else {
                arch.contains("Mainline")
            },
            "{text}"
        );
        assert_eq!(verdict(&r, "-fropi"), yes_no(c.ropi), "{text}");
        assert_ne!(
            r.family,
            Some(family(if c.cc == Cc::Gcc { Cc::Clang } else { Cc::Gcc })),
            "{text}"
        );
    }
}

/// Replace one section of `target` with the same section of `donor`.
fn graft(target: &PathBuf, donor: &PathBuf, section: &str, tag: &str) -> PathBuf {
    static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
    let tag = format!("{tag}{}", N.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
    let blob = target.with_extension(format!("{tag}.blob"));
    let out = target.with_extension(format!("{tag}.forged"));
    assert!(run_ok(
        Command::new("arm-none-eabi-objcopy")
            .arg("--dump-section")
            .arg(format!("{section}={}", blob.display()))
            .arg(donor)
            .arg(donor.with_extension(format!("{tag}.copy")))
    ));
    assert!(run_ok(
        Command::new("arm-none-eabi-objcopy")
            .arg("--update-section")
            .arg(format!("{section}={}", blob.display()))
            .arg(target)
            .arg(&out)
    ));
    out
}

/// Metadata that does not belong to the code is called out, not believed.
#[test]
fn forged_metadata_is_contradicted() {
    let has = |r: &FlagReport, what: &str| r.contradictions.iter().any(|c| c.contains(what));
    if have(Cc::Gcc) {
        let m3 = config("gcc-m3");
        // A producer string edited to claim -O0 for optimised code.
        if let Some(o) = build(m3, "-O2", &["-g"]) {
            let mut bytes = std::fs::read(&o).unwrap();
            let honest = detect(&Image::from_elf(&bytes).unwrap());
            assert!(honest.declared.as_deref().is_some_and(|d| d.contains("-O2")));
            assert!(!has(&honest, "declares"), "{}", honest.render(true));
            let mut n = 0;
            for i in 0..bytes.len().saturating_sub(4) {
                if &bytes[i..i + 4] == b" -O2" {
                    bytes[i + 3] = b'0';
                    n += 1;
                }
            }
            assert!(n > 0, "producer string not found");
            let r = detect(&Image::from_elf(&bytes).unwrap());
            assert!(has(&r, "declares -O0"), "{}", r.render(true));
            assert!(r.render(false).contains("CONTRADICTION:"));
            assert_ne!(r.best(), Some(OptLevel::O0));
        }
        // Build attributes of an unoptimised ARMv6-M build on optimised ARMv7-M code.
        if let (Some(o2), Some(o0)) = (build(m3, "-O2", &[]), build(config("gcc-m0plus"), "-O0", &[])) {
            let r = detect(&load(&graft(&o2, &o0, ".ARM.attributes", "attr")));
            assert!(has(&r, "optimisation goal"), "{}", r.render(true));
            assert!(has(&r, "Thumb-1 only"), "{}", r.render(true));
        }
    }
    if have(Cc::Clang) {
        // Attributes of a build without -fropi on position-independent code, and the reverse.
        let (fw, plain) = (config("clang-firmware"), config("clang-m0plus"));
        if let (Some(ropi), Some(abs)) = (build(fw, "-Os", &[]), build(plain, "-Os", &[])) {
            let r = detect(&load(&graft(&ropi, &abs, ".ARM.attributes", "attr")));
            assert!(has(&r, "-fropi is declared off"), "{}", r.render(true));
            assert_eq!(verdict(&r, "-fropi"), Verdict::Yes);
            let r = detect(&load(&graft(&abs, &ropi, ".ARM.attributes", "attr")));
            assert!(has(&r, "-fropi is declared on"), "{}", r.render(true));
            assert_eq!(verdict(&r, "-fropi"), Verdict::No);
        }
        // A GCC identification string on clang's code.
        if let (true, true, Some(clang), Some(gcc)) = (
            have(Cc::Gcc),
            calibrated(Cc::Clang),
            build(config("clang-m3"), "-O2", &[]),
            build(config("gcc-m3"), "-O2", &[]),
        ) {
            let forged = graft(&clang, &gcc, ".comment", "comment");
            let r = detect(&load(&forged));
            assert!(has(&r, "in the style of clang"), "{}", r.render(true));
        }
    }
}

/// The JSON form carries the same facts as the text.
#[test]
fn json_and_text_agree() {
    let c = config("clang-firmware");
    if !have(c.cc) {
        return;
    }
    let Some(o) = build(c, "-Os", &[]) else { return };
    let r = detect(&load(&o));
    let json = r.json();
    assert!(json.starts_with('{') && json.ends_with('}'), "{json}");
    for key in [
        "\"compiler\"",
        "\"architecture\"",
        "\"optimisation\"",
        "\"flags\"",
        "\"command_line\"",
        "\"contradictions\"",
    ] {
        assert!(json.contains(key), "{key} missing in {json}");
    }
    assert!(json.contains("-fropi"));
    let text = r.render(true);
    for prefix in ["compiler:", "target:", "optimisation:", "likely built as:"] {
        assert!(
            text.lines().any(|l| l.starts_with(prefix)),
            "{prefix} missing in\n{text}"
        );
    }
    assert!(text.contains("cannot tell -ffast-math"));
}