cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
//! The compiled-object cache of the tests (`tests/support/cc_cache.rs`): a repeated compile is
//! served from it, and nothing that changes what the compiler would produce is served stale —
//! not a changed header, not a damaged entry, not a failed compile, not a missing compiler.
//!
//! Skips itself when `arm-none-eabi-gcc` is not installed or the cache is turned off.

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

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;

const GCC: &str = "arm-none-eabi-gcc";

/// The tests count the hits of the whole process: one at a time.
static SERIAL: Mutex<()> = Mutex::new(());

fn usable() -> bool {
    let gcc = Command::new(GCC)
        .arg("--version")
        .output()
        .is_ok_and(|o| o.status.success());
    let on = std::env::var_os("CVERIF_TEST_CC_CACHE").is_none_or(|v| v != "0");
    if !gcc || !on {
        eprintln!("skipping: no {GCC} or the cache is off");
    }
    gcc && on
}

/// A directory of its own with sources no earlier run compiled (so the first compile misses).
fn fresh(test: &str) -> PathBuf {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let d = Path::new(env!("CARGO_TARGET_TMPDIR"))
        .join("cc_cache")
        .join(format!("{test}-{}-{nanos}", std::process::id()));
    std::fs::create_dir_all(&d).unwrap();
    d
}

fn compile(dir: &Path, src: &str, obj: &str) -> Command {
    let mut cmd = Command::new(GCC);
    cmd.args(["-mthumb", "-mcpu=cortex-m3", "-Os", "-c", "-I"])
        .arg(dir.join("inc"))
        .arg(dir.join(src))
        .arg("-o")
        .arg(dir.join(obj));
    cmd
}

/// Compile; the object's bytes and whether it came from the cache.
fn build(dir: &Path, src: &str, obj: &str) -> (Vec<u8>, bool) {
    let before = cc_cache::hits();
    let out = cc_cache::output(&mut compile(dir, src, obj)).unwrap();
    assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
    (std::fs::read(dir.join(obj)).unwrap(), cc_cache::hits() > before)
}

/// A source that includes a header, so that a change of the header changes the object.
fn sources(dir: &Path, value: u32) {
    std::fs::create_dir_all(dir.join("inc")).unwrap();
    std::fs::write(dir.join("inc/value.h"), format!("#define VALUE {value}u\n")).unwrap();
    let tag = dir.file_name().unwrap().to_string_lossy().replace('-', "_");
    std::fs::write(
        dir.join("f.c"),
        format!("#include \"value.h\"\nunsigned f_{tag}(unsigned x) {{ return x * VALUE; }}\n"),
    )
    .unwrap();
}

#[test]
fn a_repeated_compile_is_served_from_the_cache_with_the_same_object() {
    let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
    if !usable() {
        return;
    }
    let dir = fresh("repeat");
    sources(&dir, 3);
    let (first, hit) = build(&dir, "f.c", "a.o");
    assert!(!hit, "a new source was found in the cache");
    // Under another output name, as the tests that build under unique names do.
    let (again, hit) = build(&dir, "f.c", "b.o");
    assert!(hit, "the same compile was not served from the cache");
    assert_eq!(first, again);
    let plain = compile(&dir, "f.c", "c.o").output().unwrap();
    assert!(plain.status.success());
    assert_eq!(
        first,
        std::fs::read(dir.join("c.o")).unwrap(),
        "the cached object is not what gcc builds"
    );
}

#[test]
fn a_changed_header_is_a_miss() {
    let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
    if !usable() {
        return;
    }
    let dir = fresh("header");
    sources(&dir, 3);
    let (three, _) = build(&dir, "f.c", "a.o");
    std::fs::write(dir.join("inc/value.h"), "#define VALUE 5u\n").unwrap();
    let (five, hit) = build(&dir, "f.c", "a.o");
    assert!(!hit, "served from the cache although the header changed");
    assert_ne!(three, five);
    // A header that disappears: the compile fails as it would without the cache.
    std::fs::remove_file(dir.join("inc/value.h")).unwrap();
    let out = cc_cache::output(&mut compile(&dir, "f.c", "a.o")).unwrap();
    assert!(!out.status.success(), "a compile without its header succeeded");
    assert!(String::from_utf8_lossy(&out.stderr).contains("value.h"));
}

#[test]
fn a_damaged_entry_is_a_miss() {
    let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
    if !usable() {
        return;
    }
    let dir = fresh("damaged");
    sources(&dir, 7);
    let (good, _) = build(&dir, "f.c", "a.o");
    let entry = cc_cache::entry(&compile(&dir, "f.c", "a.o")).expect("a cacheable compile");
    let bytes = std::fs::read(&entry).expect("the compile left an entry");
    // Truncated, then with one byte of the object flipped (its last 16 bytes are the checksum).
    for damaged in [bytes[..bytes.len() / 2].to_vec(), {
        let mut b = bytes.clone();
        let at = b.len() - 40;
        b[at] ^= 0x10;
        b
    }] {
        std::fs::write(&entry, &damaged).unwrap();
        let (built, hit) = build(&dir, "f.c", "a.o");
        assert!(!hit, "a damaged entry was used");
        assert_eq!(built, good);
    }
}

#[test]
fn failures_and_missing_compilers_are_not_cached() {
    let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
    if !usable() {
        return;
    }
    let dir = fresh("failure");
    sources(&dir, 1);
    std::fs::write(dir.join("bad.c"), "int f(void) { return }\n").unwrap();
    let first = cc_cache::output(&mut compile(&dir, "bad.c", "bad.o")).unwrap();
    let before = cc_cache::hits();
    let second = cc_cache::output(&mut compile(&dir, "bad.c", "bad.o")).unwrap();
    assert!(!first.status.success() && !second.status.success());
    assert_eq!(cc_cache::hits(), before);
    assert_eq!(first.stderr, second.stderr);
    assert!(String::from_utf8_lossy(&first.stderr).contains("error"));
    let mut missing = Command::new("cverif-no-such-compiler-gcc");
    missing.args(["-c", "f.c", "-o", "f.o"]).current_dir(&dir);
    assert!(cc_cache::output(&mut missing).is_err(), "a missing compiler ran");
}

#[test]
fn assembly_that_reads_other_files_is_not_cached() {
    let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
    if !usable() {
        return;
    }
    let dir = fresh("include");
    std::fs::create_dir_all(dir.join("inc")).unwrap();
    std::fs::write(dir.join("part.s"), ".word 1\n").unwrap();
    std::fs::write(dir.join("f.s"), ".syntax unified\n.thumb\n.include \"part.s\"\n").unwrap();
    let mut cmd = Command::new(GCC);
    cmd.args(["-mthumb", "-mcpu=cortex-m3", "-c", "f.s", "-o", "f.o"])
        .current_dir(&dir);
    assert!(
        cc_cache::entry(&cmd).is_none(),
        "`.include` is not followed by the cache"
    );
    assert!(cc_cache::output(&mut cmd).unwrap().status.success());
}