use crate::c::ast::{Program, Type, VOID};
use crate::c::exec::{CEnv, CExec};
use crate::image::{Image, SymKind};
use crate::sym::{ArgLoc, Ctx, Event, Exposed, Limits, Mem, 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};
mod loops;
#[derive(Clone, Debug)]
pub struct Options {
pub limits: Limits,
pub only: Vec<String>,
pub time_limit: Duration,
pub mmio: Vec<(u32, u32)>,
pub jobs: usize,
pub work_limit: u64,
pub max_terms: usize,
pub dump: usize,
pub deadline: Option<Instant>,
pub check_solver: bool,
}
pub const DEFAULT_MMIO: [(u32, u32); 2] = [(0x4000_0000, 0x5fff_ffff), (0xe000_0000, 0xffff_ffff)];
impl Default for Options {
fn default() -> Self {
Options {
limits: Limits::default(),
only: Vec::new(),
time_limit: Duration::from_secs(300),
jobs: 0,
work_limit: 500_000,
max_terms: 20_000_000,
dump: 0,
deadline: None,
check_solver: false,
mmio: DEFAULT_MMIO.to_vec(),
}
}
}
#[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,
pub sat_calls: u64,
pub conflicts: u64,
pub work: u64,
pub detail: Option<Box<crate::explain::FuncDetail>>,
}
#[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())
}
}
const FRAME_SPAN: u32 = 1 << 20;
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)>,
}
const VA_STACK_WORDS: u32 = 8;
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,
mmio: &'a [(u32, u32)],
}
fn check_result_slot(ctx: &mut Ctx, job: &Job, m: &Machine) -> R<()> {
let Some(slot) = job.ret_slot else { return Ok(()) };
let Some(log) = m.mem.private.get(&slot) else {
return Ok(());
};
let f = &job.prog.funcs[job.fid as usize];
let len = job.prog.size_of(f.ty.ret).unwrap_or(0) as u64;
let stores: Vec<(T, u8)> = log.iter().map(|w| (w.addr, w.size)).collect();
for (addr, size) in stores {
let off = ctx.tm.sub(addr, slot);
if let Some(o) = ctx.tm.as_const(off)
&& o + size as u64 <= len
{
continue;
}
let ok = if size as u64 <= len {
let lim = ctx.tm.konst(32, len - size as u64 + 1);
ctx.tm.ult(off, lim)
} else {
ctx.tm.konst(1, 0)
};
match ctx.check(ok) {
Ok(()) => {}
Err(Some(env)) => {
let mut memo = Default::default();
let o = ctx.tm.eval(off, &env, &mut memo) as u32 as i32;
return Err(Stop::Mismatch(
format!(
"binary stores {size} byte(s) outside the {len}-byte result object (offset {o}) for {}",
witness(ctx, &env)
),
Some(env),
));
}
Err(None) => {
return Err(Stop::Inconclusive(
"a store relative to the result object: prover gave up on whether it stays inside".into(),
));
}
}
}
Ok(())
}
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);
if std::env::var("CVERIF_DEBUG").is_ok_and(|v| v == "2") {
eprintln!(
"solver {what}:\n source: {}\n binary: {}",
ctx.tm.show(c),
ctx.tm.show(b)
);
for (n, l) in [("pc", ctx.pc.clone()), ("ub", ctx.ub.clone())] {
for t in l {
eprintln!(" {n}: {}", ctx.tm.show(t));
}
}
}
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_unbound_private(c) || ctx.mentions_unbound_private(b) {
return Err(Stop::Unsupported(format!(
"{what}: the address of a local object escapes"
)));
}
if let Some(name) = env
.syms
.keys()
.map(|id| ctx.tm.sym_name(*id))
.filter(|n| n.starts_with('&') && (n.contains("#g") || n.contains("#f")))
.min()
{
let name = name[1..].rsplit_once('#').map_or(&name[1..], |p| p.0);
return Err(Stop::Unsupported(format!(
"{what}: uses `{name}`, which could not be located in the binary (no symbol, or several candidates)"
)));
}
crate::explain::report::note_goal(c, b);
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)
);
}
crate::explain::report::note_goal(c, b);
Err(Stop::Inconclusive(format!("{what}: prover gave up")))
}
}
}
#[allow(clippy::too_many_arguments)]
fn compare_world(
ctx: &mut Ctx,
job: &Job,
c_log: &[Write],
c_epoch: u32,
exposed: &[Exposed],
m: &Machine,
what: &str,
eq: &mut dyn FnMut(&mut Ctx, T, T, &str) -> R<()>,
) -> 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.read_world(&m.mem.world, addr, size, &mut b_init);
if size == 4 && cv != bv && same_literal(ctx, job, cv, bv) {
continue;
}
crate::explain::report::note_addr(addr);
let at = ctx.tm.show(addr);
let what = format!("{what}: {size}-byte value stored at {at}");
let mut elsewhere = ctx.tm.fals();
for e in exposed {
if ctx.may_point_into(addr, e) {
let inside = ctx.inside(addr, e);
elsewhere = ctx.tm.or(elsewhere, inside);
}
}
if ctx.tm.is_false(elsewhere) {
eq(ctx, cv, bv, &what)?;
} else if cv != bv {
let outside = ctx.tm.not(elsewhere);
ctx.pc.push(outside);
let r = eq(ctx, cv, bv, &what);
ctx.pc.pop();
r?;
}
}
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 same_literal(ctx: &mut Ctx, job: &Job, c: T, b: T) -> bool {
if ctx.tm.width(c) != 32 || ctx.tm.width(b) != 32 {
return false;
}
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)
{
return job.image.read_const(ba as u32, lit.len() as u32) == Some(lit);
}
false
}
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));
let same = ctx.tm.eq(base, bb);
ctx.pc.push(same);
ctx.bound.insert(base);
ctx.bound.insert(sp0);
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);
let (expect, got) = match ev.arg_masks.iter().find(|m| m.0 == i) {
Some(&(_, mask)) => {
let km = ctx.tm.konst(ctx.tm.width(expect), mask);
(ctx.tm.and(expect, km), ctx.tm.and(got, km))
}
None => (expect, got),
};
match_value(ctx, job, cx, esc, ev, (expect, got), &what)?;
}
compare_world(
ctx,
job,
&ev.writes,
ev.epoch,
&ev.exposed,
m,
&format!("memory at call #{} to {}", k + 1, ev.name),
&mut |ctx, c, b, what| match_value(ctx, job, cx, esc, ev, (c, b), 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)?;
}
}
Ok(())
}
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.event_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
}
pub(crate) fn model_runtime_call(ctx: &mut Ctx, m: &mut Machine, name: &str, count: &mut usize) -> bool {
let r = m.regs;
if let Some(o) = crate::fp::runtime_call(&mut ctx.tm, name, [r[0], r[1], r[2], r[3]]) {
*count += 1;
match o {
crate::fp::Outcome::Value(v) if ctx.tm.width(v) == 64 => {
let (lo, hi) = (ctx.tm.extract(v, 0, 32), ctx.tm.extract(v, 32, 32));
m.finish_call(ctx, 1000 + *count, Some(lo), Some(hi));
}
crate::fp::Outcome::Value(v) => m.finish_call(ctx, 1000 + *count, Some(v), None),
crate::fp::Outcome::Flags { z, c } => {
m.finish_call(ctx, 1000 + *count, Some(r[0]), Some(r[1]));
m.regs[2] = r[2];
m.regs[3] = r[3];
m.set_zc(ctx, z, c);
}
}
return true;
}
let undefined_at: Option<T> = {
let tm = &mut ctx.tm;
match name {
"__aeabi_uidiv" | "__udivsi3" | "__aeabi_idiv" | "__divsi3" | "__umodsi3" | "__modsi3"
| "__aeabi_uidivmod" | "__aeabi_idivmod" => Some(r[1]),
"__aeabi_uldivmod" | "__aeabi_ldivmod" | "__udivdi3" | "__divdi3" | "__umoddi3" | "__moddi3" => {
Some(tm.concat(r[3], r[2]))
}
"__clzsi2" | "__ctzsi2" => Some(r[0]),
_ => None,
}
};
let unknown: Option<(T, [T; 4])> = undefined_at.and_then(|v| {
let zero = ctx.tm.konst(ctx.tm.width(v), 0);
let z = ctx.tm.eq(v, zero);
let nz = ctx.tm.not(z);
if ctx.implied(nz) {
return None;
}
let key = format!("{}.{}.{}.{}", r[0], r[1], r[2], r[3]);
Some((
z,
std::array::from_fn(|i| ctx.named_sym(&format!("undefined.{name}.{key}.r{i}"), 32)),
))
});
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" => out[0] = Some(tm.ctz(r[0])),
"__popcountsi2" => out[0] = Some(tm.popcount(r[0])),
"__bswapsi2" => out[0] = Some(tm.bswap(r[0])),
"__paritysi2" => {
let c = tm.popcount(r[0]);
let b = tm.extract(c, 0, 1);
out[0] = Some(tm.zext(b, 32));
}
"__ffssi2" => {
let c = tm.ctz(r[0]);
let c1 = tm.add_const(c, 1);
let z = tm.konst(32, 0);
let nz = tm.nonzero(r[0]);
out[0] = Some(tm.ite(nz, c1, z));
}
"__clzdi2" | "__ctzdi2" | "__popcountdi2" => {
let v = tm.concat(r[1], r[0]);
let c = match name {
"__clzdi2" => tm.clz(v),
"__ctzdi2" => tm.ctz(v),
_ => tm.popcount(v),
};
out[0] = Some(tm.trunc(c, 32));
}
_ => return false,
}
if let Some((z, fresh)) = unknown {
for (o, f) in out.iter_mut().zip(fresh) {
if let Some(v) = *o {
*o = Some(tm.ite(z, f, v));
}
}
}
*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> {
run_seg(ctx, job, &SegCtl::default()).map(|e| e.res)
}
struct SegInit {
c_block: usize,
c_mem: Mem,
m_pc: u32,
m_regs: [T; 16],
m_mem: Mem,
tag: String,
}
#[derive(Default)]
struct SegCtl<'s> {
init: Option<&'s SegInit>,
assume: Vec<(&'s crate::c::ast::Expr, bool)>,
c_cuts: &'s [usize],
m_cuts: &'s [u32],
stop: usize,
m_stop: usize,
}
struct SegEnd<'a> {
res: PathResult,
cut: Option<(usize, u32)>,
cx: CExec<'a>,
m: Machine,
}
fn cut_error(what: &str) -> Stop {
Stop::Unsupported(format!("loop proof: {what}"))
}
fn run_seg<'a>(ctx: &mut Ctx, job: &Job<'a>, ctl: &SegCtl) -> R<SegEnd<'a>> {
use crate::c::exec::BodyEnd;
let p = job.prog;
let f = &p.funcs[job.fid as usize];
let stop = if ctl.stop == 0 { usize::MAX } else { ctl.stop };
let m_stop = if ctl.m_stop == 0 { usize::MAX } else { ctl.m_stop };
let mut cx = CExec::new(job.env);
cx.cut_blocks = ctl.c_cuts.to_vec();
cx.cut_stop = stop;
let c_end = match ctl.init {
None => {
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);
}
}
cx.run_segment(ctx, job.fid, Some(&job.args), 0, &[])
}
Some(init) => {
cx.mem = init.c_mem.clone();
cx.run_segment(ctx, job.fid, None, init.c_block, &ctl.assume)
}
};
let (ret, halted, c_cut) = match c_end {
Ok(BodyEnd::Ret(r)) => (r, false, None),
Ok(BodyEnd::Cut(b)) => (None, false, Some(b)),
Err(Stop::Halt) => (None, true, None),
Err(e) => return Err(e),
};
crate::explain::report::note_source(&cx, ret, halted);
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 = match ctl.init {
None => {
let mut m = Machine::new(ctx, job.entry, job.regs);
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);
}
m
}
Some(init) => {
let mut m = Machine::new(ctx, init.m_pc, init.m_regs);
m.mem = init.m_mem.clone();
m.sp0 = job.regs[13];
m.havoc_flags(ctx, &init.tag);
m.at_start = true;
m
}
};
m.cuts = ctl.m_cuts.to_vec();
m.cut_stop = m_stop;
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();
m.mmio = job.mmio.to_vec();
m.plain = cx.plain_accesses(ctx);
m.stack_top = job.stack_args.iter().map(|a| a.0 + 4).max().unwrap_or(0);
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 } => {
check_result_slot(ctx, job, &m)?;
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;
}
crate::explain::report::note_call(&m, &name, cx.events.get(k).map(|e| e.args.len()));
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;
m.mem.exposed = ev
.exposed
.iter()
.filter_map(|e| {
esc.map.get(&e.base).map(|&(bb, _, size)| Exposed {
base: bb,
size,
since: e.since,
})
})
.collect();
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::Cut(pc) => {
let Some(b) = c_cut else {
return Err(cut_error(
"the binary reaches a loop head where the source leaves the function",
));
};
if k != cx.events.len() {
return Err(cut_error("the binary reaches a loop head before the source's calls"));
}
check_volatile(ctx, &cx, &m, usize::MAX)?;
let res = PathResult {
cov: cx.cov.clone(),
insns: m.covered.clone(),
data: m.data_covered.clone(),
};
return Ok(SegEnd {
res,
cut: Some((b, pc)),
cx,
m,
});
}
Exit::Trap => {
check_result_slot(ctx, job, &m)?;
if c_cut.is_some() {
return Err(cut_error("the binary traps where the source reaches a loop head"));
}
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,
&ev.exposed,
&m,
"memory at trap",
&mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
)?;
k += 1;
break;
}
Exit::Return => {
check_result_slot(ctx, job, &m)?;
crate::explain::report::note_return(&m, ret.map(|v| ctx.tm.width(v)));
if c_cut.is_some() {
return Err(cut_error("the binary returns where the source reaches a loop head"));
}
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));
if let Some((base, off)) = ctx.private_split(expect)
&& let Some(&sid) = cx.str_bases.get(&base)
&& let (Some(o), Some(ba)) = (ctx.tm.as_const(off), ctx.unique_value(m.regs[0]))
&& let Some(rest) = job.env.prog.strings[sid as usize].get(o as usize..)
{
if job.image.read_const(ba as u32, rest.len() as u32) != Some(rest) {
return Err(Stop::Mismatch(
format!(
"return value: binary returns {ba:#x}, which does not hold the source's string literal"
),
None,
));
}
} else if !same_literal(ctx, job, expect, m.regs[0]) {
prove_eq(ctx, expect, m.regs[0], "return value")?;
}
}
}
compare_world(
ctx,
job,
&cx.mem.world,
cx.mem.epoch,
&cx.mem.exposed,
&m,
"memory at return",
&mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
)?;
for r in (4..=11).chain([13]) {
let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
if r == 13
&& let Some(d) = ctx.tm.const_diff(m.regs[13], job.regs[13])
&& d != 0
{
return Err(Stop::Mismatch(
format!(
"stack pointer at return: the binary leaves it {} bytes from its value at entry",
d as u32 as i32
),
None,
));
}
prove_eq(
ctx,
job.regs[r],
m.regs[r],
&format!("callee-saved register {name} at return"),
)?;
}
let res = PathResult {
cov: cx.cov.clone(),
insns: m.covered.clone(),
data: m.data_covered.clone(),
};
return Ok(SegEnd { res, cut: None, cx, m });
}
}
}
if c_cut.is_some() {
return Err(cut_error("the binary stops where the source reaches a loop head"));
}
if k != cx.events.len() {
return Err(Stop::Mismatch(
"binary stops before the source's remaining calls".into(),
None,
));
}
let res = PathResult {
cov: cx.cov.clone(),
insns: m.covered.clone(),
data: m.data_covered.clone(),
};
Ok(SegEnd { res, cut: None, cx, m })
}
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 = env.func_addr[fid as usize]
.and_then(|a| image.func_at(a))
.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,
sat_calls: 0,
conflicts: 0,
work: 0,
detail: None,
},
cov: BTreeSet::new(),
bytes: BTreeSet::new(),
};
let mut ctx = Ctx::new(opts.limits);
crate::explain::report::begin_function(opts.dump);
let mut why_inconclusive: Option<crate::explain::Explanation> = None;
let mut why_bounded: Option<crate::explain::Explanation> = None;
let mut why_mismatch: Option<crate::explain::Explanation> = None;
if opts.check_solver {
ctx.prover = crate::bv::Prover::new_checked();
}
let mut deadline = start + opts.time_limit;
if let Some(d) = opts.deadline {
deadline = deadline.min(d);
}
ctx.set_budget(opts.work_limit, opts.max_terms, Some(deadline));
ctx.prover.rom = image
.segments
.iter()
.filter(|s| !s.writable)
.map(|s| (s.addr, s.data.clone()))
.collect();
ctx.prover.rom.extend(env.frozen.iter().cloned());
let scalar = |t| prog.is_scalar(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)) {
out.report.status = Status::Unsupported("non-integer parameter or return type".into());
return out;
}
if image.hard_float && (has_float(prog, f.ty.ret) || f.ty.params.iter().any(|&t| has_float(prog, t))) {
out.report.status = Status::Unsupported("hard-float calling convention".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);
if w < 32 && locs.len() == 1 {
let is_bool = ty == crate::c::ast::BOOL;
let (name, vw) = match locs[0] {
WordLoc::Reg(n) => (format!("r{n}"), if is_bool { 1 } else { w }),
WordLoc::Stack(off) => (format!("stk{off}"), if is_bool { 1 } else { w }),
};
let narrow = ctx.named_sym(&format!("{name}:{vw}"), vw);
let v = ctx.tm.resize(narrow, w, false);
let word = ctx.tm.resize(v, 32, prog.is_signed(ty));
match locs[0] {
WordLoc::Reg(n) => regs[n as usize] = word,
WordLoc::Stack(off) => {
if let Some(slot) = stack_args.iter_mut().rev().find(|s| s.0 == off) {
slot.1 = word;
}
}
}
args.push(v);
continue;
}
let v = ctx.tm.trunc(raw, w);
if prog.is_ptr(ty) {
let below = ctx.tm.add_const(regs[13], (FRAME_SPAN as u64).wrapping_neg());
let d = ctx.tm.sub(v, below);
let span = ctx.tm.konst(32, FRAME_SPAN as u64);
pre.push(ctx.tm.ule(span, d));
}
args.push(v);
}
if f.variadic_def {
let start = crate::c::exec::va_start_word(&shapes, ret_slot.is_some() as u8);
for w in start..start.max(4) + VA_STACK_WORDS {
if w < 4 {
args.push(regs[w as usize]);
} else {
let off = (w - 4) * 4;
let s = ctx.named_sym(&format!("stk{off}"), 32);
stack_args.push((off, s));
args.push(s);
}
}
}
let job = Job {
prog,
image,
env,
fid,
entry: sym.addr,
regs,
args,
stack_args,
struct_args,
ret_slot,
lr0,
mmio: &opts.mmio,
};
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;
let mut tried_induction = false;
'rounds: for (round, &depth) in schedule.iter().enumerate() {
ctx.limits.max_depth = depth;
ctx.decisions.clear();
let mut depth_hit = false;
inconclusive = None;
why_inconclusive = None;
crate::explain::report::begin_round();
out.report.paths = 0;
out.report.undefined_paths = 0;
loop {
ctx.restart(&pre);
crate::explain::report::begin_path(pre.len());
explored += 1;
let res = run_path(&mut ctx, &job);
crate::explain::report::end_path(&ctx, Some(prog), fid, &res);
match res {
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;
if round + 1 == schedule.len() && why_bounded.is_none() && bounded.is_none() {
why_bounded = Some(crate::explain::report::capture(
&ctx,
Some(prog),
fid,
"bounded",
&why,
None,
));
}
} else {
if bounded.is_none() {
why_bounded = Some(crate::explain::report::capture(
&ctx,
Some(prog),
fid,
"bounded",
&why,
None,
));
}
bounded.get_or_insert(why);
}
}
Err(Stop::Inconclusive(why)) => {
match ctx.check_deadline() {
Err(Stop::Truncated(limit)) => {
if bounded.is_none() {
let mut e =
crate::explain::report::capture(&ctx, Some(prog), fid, "inconclusive", &why, None);
e.outcome = "bounded".into();
why_bounded = Some(e);
}
bounded.get_or_insert(limit);
}
_ => {
if inconclusive.is_none() {
why_inconclusive = Some(crate::explain::report::capture(
&ctx,
Some(prog),
fid,
"inconclusive",
&why,
None,
));
}
inconclusive.get_or_insert(why);
}
}
}
Err(Stop::Mismatch(why, model)) => {
why_mismatch = Some(crate::explain::report::capture(
&ctx,
Some(prog),
fid,
"mismatch",
&why,
model.as_deref(),
));
let unlocated = ctx
.names()
.filter(|n| n.starts_with('&') && (n.contains("#g") || n.contains("#f")))
.min()
.map(|n| n[1..].rsplit_once('#').map_or(&n[1..], |p| p.0).to_string());
out.report.status = match unlocated {
Some(name) => Status::Unsupported(format!(
"uses `{name}`, which could not be located in the binary (no symbol, or several candidates)"
)),
None => 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 let Err(Stop::Truncated(limit)) = ctx.check_deadline() {
bounded.get_or_insert(limit);
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;
}
let last = round + 1 == schedule.len();
if !tried_induction && bounded.is_none() && inconclusive.is_none() && (depth >= 3 || last) {
tried_induction = true;
let saved = (ctx.work_limit, ctx.max_terms, ctx.deadline);
let now = Instant::now();
let half_time = saved.2.map(|d| if d > now { now + (d - now) / 2 } else { d });
let used = ctx.work();
let half_work = match saved.0 {
u64::MAX => u64::MAX,
limit => used + limit.saturating_sub(used) / 2,
};
ctx.set_budget(half_work, saved.1, half_time);
let proof = loops::prove(&mut ctx, &job, &pre, (sym.addr, sym.addr + sym.size.max(2)));
ctx.set_budget(saved.0, saved.1, saved.2);
ctx.prover.forget_unknown();
if let Some(proof) = proof {
out.report.paths += proof.paths;
out.cov.extend(proof.cov);
for (a, n) in proof.bytes {
out.bytes.extend(a..a + n as u32);
}
break;
}
}
if last {
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();
}
let explanation = match &out.report.status {
Status::Mismatch(_) => why_mismatch,
Status::Inconclusive(_) => why_inconclusive,
Status::Bounded(why) => {
let limit = why.split(';').next().unwrap_or(why);
let mut e = why_bounded.unwrap_or_else(|| crate::explain::report::limit_only(limit));
e.reason = limit.to_string();
e.induction = Some(tried_induction);
Some(e)
}
_ => None,
};
let (paths, skipped_paths) = crate::explain::report::take_paths();
if explanation.is_some() || !paths.is_empty() {
out.report.detail = Some(Box::new(crate::explain::FuncDetail {
explanation,
paths,
skipped_paths,
}));
}
out.report.millis = start.elapsed().as_millis();
let (_, sat_calls, conflicts, props) = ctx.prover.counters();
out.report.sat_calls = sat_calls;
out.report.conflicts = conflicts;
out.report.work = props / 1000 + ctx.tm.len() as u64;
out
}
fn check_data(prog: &Program, image: &Image, env: &CEnv, report: &mut Report) {
report.data_issues.extend(env.data_notes.iter().cloned());
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 env.is_synthetic(addr) {
continue;
}
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]
));
}
}
}
fn resolve_ambiguous(prog: &Program, image: &Image, env: &mut CEnv, opts: &Options) {
let pending = std::mem::take(&mut env.ambiguous);
if pending.is_empty() {
return;
}
let trial = Options {
only: Vec::new(),
time_limit: opts.time_limit.min(Duration::from_secs(5)),
..opts.clone()
};
let mut fits: Vec<(u32, Vec<u32>)> = Vec::new();
for (fid, cands) in &pending {
let mut ok = Vec::new();
for &a in cands {
env.func_addr[*fid as usize] = Some(a);
let o = verify_function(prog, image, env, *fid, &trial);
let good = match o.report.status {
Status::Proved => true,
Status::Bounded(_) => o.report.paths > 0,
_ => false,
};
if good {
ok.push(a);
}
}
env.func_addr[*fid as usize] = None;
fits.push((*fid, ok));
}
fits.sort_by_key(|f| f.1.len());
let mut taken: HashSet<u32> = HashSet::new();
for (fid, ok) in fits {
if let Some(&a) = ok.iter().find(|a| !taken.contains(a)) {
taken.insert(a);
env.bind_func(fid, a);
}
}
}
const WORKER_STACK: usize = 32 << 20;
struct Permit;
static RUNNING: std::sync::Mutex<usize> = std::sync::Mutex::new(0);
static FREED: std::sync::Condvar = std::sync::Condvar::new();
impl Permit {
fn acquire(cap: usize) -> Permit {
let mut n = RUNNING.lock().unwrap_or_else(|e| e.into_inner());
while *n >= cap {
n = FREED.wait(n).unwrap_or_else(|e| e.into_inner());
}
*n += 1;
Permit
}
}
impl Drop for Permit {
fn drop(&mut self) {
*RUNNING.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
FREED.notify_one();
}
}
pub(crate) fn run_jobs<R: Send>(items: &[u32], jobs: usize, work: impl Fn(u32) -> R + Sync) -> Vec<R> {
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
let cpus = std::thread::available_parallelism().map_or(1, |n| n.get());
let jobs = match jobs {
0 => cpus,
n => n,
}
.min(items.len().max(1));
let cap = jobs.max(cpus);
let next = AtomicUsize::new(0);
let results: Mutex<Vec<Option<R>>> = Mutex::new(items.iter().map(|_| None).collect());
std::thread::scope(|s| {
let handles: Vec<_> = (0..jobs)
.map(|_| {
std::thread::Builder::new()
.stack_size(WORKER_STACK)
.spawn_scoped(s, || {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
let Some(&item) = items.get(i) else { break };
let permit = Permit::acquire(cap);
let r = work(item);
drop(permit);
results.lock().unwrap()[i] = Some(r);
}
})
.expect("spawn verification thread")
})
.collect();
for h in handles {
if let Err(e) = h.join() {
std::panic::resume_unwind(e);
}
}
});
results
.into_inner()
.unwrap()
.into_iter()
.map(|r| r.expect("every item was processed"))
.collect()
}
pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
let mut env = CEnv::new(prog, image);
resolve_ambiguous(prog, image, &mut env, opts);
let env = env;
let mut report = Report::default();
let mut cov: BTreeSet<u32> = BTreeSet::new();
let mut bytes: BTreeSet<u32> = BTreeSet::new();
let todo: Vec<u32> = prog
.funcs
.iter()
.enumerate()
.filter(|(fid, f)| f.body.is_some() && env.func_addr[*fid].is_some())
.filter(|(_, f)| opts.only.is_empty() || opts.only.iter().any(|n| **n == *f.name))
.map(|(fid, _)| fid as u32)
.collect();
for o in run_jobs(&todo, opts.jobs, |fid| verify_function(prog, image, &env, fid, 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() && env.func_addr[fid].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
}
fn has_float(prog: &Program, t: crate::c::ast::TypeId) -> bool {
match prog.ty(t) {
Type::Float { .. } => true,
Type::Array(e, _) => has_float(prog, *e),
Type::Record(r) => prog.records[*r as usize].fields.iter().any(|f| has_float(prog, f.ty)),
_ => false,
}
}