cverif 0.1.4

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Callers that rely on the registers a callee leaves alone (gcc's `-fipa-ra`): a function
//! of the same translation unit that does not touch `r0` lets its caller keep a pointer
//! there across the call.  cverif follows every path of the code the call reaches and
//! keeps, after the call, only the registers that code leaves as it found them on all of
//! them.  A binary whose callee clobbers such a register on one path (the callee still
//! correct by itself) must not be proved.
//!
//! 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::sync::atomic::{AtomicU32, Ordering};

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

fn have_gcc() -> bool {
    let ok = Command::new(GCC).arg("--version").output().is_ok();
    if !ok {
        eprintln!("skipping: {GCC} not installed");
    }
    ok
}

/// The source of every binary below.
const SOURCE: &str = r#"
struct s { int a; int b; };
void ext(struct s *p, int w);
__attribute__((noinline)) void touch(struct s *p, int v) {
    if (v > 0)
        p->a = v;
    else
        p->b = v;
}
void g(struct s *p, int v, int w) {
    touch(p, v);
    p->b += w;
}
void h(struct s *p, int v, int w) {
    touch(p, v);
    ext(p, w);
}
"#;

/// The binary gcc makes of `SOURCE` at -O2 keeps `p` in r0 and `w` in r2 across the call to
/// `touch`; the same, written out, with `touch` changed as each mutant says.
const ASM: &str = r#"
    .syntax unified
    .thumb
    .text
    .global touch
    .type touch, %function
    .thumb_func
touch:
    cmp     r1, #0
    ble     1f
    str     r1, [r0]
    bx      lr
1:  str     r1, [r0, #4]
    bx      lr
    .size touch, .-touch
    .global g
    .type g, %function
    .thumb_func
g:
    push    {r3, lr}
    bl      touch
    ldr     r3, [r0, #4]
    add     r3, r3, r2
    str     r3, [r0, #4]
    pop     {r3, pc}
    .size g, .-g
    .global h
    .type h, %function
    .thumb_func
h:
    push    {r3, lr}
    bl      touch
    mov     r1, r2
    pop     {r3, lr}
    b.w     ext
    .size h, .-h
"#;

/// Build an object from `text` (assembly, or C with `lang` "c").
fn build(text: &str, lang: &str, flags: &[&str]) -> Image {
    static SERIAL: AtomicU32 = AtomicU32::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("keeps");
    std::fs::create_dir_all(&dir).unwrap();
    let n = SERIAL.fetch_add(1, Ordering::Relaxed);
    let stem = dir.join(format!("{}-{n}", std::process::id()));
    let (src, obj) = (
        stem.with_extension(if lang == "c" { "c" } else { "s" }),
        stem.with_extension("o"),
    );
    std::fs::write(&src, text).unwrap();
    let out = cc_cache::output(
        Command::new(GCC)
            .args(["-mthumb", "-mcpu=cortex-m4", "-ffreestanding", "-c"])
            .args(flags)
            .arg(&src)
            .arg("-o")
            .arg(&obj),
    )
    .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(&src);
    let _ = std::fs::remove_file(&obj);
    image
}

fn source() -> PathBuf {
    static SERIAL: AtomicU32 = AtomicU32::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("keeps");
    std::fs::create_dir_all(&dir).unwrap();
    let n = SERIAL.fetch_add(1, Ordering::Relaxed);
    let path = dir.join(format!("src-{}-{n}.c", std::process::id()));
    std::fs::write(&path, SOURCE).unwrap();
    path
}

fn check(image: &Image) -> Report {
    let src = source();
    let prog =
        cverif::c::parse_files(std::slice::from_ref(&src), &cverif::c::Options::for_image(image)).expect("parse C");
    let opts = {
        let mut built = Options::default();
        built.work_limit = 30_000;
        built.jobs = 2;
        built
    };
    let r = verify(&prog, image, &opts);
    let _ = std::fs::remove_file(&src);
    r
}

fn describe(r: &Report) -> String {
    r.funcs
        .iter()
        .map(|f| format!("  {} {}: {}\n", f.status.label(), 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!("{name} is not in the report\n{}", describe(r)))
        .status
}

#[test]
fn callers_that_rely_on_registers_a_callee_keeps_are_proved() {
    if !have_gcc() {
        return;
    }
    for image in [build(SOURCE, "c", &["-O2"]), build(ASM, "s", &[])] {
        let r = check(&image);
        for f in ["touch", "g", "h"] {
            assert_eq!(*status(&r, f), Status::Proved, "{f}\n{}", describe(&r));
        }
    }
}

/// (what `touch` has, what the mutant has instead, the callers that must not be proved)
const MUTANTS: &[(&str, &str, &[&str])] = &[
    // r0 moved on one path (touch itself still stores where the source does)
    (
        "1:  str     r1, [r0, #4]",
        "1:  adds    r0, r0, #4\n    str     r1, [r0]",
        &["g"],
    ),
    // r2 clobbered on one path
    (
        "1:  str     r1, [r0, #4]",
        "1:  str     r1, [r0, #4]\n    movs r2, #0",
        &["g", "h"],
    ),
    // r0 clobbered on the other path, after the store
    (
        "    str     r1, [r0]\n",
        "    str     r1, [r0]\n    movs    r0, #1\n",
        &["g"],
    ),
];

#[test]
fn a_caller_relying_on_a_register_the_callee_changes_is_not_proved() {
    if !have_gcc() {
        return;
    }
    for (i, (from, to, callers)) in MUTANTS.iter().enumerate() {
        assert!(ASM.contains(from), "mutant {i}: {from:?} not in the binary");
        let image = build(&ASM.replacen(from, to, 1), "s", &[]);
        let r = check(&image);
        for f in *callers {
            let s = status(&r, f);
            assert!(
                matches!(s, Status::Mismatch(..)),
                "mutant {i}: {f} must be a mismatch\n{}",
                describe(&r)
            );
        }
    }
}