cverif 0.1.3

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Loops a blind search for a path round them does not reach within the budget
//! (`tests/corpus/steer.c`): behind many checks that each may fail, inside a macro's
//! `do { ... } while (0)`, inside a helper the binary has inline.  Induction steers the source
//! towards them (`verify::loops::search`).  Built by gcc and clang for the firmware targets:
//! proved where the steered path is enough, never a difference reported for the original, and
//! every mutant rejected or at least not proved.
//!
//! The tests skip themselves when a cross compiler is not installed.

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

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

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

const CONFIGS: &[Config] = &[
    Config {
        name: "gcc-m3-Os",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m3", "-Os"],
    },
    Config {
        name: "gcc-m0-O2",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m0plus", "-O2"],
    },
    Config {
        name: "gcc-m4-O2",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m4", "-O2"],
    },
    Config {
        name: "clang-m0plus-Os",
        cc: "clang",
        flags: &["--target=armv6m-none-eabi", "-mcpu=cortex-m0plus", "-mthumb", "-Os"],
    },
];

/// `(function, config)`: not proved there, at the test's budget (the step from `s_two`'s cut
/// points fails with the binary at a loop head where the source leaves the function; the base
/// case or the step of `s_checked` runs out of budget for clang and for gcc -O2).  None
/// of them may be a difference.
const MAY_BE_BOUNDED: &[(&str, &str)] = &[
    ("s_two", "gcc-m3-Os"),
    ("s_two", "gcc-m0-O2"),
    ("s_two", "gcc-m4-O2"),
    ("s_two", "clang-m0plus-Os"),
    ("s_checked", "gcc-m0-O2"),
    ("s_checked", "gcc-m4-O2"),
    ("s_checked", "clang-m0plus-Os"),
];

/// `(n, function)`: building with `-DMUTANT=n` changes `function`.
const MUTANTS: &[(u32, &str)] = &[(1, "s_checked"), (2, "s_checked"), (3, "s_two"), (4, "s_inline")];

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

impl Config {
    fn compile(&self, mutant: u32) -> Option<PathBuf> {
        let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("steer");
        std::fs::create_dir_all(&dir).unwrap();
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let obj = dir.join(format!("{}-{mutant}-{}-{n}.o", self.name, std::process::id()));
        toolchain::compile_or_skip(
            Command::new(self.cc)
                .args(self.flags)
                .args(["-ffreestanding", "-c"])
                .arg(format!("-DMUTANT={mutant}"))
                .arg(src())
                .arg("-o")
                .arg(&obj),
            self.name,
        )?;
        Some(obj)
    }
}

fn check(obj: &Path, only: Option<&str>) -> Report {
    let image = Image::from_elf(&std::fs::read(obj).unwrap()).expect("load ELF");
    let prog = cverif::c::parse_files(&[src()], &Default::default()).expect("parse C");
    let opts = {
        let mut built = Options::default();
        // A work budget, not a time limit: the outcome must not depend on the machine.
        built.work_limit = 30_000;
        built.jobs = 1;
        built.only = only.map(|n| vec![n.to_string()]).unwrap_or_default();
        built
    };
    let r = verify(&prog, &image, &opts);
    let _ = std::fs::remove_file(obj);
    r
}

/// Run `job` for every item on a few threads with deep stacks, collecting the complaints.
fn for_each<I: Send + Sync>(items: &[I], job: impl Fn(&I) -> Vec<String> + Sync) {
    let next = Mutex::new(0usize);
    let complaints = Mutex::new(Vec::new());
    let workers = std::thread::available_parallelism().map_or(4, |n| n.get()).min(4);
    std::thread::scope(|s| {
        for _ in 0..workers {
            std::thread::Builder::new()
                .stack_size(32 << 20)
                .spawn_scoped(s, || {
                    loop {
                        let i = {
                            let mut n = next.lock().unwrap();
                            *n += 1;
                            *n - 1
                        };
                        let Some(item) = items.get(i) else { break };
                        let found = job(item);
                        complaints.lock().unwrap().extend(found);
                    }
                })
                .unwrap();
        }
    });
    let complaints = complaints.into_inner().unwrap();
    assert!(complaints.is_empty(), "\n{}", complaints.join("\n"));
}

#[test]
fn steered_loops_are_proved() {
    for_each(CONFIGS, |c| {
        let Some(obj) = c.compile(0) else { return Vec::new() };
        let r = check(&obj, None);
        let mut bad = Vec::new();
        if r.funcs.len() != 3 {
            bad.push(format!("{}: {} functions verified", c.name, r.funcs.len()));
        }
        for f in &r.funcs {
            let ok = match &f.status {
                Status::Proved => true,
                Status::Bounded(_) => MAY_BE_BOUNDED.contains(&(f.name.as_str(), c.name)),
                _ => false,
            };
            if !ok {
                bad.push(format!(
                    "{}: {} is {} {}",
                    c.name,
                    f.name,
                    f.status.label(),
                    f.status.detail()
                ));
            }
        }
        bad
    });
}

#[test]
fn steered_loop_mutants_are_not_proved() {
    let items: Vec<(Config, u32, &str)> = (CONFIGS.iter())
        .flat_map(|&c| MUTANTS.iter().map(move |&(n, f)| (c, n, f)))
        .collect();
    for_each(&items, |&(c, n, name)| {
        let Some(obj) = c.compile(n) else { return Vec::new() };
        let r = check(&obj, Some(name));
        let f = r.funcs.iter().find(|f| f.name == name).expect("the mutated function");
        // (A difference only past what the bounded exploration reaches is seen by no path the
        // steps of a failed induction prove: not proved is all there is then.)
        match &f.status {
            Status::Proved => vec![format!("mutant {n} ({name}) {}: proved", c.name)],
            _ => Vec::new(),
        }
    });
}