cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
//! State merging: small conditional regions without calls are executed on both sides of
//! their condition and joined into if-then-else terms, on the source side and on the
//! machine side, instead of one path per way through them.  `tests/corpus/paths.c` holds
//! the shapes that made the path count explode; here they are verified with merging on and
//! off, for the firmware profiles, and mutants that differ on one combination of arms only
//! must still be found.

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

use cverif::verify::{Options, Report, Status, verify};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};

struct Tc {
    name: &'static str,
    cc: &'static str,
    flags: &'static [&'static str],
}

const GCC_M0PLUS: Tc = Tc {
    name: "gcc-m0plus",
    cc: "arm-none-eabi-gcc",
    flags: &[
        "-fomit-frame-pointer",
        "-mcpu=cortex-m0plus",
        "-mthumb",
        "-mno-unaligned-access",
        "-fno-jump-tables",
    ],
};

const GCC_M3: Tc = Tc {
    name: "gcc-m3",
    cc: "arm-none-eabi-gcc",
    flags: &["-mcpu=cortex-m3", "-mthumb"],
};

const GCC_M4: Tc = Tc {
    name: "gcc-m4",
    cc: "arm-none-eabi-gcc",
    flags: &["-mcpu=cortex-m4", "-mthumb"],
};

const CLANG_M0PLUS_ROPI: Tc = Tc {
    name: "clang-m0plus-ropi",
    cc: "clang",
    flags: &[
        "--target=armv6m-none-eabi",
        "-fomit-frame-pointer",
        "-momit-leaf-frame-pointer",
        "-mcpu=cortex-m0plus",
        "-mthumb",
        "-mno-unaligned-access",
        "-fropi",
        "-fno-jump-tables",
    ],
};

const TCS: &[Tc] = &[GCC_M0PLUS, GCC_M3, GCC_M4, CLANG_M0PLUS_ROPI];

const LEVELS: &[&str] = &["-Os", "-O2"];

fn source() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/paths.c")
}

/// paths.c compiled with `-DMUTANT=n` (built under a name of its own and renamed: tests run
/// in parallel).
fn build(tc: &Tc, level: &str, mutant: u32) -> Option<PathBuf> {
    static SEQ: AtomicUsize = AtomicUsize::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("paths");
    std::fs::create_dir_all(&dir).unwrap();
    let out = dir.join(format!("{}{level}-m{mutant}.o", tc.name));
    let part = dir.join(format!(
        "{}{level}-m{mutant}-{}-{}.part.o",
        tc.name,
        std::process::id(),
        SEQ.fetch_add(1, Ordering::Relaxed)
    ));
    let ok = cc_cache::output(
        Command::new(tc.cc)
            .args(tc.flags)
            .args(["-ffreestanding", "-c", level])
            .arg(format!("-DMUTANT={mutant}"))
            .arg(source())
            .arg("-o")
            .arg(&part),
    )
    .is_ok_and(|o| o.status.success());
    if !ok {
        return None;
    }
    std::fs::rename(&part, &out).unwrap();
    Some(out)
}

fn check(obj: &Path, merge: bool) -> Report {
    let image = cverif::inputs::load(&std::fs::read(obj).unwrap(), 0, &[], &[], None).unwrap();
    let copts = cverif::c::Options::for_image(&image);
    let prog = cverif::c::parse_files(&[source()], &copts).expect("parse C");
    let opts = {
        let mut built = Options::default();
        built.jobs = 2;
        built.work_limit = 30_000;
        // (Merging by itself: by default it is only tried where path by path runs out.)
        built.merge = merge;
        built.merge_only = merge;
        built
    };
    verify(&prog, &image, &opts)
}

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

/// Lines of paths.c marked `/* DEAD */`.
fn dead_lines() -> Vec<u32> {
    let text = std::fs::read_to_string(source()).unwrap();
    text.lines()
        .enumerate()
        .filter(|l| l.1.contains("/* DEAD */"))
        .map(|l| l.0 as u32 + 1)
        .collect()
}

/// Every shape is proved with merging and without, with far fewer paths, and the two
/// agree on what is covered: an arm counts only where some defined execution takes it.
#[test]
fn merged_regions_are_proved() {
    let mut ran = 0;
    let (mut plain_paths, mut merged_paths) = (0, 0);
    let (mut plain_work, mut merged_work) = (0, 0);
    for tc in TCS {
        for level in LEVELS {
            let Some(obj) = build(tc, level, 0) else {
                eprintln!("skipping: {} {level} cannot build", tc.name);
                continue;
            };
            ran += 1;
            let plain = check(&obj, false);
            let merged = check(&obj, true);
            // Path by path, the budget of the tests may run out (that is the point); with
            // merging everything is proved.
            let complete = plain.funcs.iter().all(|f| matches!(f.status, Status::Proved));
            for (r, is_merged) in [(&plain, false), (&merged, true)] {
                assert!(r.funcs.len() >= 14, "{} {level}: {} functions", tc.name, r.funcs.len());
                for f in &r.funcs {
                    assert!(
                        matches!(f.status, Status::Proved) || (!is_merged && matches!(f.status, Status::Bounded(_))),
                        "{} {level}: {} is {:?}",
                        tc.name,
                        f.name,
                        f.status
                    );
                }
                if !is_merged && !complete {
                    continue;
                }
                // The arm that is undefined is not covered, and it is the only thing.
                let mut lines: Vec<u32> = r.uncovered_lines.iter().map(|l| l.1).collect();
                lines.dedup();
                assert_eq!(lines, dead_lines(), "{} {level}: uncovered lines", tc.name);
            }
            if complete {
                assert_eq!(plain.src, merged.src, "{} {level}: source coverage", tc.name);
                assert_eq!(plain.bin, merged.bin, "{} {level}: binary coverage", tc.name);
            }
            eprintln!("{} {level}:", tc.name);
            for f in &plain.funcs {
                let m = func(&merged, &f.name);
                eprintln!(
                    "  {:14} paths {:4} -> {:3}   work {:6} -> {:6}",
                    f.name, f.paths, m.paths, f.work, m.work
                );
                plain_paths += f.paths;
                merged_paths += m.paths;
                plain_work += f.work;
                merged_work += m.work;
            }
            // 2^8 ways through the flag tests, one with merging.
            assert!(func(&plain, "flag_cost").paths >= 64, "{} {level}", tc.name);
            assert!(func(&merged, "flag_cost").paths <= 4, "{} {level}", tc.name);
        }
    }
    if ran == 0 {
        eprintln!("skipping: no ARM toolchain");
        return;
    }
    eprintln!("total: paths {plain_paths} -> {merged_paths}, work {plain_work} -> {merged_work}");
    assert!(merged_paths * 4 <= plain_paths, "paths {plain_paths} -> {merged_paths}");
}

/// A binary that differs from the source on one combination of arms, or only where an arm
/// guarded against undefined behaviour is taken, is not proved.  (One test per toolchain, so
/// that they run in parallel.)
fn merging_does_not_hide_differences(tc: &Tc) {
    let changed = [
        (1, "flag_cost"),
        (2, "slice_len"),
        (3, "mid3"),
        (4, "fmt_fix"),
        (5, "digit_of"),
        (6, "guarded"),
        (7, "guarded"),
        (8, "columns"),
        (9, "pad_and_emit"),
        (10, "cmp3"),
        (11, "pick"),
        (12, "sized_copy"),
        (13, "sized_fill"),
    ];
    for level in LEVELS {
        for (mutant, name) in changed {
            let Some(obj) = build(tc, level, mutant) else {
                eprintln!("skipping: {} {level} cannot build", tc.name);
                continue;
            };
            let r = check(&obj, true);
            for f in &r.funcs {
                if f.name == name {
                    assert!(
                        matches!(f.status, Status::Mismatch(_)),
                        "{} {level} mutant {mutant}: {name} is {:?}",
                        tc.name,
                        f.status
                    );
                } else {
                    assert!(
                        matches!(f.status, Status::Proved),
                        "{} {level} mutant {mutant}: {} is {:?}",
                        tc.name,
                        f.name,
                        f.status
                    );
                }
            }
        }
    }
}

#[test]
fn merging_does_not_hide_differences_gcc_m0plus() {
    merging_does_not_hide_differences(&GCC_M0PLUS);
}

#[test]
fn merging_does_not_hide_differences_gcc_m3() {
    merging_does_not_hide_differences(&GCC_M3);
}

#[test]
fn merging_does_not_hide_differences_gcc_m4() {
    merging_does_not_hide_differences(&GCC_M4);
}

#[test]
fn merging_does_not_hide_differences_clang_m0plus_ropi() {
    merging_does_not_hide_differences(&CLANG_M0PLUS_ROPI);
}