cverif 0.1.3

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Library routines the image has without source (the compiler's run-time library, the C
//! library) are verified against what their names promise, and the results that rest on
//! them say what became of that; linker stubs are calls to their targets.

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

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

const CPUS: &[&str] = &["cortex-m0plus", "cortex-m3"];

fn corpus(f: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus/lib").join(f)
}

/// Runs a compile or a link: false (after a `skipping` line) when the toolchain is absent or
/// cannot build for the CPU; a failure of a toolchain that can is a broken test, and panics.
fn run(cmd: &mut Command) -> bool {
    toolchain::run_or_skip(cmd, "the library tests").is_some()
}

/// Compile `units` (file, extra flags) and link them with `link.ld` and libgcc into an
/// executable, built under a name of its own and renamed (tests run in parallel).
fn link(tag: &str, cpu: &str, units: &[(&str, &[&str])]) -> Option<PathBuf> {
    link_with(tag, cpu, units, "link.ld")
}

fn link_with(tag: &str, cpu: &str, units: &[(&str, &[&str])], script: &str) -> Option<PathBuf> {
    static SEQ: AtomicUsize = AtomicUsize::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("library");
    std::fs::create_dir_all(&dir).unwrap();
    let uniq = format!("{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed));
    let mcpu = format!("-mcpu={cpu}");
    let mut objs = Vec::new();
    for (i, (f, flags)) in units.iter().enumerate() {
        let o = dir.join(format!("{tag}-{cpu}-{i}-{uniq}.o"));
        let ok = run(Command::new("arm-none-eabi-gcc")
            .args([
                &mcpu,
                "-mthumb",
                "-Os",
                "-ffreestanding",
                "-fno-tree-loop-distribute-patterns",
                "-c",
            ])
            .args(*flags)
            .arg(corpus(f))
            .arg("-o")
            .arg(&o));
        if !ok {
            return None;
        }
        objs.push(o);
    }
    let part = dir.join(format!("{tag}-{cpu}-{uniq}.part.elf"));
    // `bad.S` replaces routines of libgcc, whose objects may define other routines the image
    // needs (`__aeabi_uidivmod` comes with `__aeabi_uidiv`): its definitions, linked first, win.
    let replaces = units.iter().any(|(f, _)| *f == "bad.S");
    let ok = run(Command::new("arm-none-eabi-gcc")
        .args([&mcpu, "-mthumb", "-nostdlib"])
        .args(replaces.then_some("-Wl,--allow-multiple-definition"))
        .arg(format!("-Wl,-T,{}", corpus(script).display()))
        .args(&objs)
        .arg("-o")
        .arg(&part)
        .arg("-lgcc"));
    if !ok {
        return None;
    }
    let out = dir.join(format!("{tag}-{cpu}.elf"));
    std::fs::rename(&part, &out).unwrap();
    Some(out)
}

fn check(elf: &Path, source: &str) -> Report {
    check_with(elf, source, &[])
}

fn check_with(elf: &Path, source: &str, defines: &[&str]) -> Report {
    let image = cverif::inputs::load(&std::fs::read(elf).unwrap(), 0, &[], &[], None).unwrap();
    let mut copts = cverif::c::Options::for_image(&image);
    copts
        .defines
        .extend(defines.iter().map(|d| (d.to_string(), "1".to_string())));
    let prog = cverif::c::parse_files(&[corpus(source)], &copts).expect("parse C");
    let opts = {
        let mut built = Options::default();
        built.jobs = 2;
        built.work_limit = 30_000;
        built
    };
    verify(&prog, &image, &opts)
}

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

fn func<'a>(r: &'a Report, name: &str) -> &'a cverif::verify::FuncReport {
    (r.funcs.iter())
        .find(|f| f.name == name)
        .unwrap_or_else(|| panic!("{name} has no result:\n{}", describe(r)))
}

fn rests_on(r: &Report, name: &str, on: &str) -> String {
    (func(r, name).modulo.iter())
        .find(|m| m.0 == on)
        .unwrap_or_else(|| panic!("{name} does not rest on {on}:\n{}", describe(r)))
        .1
        .clone()
}

#[test]
fn library_routines_have_verdicts_of_their_own() {
    let mut ran = 0;
    for cpu in CPUS {
        let Some(elf) = link("lib", cpu, &[("app.c", &[]), ("mini.c", &[])]) else {
            eprintln!("skipping: cannot build for {cpu}");
            continue;
        };
        ran += 1;
        let r = check(&elf, "app.c");
        let d = describe(&r);
        assert!(!r.has_mismatch(), "{cpu}:\n{d}");
        // The small C library: loops over bytes, proved to be what the names say.
        for (caller, routine) in [
            ("fill", "memset"),
            ("copy", "memcpy"),
            ("len", "strlen"),
            ("chr", "strchr"),
        ] {
            let f = func(&r, routine);
            assert!(f.library.is_some(), "{cpu} {routine}:\n{d}");
            assert_eq!(f.status, Status::Proved, "{cpu} {routine}:\n{d}");
            assert_eq!(rests_on(&r, caller, routine), "PROVED", "{cpu}:\n{d}");
            assert!(func(&r, caller).unconditional, "{cpu} {caller}:\n{d}");
        }
        // A function that calls no library routine rests on none.
        assert!(func(&r, "plain").modulo.is_empty(), "{cpu}:\n{d}");
        // Soft-float arithmetic has no statement here: trusted, and said to be (under
        // whichever of its two names the library gives the code).
        let add = (func(&r, "fadd").modulo.iter())
            .find(|m| m.0 == "__aeabi_fadd" || m.0 == "__addsf3")
            .unwrap_or_else(|| panic!("{cpu}: fadd rests on no addition routine:\n{d}"));
        assert_eq!(add.1, "NOT VERIFIED", "{cpu}:\n{d}");
        assert!(!func(&r, "fadd").unconditional, "{cpu}:\n{d}");
        assert!(
            r.library_trusted.iter().any(|t| t.0 == add.0 && t.1 > 100),
            "{cpu}: {:?}",
            r.library_trusted
        );
        // (The Cortex-M3 shifts and divides in line.)
        if *cpu != "cortex-m0plus" {
            continue;
        }
        // 64-bit shifts are straight-line code: proved.
        for (caller, routine) in [
            ("shl64", "__aeabi_llsl"),
            ("shr64", "__aeabi_llsr"),
            ("sar64", "__aeabi_lasr"),
        ] {
            assert_eq!(func(&r, routine).status, Status::Proved, "{cpu} {routine}:\n{d}");
            assert_eq!(rests_on(&r, caller, routine), "PROVED", "{cpu}:\n{d}");
            assert!(func(&r, caller).unconditional, "{cpu} {caller}:\n{d}");
        }
        // No divide instruction: the division routine is code of the image.  It is not
        // proved (and never a difference): the callers say what they rest on.
        let routine = (func(&r, "udiv").modulo.iter())
            .find(|m| m.0.contains("div"))
            .unwrap_or_else(|| panic!("udiv rests on no division routine:\n{d}"));
        assert_ne!(routine.1, "MISMATCH", "{cpu}:\n{d}");
        assert_eq!(routine.1 == "PROVED", func(&r, "udiv").unconditional, "{cpu}:\n{d}");
    }
    if ran == 0 {
        eprintln!("skipping: no arm-none-eabi-gcc");
    }
}

/// A routine that does not do what its name says is a difference, and exactly the results
/// that rest on it say so.
#[test]
fn wrong_library_routines_are_found() {
    type Case = (
        &'static str,
        &'static [&'static str],
        &'static str,
        &'static str,
        &'static [&'static str],
    );
    // (mini.c flag, bad.S flag, routine, a caller, callers that must stay unconditional)
    let cases: &[Case] = &[
        ("-DMUTANT=1", &[], "memset", "fill", &["copy", "len", "chr", "shl64"]),
        ("-DMUTANT=2", &[], "strlen", "len", &["fill", "copy", "chr"]),
        ("-DMUTANT=3", &[], "memcpy", "copy", &["fill", "len"]),
        (
            "-DMUTANT=0",
            &["-DBAD=1"],
            "__aeabi_llsl",
            "shl64",
            &["shr64", "sar64", "fill"],
        ),
    ];
    let mut ran = 0;
    for cpu in CPUS {
        for (mini, bad, routine, caller, others) in cases {
            // (The Cortex-M3 shifts in line: nothing rests on the routine there.)
            if routine.starts_with("__aeabi") && *cpu != "cortex-m0plus" {
                continue;
            }
            let mut units: Vec<(&str, &[&str])> = vec![("app.c", &[])];
            let mini = [*mini];
            units.push(("mini.c", &mini));
            if !bad.is_empty() {
                units.push(("bad.S", bad));
            }
            let Some(elf) = link(&format!("bad-{routine}"), cpu, &units) else {
                eprintln!("skipping: cannot build for {cpu}");
                continue;
            };
            ran += 1;
            let r = check(&elf, "app.c");
            let d = describe(&r);
            assert!(
                matches!(func(&r, routine).status, Status::Mismatch(_)),
                "{cpu} {routine}:\n{d}"
            );
            assert_eq!(rests_on(&r, caller, routine), "MISMATCH", "{cpu}:\n{d}");
            assert!(!func(&r, caller).unconditional, "{cpu} {caller}:\n{d}");
            assert!(r.has_mismatch(), "{cpu} {routine}:\n{d}");
            for o in *others {
                assert!(func(&r, o).unconditional, "{cpu} {routine}: {o}\n{d}");
            }
        }
        // A division routine that returns the dividend (Cortex-M0+ only: the M3 divides itself).
        if *cpu == "cortex-m0plus"
            && let Some(elf) = link(
                "bad-div",
                cpu,
                &[("app.c", &[]), ("mini.c", &[]), ("bad.S", &["-DBAD=2"])],
            )
        {
            let r = check(&elf, "app.c");
            let d = describe(&r);
            assert!(matches!(func(&r, "__aeabi_uidiv").status, Status::Mismatch(_)), "{d}");
            assert_eq!(rests_on(&r, "udiv", "__aeabi_uidiv"), "MISMATCH", "{d}");
            assert!(func(&r, "fill").unconditional, "{d}");
        }
    }
    if ran == 0 {
        eprintln!("skipping: no arm-none-eabi-gcc");
    }
}

/// A call that reaches its target through a linker stub is a call to the target.
#[test]
fn linker_stubs_are_calls_to_their_targets() {
    let mut ran = 0;
    for cpu in CPUS {
        let Some(elf) = link("far", cpu, &[("far.c", &["-DBUILD"])]) else {
            eprintln!("skipping: cannot build for {cpu}");
            continue;
        };
        ran += 1;
        let r = check(&elf, "far.c");
        let d = describe(&r);
        assert_eq!(r.veneers, 3, "{cpu}:\n{d}");
        for f in [
            "far_add",
            "far_twice",
            "near_mul",
            "use",
            "use2",
            "back",
            "twin",
            "is_twin",
            "via",
        ] {
            assert_eq!(func(&r, f).status, Status::Proved, "{cpu} {f}:\n{d}");
            assert!(func(&r, f).unconditional, "{cpu} {f}:\n{d}");
        }
        // (A call through a stub is bound like a direct one: `far_twice` rests on `far_add`.)
        assert_eq!(rests_on(&r, "far_twice", "far_add"), "PROVED", "{cpu}:\n{d}");
        // Every byte of the stubs is accounted for.
        assert_eq!(r.bin.0, r.bin.1, "{cpu}: {:?}\n{d}", r.bin);
        // The stub of another function is a call to that other function.
        let elf = link("far-m1", cpu, &[("far.c", &["-DBUILD", "-DMUTANT=1"])]).unwrap();
        let r = check(&elf, "far.c");
        assert!(
            matches!(func(&r, "use").status, Status::Mismatch(_)),
            "{cpu}:\n{}",
            describe(&r)
        );
        assert_eq!(func(&r, "use2").status, Status::Proved, "{cpu}:\n{}", describe(&r));
    }
    if ran == 0 {
        eprintln!("skipping: no arm-none-eabi-gcc");
    }
}

/// Start-up code that copies and clears sections: loops in the source and calls to `memcpy`
/// and `memset` in the binary (what -O2 makes of the loops), or the other way round, are the
/// same stores at the addresses the linker fixed.
#[test]
fn startup_loops_and_library_calls_are_the_same() {
    // The binary: (flags of start.c), and how the source is read.
    const LOOPS: &[&str] = &[];
    const TO_CALLS: &[&str] = &["-O2", "-ftree-loop-distribute-patterns"];
    const CALLS: &[&str] = &["-DCALLS"];
    let mut ran = 0;
    for cpu in CPUS {
        for (what, flags, defines) in [
            ("loops, loops", LOOPS, &[][..]),
            ("loops made calls by the compiler", TO_CALLS, &[][..]),
            ("calls in the binary, loops in the source", CALLS, &[][..]),
            ("loops in the binary, calls in the source", LOOPS, &["CALLS"][..]),
            ("calls, calls", CALLS, &["CALLS"][..]),
        ] {
            let build = |tag: &str, mutant: &str| {
                let mut f: Vec<&str> = flags.to_vec();
                f.push(mutant);
                link_with(tag, cpu, &[("start.c", &f), ("mini.c", &[])], "start.ld")
            };
            let Some(elf) = build("start", "-DMUTANT=0") else {
                eprintln!("skipping: cannot build for {cpu}");
                continue;
            };
            ran += 1;
            let r = check_with(&elf, "start.c", defines);
            let d = describe(&r);
            assert_eq!(func(&r, "Reset_Handler").status, Status::Proved, "{cpu}, {what}:\n{d}");
            assert!(!r.has_mismatch(), "{cpu}, {what}:\n{d}");
            for mutant in ["-DMUTANT=1", "-DMUTANT=2"] {
                let elf = build("start-m", mutant).unwrap();
                let r = check_with(&elf, "start.c", defines);
                assert!(
                    matches!(func(&r, "Reset_Handler").status, Status::Mismatch(_)),
                    "{cpu}, {what}, {mutant}:\n{}",
                    describe(&r)
                );
            }
        }
    }
    if ran == 0 {
        eprintln!("skipping: no arm-none-eabi-gcc");
    }
}