cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Benchmark harness: compiles the test corpora with every available toolchain at every
//! optimisation level, verifies them, and prints where the time goes.
//!
//!     cargo run --release --example bench [-- --jobs N] [--quick] [--filter SUBSTR]
//!
//! `--quick` uses one profile per compiler.  Output: totals per configuration, the most
//! expensive functions, and a status histogram.

use cverif::image::Image;
use cverif::verify::{Options, verify};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

const FILES: &[&str] = &[
    "arith.c",
    "control.c",
    "memory.c",
    "calls.c",
    "cfeatures.c",
    "extcalls.c",
    "mutants.c",
    "mutants_c.c",
    "mutants_x.c",
];

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

const GCC_LEVELS: &[&str] = &["-O0", "-O1", "-O2", "-O3", "-Os", "-Og"];
const ALL_LEVELS: &[&str] = &["-Oz", "-Os", "-O0", "-O1", "-O2", "-O3"];

const PROFILES: &[Profile] = &[
    Profile {
        name: "gcc-m3",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m3"],
        levels: GCC_LEVELS,
    },
    Profile {
        name: "clang-m0plus-ropi",
        cc: "clang",
        flags: &[
            "-fomit-frame-pointer",
            "-momit-leaf-frame-pointer",
            "-mcpu=cortex-m0plus",
            "-mthumb",
            "-mno-unaligned-access",
            "--target=armv6m-none-eabi",
            "-fropi",
            "-fno-jump-tables",
        ],
        levels: ALL_LEVELS,
    },
    Profile {
        name: "gcc-m0",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m0"],
        levels: GCC_LEVELS,
    },
    Profile {
        name: "gcc-m4",
        cc: "arm-none-eabi-gcc",
        flags: &["-mthumb", "-mcpu=cortex-m4"],
        levels: GCC_LEVELS,
    },
    Profile {
        name: "clang-m3-rwpi",
        cc: "clang",
        flags: &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb", "-frwpi"],
        levels: ALL_LEVELS,
    },
    Profile {
        name: "clang-m35p-rwpi",
        cc: "clang",
        flags: &[
            "--target=armv8m.main-none-eabi",
            "-mcpu=cortex-m35p+nodsp",
            "-mthumb",
            "-msoft-float",
            "-frwpi",
        ],
        levels: ALL_LEVELS,
    },
];

fn compile(p: &Profile, level: &str, src: &Path, out: &Path) -> bool {
    let inc = src.parent().unwrap().join("include");
    Command::new(p.cc)
        .args(p.flags)
        .args(["-ffreestanding", "-c", level, "-I"])
        .arg(inc)
        .arg(src)
        .arg("-o")
        .arg(out)
        .output()
        .is_ok_and(|o| o.status.success())
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let mut jobs = 0usize;
    let mut quick = false;
    let mut work_limit = u64::MAX;
    let mut time_limit = 4u64;
    let mut filter = String::new();
    let mut it = args.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--jobs" => jobs = it.next().and_then(|v| v.parse().ok()).expect("--jobs N"),
            "--quick" => quick = true,
            "--work-limit" => work_limit = it.next().and_then(|v| v.parse().ok()).expect("--work-limit UNITS"),
            "--time-limit" => time_limit = it.next().and_then(|v| v.parse().ok()).expect("--time-limit SECS"),
            "--filter" => filter = it.next().expect("--filter SUBSTR").clone(),
            other => panic!("unknown argument {other}"),
        }
    }
    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus");
    let tmp: PathBuf = std::env::temp_dir().join(format!("cverif-bench-{}", std::process::id()));
    std::fs::create_dir_all(&tmp).unwrap();
    let opts = Options {
        jobs,
        work_limit,
        time_limit: std::time::Duration::from_secs(time_limit),
        ..Default::default()
    };
    let progs: Vec<_> = FILES
        .iter()
        .map(|f| cverif::c::parse_files(&[root.join(f)], &Default::default()).expect("parse"))
        .collect();

    // (cost ms, description)
    let mut funcs: Vec<(u128, String)> = Vec::new();
    let mut statuses: BTreeMap<&'static str, usize> = BTreeMap::new();
    let mut proved_work: Vec<(u64, String)> = Vec::new();
    let mut by_func: BTreeMap<String, (u128, u64, usize)> = BTreeMap::new();
    let (mut total_cpu, mut total_sat, mut total_conf, mut total_work) = (0u128, 0u64, 0u64, 0u64);
    let t0 = Instant::now();
    let profiles: Vec<&Profile> = if quick {
        PROFILES.iter().take(2).collect()
    } else {
        PROFILES.iter().collect()
    };
    for p in profiles {
        let mut wall = 0u128;
        let mut cpu = 0u128;
        let mut n = 0usize;
        for level in p.levels {
            for (file, prog) in FILES.iter().zip(&progs) {
                let tag = format!("{} {level} {file}", p.name);
                if !tag.contains(&filter) {
                    continue;
                }
                let obj = tmp.join("x.o");
                if !compile(p, level, &root.join(file), &obj) {
                    continue;
                }
                let image = Image::from_elf(&std::fs::read(&obj).unwrap()).expect("load");
                let t = Instant::now();
                let r = verify(prog, &image, &opts);
                wall += t.elapsed().as_millis();
                for f in &r.funcs {
                    cpu += f.millis;
                    n += 1;
                    total_sat += f.sat_calls;
                    total_conf += f.conflicts;
                    total_work += f.work;
                    *statuses.entry(f.status.label()).or_default() += 1;
                    if f.status == cverif::verify::Status::Proved {
                        proved_work.push((f.work, format!("{tag} {} ({} ms)", f.name, f.millis)));
                    }
                    let e = by_func.entry(format!("{file}:{}", f.name)).or_default();
                    e.0 += f.millis;
                    e.1 += f.work;
                    e.2 += 1;
                    funcs.push((
                        f.millis,
                        format!(
                            "{tag} {}: {} paths={} sat={} conflicts={} work={} {}",
                            f.name,
                            f.status.label(),
                            f.paths,
                            f.sat_calls,
                            f.conflicts,
                            f.work,
                            f.status.detail()
                        ),
                    ));
                }
            }
        }
        if n > 0 {
            println!("{:<20} {n:>5} functions  wall {wall:>7} ms  cpu {cpu:>7} ms", p.name);
            total_cpu += cpu;
        }
    }
    let _ = std::fs::remove_dir_all(&tmp);
    funcs.sort_by_key(|a| std::cmp::Reverse(a.0));
    println!("\nmost expensive functions:");
    for (ms, d) in funcs.iter().take(12) {
        println!("{ms:>7} ms  {}", &d[..d.len().min(150)]);
    }
    println!("\nby function, summed over configurations:");
    let mut by_name: Vec<(u128, u64, usize, &str)> = by_func.iter().map(|(n, v)| (v.0, v.1, v.2, n.as_str())).collect();
    by_name.sort_by_key(|a| std::cmp::Reverse(a.0));
    for (ms, work, n, name) in by_name.iter().take(25) {
        println!("{ms:>7} ms  work {work:>9}  {n:>3} runs  {name}");
    }
    println!("\nlargest work among proved functions:");
    proved_work.sort_by_key(|a| std::cmp::Reverse(a.0));
    for (w, d) in proved_work.iter().take(12) {
        println!("{w:>9}  {d}");
    }
    println!("\nstatuses: {statuses:?}");
    println!(
        "total: wall {} ms, cpu {total_cpu} ms, {} functions, {total_sat} SAT calls, {total_conf} conflicts, work {total_work}",
        t0.elapsed().as_millis(),
        funcs.len()
    );
}