cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Routines written in assembly are compared with their source instruction by instruction
//! (`cverif::thumb::asm`): assembly files given next to the C sources, and `naked` functions
//! made of assembly statements inside C files.  Every mutant of the binary (an instruction
//! changed, dropped, added or moved, a branch or a literal that goes elsewhere, data that
//! differs) must be a MISMATCH.
//!
//! The tests skip themselves when the cross compiler is not installed.

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
}

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

/// Build an object from `text` (assembly, or C with `lang` "c").  Written under a name of
/// its own and read back, so that tests running at the same time do not share files.
fn build(text: &str, lang: &str, flags: &[&str]) -> Image {
    static SERIAL: AtomicU32 = AtomicU32::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("asm_src");
    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 = Command::new(GCC)
        .args(["-mthumb", "-ffreestanding", "-Os", "-c"])
        .args(flags)
        .arg(&src)
        .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(&src);
    let _ = std::fs::remove_file(&obj);
    image
}

fn check(image: &Image, c_sources: &[PathBuf], asm: &[(&str, &str)]) -> Report {
    let prog = cverif::c::parse_files(c_sources, &cverif::c::Options::for_image(image)).expect("parse C");
    let opts = Options {
        work_limit: 30_000,
        jobs: 2,
        asm_sources: asm.iter().map(|(n, t)| (n.to_string(), t.to_string())).collect(),
        ..Default::default()
    };
    verify(&prog, image, &opts)
}

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
}

/// An empty C translation unit, for runs whose sources are all assembly.
fn no_c() -> Vec<PathBuf> {
    vec![corpus("empty.c")]
}

#[test]
fn assembly_files_are_proved_instruction_by_instruction() {
    if !have_gcc() {
        return;
    }
    for (file, cpu, routines) in [
        (
            "routines.s",
            "-mcpu=cortex-m3",
            &["save_ctx", "load_consts", "sum_bytes", "mixed", "system", "startup"][..],
        ),
        (
            "thumb1.s",
            "-mcpu=cortex-m0plus",
            &["save_ctx", "sum_bytes", "startup"][..],
        ),
    ] {
        let text = std::fs::read_to_string(corpus(file)).unwrap();
        let image = build(&text, "s", &[cpu]);
        let r = check(&image, &no_c(), &[(file, &text)]);
        for f in routines {
            assert_eq!(*status(&r, f), Status::Proved, "{file}: {f}\n{}", describe(&r));
        }
        assert!(r.funcs.iter().all(|f| f.assembly), "{}", describe(&r));
        assert_eq!(
            r.bin.0,
            r.bin.1,
            "{file}: every byte is accounted for\n{}",
            describe(&r)
        );
    }
}

/// (routine, text of the source, what the binary has instead)
const MUTANTS: &[(&str, &str, &str)] = &[
    ("save_ctx", "str     r7, [r0, #24]", "str     r6, [r0, #24]"),
    ("save_ctx", "        str     r9, [r0, #32]\n", ""),
    ("save_ctx", "str     r13, [r0, #44]", "str     r13, [r0, #48]"),
    (
        "save_ctx",
        "        str     r5, [r0, #16]\n        str     r6, [r0, #20]\n",
        "        str     r6, [r0, #20]\n        str     r5, [r0, #16]\n",
    ),
    ("save_ctx", "b       save_tail", "b       other_tail"),
    (
        "save_ctx",
        "str     lr, [r0, #8]",
        "str     lr, [r0, #8]\n        adds r0, #1",
    ),
    ("load_consts", "=0x12345678", "=0x12345679"),
    ("load_consts", "ldr     r1, =table", "ldr     r1, =table+4"),
    ("load_consts", "=ext_var+4", "=ext_var"),
    ("load_consts", "ldr     r3, =save_ctx", "ldr     r3, =sum_bytes"),
    ("load_consts", ".word   1, 2, 0xdeadbeef", ".word   1, 3, 0xdeadbeef"),
    ("load_consts", ".asciz  \"hi\"", ".asciz  \"ho\""),
    ("load_consts", "adds    r0, r0, r3", "add     r0, r0, r3"),
    ("sum_bytes", "bne     1b", "beq     1b"),
    ("sum_bytes", "cbz     r1, 2f", "cbz     r1, 1f"),
    ("sum_bytes", "ldrb    r3, [r0], #1", "ldrb    r3, [r0, #1]!"),
    ("sum_bytes", "add     r2, r3", "add     r2, r2"),
    (
        "mixed",
        "it      lt\n        movlt   r0, #10",
        "it      gt\n        movgt   r0, #10",
    ),
    (
        "mixed",
        "moveq   r1, #1\n        movne   r1, #2",
        "moveq   r1, #2\n        movne   r1, #1",
    ),
    ("mixed", "push    {r4-r7, lr}", "push    {r4-r6, lr}"),
    ("mixed", "orr     r0, r0, r4, lsl #3", "orr     r0, r0, r4, lsl #4"),
    ("mixed", "lsr     r6, r4, r5", "asr     r6, r4, r5"),
    ("mixed", "ldrh    r2, [r4, r5, lsl #1]", "ldrh    r2, [r4, r5]"),
    ("mixed", "ldrsb   r2, [r4, #3]", "ldrb    r2, [r4, #3]"),
    ("mixed", "bl      helper\n        blx", "bl      helper2\n        blx"),
    ("mixed", "blx     r4", "blx     r5"),
    ("mixed", "sub     sp, #12", "sub     sp, #16"),
    ("mixed", "udiv    r0, r0, r1", "sdiv    r0, r0, r1"),
    ("system", "cpsid   i", "cpsid   f"),
    ("system", "mrs     r0, primask", "mrs     r0, basepri"),
    ("system", "svc     3", "svc     4"),
    ("system", "        wfi\n", ""),
    ("startup", "ldr     sp, =stack_top", "ldr     sp, =stack_top+4"),
    ("startup", "b       hang", "b       startup"),
    ("startup", ".ascii  \"up\\n\"", ".ascii  \"uq\\n\""),
    ("startup", "adr     r0, message", "adr     r0, hang"),
];

#[test]
fn every_mutant_of_an_assembly_routine_is_a_mismatch() {
    if !have_gcc() {
        return;
    }
    let text = std::fs::read_to_string(corpus("routines.s")).unwrap();
    for (routine, from, to) in MUTANTS {
        assert_eq!(text.matches(from).count(), 1, "`{from}` must be unique in the corpus");
        let image = build(&text.replacen(from, to, 1), "s", &["-mcpu=cortex-m3"]);
        let r = check(&image, &no_c(), &[("routines.s", &text)]);
        assert!(
            matches!(status(&r, routine), Status::Mismatch(_)),
            "`{from}` -> `{to}`: {routine} is not a mismatch\n{}",
            describe(&r)
        );
        // (the other routines are unaffected, but for what moves with the change)
        assert!(r.score() < 100.0);
    }
}

#[test]
fn a_function_written_in_assembly_in_a_c_file() {
    if !have_gcc() {
        return;
    }
    let c = std::fs::read_to_string(corpus("naked.c")).unwrap();
    for cpu in ["-mcpu=cortex-m3", "-mcpu=cortex-m0plus"] {
        let image = build(&c, "c", &[cpu]);
        let r = check(&image, &[corpus("naked.c")], &[]);
        assert_eq!(*status(&r, "save_ctx"), Status::Proved, "{cpu}\n{}", describe(&r));
        // Its C caller is verified as before: the routine is a call to it.
        assert_eq!(*status(&r, "use"), Status::Proved, "{cpu}\n{}", describe(&r));
        for mutant in 1..=6 {
            let image = build(&c, "c", &[cpu, &format!("-DMUTANT={mutant}")]);
            let r = check(&image, &[corpus("naked.c")], &[]);
            assert!(
                matches!(status(&r, "save_ctx"), Status::Mismatch(_)),
                "{cpu} mutant {mutant}\n{}",
                describe(&r)
            );
        }
    }
}

/// A literal load written `ldr rX, [pc, #n]` is the load of the word at Align(pc + 4, 4) + n,
/// which is how the binary's instruction reads.
#[test]
fn literal_loads_written_with_their_offset() {
    if !have_gcc() {
        return;
    }
    let c = std::fs::read_to_string(corpus("litload.c")).unwrap();
    for cpu in ["-march=armv6-m", "-mcpu=cortex-m3"] {
        let image = build(&c, "c", &[cpu]);
        let r = check(&image, &[corpus("litload.c")], &[]);
        for f in ["litload", "litload_odd"] {
            assert_eq!(*status(&r, f), Status::Proved, "{cpu}\n{}", describe(&r));
        }
        for (mutant, f) in [(1, "litload"), (2, "litload"), (3, "litload"), (4, "litload_odd")] {
            let image = build(&c, "c", &[cpu, &format!("-DMUTANT={mutant}")]);
            let r = check(&image, &[corpus("litload.c")], &[]);
            assert!(
                matches!(status(&r, f), Status::Mismatch(_)),
                "{cpu} mutant {mutant}\n{}",
                describe(&r)
            );
        }
    }
}

/// Inline assembly in the middle of C: a statement that never falls through is the end of
/// the path, reached with the operand and the memory the source says; `ldr sp, =symbol` at
/// the start of a naked function switches stacks and the C that follows is verified.
#[test]
fn assembly_statements_inside_c_functions() {
    if !have_gcc() {
        return;
    }
    let c = std::fs::read_to_string(corpus("blocks.c")).unwrap();
    for cpu in ["-mcpu=cortex-m3", "-mcpu=cortex-m0plus"] {
        let image = build(&c, "c", &[cpu]);
        let r = check(&image, &[corpus("blocks.c")], &[]);
        let m3 = cpu.ends_with("m3");
        for f in ["jump", "reset"] {
            if m3 || f == "jump" {
                assert_eq!(*status(&r, f), Status::Proved, "{cpu}: {f}\n{}", describe(&r));
            }
        }
        for (mutant, f, mismatch) in [
            (1, "jump", false),
            (2, "jump", true),
            (3, "jump", true),
            (4, "jump", true),
            (5, "reset", false),
            (6, "reset", true),
            (7, "reset", true),
            (8, "jump", false),
        ] {
            if !m3 && f == "reset" {
                continue;
            }
            let image = build(&c, "c", &[cpu, &format!("-DMUTANT={mutant}")]);
            let r = check(&image, &[corpus("blocks.c")], &[]);
            let s = status(&r, f);
            // (A block that is not in the binary is not found there: unsupported, not proved.)
            let ok = if mismatch {
                matches!(s, Status::Mismatch(_))
            } else {
                matches!(s, Status::Unsupported(_))
            };
            assert!(ok, "{cpu} mutant {mutant}: {f}\n{}", describe(&r));
        }
    }
}

#[test]
fn what_the_front_end_does_not_know_is_unsupported() {
    if !have_gcc() {
        return;
    }
    // An instruction outside the supported set: never equal, never different.
    let text = ".syntax unified\n.cpu cortex-m4\n.thumb\n.text\n.global f\n.type f,%function\n.thumb_func\nf: ldrex r0, [r1]\n bx lr\n";
    let image = build(text, "s", &[]);
    let r = check(&image, &no_c(), &[("f.s", text)]);
    assert!(
        r.funcs
            .iter()
            .all(|f| f.name != "f" || !matches!(f.status, Status::Proved)),
        "{}",
        describe(&r)
    );
}