use crate::c::ast::{Program, Type, VOID};
use crate::c::exec::{CEnv, CExec};
use crate::image::{Image, SymKind};
use crate::sym::{ArgLoc, Ctx, Event, Limits, R, Stop, WordLoc, Write, arg_locs, arg_words};
use crate::term::{Env, T};
use crate::thumb::exec::{Callee, Exit, Machine, image_init};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};
#[derive(Clone, Debug)]
pub struct Options {
pub limits: Limits,
pub only: Vec<String>,
pub time_limit: Duration,
}
impl Default for Options {
fn default() -> Self {
Options {
limits: Limits::default(),
only: Vec::new(),
time_limit: Duration::from_secs(60),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
Proved,
Bounded(String),
Mismatch(String),
Inconclusive(String),
Unsupported(String),
}
impl Status {
pub fn label(&self) -> &'static str {
match self {
Status::Proved => "PROVED",
Status::Bounded(_) => "BOUNDED",
Status::Mismatch(_) => "MISMATCH",
Status::Inconclusive(_) => "INCONCLUSIVE",
Status::Unsupported(_) => "UNSUPPORTED",
}
}
pub fn detail(&self) -> &str {
match self {
Status::Proved => "",
Status::Bounded(s) | Status::Mismatch(s) | Status::Inconclusive(s) | Status::Unsupported(s) => s,
}
}
}
#[derive(Clone, Debug)]
pub struct FuncReport {
pub name: String,
pub addr: u32,
pub size: u32,
pub status: Status,
pub paths: usize,
pub undefined_paths: usize,
pub millis: u128,
}
#[derive(Clone, Debug, Default)]
pub struct Report {
pub funcs: Vec<FuncReport>,
pub src: (usize, usize),
pub bin: (usize, usize),
pub unmatched: Vec<(String, u32)>,
pub absent: Vec<String>,
pub data_issues: Vec<String>,
pub data_checked: usize,
pub uncovered_lines: Vec<(String, u32)>,
pub src_points: Vec<SrcPoint>,
pub bin_ranges: Vec<BinRange>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SrcPoint {
pub file: String,
pub line: u32,
pub func: String,
pub proved: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ByteState {
Proved,
Unproved,
Padding,
}
impl ByteState {
pub fn label(self) -> &'static str {
match self {
ByteState::Proved => "proved",
ByteState::Unproved => "unproved",
ByteState::Padding => "padding",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BinRange {
pub start: u32,
pub end: u32,
pub state: ByteState,
}
impl Report {
pub fn src_coverage(&self) -> f64 {
if self.src.1 == 0 {
0.0
} else {
self.src.0 as f64 / self.src.1 as f64
}
}
pub fn bin_coverage(&self) -> f64 {
if self.bin.1 == 0 {
0.0
} else {
self.bin.0 as f64 / self.bin.1 as f64
}
}
pub fn has_mismatch(&self) -> bool {
!self.data_issues.is_empty() || self.funcs.iter().any(|f| matches!(f.status, Status::Mismatch(_)))
}
pub fn score(&self) -> f64 {
if self.has_mismatch() {
return 0.0;
}
50.0 * (self.src_coverage() + self.bin_coverage())
}
}
fn base_name(name: &str) -> &str {
match name.find('.') {
Some(i) if i > 0 => &name[..i],
_ => name,
}
}
struct PathResult {
cov: Vec<u32>,
insns: Vec<(u32, u8)>,
data: Vec<(u32, u8)>,
}
struct Job<'a> {
prog: &'a Program,
image: &'a Image,
env: &'a CEnv<'a>,
fid: u32,
entry: u32,
regs: [T; 16],
args: Vec<T>,
stack_args: Vec<(u32, T)>,
struct_args: Vec<(T, Vec<T>)>,
ret_slot: Option<T>,
lr0: T,
}
fn witness(ctx: &Ctx, env: &Env) -> String {
let mut items: Vec<(String, u64)> = env
.syms
.iter()
.map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
.filter(|(n, _)| {
let b = n.as_bytes();
(b.len() == 2 && b[0] == b'r' && b[1] <= b'3') || n.starts_with("stk") || n.starts_with("ret")
})
.collect();
items.sort();
let mut parts: Vec<String> = items.iter().map(|(n, v)| format!("{n}={v:#x}")).collect();
let mut mem: Vec<(u64, u8)> = env
.mem
.iter()
.filter(|((m, _), _)| *m < 0x8000_0000)
.map(|((_, a), v)| (*a, *v))
.collect();
mem.sort();
for (a, v) in mem.iter().take(8) {
parts.push(format!("mem[{a:#x}]={v:#04x}"));
}
if parts.is_empty() {
"any input".into()
} else {
parts.join(" ")
}
}
fn prove_eq(ctx: &mut Ctx, c: T, b: T, what: &str) -> R<()> {
if c == b {
return Ok(());
}
let e = ctx.tm.eq(c, b);
match ctx.check(e) {
Ok(()) => Ok(()),
Err(Some(env)) => {
if ctx.mentions_unspecified(c) || ctx.mentions_unspecified(b) {
return Err(Stop::Unsupported(format!(
"{what}: depends on the unspecified magnitude of a string comparison result"
)));
}
if ctx.mentions_private(c) || ctx.mentions_private(b) {
return Err(Stop::Unsupported(format!(
"{what}: the address of a local object escapes"
)));
}
let mut memo = Default::default();
let (cv, bv) = (ctx.tm.eval(c, &env, &mut memo), ctx.tm.eval(b, &env, &mut memo));
Err(Stop::Mismatch(
format!(
"{what}: source gives {cv:#x}, binary gives {bv:#x} for {}",
witness(ctx, &env)
),
Some(env),
))
}
Err(None) => {
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!(
"inconclusive {what}:\n source: {}\n binary: {}",
ctx.tm.show(c),
ctx.tm.show(b)
);
}
Err(Stop::Inconclusive(format!("{what}: prover gave up")))
}
}
}
fn compare_world(ctx: &mut Ctx, job: &Job, c_log: &[Write], c_epoch: u32, m: &Machine, what: &str) -> R<()> {
let mut seen: HashSet<(T, u8)> = HashSet::new();
let entries: Vec<(T, u8)> = c_log
.iter()
.chain(m.mem.world.iter())
.map(|w| (w.addr, w.size))
.collect();
for (addr, size) in entries {
if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
continue;
}
let env = job.env;
let mut c_init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, c_epoch);
let cv = ctx.read_world(c_log, addr, size, &mut c_init);
let mut b_init = image_init(job.image, m.mem.epoch, None);
let bv = ctx.mem_read(&m.mem, addr, size, &mut b_init);
let at = ctx.tm.show(addr);
prove_eq(ctx, cv, bv, &format!("{what}: {size}-byte value stored at {at}"))?;
}
Ok(())
}
#[derive(Default)]
struct Escapes {
map: HashMap<T, (T, i64, u32)>,
}
fn literal_at<'a>(env: &'a CEnv<'a>, addr: u32) -> Option<&'a [u8]> {
env.prog.strings.iter().zip(&env.str_addr).find_map(|(s, a)| {
let o = addr.checked_sub((*a)?)? as usize;
s.get(o..).filter(|r| !r.is_empty())
})
}
fn match_value(
ctx: &mut Ctx,
job: &Job,
cx: &CExec,
esc: &mut Escapes,
ev: &Event,
(c, b): (T, T),
what: &str,
) -> R<()> {
if c == b {
return Ok(());
}
if ctx.tm.width(c) != 32 {
return prove_eq(ctx, c, b, what);
}
if let (Some(ca), Some(ba)) = (ctx.tm.as_const(c), ctx.unique_value(b))
&& ca != ba
&& let Some(lit) = literal_at(job.env, ca as u32)
&& job.image.read_const(ba as u32, lit.len() as u32) == Some(lit)
{
return Ok(());
}
let Some((base, off)) = ctx.private_split(c) else {
return prove_eq(ctx, c, b, what);
};
if let Some(&sid) = cx.str_bases.get(&base) {
let lit = &job.env.prog.strings[sid as usize];
if let (Some(o), Some(ba)) = (ctx.tm.as_const(off), ctx.unique_value(b))
&& let Some(rest) = lit.get(o as usize..)
{
if job.image.read_const(ba as u32, rest.len() as u32) == Some(rest) {
return Ok(());
}
return Err(Stop::Mismatch(
format!("{what}: binary passes {ba:#x}, which does not hold the source's string literal"),
None,
));
}
return prove_eq(ctx, c, b, what);
}
let Some(obj) = ev.escaped.iter().find(|e| e.base == base) else {
return prove_eq(ctx, c, b, what);
};
let name = obj.name.trim_start_matches('&');
let bb = match esc.map.get(&base) {
Some(e) => e.0,
None => {
let bb = ctx.tm.sub(b, off);
let sp0 = job.regs[13];
let Some(d) = ctx.tm.const_diff(bb, sp0) else {
return Err(Stop::Unsupported(format!(
"{what}: source passes the address of local {name}, binary passes {} which is not a fixed stack slot",
ctx.tm.show(b)
)));
};
let d = d as u32 as i32 as i64;
let top = job.stack_args.iter().map(|a| a.0 as i64 + 4).max().unwrap_or(0);
if d + obj.size as i64 > top {
return Err(Stop::Mismatch(
format!(
"{what}: source passes the address of local {name}, binary passes a stack address outside its frame"
),
None,
));
}
let live = |b: &T| ev.escaped.iter().any(|e| e.base == *b);
if esc
.map
.iter()
.any(|(b2, &(_, d2, s2))| live(b2) && d < d2 + s2 as i64 && d2 < d + obj.size as i64)
{
return Err(Stop::Mismatch(
format!("{what}: binary places local {name} over another local visible to the callee"),
None,
));
}
esc.map.insert(base, (bb, d, obj.size));
bb
}
};
let expect = ctx.tm.add(bb, off);
if expect == b {
return Ok(());
}
let e = ctx.tm.eq(expect, b);
match ctx.check(e) {
Ok(()) => Ok(()),
Err(Some(_)) => Err(Stop::Mismatch(
format!(
"{what}: source passes the address of local {name}, binary passes {} instead of {}",
ctx.tm.show(b),
ctx.tm.show(expect)
),
None,
)),
Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
}
}
fn match_call(ctx: &mut Ctx, job: &Job, cx: &CExec, esc: &mut Escapes, m: &mut Machine, ev: &Event, k: usize) -> R<()> {
let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
let sp = m.regs[13];
for (i, (&(val, signed), loc)) in ev.args.iter().zip(arg_locs(&widths)).enumerate() {
let (expect, got) = match loc {
ArgLoc::Reg(n) => (ctx.tm.resize(val, 32, signed), m.regs[n as usize]),
ArgLoc::RegPair(n) => (val, ctx.tm.concat(m.regs[n as usize + 1], m.regs[n as usize])),
ArgLoc::Stack(off) => {
let a = ctx.tm.add_const(sp, off as u64);
(ctx.tm.resize(val, 32, signed), m.read32(ctx, job.image, a))
}
ArgLoc::Stack64(off) => {
let a = ctx.tm.add_const(sp, off as u64);
let lo = m.read32(ctx, job.image, a);
let a = ctx.tm.add_const(sp, off as u64 + 4);
let hi = m.read32(ctx, job.image, a);
(val, ctx.tm.concat(hi, lo))
}
};
let what = format!("argument {} of call #{} to {}", i + 1, k + 1, ev.name);
match_value(ctx, job, cx, esc, ev, (expect, got), &what)?;
}
for obj in &ev.escaped {
let name = obj.name.trim_start_matches('&');
let Some(&(bb, d, _)) = esc.map.get(&obj.base) else {
return Err(Stop::Unsupported(format!(
"call #{} to {}: local {name} is reachable by the callee but its place in the binary's frame is unknown",
k + 1,
ev.name
)));
};
if let Some(s) = ctx.tm.const_diff(sp, job.regs[13])
&& d < s as u32 as i32 as i64
{
return Err(Stop::Mismatch(
format!(
"call #{} to {}: local {name} lies below the stack pointer",
k + 1,
ev.name
),
None,
));
}
for &(off, size, v) in &obj.pre {
let Some(v) = v else { continue };
let a = ctx.tm.add_const(bb, off as u64);
let mut init = image_init(job.image, m.mem.epoch, None);
let bv = ctx.mem_read(&m.mem, a, size, &mut init);
let what = format!("local {name} (offset {off}) at call #{} to {}", k + 1, ev.name);
match_value(ctx, job, cx, esc, ev, (v, bv), &what)?;
}
}
compare_world(
ctx,
job,
&ev.writes,
ev.epoch,
m,
&format!("memory at call #{} to {}", k + 1, ev.name),
)
}
fn after_call(ctx: &mut Ctx, esc: &Escapes, m: &mut Machine, ev: &Event, k: usize) {
for obj in &ev.escaped {
let Some(&(bb, _, _)) = esc.map.get(&obj.base) else {
continue;
};
for &(off, size, v) in &obj.post {
let a = ctx.tm.add_const(bb, off as u64);
ctx.mem_write(&mut m.mem, a, size, v);
}
}
let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
let sp = m.regs[13];
for loc in arg_locs(&widths) {
let (off, n) = match loc {
ArgLoc::Stack(off) => (off, 1),
ArgLoc::Stack64(off) => (off, 2),
_ => continue,
};
for i in 0..n {
let off = off + 4 * i;
let v = ctx.named_sym(&format!("clob{k}.stk{off}"), 32);
let a = ctx.tm.add_const(sp, off as u64);
ctx.mem_write(&mut m.mem, a, 4, v);
}
}
}
fn model_mem_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
use crate::c::exec::{MAX_MEM_INLINE, mem_fill};
let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
let zero = ctx.tm.konst(32, 0);
let (dst, arg, len, fill) = match name {
"memset" => (r0, r1, r2, true),
"__aeabi_memset" | "__aeabi_memset4" | "__aeabi_memset8" => (r0, r2, r1, true),
"__aeabi_memclr" | "__aeabi_memclr4" | "__aeabi_memclr8" => (r0, zero, r1, true),
"memcpy" | "memmove" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" | "__aeabi_memmove"
| "__aeabi_memmove4" | "__aeabi_memmove8" => (r0, r1, r2, false),
_ => return false,
};
let Some(n) = ctx.unique_value(len).filter(|&n| n <= MAX_MEM_INLINE) else {
return false;
};
let n = n as u32;
if fill {
let byte = ctx.tm.trunc(arg, 8);
mem_fill(ctx, &mut m.mem, dst, byte, n);
} else {
let mut chunks = Vec::new();
let mut off = 0;
while off < n {
let sz = if n - off >= 4 { 4u8 } else { 1 };
let a = ctx.tm.add_const(arg, off as u64);
let mut init = image_init(job.image, m.mem.epoch, None);
chunks.push((off, sz, ctx.mem_read(&m.mem, a, sz, &mut init)));
off += sz as u32;
}
for (off, sz, v) in chunks {
let a = ctx.tm.add_const(dst, off as u64);
ctx.mem_write(&mut m.mem, a, sz, v);
}
}
*count += 1;
let ret = if name.starts_with("__aeabi") { None } else { Some(dst) };
m.finish_call(ctx, 1000 + *count, ret, None);
true
}
fn model_switch_helper(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> R<bool> {
let (esize, signed) = match name {
"__gnu_thumb1_case_sqi" => (1u32, true),
"__gnu_thumb1_case_uqi" => (1, false),
"__gnu_thumb1_case_shi" => (2, true),
"__gnu_thumb1_case_uhi" => (2, false),
"__gnu_thumb1_case_si" => (4, true),
_ => return Ok(false),
};
let ret = m.resume_pc();
let idx = m.regs[0];
let mut found = None;
for i in 0..1024u32 {
let k = ctx.tm.konst(32, i as u64);
let e = ctx.tm.eq(idx, k);
if ctx.branch(e)? {
found = Some(i);
break;
}
}
let Some(i) = found else {
return Err(Stop::Unsupported(format!(
"switch table with more than 1024 entries at {ret:#x}"
)));
};
let base = if esize == 4 { (ret + 3) & !3 } else { ret };
let eaddr = base + esize * i;
let Some(bytes) = job.image.read_const(eaddr, esize) else {
return Err(Stop::Unsupported(format!(
"switch table entry outside the image at {eaddr:#x}"
)));
};
let mut v = 0u32;
for (j, &b) in bytes.iter().enumerate() {
v |= (b as u32) << (8 * j);
}
let target = match (esize, signed) {
(4, _) => base.wrapping_add(v),
(1, true) => ret.wrapping_add((v as u8 as i8 as i32 as u32) << 1),
(2, true) => ret.wrapping_add((v as u16 as i16 as i32 as u32) << 1),
_ => ret.wrapping_add(v << 1),
};
m.data_covered.push((eaddr, esize as u8));
*count += 1;
m.resume_at(ctx, 1000 + *count, target);
Ok(true)
}
fn model_string_call(ctx: &mut Ctx, job: &Job, m: &mut Machine, name: &str, count: &mut usize) -> bool {
use crate::c::exec::{c_str, compare_result};
let rom = |ctx: &mut Ctx, t: T| -> Option<&[u8]> {
let a = ctx.unique_value(t)? as u32;
let s = job.image.segment_at(a).filter(|s| !s.writable)?;
s.data.get((a - s.addr) as usize..)
};
let (r0, r1, r2) = (m.regs[0], m.regs[1], m.regs[2]);
let v = match name {
"strlen" => {
let Some(s) = rom(ctx, r0).and_then(c_str) else {
return false;
};
ctx.tm.konst(32, s.len() as u64)
}
"strcmp" => {
let (Some(a), Some(b)) = (rom(ctx, r0).and_then(c_str), rom(ctx, r1).and_then(c_str)) else {
return false;
};
compare_result(ctx, a, b)
}
"memcmp" => {
let Some(n) = ctx.unique_value(r2) else { return false };
let (Some(a), Some(b)) = (
rom(ctx, r0).and_then(|s| s.get(..n as usize)),
rom(ctx, r1).and_then(|s| s.get(..n as usize)),
) else {
return false;
};
compare_result(ctx, a, b)
}
_ => return false,
};
*count += 1;
m.finish_call(ctx, 1000 + *count, Some(v), None);
true
}
fn model_runtime_call(ctx: &mut Ctx, m: &mut Machine, name: &str, count: &mut usize) -> bool {
let r = m.regs;
let tm = &mut ctx.tm;
let a64 = tm.concat(r[1], r[0]);
let b64 = tm.concat(r[3], r[2]);
let halves = |tm: &mut crate::term::Terms, v: T| (tm.extract(v, 0, 32), tm.extract(v, 32, 32));
let mut out: [Option<T>; 4] = [None; 4];
match name {
"__aeabi_uidiv" | "__udivsi3" => out[0] = Some(tm.udiv(r[0], r[1])),
"__aeabi_idiv" | "__divsi3" => out[0] = Some(tm.sdiv(r[0], r[1])),
"__umodsi3" => out[0] = Some(tm.urem(r[0], r[1])),
"__modsi3" => out[0] = Some(tm.srem(r[0], r[1])),
"__aeabi_uidivmod" => {
out[0] = Some(tm.udiv(r[0], r[1]));
out[1] = Some(tm.urem(r[0], r[1]));
}
"__aeabi_idivmod" => {
out[0] = Some(tm.sdiv(r[0], r[1]));
out[1] = Some(tm.srem(r[0], r[1]));
}
"__aeabi_uldivmod" | "__aeabi_ldivmod" => {
let signed = name == "__aeabi_ldivmod";
let q = if signed { tm.sdiv(a64, b64) } else { tm.udiv(a64, b64) };
let rem = if signed { tm.srem(a64, b64) } else { tm.urem(a64, b64) };
let (q0, q1) = halves(tm, q);
let (r0, r1) = halves(tm, rem);
out = [Some(q0), Some(q1), Some(r0), Some(r1)];
}
"__udivdi3" | "__divdi3" | "__umoddi3" | "__moddi3" | "__aeabi_lmul" | "__muldi3" => {
let v = match name {
"__udivdi3" => tm.udiv(a64, b64),
"__divdi3" => tm.sdiv(a64, b64),
"__umoddi3" => tm.urem(a64, b64),
"__moddi3" => tm.srem(a64, b64),
_ => crate::sym::mul64(tm, a64, b64),
};
let (lo, hi) = halves(tm, v);
out[0] = Some(lo);
out[1] = Some(hi);
}
"__aeabi_llsl" | "__aeabi_llsr" | "__aeabi_lasr" | "__ashldi3" | "__lshrdi3" | "__ashrdi3" => {
let amt = tm.zext(r[2], 64);
let v = match name {
"__aeabi_llsl" | "__ashldi3" => tm.shl(a64, amt),
"__aeabi_llsr" | "__lshrdi3" => tm.lshr(a64, amt),
_ => tm.ashr(a64, amt),
};
let (lo, hi) = halves(tm, v);
out[0] = Some(lo);
out[1] = Some(hi);
}
"__aeabi_lcmp" | "__aeabi_ulcmp" => {
let signed = name == "__aeabi_lcmp";
let lt = if signed { tm.slt(a64, b64) } else { tm.ult(a64, b64) };
let gt = if signed { tm.slt(b64, a64) } else { tm.ult(b64, a64) };
let g = tm.zext(gt, 32);
let m1 = tm.konst(32, 0xffff_ffff);
out[0] = Some(tm.ite(lt, m1, g));
}
"__clzsi2" => out[0] = Some(tm.clz(r[0])),
"__ctzsi2" => {
let n = tm.neg(r[0]);
let low = tm.and(r[0], n);
let c = tm.clz(low);
let k = tm.konst(32, 31);
out[0] = Some(tm.sub(k, c));
}
"__popcountsi2" => {
let mut acc = tm.konst(32, 0);
for i in 0..32 {
let b = tm.extract(r[0], i, 1);
let z = tm.zext(b, 32);
acc = tm.add(acc, z);
}
out[0] = Some(acc);
}
"__bswapsi2" => {
let mut acc = tm.extract(r[0], 0, 8);
for i in 1..4 {
let b = tm.extract(r[0], i * 8, 8);
acc = tm.concat(acc, b);
}
out[0] = Some(acc);
}
_ => return false,
}
*count += 1;
m.finish_call(ctx, 1000 + *count, out[0], out[1]);
for i in 2..4 {
if let Some(v) = out[i] {
m.regs[i] = v;
}
}
true
}
fn check_volatile(ctx: &Ctx, cx: &CExec, m: &Machine, k: usize) -> R<()> {
let due = cx.volatile.iter().filter(|a| a.event <= k).count();
if m.vol_pos == due {
return Ok(());
}
let a = &cx.volatile[m.vol_pos.min(due)];
let what = if a.write { "write to" } else { "read of" };
let at = ctx.tm.show(a.addr);
Err(Stop::Mismatch(
if m.vol_pos < due {
format!(
"binary omits the source's {}-byte {what} the volatile object at {at}",
a.size
)
} else {
format!(
"binary performs the {}-byte {what} the volatile object at {at} too early",
a.size
)
},
None,
))
}
fn run_path(ctx: &mut Ctx, job: &Job) -> R<PathResult> {
let p = job.prog;
let f = &p.funcs[job.fid as usize];
let mut cx = CExec::new(job.env);
for (base, words) in &job.struct_args {
for (i, &w) in words.iter().enumerate() {
let a = ctx.tm.add_const(*base, 4 * i as u64);
ctx.mem_write(&mut cx.mem, a, 4, w);
}
}
let (ret, halted) = match cx.run_function(ctx, job.fid, &job.args) {
Ok(r) => (r, false),
Err(Stop::Halt) => (None, true),
Err(e) => return Err(e),
};
let classify = |addr: u32| -> Callee {
if let Some(name) = job.image.externals.get(&addr) {
return Callee::External(name.clone());
}
match job.image.func_at(addr) {
Some(s) => {
let has_body = p
.funcs
.iter()
.any(|f| f.body.is_some() && *f.name == *base_name(&s.name));
if has_body || s.name.starts_with("OUTLINED_FUNCTION_") {
Callee::Internal
} else {
Callee::External(s.name.clone())
}
}
None => Callee::Internal,
}
};
let mut m = Machine::new(ctx, job.entry, job.regs);
m.targets = job.env.targets.iter().map(|t| t.0).collect();
m.known_indirect = cx.indirect.iter().map(|t| t.1).collect();
m.vol = cx.volatile.clone();
for &(off, v) in &job.stack_args {
let a = ctx.tm.add_const(job.regs[13], off as u64);
ctx.mem_write(&mut m.mem, a, 4, v);
}
let mut k = 0usize;
let mut helper_calls = 0usize;
let mut esc = Escapes::default();
loop {
match m.run(ctx, job.image, job.lr0, &classify)? {
Exit::Call { name } => {
if model_switch_helper(ctx, job, &mut m, &name, &mut helper_calls)? {
continue;
}
if cx.events.get(k).is_none_or(|ev| ev.name != name)
&& (model_mem_call(ctx, job, &mut m, &name, &mut helper_calls)
|| model_runtime_call(ctx, &mut m, &name, &mut helper_calls)
|| model_string_call(ctx, job, &mut m, &name, &mut helper_calls))
{
continue;
}
let Some(ev) = cx.events.get(k) else {
return Err(Stop::Mismatch(
format!("binary calls {name}, which the source does not call at this point"),
None,
));
};
if ev.name != name {
return Err(Stop::Mismatch(
format!("binary calls {name} where the source calls {}", ev.name),
None,
));
}
check_volatile(ctx, &cx, &m, k)?;
if let Some(got) = m.indirect.take() {
let want = cx
.indirect
.iter()
.find(|t| t.0 == k)
.expect("indirect event has a target")
.1;
prove_eq(ctx, want, got, &format!("target of call #{} through a pointer", k + 1))?;
}
match_call(ctx, job, &cx, &mut esc, &mut m, ev, k)?;
m.mem.world.clear();
m.mem.epoch = ev.epoch + 1;
k += 1;
if ev.noreturn {
break;
}
let (lo, hi) = match ev.ret {
None => (None, None),
Some((sym, signed)) => {
if ctx.tm.width(sym) == 64 {
(Some(ctx.tm.extract(sym, 0, 32)), Some(ctx.tm.extract(sym, 32, 32)))
} else {
(Some(ctx.tm.resize(sym, 32, signed)), None)
}
}
};
after_call(ctx, &esc, &mut m, ev, k - 1);
m.finish_call(ctx, k - 1, lo, hi);
}
Exit::Trap => {
let Some(ev) = cx.events.get(k) else {
return Err(Stop::Mismatch(
"binary traps (udf) where the source does not".into(),
None,
));
};
if ev.name != "<trap>" {
return Err(Stop::Mismatch(
format!("binary traps (udf) where the source calls {}", ev.name),
None,
));
}
check_volatile(ctx, &cx, &m, k)?;
compare_world(ctx, job, &ev.writes, ev.epoch, &m, "memory at trap")?;
k += 1;
break;
}
Exit::Return => {
if let Some(ev) = cx.events.get(k) {
return Err(Stop::Mismatch(
format!("binary returns without calling {}", ev.name),
None,
));
}
if halted {
return Err(Stop::Mismatch(
"binary returns where the source does not return".into(),
None,
));
}
check_volatile(ctx, &cx, &m, usize::MAX)?;
if let Some(v) = ret
&& matches!(p.ty(f.ty.ret), Type::Record(_))
{
let size = p.size_of(f.ty.ret).unwrap_or(0);
let mask = p.value_mask(f.ty.ret);
let mut off = 0;
while off < size {
let n = (size - off).min(4);
let bits = (0..n).fold(0u64, |b, i| b | (mask[(off + i) as usize] as u64) << (8 * i));
let a = ctx.tm.add_const(v, off as u64);
let want = cx.read_bytes(ctx, a, n as u8);
let got = match job.ret_slot {
Some(slot) => {
let a = ctx.tm.add_const(slot, off as u64);
let mut init = image_init(job.image, m.mem.epoch, None);
ctx.mem_read(&m.mem, a, n as u8, &mut init)
}
None => ctx.tm.trunc(m.regs[0], n as u8 * 8),
};
let k = ctx.tm.konst(n as u8 * 8, bits);
let (want, got) = (ctx.tm.and(want, k), ctx.tm.and(got, k));
prove_eq(
ctx,
want,
got,
&format!("bytes {off}..{} of the returned structure", off + n),
)?;
off += n;
}
} else if let Some(v) = ret {
let w = ctx.tm.width(v);
if w == 64 {
let got = ctx.tm.concat(m.regs[1], m.regs[0]);
prove_eq(ctx, v, got, "return value")?;
} else {
let expect = ctx.tm.resize(v, 32, p.is_signed(f.ty.ret));
prove_eq(ctx, expect, m.regs[0], "return value")?;
}
}
compare_world(ctx, job, &cx.mem.world, cx.mem.epoch, &m, "memory at return")?;
for r in (4..=11).chain([13]) {
let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
prove_eq(
ctx,
job.regs[r],
m.regs[r],
&format!("callee-saved register {name} at return"),
)?;
}
return Ok(PathResult {
cov: cx.cov,
insns: m.covered,
data: m.data_covered,
});
}
}
}
if k != cx.events.len() {
return Err(Stop::Mismatch(
"binary stops before the source's remaining calls".into(),
None,
));
}
Ok(PathResult {
cov: cx.cov,
insns: m.covered,
data: m.data_covered,
})
}
struct FuncOutcome {
report: FuncReport,
cov: BTreeSet<u32>,
bytes: BTreeSet<u32>,
}
fn verify_function(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
let f = &prog.funcs[fid as usize];
let sym = image.func(&f.name).expect("entry has a symbol");
let start = Instant::now();
let mut out = FuncOutcome {
report: FuncReport {
name: f.name.to_string(),
addr: sym.addr,
size: sym.size,
status: Status::Proved,
paths: 0,
undefined_paths: 0,
millis: 0,
},
cov: BTreeSet::new(),
bytes: BTreeSet::new(),
};
let mut ctx = Ctx::new(opts.limits);
ctx.deadline = Some(start + opts.time_limit);
ctx.prover.rom = image
.segments
.iter()
.filter(|s| !s.writable)
.map(|s| (s.addr, s.data.clone()))
.collect();
let scalar = |t| prog.is_scalar(t) && !prog.is_float(t);
let record = |t| matches!(prog.ty(t), Type::Record(_)) && prog.size_of(t).is_some_and(|s| s > 0);
let passable = |t| scalar(t) || record(t);
if !(f.ty.ret == VOID || passable(f.ty.ret)) || !f.ty.params.iter().all(|&t| passable(t)) || f.ty.variadic {
out.report.status = Status::Unsupported("non-integer parameter or return type".into());
return out;
}
let mut regs = [0 as T; 16];
for (i, r) in regs.iter_mut().enumerate().take(13) {
*r = ctx.named_sym(&format!("r{i}"), 32);
}
if let Some(sb) = image.static_base {
regs[9] = ctx.tm.konst(32, sb as u64);
}
regs[13] = ctx.private_base("SP0");
regs[14] = ctx.named_sym("LR0", 32);
regs[15] = ctx.tm.konst(32, 0);
let lr0 = regs[14];
let mut pre = Vec::new();
let low = ctx.tm.extract(regs[13], 0, 3);
let z3 = ctx.tm.konst(3, 0);
pre.push(ctx.tm.eq(low, z3));
let ret_slot = if record(f.ty.ret) && prog.size_of(f.ty.ret).unwrap_or(0) > 4 {
let slot = ctx.private_base("RET0");
regs[0] = slot;
let low = ctx.tm.extract(slot, 0, 2);
let z2 = ctx.tm.konst(2, 0);
pre.push(ctx.tm.eq(low, z2));
Some(slot)
} else {
None
};
let shapes: Vec<(u32, bool)> =
f.ty.params
.iter()
.map(|&t| (prog.size_of(t).unwrap_or(4), prog.align_of(t) == 8))
.collect();
let mut args = Vec::new();
let mut stack_args = Vec::new();
let mut struct_args = Vec::new();
for (i, (&ty, locs)) in
f.ty.params
.iter()
.zip(arg_words(&shapes, ret_slot.is_some() as u8))
.enumerate()
{
let words: Vec<T> = locs
.iter()
.map(|loc| match *loc {
WordLoc::Reg(n) => regs[n as usize],
WordLoc::Stack(off) => {
let s = ctx.named_sym(&format!("stk{off}"), 32);
stack_args.push((off, s));
s
}
})
.collect();
if record(ty) {
let base = ctx.private_base(&format!("&arg{i}"));
struct_args.push((base, words));
args.push(base);
continue;
}
let raw = if words.len() == 2 {
ctx.tm.concat(words[1], words[0])
} else {
words[0]
};
let w = prog.bits(ty);
let v = ctx.tm.trunc(raw, w);
if w < 32 {
let ext = ctx.tm.resize(v, 32, prog.is_signed(ty));
pre.push(ctx.tm.eq(raw, ext));
if ty == crate::c::ast::BOOL {
let two = ctx.tm.konst(8, 2);
pre.push(ctx.tm.ult(v, two));
}
}
args.push(v);
}
let job = Job {
prog,
image,
env,
fid,
entry: sym.addr,
regs,
args,
stack_args,
struct_args,
ret_slot,
lr0,
};
let mut bounded: Option<String> = None;
let mut inconclusive: Option<String> = None;
let mut explored = 0usize;
let max_depth = opts.limits.max_depth;
let mut schedule: Vec<usize> = [1, 2, 3, 4, 6, 8, 12, 16, 24, 32]
.into_iter()
.filter(|&d| d < max_depth)
.collect();
schedule.push(max_depth);
let mut best_paths = 0usize;
'rounds: for (round, &depth) in schedule.iter().enumerate() {
ctx.limits.max_depth = depth;
ctx.decisions.clear();
let mut depth_hit = false;
inconclusive = None;
out.report.paths = 0;
out.report.undefined_paths = 0;
loop {
ctx.restart(&pre);
explored += 1;
match run_path(&mut ctx, &job) {
Ok(r) => {
out.report.paths += 1;
out.cov.extend(r.cov);
for (a, n) in r.insns.into_iter().chain(r.data) {
out.bytes.extend(a..a + n as u32);
}
}
Err(Stop::Undefined) => out.report.undefined_paths += 1,
Err(Stop::Halt) => unreachable!("Halt is handled by run_path"),
Err(Stop::Truncated(why)) => {
if why == "branch depth limit" {
depth_hit = true;
} else {
bounded.get_or_insert(why);
}
}
Err(Stop::Inconclusive(why)) => {
inconclusive.get_or_insert(why);
}
Err(Stop::Mismatch(why, _)) => {
out.report.status = Status::Mismatch(why);
break 'rounds;
}
Err(Stop::Unsupported(why)) => {
out.report.status = Status::Unsupported(why);
break 'rounds;
}
}
best_paths = best_paths.max(out.report.paths);
if start.elapsed() > opts.time_limit {
bounded.get_or_insert_with(|| "time limit".into());
break 'rounds;
}
if explored >= opts.limits.max_paths {
bounded.get_or_insert_with(|| "path limit".into());
break 'rounds;
}
if !ctx.next_path() {
break;
}
}
if !depth_hit {
break;
}
if round + 1 == schedule.len() {
bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
}
}
out.report.paths = out.report.paths.max(best_paths);
if out.report.status == Status::Proved {
if let Some(why) = inconclusive {
out.report.status = Status::Inconclusive(why);
} else if let Some(why) = bounded {
out.report.status = Status::Bounded(format!("{why}; {} paths proved", out.report.paths));
}
}
if matches!(out.report.status, Status::Mismatch(_) | Status::Unsupported(_)) {
out.cov.clear();
out.bytes.clear();
}
out.report.millis = start.elapsed().as_millis();
out
}
fn check_data(prog: &Program, image: &Image, env: &CEnv, report: &mut Report) {
for (i, g) in prog.globals.iter().enumerate() {
if !g.defined {
continue;
}
let Some(addr) = env.global_addr[i] else { continue };
let Some(expect) = env.init_bytes(i as u32) else {
continue;
};
let Some(got) = image.read(addr, expect.len() as u32) else {
if image.segments.iter().all(|s| !s.writable) {
continue;
}
report
.data_issues
.push(format!("{}: object at {addr:#x} is outside the image", g.name));
continue;
};
report.data_checked += 1;
if let Some(off) = expect.iter().zip(got).position(|(a, b)| a != b) {
report.data_issues.push(format!(
"{}: initial value differs at offset {off}: source has {:#04x}, binary has {:#04x}",
g.name, expect[off], got[off]
));
}
}
}
pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
let env = CEnv::new(prog, image);
let mut report = Report::default();
let mut cov: BTreeSet<u32> = BTreeSet::new();
let mut bytes: BTreeSet<u32> = BTreeSet::new();
for (fid, f) in prog.funcs.iter().enumerate() {
if f.body.is_none() || image.func(&f.name).is_none() {
continue;
}
if !opts.only.is_empty() && !opts.only.iter().any(|n| **n == *f.name) {
continue;
}
let o = verify_function(prog, image, &env, fid as u32, opts);
cov.extend(o.cov);
bytes.extend(o.bytes);
report.funcs.push(o.report);
}
check_data(prog, image, &env, &mut report);
report.src = (cov.len(), prog.ncov as usize);
let mut lines: BTreeSet<(String, u32)> = BTreeSet::new();
let mut hit: HashSet<(u16, u32)> = HashSet::new();
for &c in &cov {
let loc = prog.cov_info[c as usize].1;
hit.insert((loc.file, loc.line));
}
for (c, (_, loc)) in prog.cov_info.iter().enumerate() {
if !cov.contains(&(c as u32)) && !hit.contains(&(loc.file, loc.line)) {
lines.insert((prog.files.get(loc.file as usize).cloned().unwrap_or_default(), loc.line));
}
}
report.uncovered_lines = lines.into_iter().collect();
for (c, (fid, loc)) in prog.cov_info.iter().enumerate() {
report.src_points.push(SrcPoint {
file: prog.files.get(loc.file as usize).cloned().unwrap_or_default(),
line: loc.line,
func: prog.funcs[*fid as usize].name.to_string(),
proved: cov.contains(&(c as u32)),
});
}
let reached_funcs: HashSet<u32> = cov.iter().map(|&c| prog.cov_info[c as usize].0).collect();
for (fid, f) in prog.funcs.iter().enumerate() {
if f.body.is_some() && image.func(&f.name).is_none() && !reached_funcs.contains(&(fid as u32)) {
report.absent.push(f.name.to_string());
}
}
let mut total = 0usize;
let mut proved = 0usize;
for seg in image.segments.iter().filter(|s| s.exec) {
let in_func = |a: u32| {
image
.symbols
.iter()
.any(|s| s.kind == SymKind::Func && a >= s.addr && a - s.addr < s.size)
};
let mut o = 0usize;
while o < seg.data.len() {
let a = seg.addr + o as u32;
let n = if o + 1 < seg.data.len() { 2 } else { 1 };
let hw = if n == 2 {
u16::from_le_bytes([seg.data[o], seg.data[o + 1]])
} else {
seg.data[o] as u16
};
let covered = (0..n as u32).filter(|i| bytes.contains(&(a + i))).count();
let padding = covered == 0 && !in_func(a) && matches!(hw, 0 | 0xbf00 | 0x46c0);
if !padding {
total += n;
proved += covered;
}
for i in 0..n as u32 {
let state = if padding {
ByteState::Padding
} else if bytes.contains(&(a + i)) {
ByteState::Proved
} else {
ByteState::Unproved
};
match report.bin_ranges.last_mut() {
Some(r) if r.end == a + i && r.state == state => r.end += 1,
_ => report.bin_ranges.push(BinRange {
start: a + i,
end: a + i + 1,
state,
}),
}
}
o += n;
}
}
report.bin = (proved, total);
for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size > 0) {
if image.segment_at(s.addr).is_some() && !(s.addr..s.addr + s.size).any(|a| bytes.contains(&a)) {
let verified = report.funcs.iter().any(|f| f.name == s.name);
if !verified {
report.unmatched.push((s.name.clone(), s.size));
}
}
}
report
}