cverif 0.1.4

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

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

use cverif::image::Image;
use cverif::verify::{FuncReport, Options, Report, Status, verify};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;

#[derive(Clone, Copy)]
struct Cc {
    name: &'static str,
    bin: &'static str,
    target: &'static [&'static str],
    levels: &'static [&'static str],
}

const GCC: Cc = Cc {
    name: "gcc",
    bin: "arm-none-eabi-gcc",
    target: &[],
    levels: &["-O0", "-O1", "-O2", "-O3", "-Os"],
};

const CLANG: Cc = Cc {
    name: "clang",
    bin: "clang",
    target: &["--target=arm-none-eabi"],
    levels: &["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz"],
};

fn root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR"))
}

fn corpus() -> PathBuf {
    root().join("tests/corpus/ct.c")
}

fn include() -> PathBuf {
    root().join("include")
}

impl Cc {
    /// Build `src` to an object: with debug information (for the source lines of violations)
    /// and with every warning an error (the annotations must cost nothing to a compiler).
    fn try_compile(&self, src: &Path, cpu: &str, level: &str) -> Result<PathBuf, String> {
        self.try_compile_with(src, cpu, level, &[])
    }

    /// The same with macros defined (`-D`).
    fn try_compile_with(&self, src: &Path, cpu: &str, level: &str, defines: &[&str]) -> Result<PathBuf, String> {
        static SERIAL: AtomicU32 = AtomicU32::new(0);
        let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
        std::fs::create_dir_all(&dir).unwrap();
        let stem = src.file_stem().unwrap().to_string_lossy();
        let tag: String = defines.iter().map(|d| format!("-{d}")).collect();
        let obj = dir.join(format!("{stem}{tag}-{}-{cpu}{level}.o", self.name));
        let part = dir.join(format!(
            "{stem}{tag}-{}-{cpu}{level}.{}.{}.part",
            self.name,
            std::process::id(),
            SERIAL.fetch_add(1, Ordering::Relaxed)
        ));
        let (core, hard) = match cpu.strip_suffix("+hard") {
            Some(core) => (core, true),
            None => (cpu, false),
        };
        let float: &[&str] = match (hard, core) {
            (false, _) => &["-mfloat-abi=soft"],
            (true, "cortex-m7") => &["-mfloat-abi=hard", "-mfpu=fpv5-d16"],
            (true, _) => &["-mfloat-abi=hard", "-mfpu=fpv4-sp-d16"],
        };
        let out = cc_cache::output(
            Command::new(self.bin)
                .args(self.target)
                .args(["-mthumb", &format!("-mcpu={core}"), level, "-g", "-ffreestanding"])
                .args(float)
                .args(defines.iter().map(|d| format!("-D{d}")))
                .args(["-Wall", "-Wextra", "-Werror", "-c"])
                .arg("-I")
                .arg(include())
                .arg(src)
                .arg("-o")
                .arg(&part),
        )
        .map_err(|e| e.to_string())?;
        if !out.status.success() {
            let _ = std::fs::remove_file(&part);
            return Err(String::from_utf8_lossy(&out.stderr).into_owned());
        }
        std::fs::rename(&part, &obj).map_err(|e| e.to_string())?;
        Ok(obj)
    }

    fn compile(&self, cpu: &str, level: &str) -> PathBuf {
        self.try_compile(&corpus(), cpu, level)
            .unwrap_or_else(|e| panic!("{} {cpu} {level} failed: {e}", self.bin))
    }

    fn available(&self) -> bool {
        let flags = [self.target, &["-mthumb", "-mcpu=cortex-m3"]].concat();
        toolchain::available(self.bin, &flags, self.name)
    }
}

/// Verify the object built for `cpu`, as `--cpu` names the core (GCC records only the
/// architecture, which does not tell a Cortex-M4 from an M7).
fn check_with(obj: &Path, cpu: &str, undefine: &[&str], opts: Options) -> Report {
    check_source(obj, &corpus(), cpu, undefine, &[], opts)
}

/// The same for the source `src`, with macros defined (`defines`) and undefined.
fn check_source(obj: &Path, src: &Path, cpu: &str, undefine: &[&str], defines: &[&str], opts: Options) -> Report {
    let src = src.to_path_buf();
    let defines: Vec<(String, String)> = defines.iter().map(|d| (d.to_string(), "1".to_string())).collect();
    let mut image = Image::from_elf(&std::fs::read(obj).unwrap()).expect("load ELF");
    let core = cpu.strip_suffix("+hard").unwrap_or(cpu);
    image.profile = image.profile.declared(Some(core), None).expect("a known core");
    let undefines: Vec<String> = undefine.iter().map(|s| s.to_string()).collect();
    std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let mut copts = cverif::c::Options::for_image(&image);
            copts.include_dirs.push(include());
            copts.undefines = undefines;
            copts.defines.extend(defines);
            let prog = cverif::c::parse_files(&[src], &copts).expect("parse C");
            verify(&prog, &image, &opts)
        })
        .unwrap()
        .join()
        .unwrap()
}

fn options() -> Options {
    {
        let mut built = Options::default();
        built.jobs = 2;
        built.work_limit = 200_000;
        built.time_limit = Duration::from_secs(600);
        built
    }
}

fn check(obj: &Path, cpu: &str) -> Report {
    check_with(obj, cpu, &[], options())
}

/// Build the corpus for `cpu` at `level` and verify it.
fn build(cc: Cc, cpu: &str, level: &str) -> Report {
    check(&cc.compile(cpu, level), cpu)
}

fn func<'a>(r: &'a Report, name: &str) -> &'a FuncReport {
    r.funcs
        .iter()
        .find(|f| f.name == name)
        .unwrap_or_else(|| panic!("{name} was not verified"))
}

fn claim(f: &FuncReport) -> &str {
    f.constant_time.as_ref().map_or("none", |c| c.claim)
}

/// Where the compilers turn constant-time C into machine code that is not: (compiler, core,
/// optimisation levels, functions).  Found with GCC 16.2 and Apple clang 21 (see
/// `INTRODUCED_IN_GCC` and `FIXED_IN_CLANG` for other releases); each is a branch
/// on a secret, or (clang, 64-bit comparison) a load from a stack address chosen by a secret.
const COMPILER_LEAKS: &[(&str, &str, &[&str], &[&str])] = &[
    // The conditional operator is a branch at -O0 everywhere (not constant-time C anyway).
    ("gcc", "cortex-m3", &["-O0"], &["cand_ternary"]),
    ("gcc", "cortex-m4", &["-O0"], &["cand_ternary"]),
    ("clang", "cortex-m3", &["-O0"], &["cand_ternary"]),
    ("clang", "cortex-m4", &["-O0"], &["cand_ternary"]),
    ("gcc", "cortex-m7", &["-O0"], &["cand_ternary"]),
    ("clang", "cortex-m7", &["-O0"], &["cand_ternary"]),
    // A mask from a 64-bit comparison selects between stack arguments: GCC branches, clang
    // computes the address of the one to load with IT instructions.
    ("gcc", "cortex-m3", &["-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
    ("gcc", "cortex-m4", &["-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
    ("gcc", "cortex-m7", &["-O1", "-O2", "-O3", "-Os"], &["cand_mask_lt64"]),
    (
        "clang",
        "cortex-m7",
        &["-O1", "-O2", "-O3", "-Os", "-Oz"],
        &["cand_mask_lt64"],
    ),
    (
        "clang",
        "cortex-m3",
        &["-O1", "-O2", "-O3", "-Os", "-Oz"],
        &["cand_mask_lt64"],
    ),
    (
        "clang",
        "cortex-m4",
        &["-O1", "-O2", "-O3", "-Os", "-Oz"],
        &["cand_mask_lt64"],
    ),
    // Absolute value with a sign mask: a conditional return (`it pl; bxpl lr`) or a branch.
    ("clang", "cortex-m3", &["-Os", "-Oz"], &["cand_abs"]),
    ("clang", "cortex-m4", &["-Os", "-Oz"], &["cand_abs"]),
    ("clang", "cortex-m7", &["-Os", "-Oz"], &["cand_abs"]),
    // ARMv6-M has no IT blocks: masks made from comparisons become branches.
    (
        "gcc",
        "cortex-m0",
        &["-O0"],
        &["cand_ternary", "cand_max_s", "cand_mask_lt64"],
    ),
    (
        "gcc",
        "cortex-m0",
        &["-O1", "-O2", "-Os"],
        &[
            "cand_mask_lt",
            "cand_mask_lt64",
            "cand_select_nz",
            "cand_ternary",
            "cand_min_lt",
            "cand_lookup_eq",
            "cand_max_s",
        ],
    ),
    (
        "gcc",
        "cortex-m0",
        &["-O3"],
        &[
            "cand_mask_lt",
            "cand_mask_lt64",
            "cand_select_nz",
            "cand_ternary",
            "cand_min_lt",
            "cand_max_s",
        ],
    ),
    (
        "clang",
        "cortex-m0",
        &["-O0", "-O1", "-O2", "-O3", "-Os", "-Oz"],
        &[
            "cand_mask_lt",
            "cand_mask_lt64",
            "cand_select_nz",
            "cand_ternary",
            "cand_min_lt",
            "cand_eq_mask",
            "cand_lookup_eq",
            "cand_max_s",
        ],
    ),
    // clang recognises the branch-free minimum and maximum, the masked table scan, and the
    // masked select of `ct_select` once inlined, and branches.
    (
        "clang",
        "cortex-m0",
        &["-O1", "-O2", "-O3", "-Os", "-Oz"],
        &["ct_lookup", "ct_min", "ct_max", "ct_calls_ct"],
    ),
    // ... and turns the accumulated boolean into an early exit.
    ("clang", "cortex-m0", &["-O1", "-Os", "-Oz"], &["cand_bool_acc"]),
];

/// Builds in which the equivalence proof of a function runs out of budget, so that the claim is
/// bounded: GCC -O3 versions the swap loop on whether the two arrays overlap.
const EQUIVALENCE_BOUNDED: &[(&str, &[&str], &str)] = &[("gcc", &["-O3"], "ct_cswap8")];

/// Leaks of `COMPILER_LEAKS` that later releases of LLVM's clang no longer make: (function,
/// first major version without it).  clang 22 makes the absolute value a predicated negation
/// (`cmp r0, #0; it mi; negmi r0, r0`), with no branch and no conditional return.
const FIXED_IN_CLANG: &[(&str, u32)] = &[("cand_abs", 22)];

/// Leaks of `COMPILER_LEAKS` that earlier releases of GCC do not make: (function, first major
/// version with it).  Up to GCC 15, ARMv6-M builds the comparison masks without a branch (`cmp;
/// sbcs` for `a < b`, `subs; sbcs` for `c != 0`); GCC 16 sees through the mask to a select and
/// branches on the comparison (`cmp r0, r1; bcs`), at -O1 and above.  (Checked on GCC 13.2,
/// 13.4, 14.4, 15.3, 16.1 and 16.2.)
const INTRODUCED_IN_GCC: &[(&str, u32)] = &[("cand_mask_lt", 16), ("cand_select_nz", 16)];

/// The major version of arm-none-eabi-gcc (`-dumpversion`: `16.2.1`, or `13` for some builds).
fn gcc_major() -> Option<u32> {
    static MAJOR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
    *MAJOR.get_or_init(|| {
        let out = Command::new(GCC.bin).arg("-dumpversion").output().ok()?;
        String::from_utf8_lossy(&out.stdout)
            .trim()
            .split('.')
            .next()?
            .parse()
            .ok()
    })
}

/// The major version of LLVM's clang (`clang version 22.1.8`); None for another clang (Apple's
/// numbers its releases differently) or none.
fn clang_major() -> Option<u32> {
    static MAJOR: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
    *MAJOR.get_or_init(|| {
        let out = Command::new(CLANG.bin).arg("--version").output().ok()?;
        let text = String::from_utf8_lossy(&out.stdout);
        let first = text.lines().next()?;
        let rest = first.strip_prefix("clang version ").or_else(|| {
            // (a distribution's build: "Ubuntu clang version 18.1.3 (...)")
            (!first.starts_with("Apple")).then(|| first.split_once(" clang version ").map(|s| s.1))?
        })?;
        rest.split('.').next()?.trim().parse().ok()
    })
}

/// The entries of a core apply to its hard-float builds too (`cortex-m4+hard`).
fn compiler_leaks(cc: &str, cpu: &str, level: &str) -> Vec<&'static str> {
    let core = cpu.strip_suffix("+hard").unwrap_or(cpu);
    let fixed = |f: &str| {
        (cc == "clang"
            && FIXED_IN_CLANG
                .iter()
                .any(|&(g, v)| g == f && clang_major().is_some_and(|m| m >= v)))
            || (cc == "gcc"
                && INTRODUCED_IN_GCC
                    .iter()
                    .any(|&(g, v)| g == f && gcc_major().is_some_and(|m| m < v)))
    };
    COMPILER_LEAKS
        .iter()
        .filter(|l| l.0 == cc && l.1 == core && l.2.contains(&level))
        .flat_map(|l| l.3.iter().copied())
        .filter(|f| !fixed(f))
        .collect()
}

/// Every function of the corpus where it belongs.
fn expect(cc: &str, cpu: &str, level: &str, r: &Report) -> Vec<String> {
    let leaks = compiler_leaks(cc, cpu, level);
    let mut bad = Vec::new();
    for f in &r.funcs {
        let n = f.name.as_str();
        let is_violation = matches!(f.status, Status::CtViolation(_));
        let ct_proved = f.status == Status::Proved && claim(f) == "proved";
        let bounded = matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded";
        let ok = if leaks.contains(&n) {
            is_violation
        } else if EQUIVALENCE_BOUNDED
            .iter()
            .any(|e| e.0 == cc && e.1.contains(&level) && e.2 == n)
        {
            ct_proved || bounded
        } else if n == "ct_memcmp" {
            // A loop over a public length: proved by induction or explored to a bound.
            (f.status == Status::Proved && claim(f) == "proved")
                || (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded")
        } else if n == "leak_mul64" && cpu.starts_with("cortex-m4") {
            // UMULL takes one cycle on the M4: the product is constant time there.
            ct_proved
        } else if n.starts_with("fp_") {
            // Fixed-latency FPU instructions on the M4 only; soft float calls variable-time
            // library routines, and nothing documents the M7's FPU timing as fixed.
            if cpu == "cortex-m4+hard" {
                ct_proved
            } else {
                is_violation
            }
        } else if n == "leak_delay" {
            // Never a constant-time claim; found by exploration or bounded by the induction.
            is_violation || (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded")
        } else if n.starts_with("leak_") {
            is_violation
        } else if n.starts_with("ct_") || n.starts_with("cand_") {
            ct_proved
        } else if n == "key_byte_helper" || n == "key_test_helper" {
            // Checked for its caller where the call is kept (GCC -O3 inlines it).
            let checked = |c: &str| f.constant_time.as_ref().is_some_and(|ct| ct.checked_for == [c]);
            (f.status == Status::Proved && f.constant_time.is_none())
                || if n == "key_byte_helper" {
                    ct_proved && checked("leak_key_result")
                } else {
                    is_violation && checked("leak_key_callee")
                }
        } else if n == "plain_lookup_helper" {
            // Not marked; checked for the secret its caller gives it.
            is_violation && f.constant_time.as_ref().is_some_and(|c| !c.checked_for.is_empty())
        } else if n == "plain_helper" {
            ct_proved
                && f.constant_time
                    .as_ref()
                    .is_some_and(|c| c.checked_for == ["ct_calls_plain"])
        } else {
            f.status == Status::Proved && f.constant_time.is_none()
        };
        if !ok {
            bad.push(format!(
                "  {cc} {cpu} {level}: {} {n} [{}]: {}",
                f.status.label(),
                claim(f),
                f.status.detail()
            ));
        }
        // A violation names the source line of the instruction (the objects have debug information).
        if is_violation
            && f.constant_time
                .as_ref()
                .is_some_and(|c| c.violation.is_some() && c.source.is_none())
        {
            bad.push(format!("  {cc} {cpu} {level}: {n}: violation without a source line"));
        }
    }
    for want in [
        "ct_memcmp16",
        "ct_lookup",
        "leak_sbox",
        "cand_abs",
        "leak_delay",
        "plain_mix",
        "fp_scale",
        "ct_calls_ct_ni",
    ] {
        if !r.funcs.iter().any(|f| f.name == want) {
            bad.push(format!("  {cc} {cpu} {level}: {want} was not verified"));
        }
    }
    bad
}

fn matrix(cc: Cc, cpu: &str) {
    if !cc.available() {
        return;
    }
    let mut bad = Vec::new();
    for level in cc.levels {
        let r = build(cc, cpu, level);
        let v = r
            .funcs
            .iter()
            .filter(|f| matches!(f.status, Status::CtViolation(_)))
            .count();
        eprintln!(
            "ct.c {} {cpu} {level}: {} functions, {v} not constant time",
            cc.name,
            r.funcs.len()
        );
        bad.extend(expect(cc.name, cpu, level, &r));
    }
    assert!(bad.is_empty(), "unexpected constant-time results:\n{}", bad.join("\n"));
}

#[test]
fn gcc_cortex_m0() {
    matrix(GCC, "cortex-m0");
}

#[test]
fn gcc_cortex_m3() {
    matrix(GCC, "cortex-m3");
}

#[test]
fn gcc_cortex_m4() {
    matrix(GCC, "cortex-m4");
}

#[test]
fn clang_cortex_m0() {
    matrix(CLANG, "cortex-m0");
}

#[test]
fn clang_cortex_m3() {
    matrix(CLANG, "cortex-m3");
}

#[test]
fn clang_cortex_m4() {
    matrix(CLANG, "cortex-m4");
}

#[test]
fn gcc_cortex_m4_hard_float() {
    matrix(GCC, "cortex-m4+hard");
}

#[test]
fn clang_cortex_m4_hard_float() {
    matrix(CLANG, "cortex-m4+hard");
}

#[test]
fn gcc_cortex_m7_hard_float() {
    matrix(GCC, "cortex-m7+hard");
}

#[test]
fn clang_cortex_m7_hard_float() {
    matrix(CLANG, "cortex-m7+hard");
}

/// Calls compared as calls: a constant-time caller of a constant-time callee verified on its
/// own rests on the callee; secrets given to a callee marked constant time that is not, or to
/// one that is not marked, make the caller a violation.
#[test]
fn modular_calls() {
    for cc in [GCC, CLANG] {
        if !cc.available() {
            continue;
        }
        for level in ["-O1", "-O2", "-Os"] {
            let r = build(cc, "cortex-m3", level);
            let ok = func(&r, "ct_calls_ct_ni");
            let ct = ok.constant_time.as_ref().expect("marked");
            assert_eq!(ct.claim, "proved", "{} {level}: {}", cc.name, ok.status.detail());
            assert!(
                ct.rests_on.iter().any(|c| c.0 == "ct_mix_ni" && c.1 == "proved"),
                "{} {level}: {:?}",
                cc.name,
                ct.rests_on
            );
            let bad = func(&r, "leak_calls_leaky");
            assert!(
                matches!(&bad.status, Status::CtViolation(d) if d.contains("leak_sbox_ni")),
                "{} {level}: {}",
                cc.name,
                bad.status.detail()
            );
            let plain = func(&r, "leak_calls_plain");
            assert!(
                matches!(&plain.status, Status::CtViolation(d) if d.starts_with("gives secrets to plain_lookup_helper, ")),
                "{} {level}: {}",
                cc.name,
                plain.status.detail()
            );
            // A function that is not marked, checked for what its caller gives it.
            let ok = func(&r, "ct_calls_plain");
            let ct = ok.constant_time.as_ref().expect("marked");
            assert!(
                ok.status == Status::Proved
                    && ct.claim == "proved"
                    && ct.rests_on.iter().any(|c| c.0 == "plain_helper" && c.1 == "proved"),
                "{} {level}: {} {:?}",
                cc.name,
                ok.status.detail(),
                ct.rests_on
            );
            // Not with --no-ct-callees: a violation, as before such callees were checked.
            let mut strict = options();
            strict.ct.no_callees = true;
            let obj = cc.compile("cortex-m3", level);
            let r = check_with(&obj, "cortex-m3", &[], strict);
            let plain = func(&r, "ct_calls_plain");
            assert!(
                matches!(&plain.status, Status::CtViolation(d) if d.contains("argument 1 of the call to plain_helper")),
                "{} {level} --no-ct-callees: {}",
                cc.name,
                plain.status.detail()
            );
            assert!(func(&r, "plain_helper").constant_time.is_none());
        }
    }
}

/// The line of the corpus that contains `text`.
fn line_of(text: &str) -> u32 {
    let src = std::fs::read_to_string(corpus()).unwrap();
    src.lines().position(|l| l.contains(text)).expect("text in the corpus") as u32 + 1
}

/// What the reports say: the instruction, the timing on the core, the witness, the line.
#[test]
fn reasons_and_witnesses() {
    if GCC.available() {
        let r = build(GCC, "cortex-m3", "-O2");
        let d = |n: &str| func(&r, n).status.detail().to_string();
        assert!(
            d("leak_mod").contains("udiv") && d("leak_mod").contains("Cortex-M3"),
            "{}",
            d("leak_mod")
        );
        assert!(d("leak_mul64").contains("umull") && d("leak_mul64").contains("finish early"));
        assert!(
            d("leak_memcmp").contains("a[0]") && d("leak_memcmp").contains("b[0]"),
            "{}",
            d("leak_memcmp")
        );
        assert!(
            d("leak_sbox").contains("address of a 1-byte load"),
            "{}",
            d("leak_sbox")
        );
        assert!(d("leak_call").contains("argument 1 of the call to ext_consume"));
        assert!(
            d("leak_calls_plain").contains("plain_lookup_helper"),
            "{}",
            d("leak_calls_plain")
        );
        assert!(d("leak_key_index").contains("device_key[3]"), "{}", d("leak_key_index"));
        let sbox = func(&r, "leak_sbox").constant_time.clone().unwrap();
        let v = sbox.violation.expect("a violation");
        // (GCC places the load on the line of the closing brace.)
        let line = sbox.source.map(|s| s.1).unwrap_or(0);
        let want = line_of("return sbox[x & 0xff];");
        assert!(line == want || line == want + 1, "line {line}, expected {want}");
        assert!(v.witness.contains("with secret x = "), "{}", v.witness);
        // A constant-time function given secrets for its secret parameters.
        assert_eq!(claim(func(&r, "ct_calls_ct")), "proved");
        // An object marked secret, read but not used in an address.
        assert_eq!(claim(func(&r, "ct_key_diff")), "proved");
        let m0 = build(GCC, "cortex-m0", "-Os");
        let d = func(&m0, "leak_mod").status.detail().to_string();
        assert!(d.contains("__aeabi_uidivmod"), "{d}");
    }
    if CLANG.available() {
        let r = build(CLANG, "cortex-m3", "-O2");
        let d = func(&r, "leak_condload").status.detail().to_string();
        assert!(d.contains("in an IT block") && d.contains("ldr"), "{d}");
        assert_eq!(claim(func(&r, "cand_mask_lt")), "proved");
    }
}

/// Loops: a public trip count proved by induction keeps the constant-time claim for every
/// iteration; a secret that reaches an address only in a later iteration never gets one.
#[test]
fn loops_by_induction() {
    if !GCC.available() {
        return;
    }
    let r = build(GCC, "cortex-m3", "-O2");
    let f = func(&r, "ct_memcmp");
    assert_eq!(f.status, Status::Proved);
    let note = &f.constant_time.as_ref().unwrap().note;
    assert!(note.contains("every loop iteration"), "{note}");
    let r = build(GCC, "cortex-m0", "-Os");
    let f = func(&r, "leak_delay");
    assert!(
        matches!(&f.status, Status::Bounded(d) if d.contains("constant time only for the loop iterations explored")),
        "{}: {}",
        f.status.label(),
        f.status.detail()
    );
    assert_eq!(claim(f), "bounded");
}

/// The checks of constant time add obligations; they change nothing about equivalence.
#[test]
fn equivalence_unchanged() {
    for (cc, cpu) in [(GCC, "cortex-m3"), (CLANG, "cortex-m0")] {
        if !cc.available() {
            continue;
        }
        let obj = cc.compile(cpu, "-Os");
        let with = check(&obj, cpu);
        let without = check_with(&obj, cpu, &["__CVERIF__"], options());
        assert!(without.funcs.iter().all(|f| f.constant_time.is_none()));
        for f in &without.funcs {
            let g = func(&with, &f.name);
            // The same verdict, except that a violation replaces it, and that a function whose
            // selects on secrets are executed as such (not as two paths) may be proved where
            // the exploration of both paths ran out of budget.  Never a mismatch of its own.
            let same = match (&f.status, &g.status) {
                (Status::Mismatch(_), s) | (s, Status::Mismatch(_)) => {
                    matches!(s, Status::Mismatch(_))
                }
                // (or bounded: the equivalence proved by induction, constant time not).
                (Status::Proved, s) => {
                    matches!(s, Status::Proved | Status::CtViolation(_))
                        || matches!(s, Status::Bounded(_)) && claim(g) == "bounded"
                }
                (_, Status::CtViolation(_)) => true,
                (Status::Bounded(_), Status::Proved) => g.constant_time.is_some(),
                (a, b) => a.label() == b.label(),
            };
            if f.constant_time.is_none() && g.constant_time.is_none() {
                assert_eq!(f.status, g.status, "{}: an unmarked function", f.name);
            }
            assert!(
                same,
                "{} {cpu}: {} is {} without the marks, {} with",
                cc.name,
                f.name,
                f.status.label(),
                g.status.label()
            );
        }
    }
}

/// The annotations of `include/cverif.h` reach the program: `CT` on a declaration or a
/// definition, `SECRET` on parameters (any declaration) and on objects.
#[test]
fn annotations_parse() {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
    std::fs::create_dir_all(&dir).unwrap();
    let src = dir.join("annotations.c");
    std::fs::write(
        &src,
        "#include \"cverif.h\"\n\
         SECRET unsigned char key[16];\n\
         unsigned char nonce[16];\n\
         CT int f(const unsigned char *SECRET a, int n);\n\
         int f(const unsigned char *a, SECRET int n) { return a[0] + n; }\n\
         int g(int x) CT;\n\
         int g(int x) { return x; }\n\
         int h(int x) { return x; }\n",
    )
    .unwrap();
    let copts = {
        let mut built = cverif::c::Options::default();
        built.include_dirs = vec![include()];
        built
    };
    let p = cverif::c::parse_files(std::slice::from_ref(&src), &copts).expect("parse");
    let ct: Vec<&str> = p.constant_time.iter().map(|s| &**s).collect();
    assert!(ct.contains(&"f") && ct.contains(&"g") && !ct.contains(&"h"), "{ct:?}");
    let f: Vec<usize> = p.secret_params.get("f").unwrap().iter().copied().collect();
    assert_eq!(f, vec![0, 1]);
    assert!(p.secret_globals.iter().any(|g| &**g == "key"));
    assert!(!p.secret_globals.iter().any(|g| &**g == "nonce"));
    // Without __CVERIF__ the macros are empty: nothing is marked.
    let copts = {
        let mut built = cverif::c::Options::default();
        built.include_dirs = vec![include()];
        built.undefines = vec!["__CVERIF__".into()];
        built
    };
    let p = cverif::c::parse_files(&[src], &copts).expect("parse");
    assert!(p.constant_time.is_empty() && p.secret_params.is_empty() && p.secret_globals.is_empty());
}

fn cli(obj: &Path, args: &[&str]) -> (i32, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_cverif"))
        .args(args)
        .arg("-I")
        .arg(include())
        .arg(obj)
        .arg(corpus())
        .output()
        .unwrap();
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&out.stdout).into_owned(),
    )
}

fn line_for<'a>(out: &'a str, name: &str) -> &'a str {
    out.lines()
        .find(|l| l.split_whitespace().nth(1) == Some(name))
        .unwrap_or_else(|| panic!("no line for {name} in\n{out}"))
}

/// The command-line forms, for code whose source cannot carry the annotations.
#[test]
fn command_line() {
    if !GCC.available() {
        return;
    }
    let obj = GCC.compile("cortex-m3", "-O2");
    let json = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct").join("cli.json");
    let (code, out) = cli(
        &obj,
        &[
            "--constant-time",
            "plain_lookup:k",
            "--secret",
            "session_nonce",
            "--constant-time",
            "plain_mix:*tbl",
            "--only",
            "plain_lookup",
            "--only",
            "plain_mix",
            "--json",
            json.to_str().unwrap(),
        ],
    );
    assert_eq!(code, 1, "{out}");
    assert!(line_for(&out, "plain_lookup").starts_with("CT-VIOLATION"), "{out}");
    assert!(
        line_for(&out, "plain_lookup").contains("address of a 4-byte load"),
        "{out}"
    );
    assert!(
        line_for(&out, "plain_mix").starts_with("PROVED") && line_for(&out, "plain_mix").contains("[constant time]")
    );
    assert!(out.contains("verdict:         CT-VIOLATION"), "{out}");
    let j = std::fs::read_to_string(&json).unwrap();
    assert!(j.contains("\"verdict\": \"ct-violation\""), "{j}");
    assert!(j.contains("\"status\":\"ct-violation\""));
    assert!(j.contains("\"constant_time\":{\"claim\":\"violation\""));
    assert!(j.contains("\"witness\":"));
    assert!(j.contains("\"constant_time\":{\"claim\":\"proved\",\"note\":\"constant time\""));
    // Positions work as well as names; the timing model can be chosen.
    let (code, out) = cli(&obj, &["--constant-time", "plain_mix:0", "--only", "plain_mix"]);
    assert_eq!(code, 0, "{out}");
    assert!(line_for(&out, "plain_mix").contains("[constant time]"), "{out}");
    let (code, out) = cli(&obj, &["--constant-time", "plain_lookup:1", "--only", "plain_lookup"]);
    assert_eq!(code, 1, "{out}");
    assert!(line_for(&out, "plain_lookup").contains("with secret tbl = "), "{out}");
    let (code, out) = cli(&obj, &["--cpu", "cortex-m4", "--only", "leak_mul64"]);
    assert_eq!(code, 0, "{out}");
    assert!(line_for(&out, "leak_mul64").contains("[constant time]"), "{out}");
    // Names that do not exist are errors.
    let (code, _) = cli(&obj, &["--constant-time", "no_such_function"]);
    assert_eq!(code, 2);
    let (code, _) = cli(&obj, &["--constant-time", "plain_lookup:zz"]);
    assert_eq!(code, 2);
    let (code, _) = cli(&obj, &["--secret", "no_such_object"]);
    assert_eq!(code, 2);
}

fn run_cverif(args: &[&std::ffi::OsStr]) -> (i32, String) {
    let out = Command::new(env!("CARGO_BIN_EXE_cverif")).args(args).output().unwrap();
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    (out.status.code().unwrap_or(-1), text)
}

fn tool(bin: &str, args: &[&std::ffi::OsStr]) -> Vec<u8> {
    let out = Command::new(bin).args(args).output().expect(bin);
    assert!(out.status.success(), "{bin}: {}", String::from_utf8_lossy(&out.stderr));
    out.stdout
}

/// `nm` output with marks added after the names in `marks`.
fn mark_table(nm: &str, marks: &[(&str, &str)]) -> String {
    let mut out = String::new();
    for line in nm.lines() {
        out.push_str(line);
        let name = line.split_whitespace().last().unwrap_or("");
        if let Some((_, m)) = marks.iter().find(|(n, _)| *n == name) {
            out.push(' ');
            out.push_str(m);
        }
        out.push('\n');
    }
    out
}

/// What `tests/corpus/ct_tags.c` must give with the marks of its symbol table.
fn expect_tagged(out: &str, code: i32, what: &str) {
    assert_eq!(code, 1, "{what}:\n{out}");
    for f in ["tag_compare", "tag_key_mix"] {
        let l = line_for(out, f);
        assert!(
            l.starts_with("PROVED") && l.contains("[constant time"),
            "{what}: {f}\n{out}"
        );
    }
    for f in ["tag_compare_leaky", "tag_key_lookup"] {
        assert!(line_for(out, f).starts_with("CT-VIOLATION"), "{what}: {f}\n{out}");
    }
}

/// Constant-time marks shipped in a symbol table (`ct=...`, `secret` after a name) for a
/// source without any annotation: for the linked ELF file, its relocatable object, and the raw
/// binary described by the table; marks add up with the command line's; a mark on a name or at
/// an address the image does not have is an error; `--emit-symbols` writes the marks back.
#[test]
fn symbol_table_marks() {
    if !GCC.available() {
        return;
    }
    let src = root().join("tests/corpus/ct_tags.c");
    let obj = GCC.try_compile(&src, "cortex-m3", "-O2").expect("compile");
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("ct");
    let p = |name: &str| dir.join(format!("ct_tags-{}-{name}", std::process::id()));
    let (elf, bin, table) = (p("linked.elf"), p("linked.bin"), p("table.sym"));
    let os = |s: &Path| s.as_os_str().to_owned();
    tool(
        "arm-none-eabi-gcc",
        &[
            "-mthumb".as_ref(),
            "-mcpu=cortex-m3".as_ref(),
            "-nostdlib".as_ref(),
            "-Wl,-Ttext=0x08000000".as_ref(),
            "-Wl,-Tbss=0x20000000".as_ref(),
            "-Wl,-e,tag_compare".as_ref(),
            "-o".as_ref(),
            &os(&elf),
            &os(&obj),
        ],
    );
    tool(
        "arm-none-eabi-objcopy",
        &[
            "-O".as_ref(),
            "binary".as_ref(),
            "-j".as_ref(),
            ".text".as_ref(),
            &os(&elf),
            &os(&bin),
        ],
    );
    let marks = [
        ("tag_compare", "ct=*a,*b"),
        ("tag_compare_leaky", "ct=*0,*1"),
        ("tag_key_mix", "ct"),
        ("tag_key_lookup", "ct"),
        ("round_keys", "secret"),
    ];
    let nm = String::from_utf8(tool("arm-none-eabi-nm", &["-S".as_ref(), &os(&elf)])).unwrap();
    std::fs::write(&table, mark_table(&nm, &marks)).unwrap();
    let common = |extra: &[&std::ffi::OsStr]| -> Vec<std::ffi::OsString> {
        let mut v: Vec<std::ffi::OsString> = vec!["--cpu".into(), "cortex-m3".into()];
        v.extend(extra.iter().map(|s| s.to_os_string()));
        v
    };
    let go = |extra: &[&std::ffi::OsStr], binary: &Path, table: &Path| {
        let mut v = common(extra);
        v.extend(["--symbols".into(), os(table), os(binary), os(&src)]);
        let refs: Vec<&std::ffi::OsStr> = v.iter().map(|s| s.as_os_str()).collect();
        run_cverif(&refs)
    };
    // The linked ELF file with the table.
    let (code, out) = go(&[], &elf, &table);
    expect_tagged(&out, code, "ELF");
    // Without the marks nothing is claimed.
    let plain = p("plain.sym");
    std::fs::write(&plain, &nm).unwrap();
    let (code, out) = go(&[], &elf, &plain);
    assert_eq!(code, 0, "{out}");
    assert!(!out.contains("constant time"), "{out}");
    // The raw binary described by the table.
    let (code, out) = go(&["--base".as_ref(), "08000000".as_ref()], &bin, &table);
    expect_tagged(&out, code, "raw binary");
    // The relocatable object with the object's own table (its addresses are not the image's).
    let otable = p("obj.sym");
    let onm = String::from_utf8(tool("arm-none-eabi-nm", &["-S".as_ref(), &os(&obj)])).unwrap();
    std::fs::write(&otable, mark_table(&onm, &marks)).unwrap();
    let (code, out) = go(&[], &obj, &otable);
    expect_tagged(&out, code, "object");
    // Marks add up with the command line's (a public length made secret leaks through the
    // loop bound), and repeating one is harmless.
    let (code, out) = go(
        &[
            "--constant-time".as_ref(),
            "tag_compare:n".as_ref(),
            "--constant-time".as_ref(),
            "tag_key_mix".as_ref(),
            "--secret".as_ref(),
            "round_keys".as_ref(),
        ],
        &elf,
        &table,
    );
    assert_eq!(code, 1, "{out}");
    assert!(line_for(&out, "tag_compare").starts_with("CT-VIOLATION"), "{out}");
    assert!(line_for(&out, "tag_key_mix").contains("[constant time"), "{out}");
    // Marks that the image or the source does not bear out are errors.
    let nm_line = |name: &str| {
        nm.lines()
            .find(|l| l.ends_with(&format!(" {name}")))
            .unwrap()
            .to_string()
    };
    let compare = nm_line("tag_compare");
    let moved = format!(
        "{:08x}{}",
        u32::from_str_radix(&compare[..8], 16).unwrap() + 0x40,
        &compare[8..]
    );
    for (bad, why) in [
        (
            "08000001 T no_such_function ct\n".to_string(),
            "no function no_such_function",
        ),
        (format!("{moved} ct\n"), "the line says"),
        (
            format!("{compare} ct=*nope\n"),
            "no parameter *nope (a mark of the symbol table)",
        ),
        (format!("{} ct\n", nm_line("round_keys")), "marks a function"),
        (format!("{compare} secret\n"), "marks a data object"),
    ] {
        let t = p("bad.sym");
        std::fs::write(&t, bad.as_bytes()).unwrap();
        let (code, out) = go(&[], &elf, &t);
        assert_eq!(code, 2, "{bad}{out}");
        assert!(out.contains(why), "{bad}: {out}");
    }
    // --emit-symbols writes the marks back, and the table it writes gives the same results.
    let emitted = p("emitted.sym");
    let (code, out) = run_cverif(&[
        "--discover".as_ref(),
        "--cpu".as_ref(),
        "cortex-m3".as_ref(),
        "--base".as_ref(),
        "08000000".as_ref(),
        "--symbols".as_ref(),
        &os(&table),
        "--emit-symbols".as_ref(),
        &os(&emitted),
        &os(&bin),
    ]);
    assert_eq!(code, 0, "{out}");
    let text = std::fs::read_to_string(&emitted).unwrap();
    for (name, mark) in marks {
        assert!(
            text.lines()
                .any(|l| l.split("  #").next().unwrap().ends_with(&format!(" {name} {mark}"))),
            "{name} {mark} not written back:\n{text}"
        );
    }
    let (code, out) = go(&["--base".as_ref(), "08000000".as_ref()], &bin, &emitted);
    expect_tagged(&out, code, "emitted table");
}

// ----- functions given secrets that are not marked (`tests/corpus/ct_callees.c`) ----------------

fn callees_corpus() -> PathBuf {
    root().join("tests/corpus/ct_callees.c")
}

/// (caller, what its violation must say): the reason is the callee's, or the call's.
const CALLEE_LEAKS: &[(&str, &str)] = &[
    ("leak_calls_lookup", "gives secrets to h_lookup, "),
    ("leak_first_index", "gives secrets to h_first_index, "),
    // Through a chain: h_l1 is a violation because h_l2 is.
    ("leak_chain", "gives secrets to h_l1, "),
    ("leak_rec", "gives secrets to h_rec_leak, "),
    // A function whose code is not here.
    ("leak_ext", "argument 1 of the call to ext_mix depends on secrets"),
    // h_store leaves the secret in g_out: memory is secret after it.
    (
        "leak_store_then_ext",
        "the call to ext_log may read secrets from memory",
    ),
    (
        "leak_store_then_index",
        "the address of a 1-byte load depends on secrets",
    ),
    ("leak_put_then_index", "the address of a 1-byte load depends on secrets"),
    // The caller stores the secret where the callee reads it.
    ("leak_via_global", "gives secrets to h_read_index, "),
    ("leak_store_ext", "the call to ext_log may read secrets from memory"),
    ("leak_local_index", "gives secrets to h_first_index, "),
];

/// Helpers that are violations for what their callers give them.
const LEAKY_HELPERS: &[&str] = &[
    "h_lookup",
    "h_first_index",
    "h_l1",
    "h_l2",
    "h_rec_leak",
    "h_read_index",
];

fn callees(cc: Cc) {
    if !cc.available() {
        return;
    }
    let src = callees_corpus();
    let mut bad = Vec::new();
    let mut note = |what: String| bad.push(what);
    for level in ["-O0", "-O1", "-O2", "-Os"] {
        let tag = format!("{} {level}", cc.name);
        let obj = cc.try_compile_with(&src, "cortex-m3", level, &[]).unwrap();
        let r = check_source(&obj, &src, "cortex-m3", &[], &[], options());
        for f in &r.funcs {
            let n = f.name.as_str();
            let ct = f.constant_time.as_ref();
            let line = format!("{tag}: {} {n} [{}]: {}", f.status.label(), claim(f), f.status.detail());
            if let Some(&(_, why)) = CALLEE_LEAKS.iter().find(|l| l.0 == n) {
                if !matches!(&f.status, Status::CtViolation(d) if d.starts_with(why)) {
                    note(format!("  expected a violation ({why}): {line}"));
                }
            } else if n == "ct_rec" || n == "h_rec" {
                // The recursion (or the loop clang makes of it) may be explored to a bound only.
                let ok = (f.status == Status::Proved && claim(f) == "proved")
                    || (matches!(f.status, Status::Bounded(_)) && claim(f) == "bounded");
                if !ok {
                    note(format!("  expected constant time (or bounded): {line}"));
                }
            } else if n.starts_with("ct_") {
                if !(f.status == Status::Proved && claim(f) == "proved") {
                    note(format!("  expected proved constant time: {line}"));
                }
            } else if n.starts_with("h_") {
                // Every helper is given secrets by some caller, and checked for it.
                if ct.is_none_or(|c| c.checked_for.is_empty()) {
                    note(format!("  expected a helper checked for its callers: {line}"));
                } else if LEAKY_HELPERS.contains(&n) != matches!(f.status, Status::CtViolation(_)) {
                    note(format!("  helper: {line}"));
                }
            }
        }
        for want in ["h_mix", "h_store", "h_c2", "ct_then_ext", "leak_store_then_ext"] {
            if !r.funcs.iter().any(|f| f.name == want) {
                note(format!("  {tag}: {want} was not verified"));
            }
        }
        let checked_for = |n: &str| {
            (r.funcs.iter().find(|f| f.name == n))
                .and_then(|f| f.constant_time.as_ref())
                .map(|c| c.checked_for.clone())
                .unwrap_or_default()
        };
        if checked_for("h_mix") != ["ct_calls_mix", "ct_then_ext"] || checked_for("h_c2") != ["h_c1"] {
            note(format!(
                "  {tag}: h_mix checked for {:?}, h_c2 for {:?}",
                checked_for("h_mix"),
                checked_for("h_c2")
            ));
        }

        // The mutant: a second caller gives h_pat a secret index.  h_pat is checked for both
        // callers together, and is not constant time for that: both callers are violations.
        let obj = cc
            .try_compile_with(&src, "cortex-m3", level, &["CALLEES_MUTANT"])
            .unwrap();
        let r = check_source(&obj, &src, "cortex-m3", &[], &["CALLEES_MUTANT"], options());
        for n in ["h_pat", "leak_pat_i", "ct_pat_a"] {
            let f = func(&r, n);
            if !matches!(f.status, Status::CtViolation(_)) {
                note(format!(
                    "  {tag} mutant: expected a violation: {} {n}: {}",
                    f.status.label(),
                    f.status.detail()
                ));
            }
        }

        // --no-ct-callees: as before such callees were checked.
        let mut strict = options();
        strict.ct.no_callees = true;
        let obj = cc.try_compile_with(&src, "cortex-m3", level, &[]).unwrap();
        let r = check_source(&obj, &src, "cortex-m3", &[], &[], strict);
        let f = func(&r, "ct_calls_mix");
        if !matches!(&f.status, Status::CtViolation(d) if d.contains("call to h_mix")) {
            note(format!(
                "  {tag} --no-ct-callees: {}: {}",
                f.status.label(),
                f.status.detail()
            ));
        }
        if r.funcs
            .iter()
            .any(|f| f.name.starts_with("h_") && f.constant_time.is_some())
        {
            note(format!("  {tag} --no-ct-callees: a helper was checked"));
        }
    }
    assert!(bad.is_empty(), "unexpected results:\n{}", bad.join("\n"));
}

#[test]
fn callees_gcc() {
    callees(GCC);
}

#[test]
fn callees_clang() {
    callees(CLANG);
}