cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Function symbols that share an address (`__attribute__((alias))`, linker aliases) are one
//! piece of code: a call is compared by the code it reaches, not by the name at the call site.

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

struct Tc {
    name: &'static str,
    cc: &'static str,
    flags: &'static [&'static str],
}

const TCS: &[Tc] = &[
    Tc {
        name: "gcc-m0p",
        cc: "arm-none-eabi-gcc",
        flags: &["-mcpu=cortex-m0plus", "-mthumb"],
    },
    Tc {
        name: "gcc-m3",
        cc: "arm-none-eabi-gcc",
        flags: &["-mcpu=cortex-m3", "-mthumb"],
    },
    Tc {
        name: "clang-m0p",
        cc: "clang",
        flags: &["--target=armv6m-none-eabi", "-mcpu=cortex-m0plus", "-mthumb"],
    },
];

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

fn run(cmd: &mut Command) -> bool {
    cmd.output().is_ok_and(|o| o.status.success())
}

/// app.c, def.c and lib.c compiled and joined into one relocatable object (built under a
/// name of its own and renamed: tests run in parallel).
fn build(tc: &Tc, level: &str, mutant: u32) -> Option<PathBuf> {
    static SEQ: AtomicUsize = AtomicUsize::new(0);
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("alias");
    std::fs::create_dir_all(&dir).unwrap();
    let tag = format!("{}{level}-m{mutant}", tc.name);
    let uniq = format!("{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed));
    let mut objs = Vec::new();
    for f in ["app.c", "def.c", "lib.c"] {
        let o = dir.join(format!("{tag}-{f}-{uniq}.o"));
        let ok = run(Command::new(tc.cc)
            .args(tc.flags)
            .args(["-ffreestanding", "-c", level])
            .arg(format!("-DMUTANT={mutant}"))
            .arg(corpus(f))
            .arg("-o")
            .arg(&o));
        if !ok {
            return None;
        }
        objs.push(o);
    }
    let part = dir.join(format!("{tag}-{uniq}.part.o"));
    if !run(Command::new("arm-none-eabi-ld")
        .arg("-r")
        .args(&objs)
        .arg("-o")
        .arg(&part))
    {
        return None;
    }
    let out = dir.join(format!("{tag}.o"));
    std::fs::rename(&part, &out).unwrap();
    Some(out)
}

fn check(obj: &Path, modular: bool) -> Report {
    let image = cverif::inputs::load(&std::fs::read(obj).unwrap(), 0, &[], &[], None).unwrap();
    let copts = cverif::c::Options::for_image(&image);
    let prog = cverif::c::parse_files(&[corpus("app.c"), corpus("def.c")], &copts).expect("parse C");
    let opts = Options {
        jobs: 2,
        work_limit: 30_000,
        modular,
        ..Default::default()
    };
    verify(&prog, &image, &opts)
}

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

#[test]
fn aliased_symbols_are_one_function() {
    let mut ran = 0;
    for tc in TCS {
        for level in ["-O0", "-Os", "-O2"] {
            let Some(obj) = build(tc, level, 0) else {
                eprintln!("skipping: {} {level} cannot build", tc.name);
                continue;
            };
            ran += 1;
            for modular in [true, false] {
                let r = check(&obj, modular);
                for f in &r.funcs {
                    assert!(
                        matches!(f.status, Status::Proved),
                        "{} {level} modular={modular}: {} is {:?}",
                        tc.name,
                        f.name,
                        f.status
                    );
                }
                assert!(r.funcs.len() >= 9, "{} {level}: {} functions", tc.name, r.funcs.len());
            }
        }
    }
    if ran == 0 {
        eprintln!("skipping: no ARM toolchain");
    }
}

/// Resolving names to code must not hide a different call or different arguments.
#[test]
fn aliases_do_not_hide_differences() {
    let changed = [(1, "call_pub"), (2, "call_e2"), (3, "call_e2"), (4, "use2")];
    for tc in TCS {
        for level in ["-Os", "-O2"] {
            for (mutant, name) in changed {
                let Some(obj) = build(tc, level, mutant) else {
                    eprintln!("skipping: {} {level} cannot build", tc.name);
                    continue;
                };
                for modular in [true, false] {
                    let r = check(&obj, modular);
                    assert!(
                        matches!(status(&r, name), Status::Mismatch(_)),
                        "{} {level} mutant {mutant} modular={modular}: {name} is {:?}",
                        tc.name,
                        status(&r, name)
                    );
                    for f in r.funcs.iter().filter(|f| f.name != name) {
                        assert!(
                            matches!(f.status, Status::Proved),
                            "{} {level} mutant {mutant} modular={modular}: {} is {:?}",
                            tc.name,
                            f.name,
                            f.status
                        );
                    }
                }
            }
        }
    }
}

/// Identical functions folded by the compiler (one becomes a jump to the other) or by the
/// linker (one copy of the code under both names).
#[test]
fn folded_identical_functions() {
    let src = corpus("folded.c");
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("alias");
    std::fs::create_dir_all(&dir).unwrap();
    let have_lld = run(Command::new("ld.lld").arg("--version"));
    // (toolchain, compiler flags, fold at link time)
    let builds: [(&Tc, &[&str], bool); 4] = [
        (&TCS[0], &["-O2", "-fno-inline"], false),
        (&TCS[1], &["-Os", "-fno-inline"], false),
        (&TCS[2], &["-Os", "-fno-inline", "-ffunction-sections"], false),
        (&TCS[2], &["-Os", "-fno-inline", "-ffunction-sections"], true),
    ];
    for (n, (tc, flags, fold)) in builds.into_iter().enumerate() {
        if fold && !have_lld {
            eprintln!("skipping: no ld.lld");
            continue;
        }
        for mutant in 0..3u32 {
            let uniq = format!("{}-{n}-{mutant}", std::process::id());
            let obj = dir.join(format!("folded-{uniq}.o"));
            let mut cc = Command::new(tc.cc);
            cc.args(tc.flags).args(flags).args(["-ffreestanding", "-c"]);
            cc.arg(format!("-DMUTANT={mutant}"));
            if fold {
                // (What `same` says is not true of an image whose linker folded the two.)
                cc.arg("-DNO_SAME");
            }
            if !run(cc.arg(&src).arg("-o").arg(&obj)) {
                eprintln!("skipping: {} cannot build", tc.name);
                continue;
            }
            let image_path = if fold {
                let ext = dir.join(format!("ext-{uniq}.o"));
                let elf = dir.join(format!("folded-{uniq}.elf"));
                let ok = run(Command::new(tc.cc)
                    .args(tc.flags)
                    .args(["-Os", "-ffreestanding", "-c"])
                    .arg(corpus("ext.c"))
                    .arg("-o")
                    .arg(&ext))
                    && run(Command::new("ld.lld")
                        .args(["--icf=all", "-e", "g1"])
                        .arg(&obj)
                        .arg(&ext)
                        .arg("-o")
                        .arg(&elf));
                if !ok {
                    eprintln!("skipping: ld.lld cannot link for {}", tc.name);
                    continue;
                }
                elf
            } else {
                obj
            };
            let image = cverif::inputs::load(&std::fs::read(&image_path).unwrap(), 0, &[], &[], None).unwrap();
            if fold {
                let at = |n: &str| image.func(n).map(|s| s.addr);
                assert_eq!(at("f1"), at("f2"), "the linker was expected to fold f1 and f2");
            }
            let mut copts = cverif::c::Options::for_image(&image);
            if fold {
                copts.defines.push(("NO_SAME".into(), "1".into()));
            }
            let prog = cverif::c::parse_files(std::slice::from_ref(&src), &copts).expect("parse C");
            for modular in [true, false] {
                let opts = Options {
                    jobs: 2,
                    work_limit: 30_000,
                    modular,
                    ..Default::default()
                };
                let r = verify(&prog, &image, &opts);
                let wrong = match mutant {
                    1 => "g2",
                    2 => "t2",
                    _ => "",
                };
                for f in &r.funcs {
                    let what = format!(
                        "{} {flags:?} fold={fold} mutant {mutant} modular={modular}: {}",
                        tc.name, f.name
                    );
                    if f.name == wrong {
                        assert!(matches!(f.status, Status::Mismatch(_)), "{what} is {:?}", f.status);
                    } else {
                        assert!(matches!(f.status, Status::Proved), "{what} is {:?}", f.status);
                    }
                }
                assert!(r.funcs.len() >= 14, "{} functions", r.funcs.len());
            }
        }
    }
}

/// One run-time routine under two ABI names (`__aeabi_uidiv` and `__aeabi_uidivmod` at one
/// address): callers that use the quotient, the remainder or both are all verified.
#[test]
fn division_routine_with_two_names() {
    let tc = &TCS[0];
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("alias");
    std::fs::create_dir_all(&dir).unwrap();
    let src = corpus("div.c");
    for level in ["-O0", "-Os", "-O2"] {
        for mutant in 0..3u32 {
            let uniq = format!("{}-{level}-{mutant}", std::process::id());
            let (o, lib, obj) = (
                dir.join(format!("div-{uniq}.o")),
                dir.join(format!("divmod-{uniq}.o")),
                dir.join(format!("divall-{uniq}.o")),
            );
            let ok = run(Command::new(tc.cc)
                .args(tc.flags)
                .args(["-ffreestanding", "-c", level])
                .arg(format!("-DMUTANT={mutant}"))
                .arg(&src)
                .arg("-o")
                .arg(&o))
                && run(Command::new(tc.cc)
                    .args(tc.flags)
                    .arg("-c")
                    .arg(corpus("divmod.S"))
                    .arg("-o")
                    .arg(&lib))
                && run(Command::new("arm-none-eabi-ld")
                    .arg("-r")
                    .arg(&o)
                    .arg(&lib)
                    .arg("-o")
                    .arg(&obj));
            if !ok {
                eprintln!("skipping: {} cannot build", tc.name);
                return;
            }
            let image = cverif::inputs::load(&std::fs::read(&obj).unwrap(), 0, &[], &[], None).unwrap();
            assert_eq!(
                image.func("__aeabi_uidiv").map(|s| s.addr),
                image.func("__aeabi_uidivmod").map(|s| s.addr)
            );
            let copts = cverif::c::Options::for_image(&image);
            let prog = cverif::c::parse_files(std::slice::from_ref(&src), &copts).expect("parse C");
            for modular in [true, false] {
                let opts = Options {
                    jobs: 2,
                    work_limit: 30_000,
                    modular,
                    ..Default::default()
                };
                let r = verify(&prog, &image, &opts);
                let wrong = ["", "qr", "sr"][mutant as usize];
                assert_eq!(r.funcs.len(), 5);
                for f in &r.funcs {
                    let what = format!("{level} mutant {mutant} modular={modular}: {}", f.name);
                    if f.name == wrong {
                        assert!(matches!(f.status, Status::Mismatch(_)), "{what} is {:?}", f.status);
                    } else {
                        assert!(matches!(f.status, Status::Proved), "{what} is {:?}", f.status);
                    }
                }
            }
        }
    }
}