use super::{Analysis, Discovery, Finding, Func, Match, Provenance};
use crate::c::ast::{Body, EK, Expr, OpKind, Program, Term, Type};
use crate::c::exec::CEnv;
use crate::image::{Image, SymKind, Symbol};
use crate::sym::{Ctx, Limits, Stop};
use crate::thumb::exec::{Callee, Exit, Machine};
use crate::verify::{Options as VerifyOptions, Preset, Status, run_jobs, trial};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::time::{Duration, Instant};
fn new_ctx(limits: Limits, work: u64, time: Duration, image: &Image) -> Ctx {
let mut ctx = Ctx::new(limits);
ctx.set_budget(work, 4_000_000, Some(Instant::now() + time));
ctx.prover.rom = image
.segments
.iter()
.filter(|s| !s.writable)
.map(|s| (s.addr, s.data.clone()))
.collect();
ctx
}
#[allow(clippy::type_complexity)]
pub(super) fn trace(image: &Image, entry: u32, limit: u32) -> (BTreeSet<(u32, u8)>, BTreeSet<(u32, u8)>, bool) {
let limits = Limits {
max_depth: 24,
max_paths: 600,
max_steps: 4000,
..Limits::default()
};
let mut ctx = new_ctx(limits, 150_000, Duration::from_secs(5), image);
let mut regs = [0; 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 lr0 = regs[14];
let classify = |addr: u32| -> Callee {
let a = addr & !1;
if a >= entry && a < limit {
return Callee::Internal;
}
match image.func_at(a) {
Some(s) => Callee::External(s.name.clone()),
None => Callee::Internal,
}
};
let (mut insns, mut data) = (BTreeSet::new(), BTreeSet::new());
let mut complete = true;
let mut explored = 0usize;
loop {
ctx.restart(&[]);
explored += 1;
let mut m = Machine::new(&mut ctx, entry, regs);
let mut k = 0usize;
loop {
match m.run(&mut ctx, image, lr0, &classify) {
Ok(Exit::Call { name }) => {
m.mem.world.clear();
m.mem.epoch += 1;
let ret = ctx.named_sym(&format!("ret{k}:{name}"), 32);
m.finish_call(&mut ctx, k, Some(ret), None);
k += 1;
if k > 32 {
complete = false;
break;
}
}
Ok(_) | Err(Stop::Undefined) | Err(Stop::Halt) => break,
Err(_) => {
complete = false;
break;
}
}
}
insns.extend(m.covered.iter().copied());
data.extend(m.data_covered.iter().copied());
if ctx.check_deadline().is_err() || explored >= limits.max_paths {
complete = false;
break;
}
if !ctx.next_path() {
break;
}
}
(insns, data, complete)
}
fn concrete(image: &Image, entry: u32, args: [u32; 4]) -> Option<[u32; 4]> {
let limits = Limits {
max_depth: 2,
max_paths: 1,
max_steps: 3000,
..Limits::default()
};
let mut ctx = new_ctx(limits, 60_000, Duration::from_millis(500), image);
let mut regs = [0; 16];
for (i, r) in regs.iter_mut().enumerate().take(13) {
*r = match args.get(i) {
Some(v) => ctx.tm.konst(32, *v as u64),
None => ctx.tm.konst(32, 0xa5a5_0000 + i 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 classify = |_: u32| Callee::Internal;
ctx.restart(&[]);
let mut m = Machine::new(&mut ctx, entry, regs);
match m.run(&mut ctx, image, lr0, &classify) {
Ok(Exit::Return) => {}
_ => return None,
}
if !ctx.decisions.is_empty() || !m.mem.world.is_empty() {
return None; }
let mut out = [0u32; 4];
for (i, o) in out.iter_mut().enumerate() {
*o = ctx.tm.as_const(m.regs[i])? as u32;
}
Some(out)
}
type Reference = fn([u32; 4]) -> Option<([u32; 4], u8)>;
fn u64of(lo: u32, hi: u32) -> u64 {
(lo as u64) | ((hi as u64) << 32)
}
const HELPERS: &[(&str, Reference)] = &[
("__aeabi_uidivmod", |a| {
(a[1] != 0).then(|| ([a[0] / a[1], a[0] % a[1], 0, 0], 0b11))
}),
("__aeabi_idivmod", |a| {
let (x, y) = (a[0] as i32, a[1] as i32);
(y != 0 && !(x == i32::MIN && y == -1)).then(|| ([(x / y) as u32, (x % y) as u32, 0, 0], 0b11))
}),
("__aeabi_uidiv", |a| (a[1] != 0).then(|| ([a[0] / a[1], 0, 0, 0], 0b1))),
("__aeabi_idiv", |a| {
let (x, y) = (a[0] as i32, a[1] as i32);
(y != 0 && !(x == i32::MIN && y == -1)).then(|| ([(x / y) as u32, 0, 0, 0], 0b1))
}),
("__aeabi_lmul", |a| {
let p = u64of(a[0], a[1]).wrapping_mul(u64of(a[2], a[3]));
Some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
}),
("__aeabi_llsl", |a| {
let p = u64of(a[0], a[1]) << (a[2] & 63);
(a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
}),
("__aeabi_llsr", |a| {
let p = u64of(a[0], a[1]) >> (a[2] & 63);
(a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
}),
("__aeabi_lasr", |a| {
let p = ((u64of(a[0], a[1]) as i64) >> (a[2] & 63)) as u64;
(a[2] < 64).then_some(([p as u32, (p >> 32) as u32, 0, 0], 0b11))
}),
("__aeabi_uldivmod", |a| {
let (x, y) = (u64of(a[0], a[1]), u64of(a[2], a[3]));
(y != 0).then(|| {
let (q, r) = (x / y, x % y);
([q as u32, (q >> 32) as u32, r as u32, (r >> 32) as u32], 0b1111)
})
}),
("__aeabi_ldivmod", |a| {
let (x, y) = (u64of(a[0], a[1]) as i64, u64of(a[2], a[3]) as i64);
(y != 0 && !(x == i64::MIN && y == -1)).then(|| {
let (q, r) = ((x / y) as u64, (x % y) as u64);
([q as u32, (q >> 32) as u32, r as u32, (r >> 32) as u32], 0b1111)
})
}),
];
const VECTORS: &[[u32; 4]] = &[
[1_000_003, 97, 12, 5],
[0xffff_fff9, 7, 3, 0],
[0x8000_0001, 0xffff_fffd, 33, 0xffff_ffff],
[5, 0x7fff_ffff, 63, 1],
[0, 3, 0, 9],
[0xdead_beef, 0x0001_0000, 17, 0],
[123_456_789, 1, 1, 0],
[0x7fff_ffff, 2, 31, 0x8000_0000],
[0xffff_ffff, 0xffff_ffff, 32, 0],
[99, 100, 8, 0],
[0x0012_3456, 0x0000_0123, 60, 0x10],
[0xfedc_ba98, 0x7654_3210, 4, 2],
];
pub fn recognise(image: &Image, funcs: &[Func]) -> Vec<(u32, &'static str, usize)> {
let mut out = Vec::new();
for f in funcs {
if f.size > 4096 || !f.notes.is_empty() {
continue;
}
if f.consts.iter().any(|c| (0x1000_0000..=0xffff_ffff).contains(c)) {
continue;
}
'helper: for (name, reference) in HELPERS {
let mut agreed = 0usize;
for v in VECTORS {
let Some((want, mask)) = reference(*v) else { continue };
let Some(got) = concrete(image, f.addr, *v) else {
continue 'helper;
};
if (0..4).any(|i| mask & (1 << i) != 0 && got[i] != want[i]) {
continue 'helper;
}
agreed += 1;
}
if agreed >= 8 {
out.push((f.addr, *name, agreed));
break;
}
}
}
out
}
#[derive(Default, Clone)]
pub(crate) struct SrcSig {
pub(crate) consts: BTreeSet<u32>,
pub(crate) strings: BTreeSet<u32>,
pub(crate) globals: BTreeSet<u32>,
pub(crate) callees: BTreeSet<u32>,
pub(crate) indirect: bool,
}
pub(crate) fn refs(prog: &Program, fid: u32) -> SrcSig {
let mut one = SrcSig::default();
if let Some(body) = &prog.funcs[fid as usize].body {
walk_body(body, &mut one);
}
one
}
fn walk_expr(e: &Expr, sig: &mut SrcSig) {
match &e.kind {
EK::Const(c) => {
if *c >= 0x100 {
sig.consts.insert(*c as u32);
}
}
EK::Str(s) => {
sig.strings.insert(*s);
}
EK::Global(g) => {
sig.globals.insert(*g);
}
EK::Func(f) => {
sig.callees.insert(*f);
}
EK::FConst(_) | EK::Local(_) | EK::Prev | EK::VlaLive(_) => {}
EK::Asm(a) => {
if let Some(x) = &a.input {
walk_expr(x, sig);
}
}
EK::Alloca(a, ..) => walk_expr(a, sig),
EK::Deref(a)
| EK::Member(a, _)
| EK::BitField(a, ..)
| EK::Bits(a, ..)
| EK::Addr(a)
| EK::Load(a)
| EK::Cast(a)
| EK::Neg(a)
| EK::BitNot(a)
| EK::LogNot(a)
| EK::VaStart(a)
| EK::VaArg(a) => walk_expr(a, sig),
EK::Bin(_, a, b)
| EK::PtrAdd(a, b, _)
| EK::PtrDiff(a, b, _)
| EK::LogAnd(a, b)
| EK::LogOr(a, b)
| EK::Comma(a, b)
| EK::Assign(a, b)
| EK::AssignOp(a, b, _) => {
walk_expr(a, sig);
walk_expr(b, sig);
}
EK::Cond(a, b, c) => {
walk_expr(a, sig);
walk_expr(b, sig);
walk_expr(c, sig);
}
EK::Compound { items, .. } => items.iter().for_each(|(_, x)| walk_expr(x, sig)),
EK::Call(f, args) => {
let direct = match &f.kind {
EK::Func(_) => true,
EK::Addr(x) => matches!(x.kind, EK::Func(_)),
_ => false,
};
sig.indirect |= !direct;
walk_expr(f, sig);
args.iter().for_each(|x| walk_expr(x, sig));
}
}
}
fn walk_body(b: &Body, sig: &mut SrcSig) {
for blk in &b.blocks {
for op in &blk.ops {
match &op.kind {
OpKind::Eval(e) => walk_expr(e, sig),
OpKind::Init { items, .. } => items.iter().for_each(|(_, x)| walk_expr(x, sig)),
}
}
match &blk.term {
Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => walk_expr(e, sig),
_ => {}
}
}
}
fn src_sig(prog: &Program, fid: u32) -> SrcSig {
let mut sig = SrcSig::default();
let mut seen: HashSet<u32> = HashSet::new();
let mut work = vec![(fid, 0)];
while let Some((f, depth)) = work.pop() {
if !seen.insert(f) {
continue;
}
let Some(body) = &prog.funcs[f as usize].body else {
continue;
};
let mut one = SrcSig::default();
walk_body(body, &mut one);
if depth < 4 {
work.extend(one.callees.iter().map(|c| (*c, depth + 1)));
}
sig.consts.extend(one.consts);
sig.strings.extend(one.strings);
sig.globals.extend(one.globals);
sig.callees.extend(one.callees);
}
sig
}
fn bin_consts(
funcs: &BTreeMap<u32, &Func>,
named: &HashMap<u32, String>,
addr: u32,
) -> (BTreeSet<u32>, BTreeSet<String>) {
let mut consts = BTreeSet::new();
let mut calls = BTreeSet::new();
let mut seen: HashSet<u32> = HashSet::new();
let mut work = vec![(addr, 0)];
while let Some((a, depth)) = work.pop() {
if !seen.insert(a) {
continue;
}
let Some(f) = funcs.get(&a) else { continue };
consts.extend(f.consts.iter().copied());
for c in &f.calls {
match named.get(c) {
Some(n) => {
calls.insert(n.clone());
}
None if depth < 3 => work.push((*c, depth + 1)),
None => {}
}
}
}
(consts, calls)
}
#[derive(Default)]
pub struct Outcome {
pub matches: Vec<Match>,
pub objects: Vec<(String, u32, u32)>,
pub tried: HashMap<u32, BTreeSet<u32>>,
pub last: HashMap<u32, String>,
pub findings: Vec<Finding>,
pub not_found: Vec<(String, String)>,
pub preset: Preset,
pub new_entries: Vec<(u32, String)>,
pub dropped: Vec<(String, u32)>,
}
struct Try {
fid: u32,
#[allow(clippy::type_complexity)]
hit: Option<(u32, bool, usize, Vec<(u32, u32)>)>,
tried: BTreeSet<u32>,
also: Vec<u32>,
trials: usize,
last: String,
modulo: Vec<String>,
bound: Vec<(String, u32)>,
}
fn direct_callees(prog: &Program, fid: u32) -> BTreeSet<u32> {
let mut one = SrcSig::default();
if let Some(body) = &prog.funcs[fid as usize].body {
walk_body(body, &mut one);
}
one.callees
}
fn callable_of(prog: &Program, env: &CEnv, unplaced: bool) -> Vec<bool> {
let mut count: HashMap<u32, u32> = HashMap::new();
for (fid, f) in prog.funcs.iter().enumerate() {
if let (true, Some(a)) = (f.body.is_some(), env.func_addr[fid]) {
*count.entry(a).or_default() += 1;
}
}
(prog.funcs.iter().enumerate())
.map(|(fid, f)| f.body.is_some() && f.ty.proto && env.func_addr[fid].map_or(unplaced, |a| count[&a] == 1))
.collect()
}
fn is_good(status: &Status, paths: usize) -> Option<bool> {
match status {
Status::Proved => Some(true),
Status::Bounded(_) if paths > 0 => Some(false),
_ => None,
}
}
fn trial_image(base: &Image, d: &Discovery, helpers: &[(u32, &'static str, usize)], extra: &[(u32, u32)]) -> Image {
let mut img = Image {
segments: base
.segments
.iter()
.map(|s| crate::image::Segment {
exec: s.exec || (base.soft_bounds && !s.writable),
..s.clone()
})
.collect(),
externals: base.externals.clone(),
static_base: base.static_base,
short_enums: base.short_enums,
hard_float: base.hard_float,
soft_bounds: base.soft_bounds,
..Default::default()
};
let mut at: BTreeSet<u32> = BTreeSet::new();
for &(a, name, _) in helpers {
let size = d.funcs.iter().find(|f| f.addr == a).map_or(2, |f| f.size.max(2));
img.symbols.push(Symbol {
name: name.to_string(),
addr: a,
size,
kind: SymKind::Func,
global: true,
file: None,
});
at.insert(a);
}
for f in &d.funcs {
if !at.insert(f.addr) {
continue;
}
img.symbols.push(Symbol {
name: if super::is_helper_name(&f.name) {
f.name.clone()
} else {
format!("fn_{:08x}", f.addr)
},
addr: f.addr,
size: f.size.max(2),
kind: SymKind::Func,
global: true,
file: None,
});
img.data_ranges.extend(f.pools.iter().copied());
}
for &(a, size) in extra {
if at.insert(a) {
img.symbols.push(Symbol {
name: format!("sub_{a:08x}"),
addr: a,
size,
kind: SymKind::Func,
global: true,
file: None,
});
}
}
img.symbols
.extend(base.symbols.iter().filter(|s| s.kind != SymKind::Func).cloned());
img.symbols.sort_by_key(|s| (s.addr, s.kind != SymKind::Func));
img.data_ranges.sort();
img
}
pub fn run(
prog: &Program,
given: &Image,
a: &Analysis,
vopts: &VerifyOptions,
prior: &HashMap<u32, BTreeSet<u32>>,
prior_last: &HashMap<u32, String>,
) -> Outcome {
let d = &a.discovery;
let mut out = Outcome::default();
let funcs: BTreeMap<u32, &Func> = d.funcs.iter().map(|f| (f.addr, f)).collect();
let probe = trial_image(given, d, &[], &[]);
let anonymous: Vec<Func> = d
.funcs
.iter()
.filter(|f| super::is_anonymous(&f.name))
.cloned()
.collect();
let helpers = recognise(&probe, &anonymous);
for &(addr, name, n) in &helpers {
out.matches.push(Match {
source: name.to_string(),
addr,
how: "recognised",
also: Vec::new(),
detail: format!("agrees with {name} on {n} test vectors; not proved"),
});
}
let mut named: HashMap<u32, String> = helpers.iter().map(|h| (h.0, h.1.to_string())).collect();
for f in &d.funcs {
if super::is_helper_name(&f.name) {
named.entry(f.addr).or_insert(f.name.clone());
}
}
let mut extra: Vec<(u32, u32)> = Vec::new();
for s in given.symbols.iter().filter(|s| s.kind == SymKind::Func) {
for delta in [-4i32, -2, 2, 4] {
let c = s.addr.wrapping_add(delta as u32);
if !funcs.contains_key(&c) && given.read_const(c, 2).is_some() {
let end = funcs
.range(c + 1..)
.next()
.map_or(c + 2, |(e, f)| if *e <= s.addr { e + f.size } else { *e });
extra.push((c, end.saturating_sub(c).max(2)));
}
}
}
extra.sort();
extra.dedup_by_key(|e| e.0);
let image = trial_image(given, d, &helpers, &extra);
let mut env = CEnv::new(prog, &image);
let mut seen_defs: HashSet<(&str, &str, u32)> = HashSet::new();
let todo: Vec<u32> = (0..prog.funcs.len() as u32)
.filter(|&f| prog.funcs[f as usize].body.is_some())
.filter(|&f| {
let func = &prog.funcs[f as usize];
let file = prog.files.get(func.loc.file as usize).map_or("", |s| s.as_str());
!func.is_static || seen_defs.insert((&*func.name, file, func.loc.line))
})
.collect();
for f in 0..prog.funcs.len() as u32 {
if prog.funcs[f as usize].body.is_some() {
env.set_func(f, None);
}
}
let given_addr = |fid: u32| -> Option<u32> {
let f = &prog.funcs[fid as usize];
let mut it = given
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && s.name == *f.name);
match (it.next(), it.next()) {
(Some(s), None) => Some(s.addr),
_ => None,
}
};
let sigs: HashMap<u32, SrcSig> = todo.iter().map(|&f| (f, src_sig(prog, f))).collect();
let bsig: BTreeMap<u32, (BTreeSet<u32>, BTreeSet<String>)> = d
.funcs
.iter()
.map(|f| (f.addr, bin_consts(&funcs, &named, f.addr)))
.collect();
let big = d.funcs.len() > 400;
let trial_opts = {
let mut o = vopts.clone();
o.only = Vec::new();
o.dump = 0;
o.work_limit = o.work_limit.min(if big { 8_000 } else { 30_000 });
o.time_limit = o.time_limit.min(Duration::from_secs(if big { 3 } else { 5 }));
o.limits.max_paths = o.limits.max_paths.min(if big { 120 } else { 300 });
o
};
let full_opts = {
let mut o = vopts.clone();
o.only = Vec::new();
o.dump = 0;
o.cache = None;
o.work_limit = o.work_limit.min(60_000);
o.time_limit = o.time_limit.min(Duration::from_secs(10));
o
};
let mut claimed: BTreeMap<u32, Vec<u32>> = BTreeMap::new(); let mut done: HashMap<u32, Try> = HashMap::new();
let mut pending: Vec<u32> = todo.clone();
let mut bound_objs: BTreeMap<u32, u32> = BTreeMap::new();
let starts: BTreeSet<u32> = (d.funcs.iter())
.filter(|f| f.provenance != Provenance::Speculative && !super::is_helper_name(&f.name))
.map(|f| f.addr)
.collect();
let mut code: Vec<(u32, u32)> = (d.funcs.iter())
.flat_map(|f| f.code.iter().chain(&f.pools).copied())
.collect();
code.sort();
let anchors = super::anchor::anchor(prog, given, &starts, &code);
let mut hyp: HashMap<u32, (u32, String)> = HashMap::new();
let mut by_calls: BTreeMap<u32, (u32, String)> = BTreeMap::new();
let mut hyp_calls: HashSet<u32> = HashSet::new();
for (&g, &at) in &anchors.globals {
env.set_global(&image, g, at);
bound_objs.insert(g, at);
}
for (&f, (at, why)) in &anchors.funcs {
if given_addr(f).is_some_and(|g| g != *at) {
continue; }
env.set_func(f, Some(*at));
if prog.funcs[f as usize].body.is_some() {
hyp.insert(f, (*at, why.clone()));
claimed.entry(*at).or_default().push(f);
}
}
crate::timing::mark("discover: anchors");
if std::env::var_os("CVERIF_TIMING").is_some() {
eprintln!(
"discover: {} objects and {} functions located by the source's constant data",
anchors.globals.len(),
hyp.len()
);
}
let direct: HashMap<u32, BTreeSet<u32>> = todo.iter().map(|&f| (f, direct_callees(prog, f))).collect();
let mut src_callers: HashMap<u32, Vec<u32>> = HashMap::new();
for (&f, cs) in &direct {
for &c in cs {
src_callers.entry(c).or_default().push(f);
}
}
let mut bin_callers: BTreeMap<u32, BTreeSet<u32>> = BTreeMap::new();
for f in &d.funcs {
for &c in &f.calls {
bin_callers.entry(c).or_default().insert(f.addr);
}
}
let mut tried_with: HashMap<u32, (usize, Vec<u32>)> = HashMap::new();
let mut attempts: HashMap<u32, usize> = HashMap::new();
let mut fallback = false;
for round in 0..if big { 48 } else { 6 } {
if pending.is_empty() {
break;
}
loop {
let mut placed = false;
for g in 0..prog.funcs.len() as u32 {
let fg = &prog.funcs[g as usize];
if env.func_addr[g as usize].is_some()
|| (fg.body.is_some() && !fg.opaque && fg.unsupported.is_none())
|| (fg.body.is_some() && !todo.contains(&g))
{
continue;
}
let free = |a: &u32| funcs.contains_key(a) && claimed.get(a).is_none_or(|c| c.is_empty());
let mut votes: BTreeMap<u32, usize> = BTreeMap::new();
let mut callers = 0usize;
let mut pinned: Option<u32> = None;
for c in src_callers.get(&g).into_iter().flatten().filter(|c| **c != g) {
let Some(bf) = env.func_addr[*c as usize].and_then(|a| funcs.get(&a)) else {
continue;
};
callers += 1;
let targets: BTreeSet<u32> = bf.calls.iter().copied().filter(|t| free(t)).collect();
for t in &targets {
*votes.entry(*t).or_default() += 1;
}
let unplaced = direct[c]
.iter()
.filter(|x| env.func_addr[**x as usize].is_none())
.count();
if unplaced == 1 && targets.len() == 1 {
pinned = targets.first().copied();
}
}
let mut order: Vec<(usize, u32)> = votes.iter().map(|(a, n)| (*n, *a)).collect();
order.sort_by(|a, b| b.cmp(a));
let pick = match order[..] {
[] => None,
[(n, a)] if n >= 2 || pinned == Some(a) => Some((a, n)),
[(n, a), (m, _), ..] if (n >= 2 && n > m && 2 * n >= callers) || pinned == Some(a) => Some((a, n)),
_ => None,
};
if let Some((addr, n)) = pick {
env.set_func(g, Some(addr));
claimed.entry(addr).or_default().push(g);
by_calls.insert(
g,
(
addr,
format!("called where the source calls it by {n} of the {callers} functions placed so far that call it; not proved"),
),
);
placed = true;
}
}
if !placed {
break;
}
}
env.callable = callable_of(prog, &env, big);
let mut plan: HashMap<u32, Vec<(u32, i32)>> = HashMap::new();
for &f in &pending {
if let Some((a, _)) = hyp.get(&f) {
plan.insert(f, vec![(*a, 1000)]);
continue;
}
let mut votes: BTreeMap<u32, i32> = BTreeMap::new();
let free = |a: &u32| funcs.contains_key(a) && claimed.get(a).is_none_or(|c| c.is_empty());
for c in src_callers.get(&f).into_iter().flatten().filter(|c| **c != f) {
if let Some(f) = env.func_addr[*c as usize].and_then(|a| funcs.get(&a)) {
for t in f.calls.iter().filter(|t| free(t)).collect::<BTreeSet<_>>() {
*votes.entry(*t).or_default() += 1;
}
}
}
for g in direct[&f].iter().filter(|g| **g != f) {
if let Some(cs) = env.func_addr[*g as usize].and_then(|a| bin_callers.get(&a)) {
for c in cs.iter().filter(|c| free(c)) {
*votes.entry(*c).or_default() += 1;
}
}
}
if !votes.is_empty() {
plan.insert(f, votes.into_iter().collect());
}
}
let known = |env: &CEnv, f: u32| {
direct[&f]
.iter()
.filter(|g| env.func_addr[**g as usize].is_some())
.count()
};
let key = |env: &CEnv, f: u32| {
let mut c: Vec<u32> = plan
.get(&f)
.map(|v| v.iter().map(|x| x.0).collect())
.unwrap_or_default();
c.sort();
(known(env, f), c)
};
let mut batch: Vec<u32> = (pending.iter().copied())
.filter(|f| !big || plan.contains_key(f))
.filter(|f| !big || tried_with.get(f) != Some(&key(&env, *f)))
.filter(|f| !big || attempts.get(f).is_none_or(|n| *n < 3))
.collect();
if batch.is_empty() && big && !fallback {
fallback = true;
batch = pending.iter().copied().filter(|f| !plan.contains_key(f)).collect();
}
if batch.is_empty() {
break;
}
for &f in &batch {
tried_with.insert(f, key(&env, f));
*attempts.entry(f).or_default() += 1;
}
if std::env::var_os("CVERIF_TIMING").is_some() {
eprintln!(
"discover: round {round}: {} of {} unmatched functions tried",
batch.len(),
pending.len()
);
}
let waiting: Vec<u32> = pending.iter().copied().filter(|f| !batch.contains(f)).collect();
pending = batch;
let unknown = |env: &CEnv, f: u32| {
sigs[&f]
.globals
.iter()
.filter(|g| env.global_addr[**g as usize].is_none())
.count()
};
pending.sort_by_key(|&f| (unknown(&env, f), f));
let results = run_jobs(&pending, vopts.jobs, |fid| {
try_function(
prog,
&image,
&env,
fid,
&sigs[&fid],
&funcs,
&bsig,
&claimed,
given_addr(fid),
prior.get(&fid),
&extra,
(&trial_opts, &full_opts),
big,
round,
plan.get(&fid).map(|v| &v[..]),
)
});
let mut next = waiting;
let mut progress = false;
for t in results {
let fid = t.fid;
match &t.hit {
Some((addr, _, _, objs)) => {
let clash_obj = objs.iter().any(|(g, a)| {
bound_objs.get(g).is_some_and(|x| x != a)
|| bound_objs.iter().any(|(g2, a2)| g2 != g && a2 == a)
});
let clash_fn = claimed.get(addr).is_some_and(|c| !c.is_empty()) && round < 4 && !t.also.is_empty();
if clash_obj || clash_fn {
next.push(fid);
continue;
}
for &(g, at) in objs {
if bound_objs.insert(g, at).is_none() {
env.set_global(&image, g, at);
}
}
let c = claimed.entry(*addr).or_default();
if !c.contains(&fid) {
c.push(fid);
}
env.set_func(fid, Some(*addr));
progress = true;
for (name, at) in &t.bound {
if claimed.get(at).is_some_and(|c| !c.is_empty()) {
continue;
}
let why = format!(
"called by {} where the source calls it (the proof of {} at {addr:#x} goes through on that assumption); not proved",
prog.funcs[fid as usize].name, prog.funcs[fid as usize].name
);
for g in 0..prog.funcs.len() as u32 {
let fg = &prog.funcs[g as usize];
if *fg.name != **name || env.func_addr[g as usize].is_some() {
continue;
}
env.set_func(g, Some(*at));
claimed.entry(*at).or_default().push(g);
if fg.body.is_some() && !fg.opaque && fg.unsupported.is_none() && todo.contains(&g) {
hyp.insert(g, (*at, why.clone()));
hyp_calls.insert(g);
} else if fg.body.is_none() || todo.contains(&g) {
by_calls.insert(g, (*at, why.clone()));
}
}
}
done.insert(fid, t);
}
None => {
if hyp_calls.contains(&fid)
&& t.last.starts_with("MISMATCH")
&& let Some((at, _)) = hyp.remove(&fid)
{
hyp_calls.remove(&fid);
env.set_func(fid, None);
if let Some(c) = claimed.get_mut(&at) {
c.retain(|x| *x != fid);
}
}
next.push(fid);
done.insert(fid, t);
}
}
}
pending = next;
crate::timing::mark("discover: round");
if !progress && !big {
break;
}
}
let name_of = |fid: u32| prog.funcs[fid as usize].name.to_string();
let mut solid: BTreeSet<String> = (done.iter())
.filter(|(_, t)| matches!(t.hit, Some((_, true, ..))))
.map(|(f, _)| name_of(*f))
.collect();
loop {
let drop: Vec<String> = (done.iter())
.filter(|(f, t)| solid.contains(&name_of(**f)) && t.modulo.iter().any(|m| !solid.contains(m)))
.map(|(f, _)| name_of(*f))
.collect();
if drop.is_empty() {
break;
}
for d in drop {
solid.remove(&d);
}
}
for &fid in &todo {
let f = &prog.funcs[fid as usize];
let ga = given_addr(fid);
let Some(t) = done.get_mut(&fid) else { continue };
if t.last.is_empty()
&& let Some(l) = prior_last.get(&fid)
{
t.last = l.clone();
}
let t = &*t;
match &t.hit {
Some((addr, proved, paths, _)) => {
out.preset.funcs.push((fid, *addr));
let rests: Vec<&str> = (t.modulo.iter())
.filter(|m| !solid.contains(*m))
.map(|m| m.as_str())
.collect();
let how = match (*proved, rests.is_empty()) {
(true, true) => "proved",
(true, false) => "conditional",
(false, _) => "bounded",
};
out.matches.push(Match {
source: f.name.to_string(),
addr: *addr,
how,
also: t.also.clone(),
detail: match how {
"proved" => format!("{paths} path(s)"),
"conditional" => format!(
"{paths} path(s), taking the functions it calls to be what the data or the call graph suggests, which is not proved for: {}",
rests.join(", ")
),
_ => format!("no difference on the {paths} path(s) explored"),
},
});
if !funcs.contains_key(addr) {
out.new_entries.push((*addr, f.name.to_string()));
}
match ga {
Some(g) if g != *addr => {
let other = given
.symbols
.iter()
.find(|s| s.kind == SymKind::Func && s.addr == *addr && s.name != *f.name);
let (kind, text) = match other {
Some(o) => (
"swapped",
format!(
"symbol {} is given at {g:#x}, where the proof against its source fails; the proof succeeds at {addr:#x}, which the table calls {}: corrected",
f.name, o.name
),
),
None => (
"wrong-address",
format!(
"symbol {} is given at {g:#x}, where the proof against its source fails; the proof succeeds at {addr:#x}: corrected",
f.name
),
),
};
out.findings.push(Finding {
addr: g,
name: f.name.to_string(),
kind,
text,
});
out.dropped.push((f.name.to_string(), g));
}
_ => {}
}
}
None => {
match ga {
Some(g) if funcs.contains_key(&g) => {
out.preset.funcs.push((fid, g));
out.matches.push(Match {
source: f.name.to_string(),
addr: g,
how: "given",
also: Vec::new(),
detail: format!("not confirmed by proof: {}", t.last),
});
if t.last.starts_with("MISMATCH") {
out.findings.push(Finding {
addr: g,
name: f.name.to_string(),
kind: "proof-fails",
text: format!(
"symbol {} at {g:#x}: the proof against its source fails ({}), and no other function of the image fits",
f.name, t.last
),
});
}
}
_ if by_calls.contains_key(&fid) => {
let (at, why) = &by_calls[&fid];
out.preset.funcs.push((fid, *at));
out.matches.push(Match {
source: f.name.to_string(),
addr: *at,
how: "by-calls",
also: Vec::new(),
detail: why.clone(),
});
}
_ if hyp.contains_key(&fid) => {
let (at, why) = &hyp[&fid];
out.preset.funcs.push((fid, *at));
out.matches.push(Match {
source: f.name.to_string(),
addr: *at,
how: if hyp_calls.contains(&fid) {
"by-calls"
} else {
"by-data"
},
also: Vec::new(),
detail: format!(
"{why}; not proved{}{}",
if t.last.is_empty() { "" } else { ": " },
t.last
),
});
}
_ => {
let tried = t.trials + prior.get(&fid).map_or(0, |p| p.len());
let why = match (tried, t.last.is_empty()) {
(0, false) => t.last.clone(),
(0, true) => "no candidate".to_string(),
(n, true) => format!("{n} candidate(s) tried"),
(n, false) => format!("{n} candidate(s) tried; the best-ranked one: {}", t.last),
};
out.not_found.push((f.name.to_string(), why))
}
}
}
}
}
for (g, (at, why)) in &by_calls {
if prog.funcs[*g as usize].body.is_none() {
out.matches.push(Match {
source: prog.funcs[*g as usize].name.to_string(),
addr: *at,
how: "by-calls",
also: Vec::new(),
detail: why.clone(),
});
}
}
let obj_size = |g: usize| prog.size_of(prog.globals[g].ty).unwrap_or(0);
for (g, at) in &bound_objs {
out.preset.globals.push((*g, *at));
out.objects
.push((prog.globals[*g as usize].name.to_string(), *at, obj_size(*g as usize)));
}
for (fid, t) in &done {
if t.hit.is_none() {
let mut all = prior.get(fid).cloned().unwrap_or_default();
all.extend(t.tried.iter().copied());
out.tried.insert(*fid, all);
out.last.insert(*fid, t.last.clone());
}
}
by_data(prog, given, d, &funcs, &mut env, &mut out);
for (i, g) in prog.globals.iter().enumerate() {
if env.global_addr[i].is_some() || !g.defined || !g.is_const {
continue;
}
let Some(bytes) = env.init_bytes(i as u32) else {
continue;
};
if bytes.len() < 8 {
continue;
}
let align = prog.align_of(g.ty).max(1);
let mut hits = Vec::new();
for seg in given.segments.iter().filter(|s| !s.writable) {
let mut from = 0usize;
while from + bytes.len() <= seg.data.len() && hits.len() < 2 {
match seg.data[from..].windows(bytes.len()).position(|w| w == bytes) {
Some(o) => {
let at = seg.addr + (from + o) as u32;
if at.is_multiple_of(align) {
hits.push(at);
}
from += o + 1;
}
None => break,
}
}
}
if let [at] = hits[..] {
env.set_global(given, i as u32, at);
out.preset.globals.push((i as u32, at));
out.objects.push((g.name.to_string(), at, obj_size(i)));
}
}
out
}
#[allow(clippy::too_many_arguments)]
fn try_function(
prog: &Program,
image: &Image,
env: &CEnv,
fid: u32,
sig: &SrcSig,
funcs: &BTreeMap<u32, &Func>,
bsig: &BTreeMap<u32, (BTreeSet<u32>, BTreeSet<String>)>,
claimed: &BTreeMap<u32, Vec<u32>>,
given: Option<u32>,
skip: Option<&BTreeSet<u32>>,
extra: &[(u32, u32)],
(opts, full): (&VerifyOptions, &VerifyOptions),
big: bool,
round: usize,
plan: Option<&[(u32, i32)]>,
) -> Try {
let f = &prog.funcs[fid as usize];
let mut t = Try {
fid,
hit: None,
tried: BTreeSet::new(),
also: Vec::new(),
trials: 0,
last: String::new(),
modulo: Vec::new(),
bound: Vec::new(),
};
if f.unsupported.is_some() {
t.last = "the source function uses something this tool does not model".into();
return t;
}
let unbound: Vec<u32> = sig
.globals
.iter()
.copied()
.filter(|g| env.global_addr[*g as usize].is_none())
.collect();
if unbound.len() > 3 {
t.last = format!("uses {} objects that have not been located", unbound.len());
return t;
}
let taken: BTreeSet<u32> = env
.global_addr
.iter()
.enumerate()
.filter(|(g, _)| prog.globals[*g].defined)
.filter_map(|(_, a)| *a)
.collect();
let externs: BTreeSet<&str> = sig
.callees
.iter()
.filter(|c| prog.funcs[**c as usize].body.is_none())
.map(|c| &*prog.funcs[*c as usize].name)
.collect();
let mut ranked: Vec<(bool, i32, u32)> = Vec::new();
let _ = round;
for (&addr, func) in funcs {
if super::is_helper_name(&func.name) {
continue;
}
let vote = plan.and_then(|p| p.iter().find(|x| x.0 == addr)).map(|x| x.1);
if big && plan.is_some() && vote.is_none() && given != Some(addr) {
continue;
}
let (consts, calls) = &bsig[&addr];
let mut score = 0i32;
for s in &sig.strings {
let lit = &prog.strings[*s as usize];
if lit.len() < 2 {
continue;
}
let hit = consts
.iter()
.any(|c| image.read_const(*c, lit.len() as u32) == Some(&lit[..]));
score += if hit { 6 } else { -3 };
}
for c in &sig.consts {
if consts.contains(c) {
score += if *c >= 0x4000_0000 { 6 } else { 3 };
} else if *c >= 0x4000_0000 {
score -= 2;
}
}
for g in &sig.globals {
match env.global_addr[*g as usize] {
Some(a) => {
let size = prog.size_of(prog.globals[*g as usize].ty).unwrap_or(1).max(1);
let hit = consts.range(a..a.saturating_add(size)).next().is_some();
score += if hit { 5 } else { -2 };
}
None => {
if !consts.iter().any(|c| !taken.contains(c)) {
score -= 6;
}
}
}
}
for e in &externs {
score += if calls.contains(*e) { 5 } else { -4 };
}
if given == Some(addr) {
score += 100;
}
score += 8 * vote.unwrap_or(0);
if func.provenance == Provenance::Speculative {
score -= 4;
}
ranked.push((
claimed.get(&addr).is_some_and(|c| c.iter().any(|x| *x != fid)),
-score,
addr,
));
}
if let Some(g) = given {
for &(a, _) in extra {
if a.abs_diff(g) <= 4 {
ranked.push((false, -50, a));
}
}
}
ranked.sort();
let keep = match (big, plan.is_some()) {
(true, true) => 5,
(true, false) => 3,
_ => 48,
};
ranked.truncate(keep);
let deadline = Instant::now() + Duration::from_secs(if big { 20 } else { 60 });
for &(_, _, addr) in &ranked {
if Instant::now() > deadline {
break;
}
if skip.is_some_and(|s| s.contains(&addr)) {
continue;
}
t.tried.insert(addr);
let consts: Vec<u32> = match bsig.get(&addr) {
Some(b) => b.0.iter().copied().collect(),
None => {
bsig.range(..addr)
.next_back()
.map(|b| b.1.0.iter().copied().collect())
.unwrap_or_default()
}
};
let mut fixed: Vec<(u32, u32)> = Vec::new();
for &g in &sig.globals {
if let Some(a) = env.global_addr[g as usize]
&& env.is_synthetic(a)
&& prog.size_of(prog.globals[g as usize].ty).is_some_and(|n| n >= 2)
&& let Some(at) = consts
.iter()
.copied()
.find(|c| !taken.contains(c) && env.matches_at(image, g, *c))
{
fixed.push((g, at));
}
}
let mut choices: Vec<Vec<u32>> = Vec::new();
for &g in &unbound {
let gl = &prog.globals[g as usize];
let mut c: Vec<u32> = Vec::new();
if gl.is_const && gl.defined {
c.extend(consts.iter().copied().filter(|a| env.matches_at(image, g, *a)));
} else {
let ram =
|a: u32| image.segment_at(a).is_none_or(|s| s.writable) && (0x1000_0000..0x4000_0000).contains(&a);
let mut offs: Vec<u32> = vec![0];
if let Type::Record(r) = prog.ty(prog.unqual(gl.ty)) {
offs.extend(
prog.records[*r as usize]
.fields
.iter()
.map(|f| f.offset)
.filter(|o| *o > 0),
);
}
offs.dedup();
for off in offs {
for a in consts.iter().copied().filter(|a| ram(*a)) {
let at = a.wrapping_sub(off);
if !taken.contains(&at) && !c.contains(&at) && at.is_multiple_of(prog.align_of(gl.ty).max(1)) {
c.push(at);
}
}
}
}
c.truncate(6);
choices.push(c);
}
if choices.iter().any(|c| c.is_empty()) {
continue;
}
let mut idx = vec![0usize; choices.len()];
let mut tried = 0usize;
'assign: loop {
let mut pick: Vec<(u32, u32)> = unbound
.iter()
.zip(&idx)
.enumerate()
.map(|(i, (g, k))| (*g, choices[i][*k]))
.collect();
pick.extend(fixed.iter().copied());
let distinct = pick.iter().map(|p| p.1).collect::<BTreeSet<_>>().len() == pick.len();
if distinct {
let mut e = env.clone();
for &(g, at) in &pick {
e.set_global(image, g, at);
}
e.set_func(fid, Some(addr));
let (status, paths, mut modulo, bound) = if big {
crate::verify::trial_unifying(prog, image, &e, fid, opts)
} else {
let (s, p, m) = trial(prog, image, &e, fid, opts);
(s, p, m, Vec::new())
};
modulo.extend(bound.iter().map(|b| b.0.clone()));
let (status, paths) = match (&status, big) {
(Status::Bounded(_), true) if paths > 0 => {
let (s, p, ..) = crate::verify::trial_unifying(prog, image, &e, fid, full);
(s, p)
}
_ => (status, paths),
};
t.trials += 1;
tried += 1;
match is_good(&status, paths) {
Some(proved) => {
match &t.hit {
None => {
t.hit = Some((addr, proved, paths, pick.clone()));
t.modulo = modulo;
t.bound = bound;
}
Some((first, was_proved, ..)) => {
if proved && !*was_proved {
let old = *first;
t.hit = Some((addr, proved, paths, pick.clone()));
t.modulo = modulo;
t.bound = bound;
t.also.push(old);
} else if *first != addr && !t.also.contains(&addr) {
t.also.push(addr);
}
}
}
break 'assign;
}
None => {
if given == Some(addr) || t.last.is_empty() {
t.last = format!("{}: {}", status.label(), status.detail());
}
}
}
}
let mut i = 0;
loop {
if i == idx.len() || tried >= 16 {
break 'assign;
}
idx[i] += 1;
if idx[i] < choices[i].len() {
break;
}
idx[i] = 0;
i += 1;
}
}
if let Some((at, true, ..)) = t.hit
&& (given == Some(at) || !t.also.is_empty() || big)
{
break;
}
}
t
}
pub fn apply(d: &mut Discovery, out: &Outcome) {
d.matches = out.matches.clone();
d.objects = out.objects.clone();
d.findings.extend(out.findings.iter().cloned());
d.not_found = out.not_found.iter().map(|n| n.0.clone()).collect();
d.not_found_why = out.not_found.iter().map(|n| n.1.clone()).collect();
for m in &out.matches {
let Some(f) = d.funcs.iter_mut().find(|f| f.addr == m.addr) else {
continue;
};
let wrong_name = out.dropped.iter().any(|(n, _)| *n == f.name);
if super::is_anonymous(&f.name)
|| wrong_name
|| (m.how != "given"
&& f.provenance == Provenance::Given
&& f.name != m.source
&& out.dropped.iter().any(|(n, _)| *n == m.source))
{
if wrong_name || f.provenance == Provenance::Given {
f.provenance = Provenance::Corrected;
} else if f.provenance == Provenance::Speculative && m.how == "recognised" {
continue;
}
f.name = m.source.clone();
}
}
let matched: BTreeSet<u32> = d.matches.iter().map(|m| m.addr).collect();
d.binary_only = d
.funcs
.iter()
.filter(|f| f.provenance != Provenance::Speculative && !matched.contains(&f.addr))
.map(|f| f.addr)
.collect();
}
fn by_data(
prog: &Program,
given: &Image,
d: &Discovery,
funcs: &BTreeMap<u32, &Func>,
env: &mut CEnv,
out: &mut Outcome,
) {
use crate::c::ast::SymRef;
let read = |a: u32| {
given
.read_const(a, 4)
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
};
for (gi, g) in prog.globals.iter().enumerate() {
let Some(init) = g.init.as_ref().filter(|_| g.defined && g.is_const) else {
continue;
};
let nfuncs = init.relocs.iter().filter(|r| matches!(r.1, SymRef::Func(_))).count();
let Some(size) = prog.size_of(g.ty).filter(|_| nfuncs >= 2) else {
continue;
};
let fits = |env: &CEnv, at: u32| -> Option<usize> {
let have = given.read_const(at, size)?;
let mut agree = 0usize;
let mut covered = vec![false; size as usize];
for (off, target, add) in &init.relocs {
let w = read(at + off)?.wrapping_sub(*add as u32);
covered.get_mut(*off as usize..*off as usize + 4)?.fill(true);
match target {
SymRef::Func(f) => {
if w & 1 == 0 || !funcs.contains_key(&(w & !1)) {
return None;
}
match env.func_addr[*f as usize] {
Some(a) if a == w & !1 => agree += 1,
Some(_) => return None,
None => {}
}
}
SymRef::Global(o) => {
if env.global_addr[*o as usize].is_some_and(|a| a != w) {
return None;
}
}
SymRef::Str(_) => {}
}
}
let same = (0..size as usize).all(|i| covered[i] || init.bytes.get(i).copied().unwrap_or(0) == have[i]);
same.then_some(agree)
};
let mut places: Vec<(u32, usize)> = Vec::new();
match env.global_addr[gi].filter(|a| !env.is_synthetic(*a)) {
Some(at) => places.extend(fits(env, at).map(|n| (at, n))),
None => {
for seg in given.segments.iter().filter(|s| !s.writable) {
let mut at = seg.addr.next_multiple_of(4);
while at + size <= seg.addr + seg.data.len() as u32 && places.len() < 2 {
if let Some(n) = fits(env, at)
&& (n >= 1 || d.vectors.is_some_and(|v| v.0 == at))
{
places.push((at, n));
}
at += 4;
}
}
}
}
let [(at, _)] = places[..] else { continue };
if env.global_addr[gi] != Some(at) {
env.set_global(given, gi as u32, at);
out.preset.globals.push((gi as u32, at));
out.objects.push((g.name.to_string(), at, size));
}
for (off, target, add) in &init.relocs {
let Some(w) = read(at + off).map(|w| w.wrapping_sub(*add as u32)) else {
continue;
};
match target {
SymRef::Func(f) if env.func_addr[*f as usize].is_none() => {
let name = prog.funcs[*f as usize].name.to_string();
env.set_func(*f, Some(w & !1));
if prog.funcs[*f as usize].body.is_some() {
out.preset.funcs.push((*f, w & !1));
out.not_found.retain(|n| n.0 != name);
}
out.matches.push(Match {
source: name,
addr: w & !1,
how: "by-data",
also: Vec::new(),
detail: format!(
"the source stores its address at {}+{off}, found at {:#x}; not proved",
g.name,
at + off
),
});
}
SymRef::Global(o) if env.global_addr[*o as usize].is_none() => {
env.set_global(given, *o, w);
out.preset.globals.push((*o, w));
let size = prog.size_of(prog.globals[*o as usize].ty).unwrap_or(0);
out.objects.push((prog.globals[*o as usize].name.to_string(), w, size));
}
_ => {}
}
}
}
}