cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Values narrower than a register where a word is expected: byte loads, call results and
//! arguments, and declarations of one function that differ between translation units (which
//! used to end in "ill-formed term: bits 0..32 taken from an 8-bit value").
//!
//! Needs `arm-none-eabi-gcc`; skipped without it.

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

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/widths")
        .join(name)
}

/// Compile (and for several sources link into one relocatable object) under a name of its
/// own, so that tests running at the same time share nothing.
fn build(srcs: &[PathBuf], flags: &[&str]) -> Image {
    static SERIAL: AtomicU32 = AtomicU32::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("widths");
    std::fs::create_dir_all(&dir).unwrap();
    let obj = dir.join(format!(
        "{}-{}.o",
        std::process::id(),
        SERIAL.fetch_add(1, Ordering::Relaxed)
    ));
    let out = Command::new(GCC)
        .args(["-mthumb", "-mcpu=cortex-m0plus", "-ffreestanding", "-nostdlib", "-w"])
        .arg(if srcs.len() == 1 { "-c" } else { "-r" })
        .args(flags)
        .args(srcs)
        .arg("-o")
        .arg(&obj)
        .output()
        .unwrap();
    assert!(out.status.success(), "{}", 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 check(image: &Image, srcs: &[PathBuf], modular: bool) -> Report {
    let prog = cverif::c::parse_files(srcs, &cverif::c::Options::for_image(image)).expect("parse C");
    let opts = Options {
        work_limit: 30_000,
        jobs: 2,
        modular,
        ..Default::default()
    };
    verify(&prog, image, &opts)
}

fn describe(r: &Report) -> String {
    (r.funcs.iter())
        .map(|f| format!("  {:?} {}: {}\n", f.status, f.name, f.status.detail()))
        .collect()
}

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

fn no_internal_error(r: &Report, what: &str) {
    assert!(
        r.funcs.iter().all(|f| !f.status.detail().contains("internal error")),
        "{what}\n{}",
        describe(r)
    );
}

#[test]
fn bytes_widen_as_their_type_says() {
    if !have_gcc() {
        return;
    }
    let src = [corpus("widths.c")];
    for opt in ["-Os", "-O2", "-O0"] {
        for modular in [true, false] {
            let r = check(&build(&src, &[opt]), &src, modular);
            no_internal_error(&r, opt);
            for f in [
                "widen_s",
                "widen_u",
                "call_s",
                "call_b",
                "pass_s",
                "bool_shr",
                "bool_word",
                "pun",
                "packed",
                "text",
                "abs",
                "use_abs",
                "use_labs",
            ] {
                assert_eq!(
                    *status(&r, f),
                    Status::Proved,
                    "{opt} modular={modular}: {f}\n{}",
                    describe(&r)
                );
            }
        }
        // The wrong extension of the byte in the binary.
        for (mutant, f) in [(1, "widen_s"), (2, "widen_u"), (3, "call_s"), (4, "pass_s")] {
            let m = format!("-DMUTANT={mutant}");
            let r = check(&build(&src, &[opt, &m]), &src, true);
            no_internal_error(&r, opt);
            assert!(
                matches!(status(&r, f), Status::Mismatch(_)),
                "{opt} mutant {mutant}: {f}\n{}",
                describe(&r)
            );
        }
    }
}

/// A function called through a declaration of another type than its definition's: each side
/// was compiled for its own, so the call means what the calling convention makes of it, or
/// nothing the source can say.
#[test]
fn declarations_that_differ_between_units() {
    if !have_gcc() {
        return;
    }
    for srcs in [
        [corpus("callers.c"), corpus("defs.c")],
        [corpus("defs.c"), corpus("callers.c")],
    ] {
        for opt in ["-Os", "-O2", "-O0"] {
            let image = build(&srcs, &[opt]);
            for modular in [true, false] {
                let what = format!("{opt} modular={modular} {:?}", srcs[0].file_name().unwrap());
                let r = check(&image, &srcs, modular);
                no_internal_error(&r, &what);
                for f in ["use_get", "use_get2", "use_s", "use_b"] {
                    let fr = r.funcs.iter().find(|x| x.name == f).unwrap();
                    assert_eq!(fr.status, Status::Proved, "{what}: {f}\n{}", describe(&r));
                    assert!(
                        fr.assumes.iter().any(|a| a.contains("calling convention")),
                        "{what}: {f}: {:?}",
                        fr.assumes
                    );
                }
                // A result wider than the caller expects, or of the other signedness: what
                // the caller sees is no value of its type.
                for f in ["use_wide", "use_h"] {
                    assert!(
                        matches!(status(&r, f), Status::Unsupported(_)),
                        "{what}: {f}\n{}",
                        describe(&r)
                    );
                }
                // Compared as a call, the argument is the one the caller's declaration
                // describes; followed, the callee would be handed a value outside its type.
                assert!(
                    matches!(
                        (modular, status(&r, "use_inc")),
                        (true, Status::Proved) | (false, Status::Unsupported(_))
                    ),
                    "{what}: use_inc\n{}",
                    describe(&r)
                );
                // Objects are accessed as the unit that accesses them declares them.
                for f in ["use_g", "rd_sg", "wr_sg", "get", "inc", "sget", "bget", "wide", "hget"] {
                    assert_eq!(*status(&r, f), Status::Proved, "{what}: {f}\n{}", describe(&r));
                }
            }
            let m = build(&srcs, &[opt, "-DMUTANT=1"]);
            let r = check(&m, &srcs, true);
            no_internal_error(&r, opt);
            assert!(
                matches!(status(&r, "use_s"), Status::Mismatch(_)),
                "{opt}\n{}",
                describe(&r)
            );
        }
    }
}