cverif 0.0.1

Verifies that compiled machine code faithfully matches its C source
Documentation
//! cverif command-line interface.

use cverif::image::Image;
use cverif::verify::{Options, Report, Status, verify};
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

const USAGE: &str = "\
cverif - prove that compiled machine code matches its C source

USAGE:
    cverif [OPTIONS] <BINARY> <SOURCE>...

ARGS:
    <BINARY>       ELF file with symbols (object or executable), or a raw binary (with --symbols)
    <SOURCE>...    C source files or directories (searched recursively for *.c)

OPTIONS:
    -I <DIR>               Add an include directory
    -D <NAME>[=<VALUE>]    Define a preprocessor macro
    --symbols <FILE>       Symbol table for a raw binary, in `nm` format: address [size] type name
    --base <HEX>           Load address of a raw binary (default 0)
    --lcov <FILE>          Write source coverage as an LCOV tracefile
    --drcov <FILE>         Write binary coverage in drcov format (for disassembler plugins)
    --json <FILE>          Write the full report, with coverage ranges, as JSON
    --static-base <HEX>    Value of r9 for linked code built with -frwpi (data base address)
    --only <FUNCTION>      Verify only this function (may be repeated)
    --max-paths <N>        Maximum number of paths explored per function (default 2000)
    --max-depth <N>        Maximum number of undetermined branches per path (default 40)
    --time-limit <SECS>    Time budget per function (default 60)
    -v, --verbose          List unproved source lines and unmatched binary functions
    -h, --help             Show this help
    -V, --version          Show the version

EXIT STATUS:
    0  no difference found    1  the binary provably differs from the source    2  usage or input error
";

struct Args {
    binary: PathBuf,
    sources: Vec<PathBuf>,
    copts: cverif::c::Options,
    symbols: Option<PathBuf>,
    base: u32,
    static_base: Option<u32>,
    lcov: Option<PathBuf>,
    drcov: Option<PathBuf>,
    json: Option<PathBuf>,
    opts: Options,
    verbose: bool,
}

fn parse_args() -> Result<Option<Args>, String> {
    let mut it = std::env::args().skip(1);
    let mut pos: Vec<PathBuf> = Vec::new();
    let mut a = Args {
        binary: PathBuf::new(),
        sources: Vec::new(),
        copts: Default::default(),
        symbols: None,
        base: 0,
        static_base: None,
        lcov: None,
        drcov: None,
        json: None,
        opts: Options::default(),
        verbose: false,
    };
    let num = |s: Option<String>, what: &str| -> Result<u64, String> {
        s.and_then(|v| v.parse().ok())
            .ok_or_else(|| format!("{what} needs a number"))
    };
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "-h" | "--help" => {
                print!("{USAGE}");
                return Ok(None);
            }
            "-V" | "--version" => {
                println!("cverif {}", env!("CARGO_PKG_VERSION"));
                return Ok(None);
            }
            "-v" | "--verbose" => a.verbose = true,
            "--symbols" => a.symbols = Some(it.next().ok_or("--symbols needs a file")?.into()),
            "--lcov" => a.lcov = Some(it.next().ok_or("--lcov needs a file name")?.into()),
            "--drcov" => a.drcov = Some(it.next().ok_or("--drcov needs a file name")?.into()),
            "--json" => a.json = Some(it.next().ok_or("--json needs a file name")?.into()),
            "--static-base" => {
                let v = it.next().ok_or("--static-base needs an address")?;
                a.static_base = Some(
                    u32::from_str_radix(v.trim_start_matches("0x"), 16)
                        .map_err(|_| "--static-base needs a hex address")?,
                );
            }
            "--base" => {
                let v = it.next().ok_or("--base needs an address")?;
                a.base =
                    u32::from_str_radix(v.trim_start_matches("0x"), 16).map_err(|_| "--base needs a hex address")?;
            }
            "--only" => a.opts.only.push(it.next().ok_or("--only needs a function name")?),
            "--max-paths" => a.opts.limits.max_paths = num(it.next(), "--max-paths")? as usize,
            "--max-depth" => a.opts.limits.max_depth = num(it.next(), "--max-depth")? as usize,
            "--time-limit" => a.opts.time_limit = Duration::from_secs(num(it.next(), "--time-limit")?),
            "-I" => a
                .copts
                .include_dirs
                .push(it.next().ok_or("-I needs a directory")?.into()),
            "-D" => {
                let d = it.next().ok_or("-D needs a macro")?;
                a.copts.defines.push(split_define(&d));
            }
            s if s.starts_with("-I") => a.copts.include_dirs.push(s[2..].into()),
            s if s.starts_with("-D") => a.copts.defines.push(split_define(&s[2..])),
            s if s.starts_with('-') => return Err(format!("unknown option {s}")),
            _ => pos.push(arg.into()),
        }
    }
    if pos.len() < 2 {
        return Err("expected a binary and at least one source file or directory".into());
    }
    a.binary = pos.remove(0);
    a.sources = pos;
    Ok(Some(a))
}

fn split_define(d: &str) -> (String, String) {
    match d.split_once('=') {
        Some((k, v)) => (k.to_string(), v.to_string()),
        None => (d.to_string(), "1".to_string()),
    }
}

fn run(a: Args) -> Result<ExitCode, String> {
    let bytes = std::fs::read(&a.binary).map_err(|e| format!("{}: {e}", a.binary.display()))?;
    let image = if Image::is_elf(&bytes) {
        Image::from_elf(&bytes).map_err(|e| format!("{}: {e}", a.binary.display()))?
    } else {
        let Some(st) = &a.symbols else {
            return Err(format!(
                "{} is not an ELF file; a raw binary needs --symbols",
                a.binary.display()
            ));
        };
        let text = std::fs::read_to_string(st).map_err(|e| format!("{}: {e}", st.display()))?;
        Image::from_raw(&bytes, a.base, &text)?
    };
    let mut image = image;
    if a.static_base.is_some() {
        image.static_base = a.static_base;
    }
    let mut files = Vec::new();
    for s in &a.sources {
        files.extend(cverif::c::collect_sources(s).map_err(|e| format!("{}: {e}", s.display()))?);
    }
    if files.is_empty() {
        return Err("no C source files found".into());
    }
    let prog = cverif::c::parse_files(&files, &a.copts)?;
    let report = verify(&prog, &image, &a.opts);
    print_report(&report, &image, a.verbose);
    let bin_name = a.binary.display().to_string();
    let write = |path: &Option<PathBuf>, data: Vec<u8>| -> Result<(), String> {
        match path {
            Some(p) => std::fs::write(p, data).map_err(|e| format!("{}: {e}", p.display())),
            None => Ok(()),
        }
    };
    write(&a.lcov, cverif::report::lcov(&report).into_bytes())?;
    write(&a.drcov, cverif::report::drcov(&report, &image, &bin_name))?;
    write(&a.json, cverif::report::json(&report, &image, &bin_name).into_bytes())?;
    Ok(if report.has_mismatch() {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

fn print_report(r: &Report, image: &Image, verbose: bool) {
    let width = r.funcs.iter().map(|f| f.name.len()).max().unwrap_or(8);
    for f in &r.funcs {
        let mut line = format!(
            "{:<12} {:<width$}  {:>5} bytes  {:>4} paths  {:>6} ms",
            f.status.label(),
            f.name,
            f.size,
            f.paths,
            f.millis
        );
        if !f.status.detail().is_empty() {
            line.push_str(&format!("  {}", f.status.detail()));
        }
        println!("{line}");
    }
    for d in &r.data_issues {
        println!("{:<12} {d}", "DATA");
    }
    let count = |p: fn(&Status) -> bool| r.funcs.iter().filter(|f| p(&f.status)).count();
    println!();
    println!(
        "functions:       {} proved, {} bounded, {} mismatched, {} inconclusive, {} unsupported",
        count(|s| matches!(s, Status::Proved)),
        count(|s| matches!(s, Status::Bounded(_))),
        count(|s| matches!(s, Status::Mismatch(_))),
        count(|s| matches!(s, Status::Inconclusive(_))),
        count(|s| matches!(s, Status::Unsupported(_))),
    );
    println!(
        "source coverage: {:5.1}%  ({} of {} statements and branches proved)",
        100.0 * r.src_coverage(),
        r.src.0,
        r.src.1
    );
    println!(
        "binary coverage: {:5.1}%  ({} of {} code bytes proved)",
        100.0 * r.bin_coverage(),
        r.bin.0,
        r.bin.1
    );
    println!(
        "initialised data: {} objects compared, {} differ",
        r.data_checked,
        r.data_issues.len()
    );
    let flags = cverif::detect::detect(image);
    if let Some(c) = &flags.compiler {
        println!("compiler:        {c}");
    }
    if let Some(d) = &flags.declared {
        println!("declared flags:  {d}");
    }
    if !flags.candidates.is_empty() {
        let best = flags.candidates[0].1;
        let c: Vec<String> = flags
            .candidates
            .iter()
            .filter(|c| c.1 >= best - 0.15)
            .map(|(l, s)| format!("{l} ({:.0}%)", s * 100.0))
            .collect();
        println!("optimisation:    {}", c.join(", "));
    }
    println!("score:           {:.1} / 100", r.score());
    println!(
        "verdict:         {}",
        if r.has_mismatch() {
            "MISMATCH - the binary does not match the source"
        } else {
            "no difference found"
        }
    );
    if verbose {
        for e in &flags.evidence {
            println!("  flag evidence: {e}");
        }
        for (n, s) in &r.unmatched {
            println!("  unmatched binary function: {n} ({s} bytes)");
        }
        for n in &r.absent {
            println!("  source function not found in binary: {n}");
        }
        for (f, l) in &r.uncovered_lines {
            println!("  unproved source line: {f}:{l}");
        }
    }
}

fn main() -> ExitCode {
    let args = match parse_args() {
        Ok(Some(a)) => a,
        Ok(None) => return ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("cverif: {e}\n\n{USAGE}");
            return ExitCode::from(2);
        }
    };
    // Term construction and evaluation recurse deeply on long paths.
    let worker = std::thread::Builder::new()
        .stack_size(512 << 20)
        .spawn(move || run(args))
        .expect("spawn worker thread");
    match worker.join() {
        Ok(Ok(code)) => code,
        Ok(Err(e)) => {
            eprintln!("cverif: {e}");
            ExitCode::from(2)
        }
        Err(_) => {
            eprintln!("cverif: internal error");
            ExitCode::from(2)
        }
    }
}