cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! The proof cache (`--cache`): a result is reused exactly when nothing it can depend on
//! has changed.  A wrong hit would be a false proof.

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

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 source() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/cache.c")
}

fn dir(test: &str) -> PathBuf {
    let d = Path::new(env!("CARGO_TARGET_TMPDIR")).join("cache").join(test);
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d
}

/// Compile the corpus with the given macro definitions.
fn build(dir: &Path, tag: &str, defs: &[&str]) -> Image {
    let obj = dir.join(format!("{tag}.o"));
    let out = Command::new(GCC)
        .args(["-mthumb", "-mcpu=cortex-m3", "-ffreestanding", "-Os", "-c"])
        .args(defs.iter().map(|d| format!("-D{d}")))
        .arg(source())
        .arg("-o")
        .arg(&obj)
        .output()
        .expect("run gcc");
    assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
    Image::from_elf(&std::fs::read(&obj).unwrap()).expect("load ELF")
}

fn check(image: &Image, defs: &[&str], opts: &Options) -> Report {
    let copts = cverif::c::Options {
        defines: defs
            .iter()
            .map(|d| match d.split_once('=') {
                Some((k, v)) => (k.to_string(), v.to_string()),
                None => (d.to_string(), "1".to_string()),
            })
            .collect(),
        ..cverif::c::Options::for_image(image)
    };
    let prog = cverif::c::parse_files(&[source()], &copts).expect("parse C");
    verify(&prog, image, opts)
}

fn options(cache: &Path) -> Options {
    Options {
        jobs: 2,
        work_limit: 30_000,
        cache: Some(cache.to_path_buf()),
        ..Default::default()
    }
}

/// The names of the functions whose result came from the cache.
fn cached(r: &Report) -> Vec<&str> {
    let mut v: Vec<&str> = r.funcs.iter().filter(|f| f.cached).map(|f| f.name.as_str()).collect();
    v.sort();
    v
}

fn status<'a>(r: &'a Report, name: &str) -> &'a Status {
    &r.funcs.iter().find(|f| f.name == name).expect(name).status
}

/// Everything a report says apart from where the results came from and how long they took.
fn content(r: &Report) -> Vec<String> {
    let mut v: Vec<String> = r
        .funcs
        .iter()
        .map(|f| {
            format!(
                "{} {:#x} {} {:?} paths={} undef={} modulo={:?} unconditional={}",
                f.name, f.addr, f.size, f.status, f.paths, f.undefined_paths, f.modulo, f.unconditional
            )
        })
        .collect();
    v.sort();
    v.push(format!("{:?} {:?} {:?}", r.src, r.bin, r.bin_ranges));
    v.push(format!(
        "{:?}",
        r.src_points.iter().map(|p| (p.line, p.proved)).collect::<Vec<_>>()
    ));
    v
}

const ALL: [&str; 4] = ["alone", "helper", "uses_both", "uses_helper"];

#[test]
fn unchanged_rerun_is_served_from_the_cache() {
    if !have_gcc() {
        return;
    }
    let d = dir("unchanged");
    let image = build(&d, "a", &[]);
    let opts = options(&d.join("cache"));
    let first = check(&image, &[], &opts);
    assert!(cached(&first).is_empty());
    assert!(
        first.funcs.iter().all(|f| f.status == Status::Proved),
        "{:?}",
        content(&first)
    );
    let second = check(&image, &[], &opts);
    assert_eq!(cached(&second), ALL);
    assert_eq!(content(&first), content(&second));
    // Without the option nothing is read.
    let plain = check(
        &image,
        &[],
        &Options {
            cache: None,
            ..opts.clone()
        },
    );
    assert!(cached(&plain).is_empty());
    assert_eq!(content(&first), content(&plain));
}

#[test]
fn a_changed_code_byte_invalidates_the_function_it_is_in() {
    if !have_gcc() {
        return;
    }
    let d = dir("code");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    check(&image, &[], &opts);
    // The same source against a binary in which `alone` has another constant.
    let other = build(&d, "b", &["BK=6"]);
    let r = check(&other, &[], &opts);
    assert_eq!(cached(&r), ["helper", "uses_both", "uses_helper"]);
    assert!(matches!(status(&r, "alone"), Status::Mismatch(_)));
    // And a difference is never stored: it is found again.
    let r = check(&other, &[], &opts);
    assert!(matches!(status(&r, "alone"), Status::Mismatch(_)));
    assert!(!cached(&r).contains(&"alone"));
}

#[test]
fn a_changed_token_invalidates_the_function_it_is_in() {
    if !have_gcc() {
        return;
    }
    let d = dir("token");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    check(&image, &[], &opts);
    // The same binary against a source in which `alone` has another constant.
    let r = check(&image, &["BK=6"], &opts);
    assert_eq!(cached(&r), ["helper", "uses_both", "uses_helper"]);
    assert!(matches!(status(&r, "alone"), Status::Mismatch(_)));
    // Both changed alike: proved afresh, the others from the cache.
    let other = build(&d, "b", &["BK=6"]);
    let r = check(&other, &["BK=6"], &opts);
    assert_eq!(cached(&r), ["helper", "uses_both", "uses_helper"]);
    assert_eq!(*status(&r, "alone"), Status::Proved);
}

#[test]
fn a_changed_callee_invalidates_its_callers() {
    if !have_gcc() {
        return;
    }
    let d = dir("callee");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    check(&image, &[], &opts);
    // Another signature of `helper`, in source and binary: only `alone` does not use it.
    let other = build(&d, "b", &["HSIG"]);
    let r = check(&other, &["HSIG"], &opts);
    assert!(!cached(&r).contains(&"helper"));
    assert!(!cached(&r).contains(&"uses_both"));
    assert!(!cached(&r).contains(&"uses_helper"));
    // (`alone` is cached only if the change did not move it or its neighbours' symbols.)
    assert!(r.funcs.iter().all(|f| f.status == Status::Proved), "{:?}", content(&r));
    // In the source only: the callers are judged afresh and found to differ.
    // (A new function type is a change to the program's types, which every key covers: here
    // not even `alone` is reused.)
    let r = check(&image, &["HSIG"], &opts);
    assert!(cached(&r).iter().all(|n| *n == "alone"), "{:?}", cached(&r));
    assert!(!cached(&r).contains(&"uses_helper") && !cached(&r).contains(&"uses_both"));
    assert!(matches!(status(&r, "helper"), Status::Mismatch(_)));
}

#[test]
fn a_changed_initialiser_invalidates_the_functions_that_use_the_object() {
    if !have_gcc() {
        return;
    }
    let d = dir("init");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    check(&image, &[], &opts);
    // The same binary against a source with another table.
    let r = check(&image, &["TV=9"], &opts);
    assert_eq!(cached(&r), ["alone", "helper", "uses_helper"]);
    assert!(r.has_mismatch(), "the table differs: {:?}", content(&r));
    // Another table in the binary: data anywhere in the image may be read by any proof, so
    // nothing is reused.
    let other = build(&d, "b", &["TV=9"]);
    let r = check(&other, &["TV=9"], &opts);
    assert!(cached(&r).is_empty());
    assert!(r.funcs.iter().all(|f| f.status == Status::Proved));
}

#[test]
fn a_changed_option_invalidates_everything() {
    if !have_gcc() {
        return;
    }
    let d = dir("option");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    check(&image, &[], &opts);
    for other in [
        Options {
            work_limit: 29_000,
            ..opts.clone()
        },
        Options {
            modular: false,
            ..opts.clone()
        },
        Options {
            aliasing: cverif::c::exec::Aliasing::Standard,
            ..opts.clone()
        },
        Options {
            mmio: Vec::new(),
            ..opts.clone()
        },
    ] {
        assert!(cached(&check(&image, &[], &other)).is_empty());
    }
    // The number of threads and the selection of functions do not bear on a result.
    let r = check(
        &image,
        &[],
        &Options {
            jobs: 1,
            only: vec!["alone".into()],
            ..opts.clone()
        },
    );
    assert_eq!(cached(&r), ["alone"]);
}

#[test]
fn a_damaged_entry_is_not_a_result() {
    if !have_gcc() {
        return;
    }
    let d = dir("damaged");
    let opts = options(&d.join("cache"));
    let image = build(&d, "a", &[]);
    let first = check(&image, &[], &opts);
    for e in std::fs::read_dir(d.join("cache")).unwrap() {
        let p = e.unwrap().path();
        let text = std::fs::read_to_string(&p).unwrap();
        std::fs::write(&p, &text[..text.len() / 2]).unwrap();
    }
    let r = check(&image, &[], &opts);
    assert!(cached(&r).is_empty());
    assert_eq!(content(&first), content(&r));
}