use cverif::image::Image;
use cverif::verify::{Options, Report, Status, verify};
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
macro_rules! println {
($($t:tt)*) => {{
use std::io::Write;
let _ = writeln!(std::io::stdout(), $($t)*);
}};
}
macro_rules! print {
($($t:tt)*) => {{
use std::io::Write;
let _ = write!(std::io::stdout(), $($t)*);
}};
}
const USAGE: &str = "\
cverif - prove that compiled machine code matches its C source
USAGE:
cverif [OPTIONS] <BINARY> <SOURCE>...
cverif --compare [OPTIONS] <OLD-BINARY> <NEW-BINARY> [<SOURCE>...]
ARGS:
<BINARY> ELF file with symbols (object or executable), or a raw binary, Intel HEX or
S-record image (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 non-ELF image: `nm` output (any format) or a GNU ld
link map; may be repeated (a map also names the object files)
--base <HEX> Load address of a raw binary (default 0)
--load <FILE>@<HEX> A further memory image (raw at the address, HEX or S-record); may be repeated
--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
-fshort-enums Enumerated types take the smallest type that fits
-fno-short-enums Enumerated types are at least int (default: what the ELF records)
--mmio <HEX>-<HEX> Peripheral address range, where the binary may access memory only as the
source does (may be repeated; replaces the default 40000000-5fffffff
and e0000000-ffffffff)
--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> Wall-clock safety net per function (default 300)
--work-limit <UNITS> Effort budget per function, in terms built plus thousands of
solver propagations: same result on any machine (default 500000)
--timeout <SECS> Stop everything after this long; unfinished functions are BOUNDED
-j, --jobs <N> Verify N functions in parallel (default: one per CPU)
-v, --verbose List unproved source lines (with their text), unproved machine code
(disassembled) and unmatched binary functions
--explain[=FUNCTION] Explain every function that is not PROVED (or the one named): what was
compared, the path, both symbolic values and where they differ, the
counterexample with the value of each side
--dump <FUNCTION> Verify only this function and print, for every path, what the source
and the machine code compute (may be repeated)
--dump-all The same for every function
--dump-binary <WHAT> Disassemble machine code and summarise it symbolically on its own;
WHAT is a symbol, an address or START-END (hex). Needs no source.
--full Do not shorten the symbolic values and lists of the three above
--list-unsupported Summarise why functions are unsupported, grouped by reason
-U <NAME> Undefine a preprocessor macro
-include <FILE> Process a file before each source file
--explain-flags Show the evidence behind every detected compiler flag
--compare Compare two binaries with each other: is the new machine code
observably equivalent to the old? With sources, both are first
verified against the source (three-way)
--old-<OPT>, --new-<OPT>
In --compare mode, --symbols, --map, --base, --load and --static-base
for one of the two binaries only (unprefixed: for both)
--assume <NAME> Rely on an assumption in --compare mode: sp-aligned, ret32 (on by
--no-assume <NAME> default), ext-arity, void-r0 (off by default); the report lists them.
--explain adds, for each difference, both values as expressions
and the code of both versions
-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: Vec<PathBuf>,
loads: Vec<(PathBuf, u32)>,
base: u32,
static_base: Option<u32>,
lcov: Option<PathBuf>,
drcov: Option<PathBuf>,
json: Option<PathBuf>,
opts: Options,
verbose: bool,
explain_flags: bool,
list_unsupported: bool,
compare: bool,
sides: [Side; 2],
assume: cverif::bindiff::Assumptions,
explain: Option<Vec<String>>,
dump: Vec<String>,
dump_all: bool,
dump_binary: Vec<String>,
full: bool,
}
#[derive(Default)]
struct Side {
symbols: Vec<PathBuf>,
loads: Vec<(PathBuf, u32)>,
base: Option<u32>,
static_base: Option<u32>,
}
fn hex_arg(v: Option<String>, what: &str) -> Result<u32, String> {
v.and_then(|v| u32::from_str_radix(v.trim_start_matches("0x"), 16).ok())
.ok_or_else(|| format!("{what} needs a hex address"))
}
fn load_arg(v: Option<String>, what: &str) -> Result<(PathBuf, u32), String> {
let v = v.ok_or_else(|| format!("{what} needs file@address"))?;
Ok(match v.rsplit_once('@') {
Some((f, x)) => (
f.into(),
u32::from_str_radix(x.trim_start_matches("0x"), 16)
.map_err(|_| format!("{what} needs file@address with a hex address"))?,
),
None => (v.into(), 0),
})
}
fn parse_args() -> Result<Option<Args>, String> {
let mut it = std::env::args().skip(1).peekable();
let mut pos: Vec<PathBuf> = Vec::new();
let mut a = Args {
binary: PathBuf::new(),
sources: Vec::new(),
copts: Default::default(),
symbols: Vec::new(),
loads: Vec::new(),
base: 0,
static_base: None,
lcov: None,
drcov: None,
json: None,
opts: Options::default(),
verbose: false,
explain_flags: false,
list_unsupported: false,
compare: false,
sides: Default::default(),
assume: Default::default(),
explain: None,
dump: Vec::new(),
dump_all: false,
dump_binary: Vec::new(),
full: 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"))
};
let mut mmio_given = false;
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" | "--map" => a.symbols.push(it.next().ok_or("--symbols needs a file")?.into()),
"--load" => {
let v = it.next().ok_or("--load needs file@address")?;
let (file, addr) = match v.rsplit_once('@') {
Some((f, x)) => (
f,
u32::from_str_radix(x.trim_start_matches("0x"), 16)
.map_err(|_| "--load needs file@address with a hex address")?,
),
None => (v.as_str(), 0),
};
a.loads.push((file.into(), addr));
}
"--explain-flags" => a.explain_flags = true,
"--compare" => a.compare = true,
"--assume" => a.assume.set(&it.next().ok_or("--assume needs a name")?, true)?,
"--no-assume" => a.assume.set(&it.next().ok_or("--no-assume needs a name")?, false)?,
s if s.starts_with("--old-") || s.starts_with("--new-") => {
let side = &mut a.sides[s.starts_with("--new-") as usize];
match &s[6..] {
"symbols" | "map" => side
.symbols
.push(it.next().ok_or_else(|| format!("{s} needs a file"))?.into()),
"base" => side.base = Some(hex_arg(it.next(), s)?),
"static-base" => side.static_base = Some(hex_arg(it.next(), s)?),
"load" => side.loads.push(load_arg(it.next(), s)?),
_ => return Err(format!("unknown option {s}")),
}
}
"--explain" => {
let names = a.explain.get_or_insert_with(Vec::new);
if let Some(n) = it.next_if(|n| !n.starts_with('-') && !std::path::Path::new(n).exists()) {
names.push(n);
}
}
s if s.starts_with("--explain=") => a
.explain
.get_or_insert_with(Vec::new)
.push(s["--explain=".len()..].to_string()),
"--dump" => a.dump.push(it.next().ok_or("--dump needs a function name")?),
"--dump-all" => a.dump_all = true,
"--dump-binary" => a
.dump_binary
.push(it.next().ok_or("--dump-binary needs a symbol or an address")?),
"--full" => a.full = true,
"--list-unsupported" => a.list_unsupported = true,
"--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")?,
);
}
"--mmio" => {
let v = it.next().ok_or("--mmio needs a range")?;
let hex = |s: &str| u32::from_str_radix(s.trim_start_matches("0x"), 16).ok();
let range = v
.split_once('-')
.and_then(|(lo, hi)| Some((hex(lo)?, hex(hi)?)))
.filter(|(lo, hi)| lo <= hi)
.ok_or("--mmio needs a range of hex addresses: START-END")?;
if !mmio_given {
a.opts.mmio.clear();
mmio_given = true;
}
a.opts.mmio.push(range);
}
"--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,
"--work-limit" => a.opts.work_limit = num(it.next(), "--work-limit")?,
"--timeout" => {
a.opts.deadline = Some(std::time::Instant::now() + Duration::from_secs(num(it.next(), "--timeout")?))
}
"-j" | "--jobs" => a.opts.jobs = num(it.next(), "--jobs")? 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));
}
"-fshort-enums" => a.copts.short_enums = Some(true),
"-fno-short-enums" => a.copts.short_enums = Some(false),
"-U" => a.copts.undefines.push(it.next().ok_or("-U needs a macro name")?),
"-include" => a
.copts
.forced_includes
.push(it.next().ok_or("-include needs a file")?.into()),
s if s.starts_with("-I") => a.copts.include_dirs.push(s[2..].into()),
s if s.starts_with("-U") => a.copts.undefines.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() == 1 && !a.dump_binary.is_empty() {
a.binary = pos.remove(0);
return Ok(Some(a));
}
if a.compare {
if pos.len() < 2 {
return Err("--compare expects two binaries".into());
}
} else 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_compare(a: Args) -> Result<ExitCode, String> {
let paths = [a.binary.clone(), a.sources[0].clone()];
let mut images = Vec::new();
for (path, side) in paths.iter().zip(&a.sides) {
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mut extra = Vec::new();
for (p, addr) in a.loads.iter().chain(&side.loads) {
extra.push((std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?, *addr));
}
let mut symtabs = Vec::new();
for p in a.symbols.iter().chain(&side.symbols) {
symtabs.push(std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?);
}
let image = cverif::inputs::load(
&bytes,
side.base.unwrap_or(a.base),
&extra,
&symtabs,
side.static_base.or(a.static_base),
)
.map_err(|e| format!("{}: {e}", path.display()))?;
images.push(image);
}
let mut files = Vec::new();
for s in &a.sources[1..] {
files.extend(cverif::c::collect_sources(s).map_err(|e| format!("{}: {e}", s.display()))?);
}
let mut progs = Vec::new();
if !files.is_empty() {
for image in &images {
let mut copts = a.copts.clone();
if copts.short_enums.is_none() {
copts.short_enums = image.short_enums;
}
progs.push(cverif::c::parse_files(&files, &copts)?);
}
} else if a.sources.len() > 1 {
return Err("no C source files found".into());
}
let opts = cverif::bindiff::Options {
verify: a.opts.clone(),
assume: a.assume.clone(),
explain: a.explain.is_some(),
};
let src = (!progs.is_empty()).then(|| (&progs[0], &progs[1]));
let cmp = cverif::bindiff::compare(&images[0], &images[1], src, &opts);
print!("{}", cmp.render());
if let Some(p) = &a.json {
let (old, new) = (paths[0].display().to_string(), paths[1].display().to_string());
std::fs::write(p, cmp.json(&old, &new)).map_err(|e| format!("{}: {e}", p.display()))?;
}
Ok(if cmp.differs() || cmp.may_differ() {
ExitCode::from(1)
} else {
ExitCode::SUCCESS
})
}
fn run(mut a: Args) -> Result<ExitCode, String> {
if a.compare {
return run_compare(a);
}
let bytes = std::fs::read(&a.binary).map_err(|e| format!("{}: {e}", a.binary.display()))?;
let mut extra = Vec::new();
for (p, addr) in &a.loads {
extra.push((std::fs::read(p).map_err(|e| format!("{}: {e}", p.display()))?, *addr));
}
let mut symtabs = Vec::new();
for p in &a.symbols {
symtabs.push(std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?);
}
let image = cverif::inputs::load(&bytes, a.base, &extra, &symtabs, a.static_base)
.map_err(|e| format!("{}: {e}", a.binary.display()))?;
let style = if a.full {
cverif::explain::Style::full()
} else {
cverif::explain::Style::default()
};
for spec in &a.dump_binary {
let mut budget = cverif::explain::binary::Budget::default();
if a.full {
budget.max_paths = a.opts.limits.max_paths;
}
print!(
"{}",
cverif::explain::binary::dump_binary(&image, spec, style, &budget)?
);
}
if a.sources.is_empty() {
return Ok(ExitCode::SUCCESS);
}
if a.dump_all || !a.dump.is_empty() {
a.opts.dump = if a.full { usize::MAX } else { 32 };
if !a.dump_all {
a.opts.only.extend(a.dump.iter().cloned());
}
}
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 mut copts = a.copts.clone();
if copts.short_enums.is_none() {
copts.short_enums = image.short_enums;
}
let prog = cverif::c::parse_files(&files, &copts)?;
let report = verify(&prog, &image, &a.opts);
print_report(&report, &image, a.verbose, a.explain_flags);
print_details(&report, &image, &prog, &a, style);
if a.list_unsupported {
list_unsupported(&report);
}
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 list_unsupported(r: &Report) {
let mut groups: Vec<(String, Vec<&str>)> = Vec::new();
for f in &r.funcs {
let Status::Unsupported(why) = &f.status else { continue };
let mut key = why.as_str();
if key.ends_with(')')
&& let Some(i) = key.rfind(" (")
&& key[i..].contains(':')
{
key = &key[..i];
}
let key = match key.strip_prefix("calls ") {
Some(rest) => match rest.split_once(": ") {
Some((_, inner)) => format!("calls a function that is unsupported: {inner}"),
None => key.to_string(),
},
None => key.to_string(),
};
match groups.iter_mut().find(|g| g.0 == key) {
Some(g) => g.1.push(&f.name),
None => groups.push((key, vec![&f.name])),
}
}
groups.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(&b.0)));
println!();
println!(
"unsupported: {} functions, {} distinct reasons",
groups.iter().map(|g| g.1.len()).sum::<usize>(),
groups.len()
);
for (why, names) in &groups {
let shown: Vec<&str> = names.iter().copied().take(4).collect();
let more = if names.len() > shown.len() { ", ..." } else { "" };
println!(" {:>4} {why} [{}{more}]", names.len(), shown.join(", "));
}
}
fn print_report(r: &Report, image: &Image, verbose: bool, explain_flags: 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
);
let objects = cverif::report::object_coverage(r, image);
if objects.len() > 1 {
let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string();
let w = objects
.iter()
.map(|o| short(&o.0).len().max(9))
.max()
.unwrap_or(9)
.min(60);
for (name, proved, total) in &objects {
let name = if name.is_empty() {
"(unknown)".to_string()
} else {
short(name)
};
println!(
" {name:<w$} {:5.1}% ({proved} of {total})",
100.0 * *proved as f64 / (*total).max(1) as f64
);
}
}
println!(
"initialised data: {} objects compared, {} differ",
r.data_checked,
r.data_issues.len()
);
let flags = cverif::detect::detect(image);
print!("{}", flags.render(explain_flags));
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 && !explain_flags {
for e in &flags.evidence {
println!(" flag evidence: {e}");
}
}
if verbose {
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}");
}
}
}
fn print_details(r: &Report, image: &Image, prog: &cverif::c::ast::Program, a: &Args, style: cverif::explain::Style) {
let names = cverif::explain::Names::new(image, Some(prog));
if a.opts.dump > 0 {
for f in &r.funcs {
let Some(d) = f.detail.as_ref().filter(|d| !d.paths.is_empty() || d.skipped_paths > 0) else {
continue;
};
println!();
println!("== {} at {:#x}: {} ==", f.name, f.addr, f.status.label());
print!("{}", d.dump_text(&names, style));
}
}
if let Some(only) = &a.explain {
for f in &r.funcs {
if f.status == Status::Proved || !(only.is_empty() || only.contains(&f.name)) {
continue;
}
println!();
println!("== {} {}: {} ==", f.status.label(), f.name, f.status.detail());
match f.detail.as_ref().and_then(|d| d.explanation.as_ref()) {
Some(e) => print!("{}", e.text(&names, style)),
None => println!(" (nothing was compared: the function was not verified)"),
}
}
for n in only {
if !r.funcs.iter().any(|f| f.name == *n) {
println!();
println!("== {n}: not a verified function ==");
}
}
}
if !(a.verbose || a.explain.is_some()) {
return;
}
let mut texts: std::collections::HashMap<&str, Vec<String>> = std::collections::HashMap::new();
for (f, l) in &r.uncovered_lines {
let lines = texts.entry(f.as_str()).or_insert_with(|| {
std::fs::read_to_string(f)
.map(|t| t.lines().map(|l| l.to_string()).collect())
.unwrap_or_default()
});
match lines.get((*l as usize).wrapping_sub(1)) {
Some(t) => println!(" unproved source line: {f}:{l}: {}", t.trim()),
None => println!(" unproved source line: {f}:{l}"),
}
}
let limit = if a.full { usize::MAX } else { 24 };
let unproved: Vec<_> = r
.bin_ranges
.iter()
.filter(|b| b.state == cverif::verify::ByteState::Unproved)
.collect();
for b in unproved.iter().take(limit) {
let at = match names.locate(b.start) {
Some(s) => format!(" <{s}>"),
None => String::new(),
};
println!();
println!(
" unproved machine code {:#x}-{:#x}{at} ({} bytes):",
b.start,
b.end,
b.end - b.start
);
let text = cverif::explain::binary::listing(image, &names, b.start, b.end);
for l in text.lines() {
println!(" {l}");
}
if let Some(s) = image
.func_at(b.start)
.filter(|s| s.addr == b.start && s.addr + s.size <= b.end + 4)
{
let budget = cverif::explain::binary::Budget {
max_paths: if a.full { 64 } else { 6 },
work_limit: 50_000,
time_limit: std::time::Duration::from_secs(5),
..Default::default()
};
let end = s.addr + s.size.max(2);
let text = cverif::explain::binary::summary_text(image, &names, s.addr, end, style, &budget);
for l in text.lines() {
println!(" {l}");
}
}
}
if unproved.len() > limit {
println!(" ... {} more unproved ranges (--full)", unproved.len() - limit);
}
}
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);
}
};
let worker = std::thread::Builder::new()
.stack_size(64 << 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)
}
}
}