#[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)
}
fn run(cmd: &mut Command) -> bool {
toolchain::run_or_skip(cmd, "the library tests").is_some()
}
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"));
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}");
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}");
}
assert!(func(&r, "plain").modulo.is_empty(), "{cpu}:\n{d}");
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
);
if *cpu != "cortex-m0plus" {
continue;
}
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}");
}
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");
}
}
#[test]
fn wrong_library_routines_are_found() {
type Case = (
&'static str,
&'static [&'static str],
&'static str,
&'static str,
&'static [&'static str],
);
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 {
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}");
}
}
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");
}
}
#[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}");
}
assert_eq!(rests_on(&r, "far_twice", "far_add"), "PROVED", "{cpu}:\n{d}");
assert_eq!(r.bin.0, r.bin.1, "{cpu}: {:?}\n{d}", r.bin);
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");
}
}
#[test]
fn startup_loops_and_library_calls_are_the_same() {
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");
}
}