cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Inline assembly end to end: the corpus files `asm_inline.c` (every Cortex-M) and `asm_v7m.c`
//! (Cortex-M3/M4) compiled with GCC at every optimisation level, and with clang when it is
//! installed, must be proved function by function; the naked handlers by identity with their
//! asm text; the computational asm must be reported by the lint.  Each `-DMUTANT=n` build
//! (a missing `cpsie`, a store moved out of a critical section, a wrong barrier, a changed
//! naked handler, ...) must be rejected in the function it changes and nowhere else.
//!
//! The tests skip themselves when the compiler they need is not installed.

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

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

const LEVELS: &[&str] = &["-O0", "-O1", "-O2", "-O3", "-Os", "-Og"];
const GCC: &str = "arm-none-eabi-gcc";
const CLANG: &str = "clang";

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

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

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

/// Compile with GCC (`cpu` is a -mcpu value) or clang (`cpu` is a target triple prefix).
fn compile(cc: &str, src: &Path, cpu: &str, level: &str, extra: &[&str]) -> PathBuf {
    let stem = src.file_stem().unwrap().to_string_lossy();
    let tag: String = extra
        .iter()
        .flat_map(|e| e.chars())
        .filter(|c| c.is_ascii_alphanumeric())
        .collect();
    let obj = tmp(&format!("{stem}-{cc}-{cpu}{level}{tag}.o"));
    let partial = obj.with_extension(format!("{}.part", std::process::id()));
    let mut cmd = Command::new(cc);
    if cc == GCC {
        cmd.args(["-mthumb", &format!("-mcpu={cpu}")]);
    } else {
        cmd.args([&format!("--target={cpu}-none-eabi"), "-mthumb"]);
    }
    let out = cmd
        .args(["-ffreestanding", "-c", level])
        .args(extra)
        .arg(src)
        .arg("-o")
        .arg(&partial);
    let out = cc_cache::output(out).expect("run the compiler");
    assert!(
        out.status.success(),
        "{cc} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    std::fs::rename(&partial, &obj).unwrap();
    obj
}

fn check(obj: &Path, src: &Path) -> Report {
    let image = Image::from_elf(&std::fs::read(obj).unwrap()).expect("load ELF");
    let src = src.to_path_buf();
    std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let copts = cverif::c::Options::default().with_target(&image);
            let prog = cverif::c::parse_files(&[src], &copts).expect("parse C");
            let opts = {
                let mut built = Options::default();
                built.work_limit = 30_000;
                built.time_limit = Duration::from_secs(900);
                built.jobs = 2;
                built
            };
            verify(&prog, &image, &opts)
        })
        .unwrap()
        .join()
        .unwrap()
}

fn describe(r: &Report) -> String {
    let mut s = String::new();
    for f in &r.funcs {
        if f.status != Status::Proved {
            s.push_str(&format!("  {} {}: {}\n", f.status.label(), f.name, f.status.detail()));
        }
    }
    s
}

const NAKED: &[&str] = &["HardFault_Handler", "PendSV_Handler", "start_first_task"];

/// Every function proved, the naked ones by identity; the lint names exactly `lints`.
fn expect_proved(r: &Report, what: &str, lints: &[&str]) {
    assert!(!r.funcs.is_empty(), "{what}: nothing verified");
    for f in &r.funcs {
        assert_eq!(f.status, Status::Proved, "{what}: {}\n{}", f.name, describe(r));
        if NAKED.contains(&f.name.as_str()) {
            // Assembly without operands is compared instruction by instruction; with
            // operands, by identity with the assembled text.
            assert!(
                f.assembly || f.note.as_deref() == Some("by identity with the asm text"),
                "{what}: {}",
                f.name
            );
        } else {
            assert_eq!(f.note, None, "{what}: {}", f.name);
        }
    }
    assert!(!r.has_mismatch(), "{what}");
    let mut got: Vec<&str> = r.asm_lints.iter().map(|l| l.func.as_str()).collect();
    got.sort_unstable();
    got.dedup();
    let mut want = lints.to_vec();
    want.sort_unstable();
    assert_eq!(got, want, "{what}: lints {:?}", r.asm_lints);
    // The lint does not change the score.
    assert!(r.score() > 50.0, "{what}: score {}", r.score());
}

const ASM_LINTS: &[&str] = &["add_carry", "load_word", "shift_mix", "__REV16"];
const V7M_LINTS: &[&str] = &["field", "__RBIT", "clamp_q7", "clamp_u10"];

#[test]
fn corpus_is_proved_with_gcc() {
    if !have(GCC) {
        eprintln!("skipping: {GCC} not installed");
        return;
    }
    for cpu in ["cortex-m0", "cortex-m3", "cortex-m4"] {
        for level in LEVELS {
            let src = corpus("asm_inline.c");
            let r = check(&compile(GCC, &src, cpu, level, &[]), &src);
            expect_proved(&r, &format!("asm_inline.c {cpu} {level}"), ASM_LINTS);
            if cpu != "cortex-m0" {
                let src = corpus("asm_v7m.c");
                let r = check(&compile(GCC, &src, cpu, level, &[]), &src);
                expect_proved(&r, &format!("asm_v7m.c {cpu} {level}"), V7M_LINTS);
            }
        }
    }
}

#[test]
fn corpus_is_proved_with_clang() {
    if !have(CLANG) {
        eprintln!("skipping: {CLANG} not installed");
        return;
    }
    for target in ["armv6m", "armv7m", "armv7em"] {
        for level in ["-O0", "-O1", "-O2", "-Os", "-Oz"] {
            let src = corpus("asm_inline.c");
            let r = check(&compile(CLANG, &src, target, level, &[]), &src);
            expect_proved(&r, &format!("asm_inline.c clang {target} {level}"), ASM_LINTS);
            if target != "armv6m" {
                let src = corpus("asm_v7m.c");
                let r = check(&compile(CLANG, &src, target, level, &[]), &src);
                expect_proved(&r, &format!("asm_v7m.c clang {target} {level}"), V7M_LINTS);
            }
        }
    }
}

/// Each mutant differs from the source in one function, which must be reported as a mismatch;
/// every other function must still be proved.
fn expect_mutants(file: &str, cpus: &[&str], mutants: &[(u32, &str)]) {
    let src = corpus(file);
    for cpu in cpus {
        for level in ["-O0", "-O2", "-Os"] {
            for &(n, func) in mutants {
                let obj = compile(GCC, &src, cpu, level, &[&format!("-DMUTANT={n}")]);
                let r = check(&obj, &src);
                let what = format!("{file} mutant {n} ({func}) {cpu} {level}");
                assert!(r.has_mismatch(), "{what} was not detected\n{}", describe(&r));
                assert_eq!(r.score(), 0.0, "{what}");
                for f in &r.funcs {
                    if f.name == func {
                        assert!(matches!(f.status, Status::Mismatch(_)), "{what}: {:?}", f.status);
                    } else {
                        assert_eq!(
                            f.status,
                            Status::Proved,
                            "{what}: {} affected\n{}",
                            f.name,
                            describe(&r)
                        );
                    }
                }
            }
        }
    }
}

#[test]
fn mutants_are_rejected() {
    if !have(GCC) {
        return;
    }
    expect_mutants(
        "asm_inline.c",
        &["cortex-m0", "cortex-m3"],
        &[
            (1, "crit_increment"),    // missing cpsie
            (2, "crit_increment"),    // store moved out of the critical section
            (3, "crit_add"),          // PRIMASK not restored
            (4, "set_vector_table"),  // dmb instead of dsb
            (5, "pend_switch"),       // barriers swapped
            (6, "svc_add"),           // other supervisor call
            (7, "swap16"),            // rev instead of rev16
            (8, "HardFault_Handler"), // naked handler reads the wrong stack
            (9, "publish"),           // compiler barrier instead of a fence
        ],
    );
    expect_mutants(
        "asm_v7m.c",
        &["cortex-m3"],
        &[
            (1, "raise_basepri"),    // basepri instead of basepri_max
            (2, "kernel_tick"),      // BASEPRI not restored
            (3, "clamp_u10"),        // other saturation
            (4, "PendSV_Handler"),   // r11 not saved
            (5, "start_first_task"), // other svc number
        ],
    );
}

/// What cannot be given a meaning is UNSUPPORTED with a reason, and only there.
#[test]
fn unmodellable_asm_is_unsupported() {
    if !have(GCC) {
        return;
    }
    let src = corpus("asm_unsupported.c");
    let r = check(&compile(GCC, &src, "cortex-m3", "-O2", &[]), &src);
    let expect: &[(&str, Option<&str>)] = &[
        ("read_sp", Some("uses sp, lr or pc")),
        ("set_lr", Some("uses sp, lr or pc")),
        ("set_psp", Some("switching stacks is not modelled")),
        ("external_branch", Some("unknown symbol `some_function`")),
        ("exclusive", Some("exclusive access instructions are not modelled")),
        ("with_goto", Some("asm goto is not modelled")),
        ("wide_operand", Some("operand modifier `%Q` is not modelled")),
        (
            "peripheral",
            Some("inline asm reads the peripheral register at 0x40000000"),
        ),
        ("naked_with_c", Some("naked function with C statements")),
        ("plain", None),
    ];
    assert_eq!(r.funcs.len(), expect.len(), "{}", describe(&r));
    for (name, why) in expect {
        let f = r.funcs.iter().find(|f| f.name == *name).unwrap();
        match why {
            None => assert_eq!(f.status, Status::Proved, "{name}"),
            Some(w) => {
                let Status::Unsupported(d) = &f.status else {
                    panic!("{name}: {:?}", f.status)
                };
                assert!(d.contains(w), "{name}: {d}");
            }
        }
    }
}

/// The JSON report carries the lint and the identity note.
#[test]
fn json_has_lints_and_notes() {
    if !have(GCC) {
        return;
    }
    let src = corpus("asm_inline.c");
    let obj = compile(GCC, &src, "cortex-m3", "-O2", &[]);
    let r = check(&obj, &src);
    let image = Image::from_elf(&std::fs::read(&obj).unwrap()).unwrap();
    let j = cverif::report::json(&r, &image, "asm.o");
    assert!(j.contains("\"asm_lints\": ["), "{j}");
    assert!(j.contains("\"message\":\"inline asm could be written in C\""));
    assert!(j.contains("\"function\":\"add_carry\""));
    assert!(j.contains("\"suggestion\":\"__builtin_bswap32(x) rotated by 16"));
    assert!(j.contains("\"assembly\":true") || j.contains("\"note\":\"by identity with the asm text\""));
}

/// A real CMSIS `cmsis_gcc.h` (set `CMSIS_INCLUDE` to its directory) parses and its
/// intrinsics are proved.
#[test]
fn real_cmsis_header() {
    let Ok(dir) = std::env::var("CMSIS_INCLUDE") else {
        eprintln!("skipping: CMSIS_INCLUDE not set");
        return;
    };
    if !have(GCC) {
        return;
    }
    let src = tmp("cmsis_use.c");
    std::fs::write(
        &src,
        "#include <stdint.h>\n#include \"cmsis_gcc.h\"\nuint32_t g;\nvolatile uint32_t v;\n\
         void crit(void) { __disable_irq(); g++; __enable_irq(); }\n\
         uint32_t pm(void) { uint32_t p = __get_PRIMASK(); __disable_irq(); g += 2; __set_PRIMASK(p); return p; }\n\
         void bar(void) { v = 1; __DSB(); __ISB(); __DMB(); }\n\
         void idle(void) { if (!v) __WFI(); __NOP(); __SEV(); }\n\
         uint32_t rev(uint32_t x) { return __REV(x) ^ __REV16(x); }\n\
         uint32_t regs(void) { __set_CONTROL(__get_CONTROL() | 1); return __get_PSP() + __get_MSP() + __get_IPSR(); }\n",
    )
    .unwrap();
    for cpu in ["cortex-m0", "cortex-m4"] {
        let obj = compile(GCC, &src, cpu, "-O2", &[&format!("-I{dir}")]);
        let image = Image::from_elf(&std::fs::read(&obj).unwrap()).unwrap();
        let mut copts = cverif::c::Options::default().with_target(&image);
        copts.include_dirs.push(PathBuf::from(&dir));
        let prog = cverif::c::parse_files(std::slice::from_ref(&src), &copts).expect("parse cmsis_gcc.h");
        let r = verify(&prog, &image, &Options::default());
        for f in &r.funcs {
            assert_eq!(f.status, Status::Proved, "{cpu} {}: {}", f.name, f.status.detail());
        }
    }
}