use crate::c::ast::{Program, Type, VOID};
use crate::c::exec::INDIRECT;
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::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};
mod loops;
#[derive(Clone, Debug)]
pub struct Options {
pub limits: Limits,
pub dropped: Option<u32>,
pub at: Option<u32>,
pub only: Vec<String>,
pub asm_sources: Vec<(String, 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 modular: bool,
pub merge: bool,
pub cache: Option<std::path::PathBuf>,
pub aliasing: crate::c::exec::Aliasing,
}
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(),
dropped: None,
at: None,
only: Vec::new(),
asm_sources: Vec::new(),
time_limit: Duration::from_secs(300),
jobs: 0,
work_limit: 500_000,
max_terms: 20_000_000,
dump: 0,
deadline: None,
modular: true,
merge: true,
aliasing: Default::default(),
check_solver: false,
cache: None,
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>>,
pub modulo: Vec<(String, String)>,
pub unconditional: bool,
pub cached: bool,
pub assumes: Vec<String>,
pub given: Option<String>,
pub hazards: Vec<crate::sym::Hazard>,
pub assembly: bool,
}
#[derive(Clone, Debug, Default)]
pub struct Report {
pub funcs: Vec<FuncReport>,
pub aliasing: &'static str,
pub src: (usize, usize),
pub bin: (usize, usize),
pub bin_constants: usize,
pub library_differs: Vec<String>,
pub unmatched: Vec<(String, u32)>,
pub absent: Vec<String>,
pub absent_points: usize,
pub src_no_code: Vec<(String, u32, 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>,
pub skipped_sources: Vec<(String, String)>,
pub set_aside: Vec<(u32, u32, String)>,
pub unexplained: usize,
}
#[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,
SetAside,
}
impl ByteState {
pub fn label(self) -> &'static str {
match self {
ByteState::Proved => "proved",
ByteState::Unproved => "unproved",
ByteState::Padding => "padding",
ByteState::SetAside => "set-aside",
}
}
}
#[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)>,
}
fn path_result(ctx: &mut Ctx, cx: &CExec, m: &Machine) -> PathResult {
let mut res = PathResult {
cov: cx.cov.clone(),
insns: m.covered.clone(),
data: m.data_covered.clone(),
};
for arm in ctx.feasible_arms() {
res.cov.extend(arm.cov);
res.insns.extend(arm.insns);
res.data.extend(arm.data);
}
res
}
const VA_STACK_WORDS: u32 = 8;
struct Job<'a> {
blocks: std::sync::Arc<crate::thumb::exec::Blocks>,
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)],
opaque: std::sync::Arc<Vec<bool>>,
opaque_names: HashMap<String, u32>,
modular: bool,
trace: std::cell::RefCell<(Vec<Option<u32>>, usize)>,
stray: std::cell::Cell<Option<u32>>,
targets: std::cell::RefCell<Vec<(usize, T)>>,
used: std::cell::RefCell<BTreeSet<u32>>,
used_at: std::cell::RefCell<BTreeSet<u32>>,
one_name_used: std::cell::RefCell<BTreeSet<String>>,
call_map: std::cell::RefCell<Option<CallMap>>,
result_unused: bool,
rt: std::cell::RefCell<Vec<RtPath>>,
rt_volatile: std::cell::Cell<(bool, bool)>,
asm_keeps: std::cell::RefCell<HashMap<u32, u16>>,
}
#[derive(Clone, Debug)]
struct CallMap {
pos: Vec<usize>,
void: bool,
flag: Option<usize>,
}
const GONE: usize = usize::MAX;
impl CallMap {
fn of(name: &str, plain: &str, n: usize) -> Option<CallMap> {
let aeabi = |stem: &str| {
name.strip_prefix(stem)
.is_some_and(|rest| matches!(rest, "" | "4" | "8"))
};
let mut flag = None;
let (pos, void): (Vec<usize>, bool) = match plain {
"memcpy" if n == 3 && aeabi("__aeabi_memcpy") => (vec![0, 1, 2], true),
"memmove" if n == 3 && aeabi("__aeabi_memmove") => (vec![0, 1, 2], true),
"memset" if n == 3 && aeabi("__aeabi_memset") => (vec![0, 2, 1], true),
"memset" if n == 3 && aeabi("__aeabi_memclr") => (vec![0, GONE, 1], true),
_ => {
let fortified = name.strip_prefix("__").and_then(|p| p.strip_suffix("_chk"));
let &(_, at) = FORTIFIED_PRINTF
.iter()
.find(|f| f.0 == plain && fortified == Some(plain))?;
flag = Some(at);
((0..n).map(|i| if i < at { i } else { i + 2 }).collect(), false)
}
};
Some(CallMap { pos, void, flag })
}
}
impl Job<'_> {
fn unused_result(&self, f: u32) -> bool {
unused_result(self.env, self.image, f)
}
fn culprit(&self, ctx: &mut Ctx) -> Option<u32> {
if !self.modular {
return None;
}
if let Some(f) = self.stray.get() {
return Some(f);
}
let t = self.trace.borrow();
if let Some(&(_, target)) = self.targets.borrow().iter().find(|x| x.0 == t.1)
&& let Some(v) = ctx.unique_value(target)
&& let Some(f) = (0..self.opaque.len())
.find(|&f| self.opaque[f] && self.env.func_addr[f].is_some_and(|a| (a | 1) as u64 == v))
{
return Some(f as u32);
}
t.0.iter().take(t.1 + 1).rev().find_map(|f| *f)
}
}
fn aliases(prog: &Program, image: &Image, env: &mut CEnv) {
let funcs = || image.symbols.iter().filter(|s| s.kind == SymKind::Func);
let weak = |n: &str| image.meta.weak_funcs.iter().any(|w| w == n);
let mut count: HashMap<&str, u32> = HashMap::new();
let mut first: HashMap<u32, &str> = HashMap::new();
for s in funcs() {
*count.entry(s.name.as_str()).or_default() += 1;
if let Some(f) = image.func_at(s.addr) {
first.entry(s.addr).or_insert(f.name.as_str());
}
}
for s in funcs() {
let to = first[&s.addr];
if env.addr_to_func.contains_key(&s.addr) || env.copies.contains_key(&s.addr) {
continue;
}
if to != s.name && count[s.name.as_str()] == 1 && !weak(&s.name) && !weak(to) {
env.canon.insert(s.name.clone(), to.to_string());
}
}
env.alias_of = vec![None; prog.funcs.len()];
for (fid, f) in prog.funcs.iter().enumerate() {
if f.body.is_some() || f.is_static || weak(&f.name) {
continue;
}
if count.get(&*f.name) != Some(&1) {
continue;
}
let Some(addr) = image.func(&f.name).map(|s| s.addr) else {
continue;
};
let Some(&def) = env.addr_to_func.get(&addr).or_else(|| env.copies.get(&addr)) else {
continue;
};
let d = &prog.funcs[def as usize];
if def as usize != fid && d.body.is_some() && prog.funcs_may_be_compatible(&f.ty, &d.ty, 0) {
env.alias_of[fid] = Some(def);
}
}
}
fn callable(prog: &Program, image: &Image, env: &CEnv) -> Vec<bool> {
let mut count: HashMap<&str, u32> = HashMap::new();
let mut at: HashSet<(u32, &str)> = HashSet::new();
for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func) {
*count.entry(s.name.as_str()).or_default() += 1;
at.insert((s.addr, s.name.as_str()));
}
prog.funcs
.iter()
.enumerate()
.map(|(fid, f)| {
f.body.is_some()
&& f.ty.proto
&& env.func_addr[fid].is_some_and(|a| {
at.contains(&(a, &*f.name)) && env.addr_to_func.get(&a) == Some(&(fid as u32))
})
&& (count.get(&*f.name) == Some(&1)
|| (image.symbols.iter())
.filter(|s| s.kind == SymKind::Func && s.name == *f.name)
.all(|s| env.func_addr[fid] == Some(s.addr) || env.copies.get(&s.addr) == Some(&(fid as u32))))
})
.collect()
}
pub(crate) fn copy_name(name: &str, addr: u32) -> String {
format!("{name} @ {addr:#x}")
}
fn asm_keeps(image: &Image, addr: u32) -> u16 {
let mut ctx = Ctx::new(Limits::default());
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);
}
regs[13] = ctx.private_base("SP0");
regs[14] = ctx.named_sym("LR0", 32);
regs[15] = ctx.tm.konst(32, 0);
let mut m = Machine::new(&mut ctx, addr, regs);
let classify = |_: u32| Callee::External("?".into());
match m.run(&mut ctx, image, regs[14], &classify) {
Ok(Exit::Return) if ctx.decisions.is_empty() && m.regs[13] == regs[13] => [0usize, 1, 2, 3, 12]
.into_iter()
.filter(|&i| m.regs[i] == regs[i])
.fold(0, |mask, i| mask | 1 << i),
_ => 0,
}
}
struct RtPath {
site: u32,
name: String,
reads: Vec<(i64, u8)>,
reads_unknown: bool,
writes: Vec<(i64, u8)>,
writes_unknown: bool,
freed: i64,
}
fn record_rt(
ctx: &mut Ctx,
job: &Job,
m: &Machine,
esc: &Escapes,
sites: &[(u32, usize, String, Option<T>, usize)],
ended: &[(usize, usize)],
k: usize,
) {
let Some(trace) = &m.trace else { return };
for (site, start, name, ret, ev) in sites {
let k = (ended.iter().find(|e| e.0 == *ev)).map_or(k, |e| e.1.min(k));
let reader = match ret {
Some(r) => {
let z = ctx.tm.konst(ctx.tm.width(*r), 0);
let zero = ctx.tm.eq(*r, z);
!ctx.implied(zero)
}
None => true,
};
let mut p = RtPath {
site: *site,
name: name.clone(),
reads: Vec::new(),
reads_unknown: false,
writes: Vec::new(),
writes_unknown: false,
freed: i64::MIN,
};
let mut written: Vec<(i64, i64)> = Vec::new();
for a in &trace[*start..] {
match (a.write, a.off) {
(true, Some(o)) if a.size == 0 => {
if (a.ev as usize) < k {
p.freed = p.freed.max(o)
}
}
(true, Some(o)) => {
written.push((o, o + a.size as i64));
if (a.ev as usize) < k {
p.writes.push((o, a.size));
}
}
(true, None) => p.writes_unknown |= (a.ev as usize) < k,
(false, Some(o)) => {
let end = o + a.size as i64;
let escaped = esc.map.values().any(|&(_, d, size)| o >= d && end <= d + size as i64);
if reader && !escaped && !written.iter().any(|&(lo, hi)| o >= lo && end <= hi) {
p.reads.push((o, a.size));
}
}
(false, None) => p.reads_unknown |= reader,
}
}
job.rt.borrow_mut().push(p);
}
}
fn rt_conflict(paths: &[RtPath]) -> Option<String> {
for p in paths {
let same = || paths.iter().filter(|q| q.site == p.site);
let any_write = same().any(|q| q.writes_unknown || !q.writes.is_empty());
let hit = if p.reads_unknown && any_write || !p.reads.is_empty() && same().any(|q| q.writes_unknown) {
Some("a computed stack address".to_string())
} else {
p.reads.iter().find_map(|&(o, n)| {
(same().any(|q| o < q.freed)
|| same()
.flat_map(|q| q.writes.iter())
.any(|&(w, wn)| o < w + wn as i64 && w < o + n as i64))
.then(|| format!("offset {o} from the entry stack pointer"))
})
};
if let Some(at) = hit {
return Some(format!(
"{} may return a second time: the code after it reads the stack frame at {at}, which the function overwrites or releases before a later call (the frame is not restored by the jump back)",
p.name
));
}
}
None
}
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));
let group =
|v: u64| COPIES.with(|c| c.borrow().iter().find(|g| g.0 == (v as u32 & !1)).map(|g| g.1.clone()));
if let (Some(g), Some(h)) = (group(cv), group(bv))
&& g == h
{
return Err(Stop::Unsupported(format!(
"{what}: the binary uses the address {bv:#x} of `{g}`, which the image has at several addresses, where the source's `{g}` is {cv:#x}"
)));
}
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(())
}
fn hang_world(ctx: &mut Ctx, job: &Job, ev: &Event, m: &Machine) -> R<()> {
let mut seen: HashSet<(T, u8)> = HashSet::new();
let entries: Vec<(T, u8, bool)> = (ev.writes.iter().map(|w| (w.addr, w.size, true)))
.chain(m.mem.world.iter().map(|w| (w.addr, w.size, false)))
.collect();
for (addr, size, source) in entries {
if !seen.insert((addr, size)) || ctx.region(addr).is_some() {
continue;
}
let (env, epoch) = (job.env, ev.epoch);
let mut c_init = move |ctx: &mut Ctx, a: T, s: u8| env.initial(ctx, a, s, epoch);
let cv = ctx.read_world(&ev.writes, 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 cv == bv || (size == 4 && same_literal(ctx, job, cv, bv)) {
continue;
}
if ev.exposed.iter().any(|e| ctx.may_point_into(addr, e)) {
continue; }
let mut b_init = image_init(job.image, m.mem.epoch, None);
let before = ctx.read_world(&[], addr, size, &mut b_init);
if source && before == bv {
let same = ctx.tm.eq(cv, bv);
if !ctx.implied(same) {
ctx.hang_dropped = true;
}
continue;
}
crate::explain::report::note_addr(addr);
let at = ctx.tm.show(addr);
prove_eq(
ctx,
cv,
bv,
&format!("memory where the function loops for ever: {size}-byte value stored at {at}"),
)?;
}
Ok(())
}
#[derive(Default)]
struct Escapes {
map: HashMap<T, (T, i64, u32)>,
dynamic: HashMap<T, (T, T)>,
}
fn frame_pos(ctx: &mut Ctx, job: &Job, a: T) -> T {
let d = ctx.tm.sub(a, job.regs[13]);
ctx.tm.add_const(d, FRAME_SPAN as u64)
}
fn frame_rule(ctx: &mut Ctx, cond: T, what: impl Fn() -> String) -> R<()> {
match ctx.check(cond) {
Ok(()) => Ok(()),
Err(Some(env)) => Err(Stop::Mismatch(what(), Some(env))),
Err(None) => Err(Stop::Inconclusive(format!("{}: prover gave up", what()))),
}
}
fn can_bind(ctx: &mut Ctx, base: T, bb: T, name: &str, what: &str) -> R<()> {
let differ = ctx.tm.ne(base, bb);
if ctx.check(differ).is_err() {
return Ok(());
}
let never = ctx.tm.fals();
if ctx.check(never).is_ok() {
return Ok(());
}
if std::env::var("CVERIF_DEBUG").is_ok_and(|v| v == "2") {
eprintln!("cannot bind {} to {}:", ctx.tm.show(base), ctx.tm.show(bb));
for (n, l) in [("pc", ctx.pc.clone()), ("ub", ctx.ub.clone())] {
for t in l {
eprintln!(" {n}: {}", ctx.tm.show(t));
}
}
}
Err(Stop::Unsupported(format!(
"{what}: the binary keeps {name} at {}, which contradicts what the source assumes about that address (its alignment, or that other pointers differ from it)",
ctx.tm.show(bb)
)))
}
fn bind_dangling(
ctx: &mut Ctx,
job: &Job,
cx: &crate::c::exec::CExec,
esc: &mut Escapes,
c: T,
b: T,
what: &str,
) -> R<()> {
for _ in 0..4 {
let mut found = None;
let (mut seen, mut stack) = (HashSet::new(), vec![c]);
while let Some(x) = stack.pop() {
if !seen.insert(x) {
continue;
}
if ctx.private_bases.contains(&x) && !ctx.bound.contains(&x) {
found = Some(x);
break;
}
stack.extend(crate::bv::Prover::children_of(ctx.tm.node(x)));
}
let Some(base) = found else { return Ok(()) };
let Some((size, align, name)) = cx.local_shapes.get(&base).cloned() else {
return Ok(());
};
let name = name.trim_start_matches('&');
let differ = ctx.tm.ne(c, b);
let Err(Some(env)) = ctx.check(differ) else {
return Ok(());
};
let sp0 = job.regs[13];
let mut memo = Default::default();
let d = ctx
.tm
.eval(base, &env, &mut memo)
.wrapping_sub(ctx.tm.eval(sp0, &env, &mut memo));
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);
let depth = frame_depth(job.image, job.entry);
if d + size as i64 > top
|| d < -depth
|| esc
.map
.values()
.any(|&(_, d2, s2)| d < d2 + s2 as i64 && d2 < d + size as i64)
{
return Ok(());
}
let bb = ctx.tm.add_const(sp0, d as u64);
if d.rem_euclid(align as i64) != 0 || can_bind(ctx, base, bb, name, what).is_err() {
return Ok(());
}
esc.map.insert(base, (bb, d, size));
let same = ctx.tm.eq(base, bb);
ctx.pc.push(same);
ctx.bound.insert(base);
ctx.bound.insert(sp0);
}
Ok(())
}
fn frame_depth(image: &Image, addr: u32) -> i64 {
use crate::thumb::decode::{Addr, DpOp, Offset, Op, Operand, decode};
let Some(f) = image.func_at(addr & !1) else { return 0 };
let (mut a, end, mut depth) = (f.addr, f.addr + f.size, 0i64);
while a < end {
if image.is_data_in_code(a) {
a += 2;
continue;
}
let Some(insn) = image
.read(a, 4)
.or_else(|| image.read(a, 2))
.and_then(|b| decode(b, a, false))
else {
break;
};
match insn.op {
Op::StoreMulti {
rn: 13,
regs,
wback: true,
..
} => depth += 4 * regs.count_ones() as i64,
Op::Dp {
op: DpOp::Sub,
rd: Some(13),
rn: Some(13),
src: Operand::Imm { value, .. },
..
} => depth += value as i64,
Op::Dp {
op: DpOp::Add,
rd: Some(13),
rn: Some(13),
src: Operand::Imm { .. },
..
} => {}
Op::Store {
addr:
Addr::Base {
rn: 13,
offset: Offset::Imm(o),
wback: true,
..
},
..
}
| Op::StoreDual {
addr:
Addr::Base {
rn: 13,
offset: Offset::Imm(o),
wback: true,
..
},
..
} => depth += (-(o as i64)).max(0),
Op::Dp { rd: Some(13), .. } | Op::Load { rt: 13, .. } => return FRAME_SPAN as i64,
_ => {}
}
a += insn.len as u32;
}
depth
}
fn eq_at_return(
ctx: &mut Ctx,
job: &Job,
cx: &crate::c::exec::CExec,
esc: &mut Escapes,
c: T,
b: T,
what: &str,
) -> R<()> {
if !ctx.mentions_unbound_private(c) {
return prove_eq(ctx, c, b, what);
}
bind_dangling(ctx, job, cx, esc, c, b, what)?;
match prove_eq(ctx, c, b, what) {
Err(Stop::Mismatch(..)) => Err(Stop::Unsupported(format!(
"{what}: the address of a local object escapes"
))),
r => r,
}
}
fn aligned(ctx: &mut Ctx, bb: T, align: u32, name: &str, what: &str) -> R<()> {
if align <= 1 {
return Ok(());
}
let mask = ctx.tm.konst(32, align as u64 - 1);
let low = ctx.tm.and(bb, mask);
let zero = ctx.tm.konst(32, 0);
let ok = ctx.tm.eq(low, zero);
frame_rule(ctx, ok, || {
format!("{what}: the binary keeps {name} at an address that is not aligned to {align} bytes")
})
}
fn apart(ctx: &mut Ctx, a: T, an: T, b: T, bn: T) -> T {
let ae = ctx.tm.add(a, an);
let be = ctx.tm.add(b, bn);
let x = ctx.tm.ule(ae, b);
let y = ctx.tm.ule(be, a);
ctx.tm.or(x, y)
}
fn bind_dynamic(
ctx: &mut Ctx,
job: &Job,
esc: &mut Escapes,
ev: &Event,
obj: &crate::sym::Escaped,
(off, b): (T, T),
what: &str,
) -> R<()> {
let name = obj.name.trim_start_matches('&');
let size = obj.dynamic.as_ref().expect("dynamic object").size;
let bb = match esc.dynamic.get(&obj.base) {
Some(e) => e.0,
None => {
let bb = ctx.tm.sub(b, off);
let sp0 = job.regs[13];
if !matches!(ctx.private_split(bb), Some((base, _)) if base == sp0) {
return Err(Stop::Unsupported(format!(
"{what}: source passes the address of {name}, binary passes {} which is not an address in its stack frame",
ctx.tm.show(b)
)));
}
let top = job.stack_args.iter().map(|a| a.0 + 4).max().unwrap_or(0);
let pos = frame_pos(ctx, job, bb);
let lim = ctx.tm.konst(32, (FRAME_SPAN + top) as u64);
let below = ctx.tm.ule(pos, lim);
let room = ctx.tm.sub(lim, pos);
let fits = ctx.tm.ule(size, room);
let inside = ctx.tm.and(below, fits);
frame_rule(ctx, inside, || {
format!("{what}: source passes the address of {name}, binary passes a stack address outside its frame")
})?;
let live = |b: &T| ev.escaped.iter().any(|e| e.base == *b);
let mut others: Vec<(T, T)> = Vec::new();
for (b2, &(_, d2, s2)) in esc.map.iter().filter(|(b2, _)| live(b2)) {
let _ = b2;
let p2 = ctx.tm.konst(32, (FRAME_SPAN as i64 + d2) as u64);
let n2 = ctx.tm.konst(32, s2 as u64);
others.push((p2, n2));
}
for (_, &(bb2, s2)) in esc.dynamic.iter().filter(|(b2, _)| live(b2)) {
others.push((frame_pos(ctx, job, bb2), s2));
}
for (p2, n2) in others {
let ok = apart(ctx, pos, size, p2, n2);
frame_rule(ctx, ok, || {
format!("{what}: binary places {name} over another local visible to the callee")
})?;
}
aligned(ctx, bb, obj.align, name, what)?;
esc.dynamic.insert(obj.base, (bb, size));
can_bind(ctx, obj.base, bb, name, what)?;
let same = ctx.tm.eq(obj.base, bb);
ctx.pc.push(same);
ctx.bound.insert(obj.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 {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_dynamic(
ctx: &mut Ctx,
job: &Job,
cx: &CExec,
esc: &mut Escapes,
m: &mut Machine,
ev: &Event,
(obj, k): (&crate::sym::Escaped, usize),
) -> R<()> {
let name = obj.name.trim_start_matches('&');
let dy = obj.dynamic.as_ref().expect("dynamic object");
let Some(&(bb, size)) = esc.dynamic.get(&obj.base) else {
return Err(Stop::Unsupported(format!(
"call #{} to {}: {name} is reachable by the callee but its place in the binary's frame is unknown",
k + 1,
ev.name
)));
};
let sp = m.regs[13];
let (psp, pbb) = (frame_pos(ctx, job, sp), frame_pos(ctx, job, bb));
let live = ctx.tm.ule(psp, pbb);
frame_rule(ctx, live, || {
format!("call #{} to {}: {name} lies below the stack pointer", k + 1, ev.name)
})?;
let mut locs: Vec<(T, u8, bool)> = Vec::new();
for w in dy.log.iter().filter(|w| w.havoc.is_none()) {
let off = ctx.tm.sub(w.addr, obj.base);
let known = w.guard.is_none();
if !locs.contains(&(off, w.size, known)) {
locs.push((off, w.size, known));
}
}
let stack: Vec<(T, u8)> = ctx
.region(bb)
.and_then(|r| m.mem.private.get(&r))
.map(|log| {
log.iter()
.filter(|w| w.havoc.is_none())
.map(|w| (w.addr, w.size))
.collect()
})
.unwrap_or_default();
for (addr, n) in stack {
let off = ctx.tm.sub(addr, bb);
if locs.iter().any(|l| l.0 == off && l.1 == n) {
continue;
}
let nk = ctx.tm.konst(32, n as u64);
let after = ctx.tm.ule(size, off);
let back = ctx.tm.sub(bb, addr);
let before = ctx.tm.ule(nk, back);
let outside = ctx.tm.and(after, before);
if ctx.implied(outside) {
continue;
}
for j in 0..n {
let o = ctx.tm.add_const(off, j as u64);
if !locs.iter().any(|l| l.0 == o && l.1 == 1) {
locs.push((o, 1, false));
}
}
}
for (off, n, known) in locs {
let ca = ctx.tm.add(obj.base, off);
let mut c_init = |ctx: &mut Ctx, a: T, s: u8| ctx.tm.load(crate::sym::UNINIT_EPOCH, a, s);
let cv = ctx.read_world(&dy.log, ca, n, &mut c_init);
let parts: Vec<(T, u8, T)> = if !ctx.mentions_uninit(cv) {
vec![(off, n, cv)]
} else {
(0..n)
.filter_map(|j| {
let o = ctx.tm.add_const(off, j as u64);
let a = ctx.tm.add_const(ca, j as u64);
let b = ctx.read_world(&dy.log, a, 1, &mut c_init);
(!ctx.mentions_uninit(b)).then_some((o, 1, b))
})
.collect()
};
for (off, n, cv) in parts {
let ba = ctx.tm.add(bb, off);
let mut init = image_init(job.image, m.mem.epoch, None);
let bv = ctx.mem_read(&m.mem, ba, n, &mut init);
if cv == bv {
continue;
}
let what = format!("{name} (offset {}) at call #{} to {}", ctx.tm.show(off), k + 1, ev.name);
if known {
match_value(ctx, job, cx, esc, ev, (cv, bv), &what)?;
} else {
let nk = ctx.tm.konst(32, n as u64);
let fits = ctx.tm.ule(nk, size);
let room = ctx.tm.sub(size, nk);
let low = ctx.tm.ule(off, room);
let inside = ctx.tm.and(fits, low);
ctx.pc.push(inside);
let r = match_value(ctx, job, cx, esc, ev, (cv, bv), &what);
ctx.pc.pop();
r?;
}
}
}
Ok(())
}
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 c != b
&& let Some(ca) = ctx.tm.as_const(c)
&& let Some(lit) = literal_at(job.env, ca as u32)
&& let Some(ba) = ctx.unique_value(b)
&& ca != ba
{
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) = ctx.tm.as_const(c)
&& let Some(lit) = literal_at(job.env, ca as u32)
&& let Some(ba) = ctx.unique_value(b)
&& ca != ba
&& 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) = ctx.tm.as_const(off)
&& let Some(ba) = 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);
};
if obj.dynamic.is_some() {
return bind_dynamic(ctx, job, esc, ev, obj, (off, 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 rel = ctx.tm.sub(bb, sp0);
let Some(d) = ctx.unique_value(rel) 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,
));
}
let live_dyn: Vec<(T, T)> = esc.dynamic.iter().filter(|(b2, _)| live(b2)).map(|(_, v)| *v).collect();
for (bb2, s2) in live_dyn {
let p = ctx.tm.konst(32, (FRAME_SPAN as i64 + d) as u64);
let n = ctx.tm.konst(32, obj.size as u64);
let p2 = frame_pos(ctx, job, bb2);
let ok = apart(ctx, p, n, p2, s2);
frame_rule(ctx, ok, || {
format!("{what}: binary places local {name} over another local visible to the callee")
})?;
}
let bb = if ctx.tm.const_diff(bb, sp0).is_some() {
bb
} else {
ctx.tm.add_const(sp0, d as u64)
};
aligned(ctx, bb, obj.align, name, what)?;
esc.map.insert(base, (bb, d, obj.size));
can_bind(ctx, base, bb, name, what)?;
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 doing(ev: &Event) -> String {
match ev.name.strip_prefix("asm:") {
Some(insn) if ev.asm.is_some() => format!("executing `{insn}`"),
_ => format!("calling {}", ev.name),
}
}
fn call_locs(ctx: &Ctx, ev: &Event, map: Option<&CallMap>) -> Vec<Option<ArgLoc>> {
let widths: Vec<u8> = ev.args.iter().map(|a| ctx.tm.width(a.0).max(32)).collect();
match map {
Some(map) if map.pos.len() == widths.len() => {
let n = map.pos.iter().filter(|&&p| p != GONE).max().map_or(0, |m| m + 1);
let mut theirs = vec![32u8; n];
for (&p, &w) in map.pos.iter().zip(&widths) {
if p != GONE {
theirs[p] = w;
}
}
let locs = arg_locs(&theirs);
map.pos.iter().map(|&p| (p != GONE).then(|| locs[p])).collect()
}
_ => arg_locs(&widths).into_iter().map(Some).collect(),
}
}
fn match_call(ctx: &mut Ctx, job: &Job, cx: &CExec, esc: &mut Escapes, m: &mut Machine, ev: &Event, k: usize) -> R<()> {
let sp = m.regs[13];
let locs = call_locs(ctx, ev, job.call_map.borrow().as_ref());
for (i, (&(val, signed), loc)) in ev.args.iter().zip(locs).enumerate() {
let Some(loc) = loc else {
let byte = ctx.tm.trunc(val, 8);
let zero = ctx.tm.konst(8, 0);
prove_eq(
ctx,
byte,
zero,
&format!("argument {} of call #{} to {}", i + 1, k + 1, ev.name),
)?;
continue;
};
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)?;
}
match_memory(ctx, job, cx, esc, m, ev, k)
}
fn match_memory(
ctx: &mut Ctx,
job: &Job,
cx: &CExec,
esc: &mut Escapes,
m: &mut Machine,
ev: &Event,
k: usize,
) -> R<()> {
let sp = m.regs[13];
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 {
if obj.dynamic.is_some() {
match_dynamic(ctx, job, cx, esc, m, ev, (obj, k))?;
continue;
}
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, job: &Job, esc: &Escapes, m: &mut Machine, ev: &Event, k: usize) {
after_escaped(ctx, esc, m, ev);
let sp = m.regs[13];
for loc in call_locs(ctx, ev, job.call_map.borrow().as_ref()).into_iter().flatten() {
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 after_escaped(ctx: &mut Ctx, esc: &Escapes, m: &mut Machine, ev: &Event) {
for obj in &ev.escaped {
if let Some(dy) = &obj.dynamic {
if let (Some(id), Some(&(bb, size))) = (dy.havoc, esc.dynamic.get(&obj.base)) {
ctx.mem_havoc(&mut m.mem, bb, size, id, obj.base);
}
continue;
}
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);
}
}
}
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,
exposed: Vec<ExposedLocal>,
}
#[derive(Clone, Debug, PartialEq)]
struct ExposedLocal {
base: T,
at: i64,
size: u32,
align: u32,
name: 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,
bound: Vec<(T, i64, u32)>,
bound_dynamic: bool,
}
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.opaque = job.opaque.clone();
cx.modular = job.modular;
*job.trace.borrow_mut() = (Vec::new(), 0);
job.stray.set(None);
job.targets.borrow_mut().clear();
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.set_escaped(init.exposed.iter().map(|e| e.base).collect());
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)),
Ok(BodyEnd::Join) => unreachable!("a segment does not end inside a merged region"),
Err(Stop::Halt) => (None, true, None),
Err(e) => return Err(e),
};
crate::explain::report::note_source(&cx, ret, halted);
if job.modular {
*job.targets.borrow_mut() = cx.indirect.clone();
job.used.borrow_mut().extend(
(cx.events.iter())
.filter_map(|ev| job.opaque_names.get(ev.name.as_str()).copied())
.filter(|f| !job.env.copies.values().any(|c| c == f)),
);
job.trace.borrow_mut().0 = (cx.events.iter())
.map(|ev| job.opaque_names.get(ev.name.as_str()).copied())
.collect();
}
let classify = |addr: u32| -> Callee {
if let Some(name) = job.image.externals.get(&addr) {
return Callee::External(name.clone());
}
if let Some(&fid) = (job.env.addr_to_func.get(&addr)).or_else(|| job.env.copies.get(&addr))
&& job.opaque[fid as usize]
{
return Callee::External(p.funcs[fid as usize].name.to_string());
}
match job.image.func_at(addr) {
Some(s) => {
let has_body = p
.funcs
.iter()
.any(|f| f.body.is_some() && !f.opaque && *f.name == *base_name(&s.name))
|| (job.env.addr_to_func.get(&addr).or_else(|| job.env.copies.get(&addr)))
.is_some_and(|&f| p.funcs[f as usize].body.is_some() && !p.funcs[f as usize].opaque);
if job.modular && crate::discover::is_anonymous(&s.name) && UNIFIED.with(|u| u.borrow().is_some()) {
return Callee::External(format!("?{addr:08x}"));
}
if has_body || s.name.starts_with("OUTLINED_FUNCTION_") || crate::discover::is_anonymous(&s.name) {
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);
m.blocks = job.blocks.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);
}
m
}
Some(init) => {
let mut m = Machine::new(ctx, init.m_pc, init.m_regs);
m.blocks = job.blocks.clone();
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.modular = job.modular;
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();
if let Some(init) = ctl.init {
for e in &init.exposed {
let sp0 = job.regs[13];
let bb = ctx.tm.add_const(sp0, e.at as u64);
let name = e.name.trim_start_matches('&');
aligned(ctx, bb, e.align, name, "loop head")?;
esc.map.insert(e.base, (bb, e.at, e.size));
can_bind(ctx, e.base, bb, name, "loop head")?;
let same = ctx.tm.eq(e.base, bb);
ctx.pc.push(same);
ctx.bound.insert(e.base);
ctx.bound.insert(sp0);
m.mem.exposed.push(Exposed {
base: bb,
size: e.size,
dyn_size: None,
since: 0,
});
}
}
let mut rt_sites: Vec<(u32, usize, String, Option<T>, usize)> = Vec::new();
let exposed_in_binary = |esc: &Escapes, ev: &Event| -> Vec<Exposed> {
ev.exposed
.iter()
.filter_map(|e| {
if let Some(&(bb, size)) = esc.dynamic.get(&e.base) {
return Some(Exposed {
base: bb,
size: 0,
dyn_size: Some(size),
since: e.since,
});
}
esc.map.get(&e.base).map(|&(bb, _, size)| Exposed {
base: bb,
size,
dyn_size: None,
since: e.since,
})
})
.collect()
};
loop {
job.trace.borrow_mut().1 = k;
m.nev = k as u32;
if cx.fell_off && k == cx.events.len() {
compare_world(
ctx,
job,
&cx.mem.world,
cx.mem.epoch,
&cx.mem.exposed,
&m,
"memory where the naked function ends",
&mut |ctx, c, b, what| prove_eq(ctx, c, b, what),
)?;
break;
}
match m.run(ctx, job.image, job.lr0, &classify)? {
Exit::Asm { name, arg, out } => {
m.note_read(0xffff);
check_result_slot(ctx, job, &m)?;
let full = format!("asm:{name}");
let Some(ev) = cx.events.get(k).filter(|ev| ev.asm.is_some() && ev.name == full) else {
return Err(Stop::Mismatch(
match cx.events.get(k) {
Some(ev) => format!("binary executes `{name}` where the source is {}", doing(ev)),
None => format!("binary executes `{name}`, which the source does not do at this point"),
},
None,
));
};
check_volatile(ctx, &cx, &m, k)?;
match (arg, ev.args.first()) {
(Some(got), Some(&(want, _))) => {
let want = ctx.tm.resize(want, 32, false);
prove_eq(ctx, want, got, &format!("value written by `{name}` (event #{})", k + 1))?;
}
(None, None) => {}
_ => {
return Err(Stop::Mismatch(
format!("binary executes `{name}` with different operands than the source"),
None,
));
}
}
if ev.asm == Some(true) {
match_memory(ctx, job, &cx, &mut esc, &mut m, ev, k)?;
m.mem.world.clear();
m.mem.epoch = ev.epoch + 1;
m.mem.exposed = exposed_in_binary(&esc, ev);
after_escaped(ctx, &esc, &mut m, ev);
}
if let Some(rd) = out {
let Some((sym, _)) = ev.ret else {
return Err(Stop::Mismatch(
format!("binary executes `{name}` with different operands than the source"),
None,
));
};
m.regs[rd as usize] = ctx.tm.resize(sym, 32, false);
}
k += 1;
if ev.noreturn {
break;
}
}
Exit::Call { name } => {
m.note_read(0x000f);
let name = if name.starts_with('?') {
unify_call(job, &name, cx.events.get(k))?
} else {
name
};
let called = m.call_addr.take();
let differs = cx.events.get(k).filter(|ev| ev.name != name);
let map = differs.and_then(|ev| CallMap::of(&name, &ev.name, ev.args.len()));
let plain = (name.strip_prefix("__").and_then(|n| n.strip_suffix("_chk"))).map(str::to_string);
let plain = plain.as_deref();
let name = match (differs, &map, plain) {
(Some(ev), Some(_), _) => ev.name.clone(),
(_, _, Some(plain))
if cx.events.get(k).is_none_or(|ev| ev.name != name) && FORTIFIED.contains(&plain) =>
{
plain.to_string()
}
_ => name,
};
if let Some(t) = &mut m.trace {
let off = ctx.tm.const_diff(m.regs[13], job.regs[13]);
t.push(crate::thumb::exec::StackAcc {
write: true,
off: off.map(|d| d as u32 as i32 as i64),
size: 0,
ev: k as u32,
});
}
let fortified = match plain {
Some(plain) if name == plain => fortified_size(ctx, job, &m, plain)?,
_ => None,
};
if let Some(at) = map.as_ref().and_then(|m| m.flag) {
fortified_flag(ctx, job, &m, &name, at)?;
}
let void = map.as_ref().is_some_and(|m| m.void);
*job.call_map.borrow_mut() = map;
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))
{
if let Some((dest, size)) = fortified {
fortified_local(ctx, job, &esc, dest, size, &name)?;
}
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 {
job.stray.set(job.opaque_names.get(name.as_str()).copied());
return Err(Stop::Mismatch(
format!("binary calls {name}, which the source does not call at this point"),
None,
));
};
let direct = (ev.name == INDIRECT && name != INDIRECT && m.indirect.is_none())
.then(|| job.opaque_names.get(name.as_str()))
.flatten()
.and_then(|&fid| job.env.func_addr[fid as usize]);
if let Some(addr) = direct {
let want = cx
.indirect
.iter()
.find(|t| t.0 == k)
.expect("indirect event has a target")
.1;
let got = ctx.tm.konst(32, (addr | 1) as u64);
prove_eq(ctx, want, got, &format!("target of call #{} through a pointer", k + 1))?;
} else if ev.name != name || ev.asm.is_some() {
if !job.opaque_names.contains_key(ev.name.as_str()) {
job.stray.set(job.opaque_names.get(name.as_str()).copied());
}
if name.starts_with("__") && name.ends_with("_chk") {
return Err(Stop::Unsupported(format!(
"fortified library call {name} where the source calls {}",
ev.name
)));
}
return Err(Stop::Mismatch(
format!("binary calls {name} where the source is {}", doing(ev)),
None,
));
}
if let Some(&fid) = job.opaque_names.get(name.as_str())
&& job.env.copies.values().any(|&c| c == fid)
{
match called {
Some(a) if job.env.copies.get(&a) == Some(&fid) => {
job.used_at.borrow_mut().insert(a);
}
Some(a) if job.env.func_addr[fid as usize] == Some(a) => {
job.used.borrow_mut().insert(fid);
}
_ => {
job.used.borrow_mut().insert(fid);
let all = (job.env.copies.iter()).filter(|c| *c.1 == fid).map(|c| *c.0);
job.used_at.borrow_mut().extend(all);
}
}
}
if job.env.one_name.contains_key(name.as_str()) {
job.one_name_used.borrow_mut().insert(name.clone());
}
check_volatile(ctx, &cx, &m, k)?;
if ctx.tm.const_diff(m.regs[13], job.regs[13]).is_none() {
let down = ctx.tm.sub(job.regs[13], m.regs[13]);
let span = ctx.tm.konst(32, FRAME_SPAN as u64);
let ok = ctx.tm.ule(down, span);
frame_rule(ctx, ok, || {
format!(
"stack pointer at call #{} to {name}: it may lie outside the function's own frame",
k + 1
)
})?;
}
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)?;
if let Some((dest, size)) = fortified {
fortified_local(ctx, job, &esc, dest, size, &name)?;
}
m.mem.world.clear();
m.mem.epoch = ev.epoch + 1;
m.mem.exposed = exposed_in_binary(&esc, ev);
k += 1;
if ev.noreturn {
break;
}
let (lo, hi) = match ev.ret {
None => (None, None),
Some(_) if void => (None, None),
Some(_) if (job.opaque_names.get(name.as_str())).is_some_and(|&f| job.unused_result(f)) => {
(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, job, &esc, &mut m, ev, k - 1);
let keeps = match (
p.funcs.iter().find(|f| f.opaque && *f.name == *base_name(&name)),
called,
) {
(Some(_), Some(addr)) if !job.image.meta.weak_funcs.contains(&name) => *job
.asm_keeps
.borrow_mut()
.entry(addr)
.or_insert_with(|| asm_keeps(job.image, addr)),
_ => 0,
};
let before = m.regs;
m.finish_call(ctx, k - 1, lo, hi);
for i in [0usize, 1, 2, 3, 12] {
let result = (i == 0 && lo.is_some()) || (i == 1 && hi.is_some());
if keeps >> i & 1 == 1 && !result {
m.regs[i] = before[i];
}
}
if ev.returns_twice {
if ctl.init.is_some() || !ctl.c_cuts.is_empty() || !ctl.m_cuts.is_empty() {
return Err(cut_error("the loop calls a function that may return twice"));
}
let at = m.trace.get_or_insert_with(Vec::new).len();
rt_sites.push((m.resume_pc(), at, ev.name.clone(), ev.ret.map(|r| r.0), k - 1));
}
}
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 = path_result(ctx, &cx, &m);
return Ok(SegEnd {
res,
cut: Some((b, pc)),
cx,
m,
bound: esc.map.iter().map(|(b, v)| (*b, v.1, v.2)).collect(),
bound_dynamic: !esc.dynamic.is_empty(),
});
}
ref e @ (Exit::Trap | Exit::Hang) => {
let (does, name) = match e {
Exit::Trap => ("traps (udf)", "<trap>"),
_ => ("loops for ever", "<hang>"),
};
check_result_slot(ctx, job, &m)?;
if c_cut.is_some() {
return Err(cut_error(&format!(
"the binary {does} where the source reaches a loop head"
)));
}
let Some(ev) = cx.events.get(k) else {
return Err(Stop::Mismatch(format!("binary {does} where the source does not"), None));
};
if ev.name != name {
return Err(Stop::Mismatch(
format!("binary {does} where the source is {}", doing(ev)),
None,
));
}
check_volatile(ctx, &cx, &m, k)?;
if matches!(e, Exit::Hang) {
hang_world(ctx, job, ev, &m)?;
} else {
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 {}", doing(ev)), 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.filter(|_| !job.result_unused) {
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) = ctx.tm.as_const(off)
&& let Some(ba) = 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]) {
{
let full = std::mem::replace(&mut ctx.prover.budget, 2_000);
let _ = ctx.unique_value(m.regs[0]);
ctx.prover.budget = full;
}
eq_at_return(ctx, job, &cx, &mut esc, 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| eq_at_return(ctx, job, &cx, &mut esc, 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"),
)?;
}
record_rt(ctx, job, &m, &esc, &rt_sites, &cx.rt_ended, k);
let (r, w) = job.rt_volatile.get();
job.rt_volatile.set((r | cx.rt_volatile.0, w | cx.rt_volatile.1));
let res = path_result(ctx, &cx, &m);
return Ok(SegEnd {
res,
cut: None,
cx,
m,
bound: esc.map.iter().map(|(b, v)| (*b, v.1, v.2)).collect(),
bound_dynamic: !esc.dynamic.is_empty(),
});
}
}
}
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,
));
}
record_rt(ctx, job, &m, &esc, &rt_sites, &cx.rt_ended, k);
let (r, w) = job.rt_volatile.get();
job.rt_volatile.set((r | cx.rt_volatile.0, w | cx.rt_volatile.1));
let res = path_result(ctx, &cx, &m);
Ok(SegEnd {
res,
cut: None,
cx,
m,
bound: esc.map.iter().map(|(b, v)| (*b, v.1, v.2)).collect(),
bound_dynamic: !esc.dynamic.is_empty(),
})
}
struct FuncOutcome {
report: FuncReport,
cov: BTreeSet<u32>,
bytes: BTreeSet<u32>,
}
fn assembly_report(image: &Image, name: &str, addr: u32, status: Status, ranges: &[(u32, u32)]) -> FuncOutcome {
FuncOutcome {
report: FuncReport {
name: name.to_string(),
addr,
size: image.func_at(addr & !1).map_or(0, |s| s.size),
paths: matches!(status, Status::Proved) as usize,
status,
undefined_paths: 0,
millis: 0,
sat_calls: 0,
conflicts: 0,
work: 0,
detail: None,
modulo: Vec::new(),
unconditional: false,
cached: false,
assumes: Vec::new(),
given: None,
hazards: Vec::new(),
assembly: true,
},
cov: BTreeSet::new(),
bytes: ranges.iter().flat_map(|&(a, b)| a..b).collect(),
}
}
fn assembly_outcome(
image: &Image,
name: &str,
addr: u32,
src: &crate::thumb::asm::Source,
lines: &[crate::thumb::asm::Line],
) -> FuncOutcome {
use crate::thumb::asm::Fail;
let addr = addr & !1;
let lenient = !src.unified && image.thumb1_only();
let m = match crate::thumb::asm::compare(image, lines, addr, lenient) {
Ok(m) => m,
Err(Fail::Differs(why)) => return assembly_report(image, name, addr, Status::Mismatch(why), &[]),
Err(Fail::Unsupported(why)) => {
return assembly_report(image, name, addr, Status::Unsupported(format!("assembly: {why}")), &[]);
}
};
let end = addr + image.func_at(addr).map_or(0, |s| s.size);
let mut ranges = m.ranges.clone();
let mut a = m.end;
while a < end {
if m.ranges.iter().any(|r| a >= r.0 && a < r.1) {
a += 1;
continue;
}
let n = if a & 1 == 0 && a + 1 < end { 2 } else { 1 };
let fill = image.read(a, n).is_some_and(|b| {
b.iter().all(|&x| x == 0) || (n == 2 && matches!(u16::from_le_bytes([b[0], b[1]]), 0xbf00 | 0x46c0))
});
if !fill && m.closed {
a += n;
continue;
}
if !fill {
return assembly_report(
image,
name,
addr,
Status::Mismatch(format!(
"the binary has code or data at {a:#x} that the assembly source does not have"
)),
&[],
);
}
ranges.push((a, a + n));
a += n;
}
assembly_report(image, name, addr, Status::Proved, &ranges)
}
fn assembly_files(prog: &Program, image: &Image, env: &CEnv, opts: &Options) -> Vec<FuncOutcome> {
use crate::thumb::asm::Item;
let mut out = Vec::new();
let mut seen: HashSet<u32> = HashSet::new();
for (file, text) in &opts.asm_sources {
let src = match crate::thumb::asm::parse(text) {
Ok(s) => s,
Err(e) => {
eprintln!("cverif: warning: {file}: {e}; its routines are not verified");
continue;
}
};
let is_func = |n: &str| image.func(n).filter(|s| s.kind == SymKind::Func);
let defined = |n: &str| {
(prog.funcs.iter().enumerate())
.any(|(i, f)| *f.name == *n && f.body.is_some() && env.func_addr[i].is_some())
};
for i in 0..src.lines.len() {
let Item::Label(name) = &src.lines[i].item else {
continue;
};
let Some(sym) = is_func(name) else { continue };
if defined(name) || !(opts.only.is_empty() || opts.only.iter().any(|o| o == name)) {
continue;
}
if !seen.insert(sym.addr) {
continue;
}
let mut j = i + 1;
while j < src.lines.len() {
match &src.lines[j].item {
Item::Section => break,
Item::Label(n) if is_func(n).is_some_and(|s| s.addr != sym.addr) => break,
_ => j += 1,
}
}
out.push(assembly_outcome(image, name, sym.addr, &src, &src.lines[i..j]));
}
}
out
}
#[allow(clippy::type_complexity)]
fn locate_blocks(
image: &Image,
f: &crate::c::ast::Func,
sym: &crate::image::Symbol,
) -> Result<(HashMap<u32, (String, Option<u8>, u32)>, Vec<(u32, u32)>), String> {
let (mut blocks, mut bytes) = (HashMap::new(), Vec::new());
for b in &f.asm_blocks {
let regs: Vec<Option<u8>> = match (b.operand, b.low || image.thumb1_only()) {
(false, _) => vec![None],
(true, true) => (0..8).map(Some).collect(),
(true, false) => (0..13).chain([14]).map(Some).collect(),
};
let mut found = Vec::new();
for r in regs {
let text = crate::c::parse::asm_operand(&b.text, &format!("r{}", r.unwrap_or(0)));
let src = crate::thumb::asm::parse(&text).map_err(|e| format!("inline assembly {}: {e}", b.name))?;
let lenient = !src.unified && image.thumb1_only();
for a in (sym.addr..sym.addr + sym.size).step_by(2) {
if !image.is_data_in_code(a)
&& let Ok(m) = crate::thumb::asm::compare(image, &src.lines, a, lenient)
{
found.push((a, r, m));
}
}
}
let [(a, r, m)] = &found[..] else {
return Err(format!(
"inline assembly {}: {} in the code of {}",
b.name,
if found.is_empty() {
"these instructions are not"
} else {
"these instructions are more than once"
},
f.name
));
};
if b.sets_sp && *a != sym.addr {
return Err(format!(
"inline assembly {}: not the first thing the binary's {} does",
b.name, f.name
));
}
let first_end = m.ranges.first().map_or(*a, |r| r.1);
for &(lo, _) in m.ranges.iter().filter(|r| r.0 > *a && r.0 < m.end) {
blocks
.entry(lo)
.or_insert(("<the middle of an assembly statement>".to_string(), None, lo));
}
blocks.insert(*a, (b.name.to_string(), *r, if b.sets_sp { first_end } else { *a }));
bytes.extend(m.ranges.iter().copied());
}
Ok((blocks, bytes))
}
fn verify_function(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
let run = |opts: &Options| {
guarded(prog, env, fid, || {
if std::env::var("CVERIF_TEST_PANIC").is_ok_and(|n| n == *prog.funcs[fid as usize].name) {
panic!("requested by CVERIF_TEST_PANIC");
}
verify_following(prog, image, env, fid, opts, &[])
})
};
if !opts.merge || opts.dump > 0 {
return run(&Options {
merge: false,
..opts.clone()
});
}
MERGED.with(|m| m.set(0));
let merged = run(&Options {
work_limit: opts.work_limit / MERGE_SHARE,
..opts.clone()
});
if merged.report.status == Status::Proved {
return merged;
}
let untouched = MERGED.with(|m| m.get()) == 0;
let plain = run(&Options {
merge: false,
..opts.clone()
});
if untouched {
return plain;
}
let further = |o: &FuncOutcome| o.cov.len() + o.bytes.len();
let both_bounded =
matches!(merged.report.status, Status::Bounded(_)) && matches!(plain.report.status, Status::Bounded(_));
let (mut kept, other) = if both_bounded && further(&merged) > further(&plain) {
(merged, plain)
} else {
(plain, merged)
};
kept.report.millis += other.report.millis;
kept.report.sat_calls += other.report.sat_calls;
kept.report.conflicts += other.report.conflicts;
kept.report.work += other.report.work;
kept
}
const MERGE_SHARE: u64 = 4;
thread_local! {
static COPIES: std::cell::RefCell<Vec<(u32, String)>> = const { std::cell::RefCell::new(Vec::new()) };
static MERGED: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static LAST_PANIC: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
static GUARDED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn caught<R>(run: impl FnOnce() -> R) -> Result<R, String> {
static HOOK: std::sync::Once = std::sync::Once::new();
HOOK.call_once(|| {
let usual = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let what = (info.payload().downcast_ref::<&str>().map(|s| s.to_string()))
.or_else(|| info.payload().downcast_ref::<String>().cloned())
.unwrap_or_else(|| "panic".to_string());
let at = info
.location()
.map(|l| format!(" at {}:{}", l.file(), l.line()))
.unwrap_or_default();
if !GUARDED.with(|g| g.get()) {
return usual(info);
}
let via = call_chain(&std::backtrace::Backtrace::force_capture().to_string());
LAST_PANIC.with(|p| *p.borrow_mut() = Some(format!("{what}{at}{via}")));
if std::env::var_os("CVERIF_DEBUG").is_some() {
usual(info);
}
}));
});
let outer = GUARDED.with(|g| g.replace(true));
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run));
GUARDED.with(|g| g.set(outer));
caught.map_err(|_| {
LAST_PANIC
.with(|p| p.borrow_mut().take())
.unwrap_or_else(|| "panic".to_string())
})
}
fn call_chain(backtrace: &str) -> String {
let mut names: Vec<&str> = Vec::new();
for line in backtrace.lines() {
let Some((n, name)) = line.trim().split_once(": ") else {
continue;
};
if n.parse::<u32>().is_err() || !name.starts_with("cverif::") {
continue;
}
let name = name.trim_start_matches("cverif::");
let name = name.split("::{{closure}}").next().unwrap_or(name);
if name.starts_with("verify::caught") || name.starts_with("verify::guarded") {
if names.is_empty() {
continue;
}
break;
}
if names.last() != Some(&name) {
names.push(name);
}
if names.len() == 8 {
break;
}
}
if names.is_empty() {
String::new()
} else {
format!(", called from {}", names.join(" < "))
}
}
pub(crate) fn internal_error(what: &str) -> String {
format!(
"internal error in cverif {} ({what}); this is a defect of the verifier, not a property of the \
function: please report it",
env!("CARGO_PKG_VERSION")
)
}
fn guarded(prog: &Program, env: &CEnv, fid: u32, run: impl FnOnce() -> FuncOutcome) -> FuncOutcome {
let start = Instant::now();
match caught(run) {
Ok(o) => o,
Err(what) => {
let f = &prog.funcs[fid as usize];
let addr = env.func_addr[fid as usize].unwrap_or(0);
FuncOutcome {
report: FuncReport {
name: f.name.to_string(),
addr,
size: 0,
status: Status::Inconclusive(internal_error(&what)),
paths: 0,
undefined_paths: 0,
millis: start.elapsed().as_millis(),
sat_calls: 0,
conflicts: 0,
work: 0,
detail: None,
modulo: Vec::new(),
unconditional: false,
cached: false,
assumes: Vec::new(),
given: None,
hazards: Vec::new(),
assembly: false,
},
cov: BTreeSet::new(),
bytes: BTreeSet::new(),
}
}
}
}
fn verify_following(
prog: &Program,
image: &Image,
env: &CEnv,
fid: u32,
opts: &Options,
follow: &[u32],
) -> FuncOutcome {
let pinned = |f: usize| {
env.replaceable.get(f).copied().unwrap_or(false)
|| (f as u32 != fid
&& (prog.funcs[f].unsupported.is_some()
|| prog.funcs[f].asm.is_some()
|| !prog.funcs[f].asm_blocks.is_empty())
&& env.callable.get(f).copied().unwrap_or(false))
};
let none = std::sync::Arc::new((0..prog.funcs.len()).map(pinned).collect::<Vec<bool>>());
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!("verifying {}", prog.funcs[fid as usize].name);
}
if !opts.modular || env.callable.is_empty() {
let lib: Vec<bool> = (env.library.iter().enumerate())
.map(|(i, &l)| l && !follow.contains(&(i as u32)))
.collect();
if lib.iter().any(|&l| l) {
let (o, culprit) = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(lib), true));
if culprit.is_none() {
return o;
}
}
return verify_attempt(prog, image, env, fid, opts, (none, false)).0;
}
let start = Instant::now();
let mut opaque = env.callable.clone();
for &f in follow {
opaque[f as usize] = false;
}
let mut spent = (0u64, 0u64, 0u64);
let finish = |mut o: FuncOutcome, spent: (u64, u64, u64)| {
o.report.millis = start.elapsed().as_millis();
o.report.sat_calls += spent.0;
o.report.conflicts += spent.1;
o.report.work += spent.2;
o
};
let mut unsettled: Option<Vec<bool>> = None;
let settle = |o: FuncOutcome, unsettled: Option<Vec<bool>>, spent: &mut (u64, u64, u64)| match unsettled {
Some(opaque) if matches!(o.report.status, Status::Unsupported(_) | Status::Inconclusive(_)) => {
*spent = (
spent.0 + o.report.sat_calls,
spent.1 + o.report.conflicts,
spent.2 + o.report.work,
);
verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(opaque), false)).0
}
_ => o,
};
for _ in 0..MODULAR_RETRIES {
GAVE_UP.with(|g| g.set(false));
let (o, culprit) = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(opaque.clone()), true));
let Some(c) = culprit else {
let o = settle(o, unsettled, &mut spent);
return finish(o, spent);
};
if unsettled.is_none() && GAVE_UP.with(|g| g.get()) {
unsettled = Some(opaque.clone());
}
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!(" following {}", prog.funcs[c as usize].name);
}
spent = (
spent.0 + o.report.sat_calls,
spent.1 + o.report.conflicts,
spent.2 + o.report.work,
);
if pinned(c as usize) {
let o = verify_attempt(prog, image, env, fid, opts, (std::sync::Arc::new(opaque), false)).0;
let o = settle(o, unsettled, &mut spent);
return finish(o, spent);
}
opaque[c as usize] = false;
}
let o = verify_attempt(prog, image, env, fid, opts, (none, false)).0;
let o = settle(o, unsettled, &mut spent);
finish(o, spent)
}
fn fortified_size(ctx: &mut Ctx, job: &Job, m: &Machine, plain: &str) -> R<Option<(T, u64)>> {
let (len, size) = match plain {
"memcpy" | "memmove" | "mempcpy" | "memset" | "strncpy" | "stpncpy" => (Some(2), 3),
"strncat" => (None, 3),
"snprintf" | "vsnprintf" => (Some(1), 3),
_ => (None, 2),
};
let os = m.regs[size];
let Some(os) = ctx.tm.as_const(os) else {
return Err(Stop::Unsupported(format!(
"fortified library call __{plain}_chk: the size of the destination is not a constant"
)));
};
if os == 0xffff_ffff {
return Ok(None);
}
if let Some(len) = len {
let k = ctx.tm.konst(32, os);
let fits = ctx.tm.ule(m.regs[len], k);
if ctx.implied(fits) {
return Ok(None);
}
}
let dest = m.regs[0];
if let Some(a) = ctx.tm.as_const(dest) {
let whole = (job.image.symbols.iter())
.filter(|s| s.kind == SymKind::Object && s.size > 0)
.find(|s| (s.addr as u64..s.addr as u64 + s.size as u64).contains(&a));
return match whole {
Some(s) if os >= s.addr as u64 + s.size as u64 - a => Ok(None),
_ => Err(Stop::Unsupported(format!(
"fortified library call __{plain}_chk: it stops the program beyond {os} bytes, which may be less than the destination holds"
))),
};
}
Ok(Some((dest, os)))
}
fn fortified_flag(ctx: &mut Ctx, job: &Job, m: &Machine, plain: &str, at: usize) -> R<()> {
let wanted: Vec<Option<u32>> = (job.prog.fortify_flags.iter())
.filter(|f| &*f.0 == plain)
.map(|f| f.1)
.collect();
if wanted.is_empty() {
return Err(Stop::Unsupported(format!(
"fortified library call __{plain}_chk where the source calls {plain}: it was compiled with a _FORTIFY_SOURCE the source was not read with (pass the same -D)"
)));
}
if wanted.contains(&None) {
return Err(Stop::Unsupported(format!(
"fortified library call __{plain}_chk: the flag the source passes is not a constant"
)));
}
let got = ctx.tm.as_const(m.regs[at]);
if got.is_some_and(|g| wanted.contains(&Some(g as u32))) {
return Ok(());
}
let wanted: Vec<String> = wanted.iter().flatten().map(|w| w.to_string()).collect();
let got = got.map_or("a value that is not a constant".to_string(), |g| g.to_string());
Err(Stop::Mismatch(
format!(
"binary passes the flag {got} to __{plain}_chk where the source passes {}",
wanted.join(" or ")
),
None,
))
}
fn fortified_local(ctx: &mut Ctx, job: &Job, esc: &Escapes, dest: T, os: u64, name: &str) -> R<()> {
if let Some(off) = ctx.tm.const_diff(dest, job.regs[13]) {
let off = off as u32 as i32 as i64;
if (esc.map.values())
.any(|&(_, d, size)| d <= off && off < d + size as i64 && os as i64 >= d + size as i64 - off)
{
return Ok(());
}
}
Err(Stop::Unsupported(format!(
"fortified form of library call {name}: it stops the program beyond {os} bytes, which may be less than the destination holds"
)))
}
fn vacuity_audit() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("CVERIF_CHECK_VACUOUS").is_some())
}
const FORTIFIED: [&str; 10] = [
"memcpy", "memmove", "mempcpy", "memset", "strcpy", "stpcpy", "strcat", "strncpy", "stpncpy", "strncat",
];
const FORTIFIED_PRINTF: [(&str, usize); 4] = [("sprintf", 1), ("vsprintf", 1), ("snprintf", 2), ("vsnprintf", 2)];
thread_local! {
static GAVE_UP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
const MODULAR_RETRIES: usize = 6;
fn unused_result(env: &CEnv, image: &Image, f: u32) -> bool {
env.callers.result_unused.get(f as usize).copied().unwrap_or(false)
&& env.func_addr[f as usize]
.and_then(|a| image.func_at(a))
.is_some_and(|s| !s.global)
}
fn verify_attempt(
prog: &Program,
image: &Image,
env: &CEnv,
fid: u32,
opts: &Options,
(opaque, modular): (std::sync::Arc<Vec<bool>>, bool),
) -> (FuncOutcome, Option<u32>) {
let f = &prog.funcs[fid as usize];
COPIES.with(|c| {
*c.borrow_mut() = (env.copies.iter())
.flat_map(|(&a, &f)| [Some(a), env.func_addr[f as usize]].map(|x| (x, f)))
.filter_map(|(a, f)| Some((a?, prog.funcs[f as usize].name.to_string())))
.chain(env.several.iter().cloned())
.collect();
});
let sym = (opts.at.or(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: match opts.at {
Some(a) if env.func_addr[fid as usize] != Some(a) => copy_name(&f.name, a),
_ => 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,
modulo: Vec::new(),
unconditional: false,
cached: false,
assumes: Vec::new(),
given: None,
hazards: Vec::new(),
assembly: false,
},
cov: BTreeSet::new(),
bytes: BTreeSet::new(),
};
let blocks = match locate_blocks(image, f, sym) {
Ok((blocks, ranges)) => {
out.bytes.extend(ranges.iter().flat_map(|&(a, b)| a..b));
blocks
}
Err(why) => {
out.report.status = Status::Unsupported(why);
return (out, None);
}
};
let mut ctx = Ctx::new(opts.limits);
ctx.merge = opts.merge;
UNIFIED.with(|u| {
if let Some(map) = u.borrow_mut().as_mut() {
map.clear();
}
});
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, None);
}
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, None);
}
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 floor = ctx.tm.konst(32, 2 * FRAME_SPAN as u64);
let ceil = ctx.tm.konst(32, (FRAME_SPAN as u64).wrapping_neg() & 0xffff_ffff);
pre.push(ctx.tm.ule(floor, regs[13]));
pre.push(ctx.tm.ule(regs[13], ceil));
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 dropped = opts.dropped.map(|d| d as usize);
let shapes: Vec<(u32, bool)> = (f.ty.params.iter().enumerate())
.filter(|(i, _)| Some(*i) != dropped)
.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();
let mut places = arg_words(&shapes, ret_slot.is_some() as u8).into_iter();
for (i, &ty) in f.ty.params.iter().enumerate() {
if Some(i) == dropped {
let w = prog.bits(ty);
let vw = if ty == crate::c::ast::BOOL { 1 } else { w };
let narrow = ctx.named_sym(&format!("unpassed{i}:{vw}"), vw);
args.push(ctx.tm.resize(narrow, w, false));
continue;
}
let Some(locs) = places.next() else { break };
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 !sym.global
&& let Some(given) = env.callers.given.get(fid as usize)
{
let mut said = Vec::new();
for (i, set) in given.iter().enumerate() {
let name = || {
f.locals
.get(i)
.map_or_else(|| format!("argument {}", i + 1), |l| l.name.to_string())
};
let bound = (env.callers.below.get(fid as usize)).and_then(|b| b.get(i).copied().flatten());
if let (None, Some(bound), Some(&v)) = (set, bound, args.get(i))
&& ctx.tm.width(v) == 32
{
let k = ctx.tm.konst(32, bound);
pre.push(ctx.tm.ult(v, k));
said.push(format!("{} < {bound}", name()));
}
let (Some(set), Some(&v)) = (set, args.get(i)) else {
continue;
};
let w = ctx.tm.width(v);
let mut any = ctx.tm.fals();
for &c in set {
let k = ctx.tm.konst(w, c);
let eq = ctx.tm.eq(v, k);
any = ctx.tm.or(any, eq);
}
pre.push(any);
let vals: Vec<String> = set.iter().map(|c| c.to_string()).collect();
let name = f
.locals
.get(i)
.map_or_else(|| format!("argument {}", i + 1), |l| l.name.to_string());
said.push(match (set.first(), set.last()) {
(Some(&a), Some(&b)) if set.len() > 2 && b - a + 1 == set.len() as u64 => format!("{name} in {a}..{b}"),
_ if set.len() == 1 => format!("{name} = {}", vals[0]),
_ => format!("{name} in {{{}}}", vals.join(", ")),
});
}
if !said.is_empty() {
out.report.given = Some(format!("for {}: all callers", said.join(", ")));
}
}
let result_unused = unused_result(env, image, fid);
if result_unused {
let said = "result not compared: no caller uses it".to_string();
out.report.given = Some(match out.report.given.take() {
Some(g) => format!("{g}; {said}"),
None => said,
});
}
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,
blocks: std::sync::Arc::new(blocks),
opaque_names: (opaque.iter().enumerate())
.filter(|o| *o.1)
.map(|(i, _)| (prog.funcs[i].name.to_string(), i as u32))
.collect(),
opaque,
modular,
trace: Default::default(),
stray: Default::default(),
targets: Default::default(),
used: Default::default(),
used_at: Default::default(),
one_name_used: Default::default(),
call_map: Default::default(),
result_unused,
rt: Default::default(),
rt_volatile: Default::default(),
asm_keeps: Default::default(),
};
let mut retry: Option<u32> = None;
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;
let mut induction_failure: Option<loops::Failure> = None;
'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();
job.rt.borrow_mut().clear();
job.rt_volatile.set((false, false));
out.report.paths = 0;
out.report.undefined_paths = 0;
loop {
ctx.restart(&pre);
crate::explain::report::begin_path(pre.len());
explored += 1;
let res = match run_path(&mut ctx, &job) {
Err(Stop::Mismatch(why, None)) => {
let never = ctx.tm.fals();
match ctx.check(never) {
Ok(()) => Err(Stop::Undefined),
Err(Some(env)) => Err(Stop::Mismatch(why, Some(env))),
Err(None) => Err(Stop::Inconclusive(format!(
"{why}: prover gave up on whether the path is feasible"
))),
}
}
r => r,
};
crate::explain::report::end_path(&ctx, Some(prog), fid, &res);
if res.is_ok() && vacuity_audit() {
let never = ctx.tm.fals();
if ctx.check(never).is_ok() {
let pc = ctx.pc.clone();
let plain = matches!(ctx.prover.prove(&mut ctx.tm, &pc, never), crate::bv::Verdict::Proved);
eprintln!(
"vacuous: {}: a proved path that no input takes ({})",
f.name,
if plain {
"its branch conditions contradict each other"
} else {
"only because of what the source is assumed not to do"
}
);
}
}
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(e @ (Stop::Mismatch(..) | Stop::Unsupported(_))) if job.culprit(&mut ctx).is_some() => {
if std::env::var_os("CVERIF_DEBUG").is_some() {
match &e {
Stop::Mismatch(w, _) => eprintln!(" attempt failed: mismatch: {w}"),
Stop::Unsupported(w) => eprintln!(" attempt failed: unsupported: {w}"),
_ => {}
}
}
retry = job.culprit(&mut ctx);
break 'rounds;
}
Err(Stop::Inconclusive(why)) if ctx.check_deadline().is_ok() && job.culprit(&mut ctx).is_some() => {
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!(" attempt failed: inconclusive: {why}");
}
GAVE_UP.with(|g| g.set(true));
retry = job.culprit(&mut ctx);
break 'rounds;
}
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();
match proof {
Ok(proof) => {
if proof.object_size {
out.report.assumes.push("no object larger than PTRDIFF_MAX".into());
}
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;
}
Err(f) => induction_failure = Some(f),
}
}
if last {
bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
}
}
out.report.paths = out.report.paths.max(best_paths);
let mut induction_note: Option<(&'static str, String)> = None;
if out.report.status == Status::Proved {
if let Some(why) = rt_conflict(&job.rt.borrow()) {
out.report.status = Status::Inconclusive(why);
out.cov.clear();
out.bytes.clear();
} else if job.rt_volatile.get() == (true, true) {
out.report.status = Status::Inconclusive(
"a call may return a second time: the source reads a volatile local after it and stores to one before a later call, so the value read is the stored one, which the comparison of the first return does not show"
.into(),
);
out.cov.clear();
out.bytes.clear();
} else if let Some(why) = inconclusive {
out.report.status = Status::Inconclusive(why);
} else if let Some(why) = bounded {
let (code, detail) = match &induction_failure {
Some(f) => (f.code, f.detail.clone()),
None if tried_induction => ("unsupported-shape", String::new()),
None => (
"not-attempted",
format!("{} reached first", why.split(" (").next().unwrap_or(&why)),
),
};
induction_note = Some((code, detail.clone()));
let sep = if detail.is_empty() { "" } else { ": " };
out.report.status = Status::Bounded(format!(
"{why}; {} paths proved; induction {code}{sep}{detail}",
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);
if let Some((code, detail)) = &induction_note {
e.induction_code = code.to_string();
e.induction_detail = detail.clone();
}
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;
if ctx.model_used {
out.report.assumes.push("strict-aliasing".into());
}
let proved = |f: &u32| env.library_proved.get(*f as usize).copied().unwrap_or(false);
if let Some((_, how)) = (env.library_differs.iter()).find(|d| ctx.library_used.contains(&d.0)) {
out.report.assumes.push(format!(
"the library's meaning for a function the program defines, though {how}"
));
} else if ctx.library_used.iter().any(|f| !proved(f)) {
out.report
.assumes
.push("the library's meaning for a function the program defines".into());
}
if !ctx.abi_calls.is_empty() {
let names: Vec<&str> = ctx.abi_calls.iter().map(|n| n.as_str()).collect();
out.report.assumes.push(format!(
"the calling convention's meaning for a call to {}, declared here with another type than it is defined with",
names.join(", ")
));
}
if ctx.hang_dropped {
out.report
.assumes
.push("nothing reads what the source stores before a loop that never ends".into());
}
out.report.hazards = ctx.hazards.iter().copied().collect();
MERGED.with(|m| m.set(m.get() + ctx.merges.0));
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!(
"attempt: {:?} after {} ms: {} terms, {} thousand propagations, {} solver calls, {} paths explored, retry {:?}",
out.report.status,
out.report.millis,
ctx.tm.len(),
props / 1000,
sat_calls,
explored,
retry.map(|f| &*prog.funcs[f as usize].name)
);
let forks: Vec<String> = (crate::sym::FORK_KINDS.iter().zip(&ctx.forks))
.filter(|f| *f.1 > 0)
.map(|(k, n)| format!("{k} {n}"))
.collect();
eprintln!(
"forks: {}; merged {} regions, gave up on {}",
forks.join(", "),
ctx.merges.0,
ctx.merges.1
);
}
out.report.modulo = (job.used.borrow().iter())
.map(|&f| (prog.funcs[f as usize].name.to_string(), String::new()))
.collect();
for &a in job.used_at.borrow().iter() {
let name = copy_name(&prog.funcs[env.copies[&a] as usize].name, a);
out.report.modulo.push((name, String::new()));
}
for name in job.one_name_used.borrow().iter() {
out.report.assumes.push(format!(
"the {} addresses named {name} are one function",
env.one_name[name]
));
}
(out, retry)
}
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]
));
}
}
}
const LIBRARY_REFERENCE: [(&str, &[u16]); 4] = [
("memset", &[0x2300, 0x4293, 0xd100, 0x4770, 0x54c1, 0x3301, 0xe7f9]),
(
"memcpy",
&[0xb510, 0x2300, 0x4293, 0xd100, 0xbd10, 0x5ccc, 0x54c4, 0x3301, 0xe7f8],
),
(
"memmove",
&[
0xb510, 0x1a43, 0x4293, 0xd206, 0x2a00, 0xd100, 0xbd10, 0x3a01, 0x5c8c, 0x5484, 0xe7f8, 0x2300, 0x4293,
0xd100, 0xbd10, 0x5ccc, 0x54c4, 0x3301, 0xe7f8,
],
),
("memcpy", &[]),
];
fn library_contracts(prog: &Program, env: &mut CEnv, opts: &Options) {
env.library_proved = vec![false; prog.funcs.len()];
let fids: Vec<u32> = (0..prog.funcs.len() as u32)
.filter(|&f| env.library.get(f as usize).copied().unwrap_or(false))
.collect();
for fid in fids {
let name = &*prog.funcs[fid as usize].name;
for (i, (which, code)) in LIBRARY_REFERENCE.iter().enumerate() {
if *which != name {
continue;
}
let code = if code.is_empty() { LIBRARY_REFERENCE[2].1 } else { code };
const AT: u32 = 0x0800_0000;
let reference = Image {
segments: vec![crate::image::Segment {
name: ".text".into(),
addr: AT,
data: code.iter().flat_map(|h| h.to_le_bytes()).collect(),
writable: false,
exec: true,
load_addr: None,
}],
symbols: vec![crate::image::Symbol {
name: name.to_string(),
addr: AT,
size: 2 * code.len() as u32,
kind: SymKind::Func,
global: true,
file: None,
}],
..Default::default()
};
let mut renv = CEnv::new(prog, &reference);
renv.aliasing = env.aliasing;
if renv.func_addr[fid as usize] != Some(AT) {
continue;
}
let o = Options {
only: Vec::new(),
cache: None,
jobs: 1,
dump: 0,
time_limit: opts.time_limit.min(Duration::from_secs(10)),
..opts.clone()
};
let r = verify_function(prog, &reference, &renv, fid, &o).report;
match r.status {
Status::Proved if r.assumes.is_empty() => {
env.library_proved[fid as usize] = true;
env.library_differs.retain(|d| d.0 != fid);
break;
}
Status::Mismatch(why) if name != "memcpy" && i < 3 => {
env.library_differs
.push((fid, format!("the program's {name} differs from the library's ({why})")));
}
_ => {}
}
}
}
}
fn bind_clones(prog: &Program, image: &Image, env: &mut CEnv) {
for (fid, f) in prog.funcs.iter().enumerate() {
if f.body.is_none()
|| env.func_addr[fid].is_some()
|| !env.callers.private.get(fid).copied().unwrap_or(false)
|| f.variadic_def
|| !f.asm_blocks.is_empty()
|| prog
.funcs
.iter()
.filter(|g| g.body.is_some() && g.name == f.name)
.count()
!= 1
{
continue;
}
let mut clones = image.symbols.iter().filter(|s| {
s.kind == SymKind::Func
&& s.size > 0
&& s.name.strip_prefix(&*f.name).is_some_and(|rest| {
let mut parts = rest.split('.');
parts.next() == Some("")
&& rest.len() > 1
&& parts.all(|p| p == "isra" || p == "constprop" || p.bytes().all(|b| b.is_ascii_digit()))
})
});
let (Some(c), None) = (clones.next(), clones.next()) else {
continue;
};
if env.addr_to_func.contains_key(&c.addr) {
continue;
}
env.func_addr[fid] = Some(c.addr);
env.clones.insert(fid as u32, c.name.clone());
}
}
fn verify_clone(prog: &Program, image: &Image, env: &CEnv, fid: u32, opts: &Options) -> FuncOutcome {
let f = &prog.funcs[fid as usize];
let n = f.ty.params.len() as u32;
let mut first = None;
for dropped in std::iter::once(None).chain((0..n).rev().map(Some)) {
if let Some(d) = dropped
&& (prog.size_of(f.ty.params[d as usize]).unwrap_or(8) > 4 || !prog.is_scalar(f.ty.params[d as usize]))
{
continue;
}
let trial = Options {
dropped,
..opts.clone()
};
let mut 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 {
let how = match dropped {
Some(d) => format!(
"as {}, which is not passed {}",
env.clones[&fid],
f.locals
.get(d as usize)
.map_or_else(|| format!("argument {}", d + 1), |l| l.name.to_string())
),
None => format!("as {}", env.clones[&fid]),
};
o.report.given = Some(match o.report.given.take() {
Some(g) => format!("{how}; {g}"),
None => how,
});
return o;
}
first.get_or_insert(o);
}
let mut o = first.expect("one candidate at least");
o.report.status = Status::Unsupported(format!(
"the binary has this function as {}, a clone whose interface could not be determined",
env.clones[&fid]
));
o
}
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<u32>)> = Vec::new();
for (fid, cands) in &pending {
let (mut ok, mut open) = (Vec::new(), Vec::new());
for &a in cands {
env.func_addr[*fid as usize] = Some(a);
let o = verify_function(prog, image, env, *fid, &trial);
match o.report.status {
Status::Proved => ok.push(a),
Status::Bounded(_) if o.report.paths > 0 => ok.push(a),
Status::Mismatch(_) => {}
_ => open.push(a),
}
}
env.func_addr[*fid as usize] = None;
fits.push((*fid, ok, open));
}
fits.sort_by_key(|f| (f.1.len(), f.2.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);
}
}
let unique = |fid: u32| {
let name = &prog.funcs[fid as usize].name;
prog.funcs
.iter()
.filter(|g| g.body.is_some() && g.name == *name)
.count()
== 1
};
for (fid, _, open) in &fits {
if env.func_addr[*fid as usize].is_none()
&& unique(*fid)
&& let Some(&a) = open.iter().find(|a| !taken.contains(a))
{
taken.insert(a);
env.bind_func(*fid, a);
}
}
for (fid, ok, open) in &fits {
if env.func_addr[*fid as usize].is_none() {
continue;
}
for &a in ok.iter().chain(open.iter().filter(|_| unique(*fid))) {
if taken.insert(a) {
env.copies.insert(a, *fid);
}
}
}
}
fn same_code(image: &Image, a: u32, b: u32, size: u32) -> bool {
let (Some(x), Some(y)) = (image.read(a, size), image.read(b, size)) else {
return false;
};
if size < 2 {
return false;
}
let aligned = (a ^ b) & 3 == 0;
let hw = |d: &[u8], i: usize| d.get(i..i + 2).map(|h| u16::from_le_bytes([h[0], h[1]]) as u32);
let target = |h1: u32, h2: u32, at: u32| {
let (sbit, j1, j2) = (h1 >> 10 & 1, h2 >> 13 & 1, h2 >> 11 & 1);
let (i1, i2) = (1 - (j1 ^ sbit), 1 - (j2 ^ sbit));
let imm = sbit << 24 | i1 << 23 | i2 << 22 | (h1 & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
at.wrapping_add(4).wrapping_add(((imm << 7) as i32 >> 7) as u32)
};
let mut i = 0usize;
while i + 2 <= size as usize {
let (Some(h1), Some(g1)) = (hw(x, i), hw(y, i)) else {
return false;
};
if h1 >> 11 < 0x1d {
if h1 & 0xf800 == 0x4800 || h1 & 0xf800 == 0xa000 {
let lit = ((i as u32 + 4) & !3) + (h1 & 0xff) * 4;
if !aligned || lit + 4 > size {
return false;
}
}
if h1 != g1 {
return false;
}
i += 2;
continue;
}
let (Some(h2), Some(g2)) = (hw(x, i + 2), hw(y, i + 2)) else {
return false;
};
if h1 & 0xf800 == 0xf000 && h2 & 0x9000 == 0x9000 && g1 & 0xf800 == 0xf000 && g2 & 0x9000 == 0x9000 {
let (ta, tb) = (target(h1, h2, a + i as u32), target(g1, g2, b + i as u32));
let inside = |t: u32, base: u32| t >= base && t < base + size;
let same = if inside(ta, a) || inside(tb, b) {
ta.wrapping_sub(a) == tb.wrapping_sub(b)
} else {
ta == tb
};
if !same || (h2 ^ g2) & 0x5000 != 0 {
return false;
}
} else if (h1, h2) != (g1, g2) || h1 & 0xff7f == 0xf85f || h1 & 0xfbff == 0xf20f || h1 & 0xfbff == 0xf2af {
return false;
}
i += 4;
}
true
}
fn several_addresses(prog: &Program, image: &Image, env: &mut CEnv) {
let mut by_name: BTreeMap<&str, Vec<(u32, u32)>> = BTreeMap::new();
for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func) {
let at = by_name.entry(s.name.as_str()).or_default();
if !at.iter().any(|x| x.0 == s.addr) {
at.push((s.addr, s.size));
}
}
for (name, at) in by_name {
if at.len() < 2 || prog.funcs.iter().any(|f| f.body.is_some() && *f.name == *name) {
continue;
}
env.several.extend(at.iter().map(|x| (x.0, name.to_string())));
let (a, size) = at[0];
if !at[1..]
.iter()
.all(|&(b, sz)| sz == size && same_code(image, a, b, size))
{
env.one_name.insert(name.to_string(), at.len() as u32);
}
}
}
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()
}
#[derive(Clone, Debug, Default)]
pub struct Preset {
pub funcs: Vec<(u32, u32)>,
pub globals: Vec<(u32, u32)>,
}
pub(crate) fn trial(
prog: &Program,
image: &Image,
env: &CEnv,
fid: u32,
opts: &Options,
) -> (Status, usize, Vec<String>) {
let o = verify_function(prog, image, env, fid, opts);
let modulo = o.report.modulo.into_iter().map(|m| m.0).collect();
(o.report.status, o.report.paths, modulo)
}
thread_local! {
static UNIFIED: std::cell::RefCell<Option<BTreeMap<String, u32>>> = const { std::cell::RefCell::new(None) };
}
pub(crate) fn trial_unifying(
prog: &Program,
image: &Image,
env: &CEnv,
fid: u32,
opts: &Options,
) -> (Status, usize, Vec<String>, Vec<(String, u32)>) {
UNIFIED.with(|u| *u.borrow_mut() = Some(BTreeMap::new()));
let o = verify_function(prog, image, env, fid, opts);
let bound = UNIFIED.with(|u| u.borrow_mut().take()).unwrap_or_default();
let modulo = o.report.modulo.into_iter().map(|m| m.0).collect();
(o.report.status, o.report.paths, modulo, bound.into_iter().collect())
}
fn unify_call(job: &Job, wild: &str, ev: Option<&Event>) -> R<String> {
let addr = u32::from_str_radix(&wild[1..], 16).unwrap_or(0);
let fail = || {
Err(Stop::Mismatch(
format!(
"binary calls the unnamed function at {addr:#x} where the source does not call a function that has no address yet"
),
None,
))
};
let Some(ev) = ev.filter(|ev| ev.asm.is_none() && ev.name != INDIRECT) else {
return fail();
};
let mut named = job
.prog
.funcs
.iter()
.enumerate()
.filter(|(_, f)| *f.name == *ev.name)
.peekable();
if named.peek().is_none() || named.any(|(i, _)| job.env.func_addr[i].is_some()) {
return fail();
}
let ok = UNIFIED.with(|u| {
let mut u = u.borrow_mut();
let Some(map) = u.as_mut() else { return false };
match map.get(&ev.name) {
Some(a) => *a == addr,
None if map.values().any(|a| *a == addr) => false,
None => {
map.insert(ev.name.clone(), addr);
true
}
}
});
if ok { Ok(ev.name.clone()) } else { fail() }
}
pub fn verify(prog: &Program, image: &Image, opts: &Options) -> Report {
verify_with(prog, image, opts, &Preset::default())
}
pub fn verify_with(prog: &Program, image: &Image, opts: &Options, preset: &Preset) -> Report {
let mut env = CEnv::new(prog, image);
for &(g, a) in &preset.globals {
env.set_global(image, g, a);
}
for &(f, a) in &preset.funcs {
if image.func_at(a).is_some() {
env.set_func(f, Some(a));
}
}
crate::timing::mark("source environment");
resolve_ambiguous(prog, image, &mut env, opts);
aliases(prog, image, &mut env);
several_addresses(prog, image, &mut env);
crate::timing::mark("resolve ambiguous");
let events = callable(prog, image, &env);
env.library = (events.iter().enumerate())
.map(|(i, &c)| c && env.is_library(&prog.funcs[i]))
.collect();
library_contracts(prog, &mut env, opts);
crate::timing::mark("library contracts");
if !image.meta.weak_funcs.is_empty() {
env.replaceable = (prog.funcs.iter().zip(&events))
.map(|(f, &c)| c && image.meta.weak_funcs.iter().any(|w| **w == *f.name))
.collect();
}
let elsewhere: Vec<bool> = (prog.funcs.iter().enumerate())
.map(|(i, f)| {
f.body.is_some()
&& !f.is_static
&& env.func_addr[i].is_none()
&& image.meta.undefined.iter().any(|u| **u == *f.name)
})
.collect();
if elsewhere.contains(&true) {
env.replaceable.resize(prog.funcs.len(), false);
for (r, e) in env.replaceable.iter_mut().zip(&elsewhere) {
*r |= *e;
}
}
if opts.modular {
env.borrowed = crate::c::borrow::borrowed_params_except(prog, &env.replaceable);
}
crate::timing::mark("callable");
if opts.modular {
env.callable = events.iter().zip(&elsewhere).map(|(&c, &e)| c || e).collect();
}
env.aliasing = opts.aliasing;
let exported: Vec<bool> = (env.func_addr.iter().enumerate())
.map(|(fid, a)| {
a.is_some_and(|a| {
image.symbols.iter().any(|s| {
s.global
&& s.kind == crate::image::SymKind::Func
&& (s.addr == a || env.copies.get(&s.addr) == Some(&(fid as u32)))
})
})
})
.collect();
env.callers = crate::c::callers::callers_except(prog, &exported);
bind_clones(prog, image, &mut env);
let trial = Options {
only: Vec::new(),
time_limit: opts.time_limit.min(Duration::from_secs(5)),
..opts.clone()
};
let mut bound: Vec<u32> = env.clones.keys().copied().collect();
bound.sort_unstable();
for fid in bound {
let listed = opts.only.is_empty() || opts.only.iter().any(|n| **n == *prog.funcs[fid as usize].name);
if !listed
|| matches!(
verify_clone(prog, image, &env, fid, &trial).report.status,
Status::Unsupported(_)
)
{
env.func_addr[fid as usize] = None;
env.clones.remove(&fid);
}
}
let env = env;
let mut report = Report {
aliasing: match opts.aliasing {
crate::c::exec::Aliasing::Compiler => "compiler",
crate::c::exec::Aliasing::Standard => "standard",
crate::c::exec::Aliasing::Off => "off",
},
library_differs: env.library_differs.iter().map(|d| d.1.clone()).collect(),
..Default::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();
let cache = match &opts.cache {
Some(dir) if opts.dump == 0 => match crate::cache::Cache::open(dir, prog, image, &env, opts) {
Ok(c) => Some(c),
Err(e) => {
eprintln!("cverif: warning: cache {}: {e}; not used", dir.display());
None
}
},
_ => None,
};
crate::timing::mark("cache keys");
let one = |fid: u32| {
if let (Some(text), Some(addr)) = (&prog.funcs[fid as usize].asm, env.func_addr[fid as usize]) {
let name = &prog.funcs[fid as usize].name;
return match crate::thumb::asm::parse(text) {
Ok(src) => assembly_outcome(image, name, addr, &src, &src.lines),
Err(e) => assembly_report(image, name, addr, Status::Unsupported(format!("assembly: {e}")), &[]),
};
}
let key = (cache.as_ref())
.filter(|_| prog.funcs[fid as usize].asm_blocks.is_empty() && !env.clones.contains_key(&fid))
.and_then(|c| c.key(fid));
if let (Some(c), Some(k)) = (&cache, &key)
&& let Some(e) = c.get(k)
&& *e.report.name == *prog.funcs[fid as usize].name
{
let mut report = e.report;
if let Status::Bounded(why) = &report.status {
let limit = why.split(';').next().unwrap_or(why);
report.detail = Some(Box::new(crate::explain::FuncDetail {
explanation: Some(crate::explain::report::limit_only(limit)),
paths: Vec::new(),
skipped_paths: 0,
}));
}
return FuncOutcome {
report,
cov: e.cov,
bytes: e.bytes,
};
}
let o = if env.clones.contains_key(&fid) {
verify_clone(prog, image, &env, fid, opts)
} else {
verify_function(prog, image, &env, fid, opts)
};
if let (Some(c), Some(k)) = (&cache, &key)
&& matches!(
o.report.status,
Status::Proved | Status::Bounded(_) | Status::Unsupported(_)
)
{
c.put(
k,
&crate::cache::Entry {
report: o.report.clone(),
cov: o.cov.clone(),
bytes: o.bytes.clone(),
},
);
}
o
};
let mut outs = run_jobs(&todo, opts.jobs, one);
private_conventions(prog, image, &env, opts, &todo, &mut outs);
let mut more: Vec<(u32, u32)> = (env.copies.iter())
.filter(|c| todo.contains(c.1))
.map(|(&a, &f)| (a, f))
.collect();
more.sort_unstable();
let addrs: Vec<u32> = more.iter().map(|c| c.0).collect();
let copies = run_jobs(&addrs, opts.jobs, |a| {
let fid = env.copies[&a];
if let Some(text) = &prog.funcs[fid as usize].asm {
let name = copy_name(&prog.funcs[fid as usize].name, a);
return match crate::thumb::asm::parse(text) {
Ok(src) => assembly_outcome(image, &name, a, &src, &src.lines),
Err(e) => assembly_report(image, &name, a, Status::Unsupported(format!("assembly: {e}")), &[]),
};
}
let at = Options {
at: Some(a),
..opts.clone()
};
verify_function(prog, image, &env, fid, &at)
});
let fids: Vec<u32> = todo.iter().copied().chain(more.iter().map(|c| c.1)).collect();
outs.extend(copies);
for (o, &fid) in outs.iter_mut().zip(&fids) {
if o.report.given.is_none() {
continue;
}
let (mut seen, mut stack) = (HashSet::new(), env.callers.callers[fid as usize].clone());
while let Some(c) = stack.pop() {
if c == fid || !seen.insert(c) {
continue;
}
if env.func_addr[c as usize].is_some() {
let name = prog.funcs[c as usize].name.to_string();
if !o.report.modulo.iter().any(|m| m.0 == name) {
o.report.modulo.push((name, String::new()));
}
} else {
stack.extend(env.callers.callers[c as usize].iter().copied());
}
}
}
for o in outs {
cov.extend(o.cov);
bytes.extend(o.bytes);
report.funcs.push(o.report);
}
for o in assembly_files(prog, image, &env, opts) {
bytes.extend(o.bytes);
report.funcs.push(o.report);
}
crate::timing::mark("verify functions");
let verdict: HashMap<String, String> = (report.funcs.iter())
.map(|f| (f.name.clone(), f.status.label().to_string()))
.collect();
for f in &mut report.funcs {
for m in &mut f.modulo {
m.1 = verdict.get(&m.0).cloned().unwrap_or_else(|| "NOT VERIFIED".to_string());
}
}
let mut solid: HashSet<String> = (report.funcs.iter())
.filter(|f| matches!(f.status, Status::Proved))
.map(|f| f.name.clone())
.collect();
loop {
let drop: Vec<String> = (report.funcs.iter())
.filter(|f| solid.contains(&f.name) && f.modulo.iter().any(|m| !solid.contains(&m.0)))
.map(|f| f.name.clone())
.collect();
if drop.is_empty() {
break;
}
for d in drop {
solid.remove(&d);
}
}
for f in &mut report.funcs {
f.unconditional = solid.contains(&f.name);
}
check_data(prog, image, &env, &mut report);
crate::timing::mark("check data");
let nf = prog.funcs.len();
let mut first: Vec<u32> = vec![u32::MAX; nf];
let mut npoints: Vec<u32> = vec![0; nf];
for (c, (fid, _)) in prog.cov_info.iter().enumerate() {
first[*fid as usize] = first[*fid as usize].min(c as u32);
npoints[*fid as usize] += 1;
}
let mut rep_of: HashMap<(&str, u16, u32, u32), u32> = HashMap::new();
let rep: Vec<u32> = (0..nf)
.map(|f| {
let func = &prog.funcs[f];
*rep_of
.entry((&*func.name, func.loc.file, func.loc.line, npoints[f]))
.or_insert(f as u32)
})
.collect();
let point_rep = |c: u32| {
let f = prog.cov_info[c as usize].0 as usize;
first[rep[f] as usize] + (c - first[f])
};
let proved_points: HashSet<u32> = cov.iter().map(|&c| point_rep(c)).collect();
let mut has_code: Vec<bool> = (0..nf).map(|f| env.func_addr[f].is_some()).collect();
for &c in &cov {
has_code[prog.cov_info[c as usize].0 as usize] = true;
}
let external: HashSet<&str> = image.externals.values().map(|n| n.as_str()).collect();
loop {
let mut changed = false;
for f in 0..nf {
if !has_code[f]
&& (prog.funcs[f].is_static || !external.contains(&*prog.funcs[f].name))
&& env
.callers
.callers
.get(f)
.is_some_and(|cs| cs.iter().any(|&c| has_code[c as usize]))
{
has_code[f] = true;
changed = true;
}
}
if !changed {
break;
}
}
let mut def_has_code = vec![false; nf];
for f in 0..nf {
def_has_code[rep[f] as usize] |= has_code[f];
}
let mut lines: BTreeSet<(String, u32)> = BTreeSet::new();
let mut hit: HashSet<(u16, u32)> = HashSet::new();
for &c in &proved_points {
let loc = prog.cov_info[c as usize].1;
hit.insert((loc.file, loc.line));
}
let file_of = |loc: &crate::c::lex::Loc| prog.files.get(loc.file as usize).cloned().unwrap_or_default();
let mut absent: Vec<(String, String, u32)> = Vec::new();
for (fid, f) in prog.funcs.iter().enumerate() {
if f.body.is_some() && rep[fid] == fid as u32 && !def_has_code[fid] {
absent.push((f.name.to_string(), file_of(&f.loc), npoints[fid]));
}
}
report.absent_points = absent.iter().map(|a| a.2 as usize).sum();
report.absent = absent.into_iter().map(|a| a.0).collect();
for (c, (fid, loc)) in prog.cov_info.iter().enumerate() {
let fid = *fid as usize;
if rep[fid] != fid as u32 || !def_has_code[fid] {
continue;
}
let proved = proved_points.contains(&(c as u32));
if !proved && prog.cov_dead.get(c).copied().unwrap_or(false) {
report
.src_no_code
.push((file_of(loc), loc.line, prog.funcs[fid].name.to_string()));
continue;
}
if !proved && !hit.contains(&(loc.file, loc.line)) {
lines.insert((file_of(loc), loc.line));
}
report.src_points.push(SrcPoint {
file: file_of(loc),
line: loc.line,
func: prog.funcs[fid].name.to_string(),
proved,
});
}
report.uncovered_lines = lines.into_iter().collect();
report.src = (
report.src_points.iter().filter(|p| p.proved).count(),
report.src_points.len(),
);
let mut total = 0usize;
let mut proved = 0usize;
let mut constants: HashSet<u32> = HashSet::new();
for (i, g) in prog.globals.iter().enumerate() {
if let (true, Some(addr), Some(expect)) = (g.defined, env.global_addr[i], env.init_bytes(i as u32))
&& image.read(addr, expect.len() as u32) == Some(&expect[..])
{
constants.extend(addr..addr + expect.len() as u32);
}
}
for (addr, expect) in &env.rom {
if image.read(*addr, expect.len() as u32) == Some(&expect[..]) {
constants.extend(*addr..*addr + expect.len() as u32);
}
}
constants.retain(|a| !bytes.contains(a));
report.bin_constants = (image.segments.iter())
.filter(|s| s.exec || image.soft_bounds)
.map(|s| {
constants
.iter()
.filter(|&&a| a >= s.addr && ((a - s.addr) as usize) < s.data.len())
.count()
})
.sum();
bytes.extend(constants);
let aside = |a: u32| image.set_aside.iter().find(|r| a >= r.0 && a < r.1);
let proved_funcs: Vec<(u32, u32)> = (report.funcs.iter())
.filter(|f| f.status == Status::Proved)
.map(|f| (f.addr & !1, (f.addr & !1) + f.size))
.collect();
for seg in image.segments.iter().filter(|s| s.exec || image.soft_bounds) {
if !seg.exec && seg.writable && seg.load_addr.is_none() {
continue; }
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 fill = if seg.exec {
matches!(hw, 0 | 0xbf00 | 0x46c0)
} else {
matches!(hw, 0 | 0xffff) || (n == 1 && matches!(hw, 0 | 0xff))
};
let dead_fill = |a: u32| {
a % 4 == 2
&& image.data_ranges.iter().any(|d| d.0 == a + 2)
&& proved_funcs.iter().any(|&(lo, hi)| a >= lo && a < hi)
};
let padding = covered == 0 && fill && (!in_func(a) || dead_fill(a));
let set_aside = !padding && (0..n as u32).all(|i| !bytes.contains(&(a + i)) && aside(a + i).is_some());
for i in 0..n as u32 {
let lone = covered == 1 && n == 2 && !in_func(a) && seg.data[o + i as usize] == 0;
let state = if padding || (lone && !bytes.contains(&(a + i))) {
ByteState::Padding
} else if set_aside {
ByteState::SetAside
} else if bytes.contains(&(a + i)) {
ByteState::Proved
} else {
ByteState::Unproved
};
match state {
ByteState::Proved => {
total += 1;
proved += 1;
}
ByteState::Unproved => {
total += 1;
if !seg.exec {
report.unexplained += 1;
}
}
_ => {}
}
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 r in &report.bin_ranges {
if r.state == ByteState::SetAside {
let why = aside(r.start).map(|x| x.2.clone()).unwrap_or_default();
report.set_aside.push((r.start, r.end, why));
}
}
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 private_conventions(
prog: &Program,
image: &Image,
env: &CEnv,
opts: &Options,
todo: &[u32],
outs: &mut [FuncOutcome],
) {
let info = &env.callers;
let verified = |f: u32| prog.funcs[f as usize].body.is_some() && env.func_addr[f as usize].is_some();
for i in 0..todo.len() {
let fid = todo[i];
let Status::Mismatch(why) = &outs[i].report.status else {
continue;
};
let why = why.clone();
let local = env.func_addr[fid as usize]
.and_then(|a| image.func_at(a))
.is_some_and(|s| !s.global);
if !local || !info.private.get(fid as usize).copied().unwrap_or(false) {
continue;
}
let (mut callers, mut seen, mut stack) = (Vec::new(), HashSet::new(), info.callers[fid as usize].clone());
while let Some(c) = stack.pop() {
if c == fid || !seen.insert(c) {
continue;
}
if verified(c) {
callers.push(c);
} else {
stack.extend(info.callers[c as usize].iter().copied());
}
}
if callers.is_empty() {
continue;
}
callers.sort_unstable();
let again = run_jobs(&callers, opts.jobs, |c| {
guarded(prog, env, c, || verify_following(prog, image, env, c, opts, &[fid]))
});
if again.iter().any(|o| matches!(o.report.status, Status::Mismatch(_))) {
continue;
}
let names: Vec<String> = callers
.iter()
.map(|&c| prog.funcs[c as usize].name.to_string())
.collect();
if again.iter().all(|o| matches!(o.report.status, Status::Proved)) {
let mut modulo: Vec<(String, String)> = Vec::new();
let mut paths = 0;
for (o, &c) in again.into_iter().zip(&callers) {
paths += o.report.paths;
for m in &o.report.modulo {
if !modulo.contains(m) {
modulo.push(m.clone());
}
}
match todo.iter().position(|&t| t == c) {
Some(k) => outs[k] = o,
None => {
outs[i].cov.extend(o.cov);
outs[i].bytes.extend(o.bytes);
}
}
}
let r = &mut outs[i].report;
r.status = Status::Proved;
r.paths = paths;
r.modulo = modulo;
r.detail = None;
r.given = Some(format!(
"as called from {}: the compiler changed how this internal function is called",
names.join(", ")
));
} else {
let r = &mut outs[i].report;
r.status = Status::Inconclusive(format!(
"an internal function the compiler may call in its own way: on its own it differs ({why}), and followed from its callers ({}) not all of them are proved",
names.join(", ")
));
}
}
}
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,
}
}
#[cfg(test)]
mod tests {
#[test]
fn ill_formed_term_names_its_caller() {
let what = super::caught(|| {
let mut tm = crate::term::Terms::new();
let byte = tm.konst(8, 0x5a);
tm.extract(byte, 0, 32)
})
.expect_err("a 32-bit slice of a byte is refused");
assert!(what.contains("bits 0..32 taken from a 8-bit value"), "{what}");
assert!(
what.contains(concat!(" at ", file!(), ":")),
"the caller's place: {what}"
);
assert!(!what.contains("term.rs"), "not the constructor's: {what}");
let chain = super::call_chain(" 3: cverif::c::exec::load\n 4: cverif::verify::caught::<x>\n");
assert_eq!(chain, ", called from c::exec::load");
}
}