cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
//! `--certify` on a representative part of the corpus: every UNSAT answer that the proofs
//! rest on is checked by the independent checker of `cverif::certify`, and every proof
//! must still go through.  (The whole suite can be run the same way with `CVERIF_CERTIFY=1`.)
//!
//! The tests skip themselves when the cross compiler 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 GCC: &str = "arm-none-eabi-gcc";

fn have_gcc() -> bool {
    Command::new(GCC)
        .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 compile(src: &Path, cpu: &str, level: &str) -> Image {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("certify");
    std::fs::create_dir_all(&dir).unwrap();
    let stem = src.file_stem().unwrap().to_string_lossy();
    // A unique name, written atomically: tests run in parallel.
    let obj = dir.join(format!("{stem}-{cpu}{level}-{}.o", std::process::id()));
    let out = cc_cache::output(
        Command::new(GCC)
            .args(["-mthumb", &format!("-mcpu={cpu}"), "-ffreestanding", "-c", level])
            .arg(src)
            .arg("-o")
            .arg(&obj),
    )
    .expect("run gcc");
    assert!(
        out.status.success(),
        "gcc failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let image = Image::from_elf(&std::fs::read(&obj).unwrap()).expect("load ELF");
    let _ = std::fs::remove_file(&obj);
    image
}

fn certified(image: Image, src: &Path) -> Report {
    let src = src.to_path_buf();
    std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let prog = cverif::c::parse_files(&[src], &Default::default()).expect("parse C");
            let opts = {
                let mut built = Options::default();
                built.work_limit = 30_000;
                built.time_limit = Duration::from_secs(900);
                built.jobs = 4;
                built.certify = true;
                built
            };
            verify(&prog, &image, &opts)
        })
        .unwrap()
        .join()
        .unwrap()
}

/// Every function proved (or bounded, for those listed), every UNSAT answer certified.
fn expect_certified(file: &str, cpu: &str, levels: &[&str], bounded: &[&str]) {
    if !have_gcc() {
        eprintln!("skipping: {GCC} not installed");
        return;
    }
    let src = corpus(file);
    for level in levels {
        let r = certified(compile(&src, cpu, level), &src);
        let cert = r.cert.as_ref().expect("certification statistics");
        assert!(cert.failure.is_none(), "{file} {level}: {:?}", cert.failure);
        for f in &r.funcs {
            assert!(
                f.cert.failure.is_none(),
                "{file} {level} {}: {:?}",
                f.name,
                f.cert.failure
            );
            let ok = match &f.status {
                Status::Proved => true,
                Status::Bounded(_) => bounded.contains(&f.name.as_str()),
                _ => false,
            };
            assert!(ok, "{file} {level} {}: {}", f.name, f.status.detail());
        }
        assert!(cert.checked > 0, "{file} {level}: no UNSAT answer was checked");
        eprintln!(
            "{file} {cpu} {level}: {} functions, {} UNSAT answers certified ({} steps, {} ms)",
            r.funcs.len(),
            cert.checked,
            cert.steps,
            cert.time.as_millis()
        );
    }
}

#[test]
fn arith_certified() {
    expect_certified("arith.c", "cortex-m3", &["-O0", "-O2", "-Os"], &[]);
}

#[test]
fn control_certified() {
    expect_certified("control.c", "cortex-m0", &["-O1", "-O3"], &["sum_n", "gcd"]);
}

#[test]
fn memory_certified() {
    expect_certified("memory.c", "cortex-m4", &["-O2"], &[]);
}

#[test]
fn float_certified() {
    expect_certified("float.c", "cortex-m3", &["-O2"], &[]);
}

#[test]
fn realworld_certified() {
    expect_certified("rw_crc.c", "cortex-m3", &["-Os"], &[]);
}

/// Machine code against machine code, with certification.
#[test]
fn compare_certified() {
    if !have_gcc() {
        eprintln!("skipping: {GCC} not installed");
        return;
    }
    let src = corpus("arith.c");
    let (a, b) = (compile(&src, "cortex-m3", "-O1"), compile(&src, "cortex-m3", "-Os"));
    let cmp = std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let opts = {
                let mut built = cverif::bindiff::Options::default();
                built.verify = {
                    let mut built = Options::default();
                    built.jobs = 4;
                    built.work_limit = 30_000;
                    built.time_limit = Duration::from_secs(900);
                    built.certify = true;
                    built
                };
                built
            };
            cverif::bindiff::compare(&a, &b, None, &opts)
        })
        .unwrap()
        .join()
        .unwrap();
    let cert = cmp.cert.as_ref().expect("certification statistics");
    assert!(cert.failure.is_none(), "{:?}", cert.failure);
    assert!(cert.checked > 0);
    assert!(cmp.funcs.iter().any(|f| f.is_equivalent() && !f.same_code));
    assert!(
        !cmp.funcs.iter().any(|f| f.label() == "INCONCLUSIVE"),
        "{}",
        cmp.render()
    );
}