#[allow(dead_code, clippy::all)]
#[path = "../tests/support/armsim.rs"]
mod armsim;
pub mod replay;
use crate::c::ast::{Program, VOID};
use crate::image::{Image, Segment, SymKind};
use crate::sym::{Ctx, R, Stop};
use crate::term::{Env, Node, T};
use crate::thumb::exec::{Callee, Exit, Machine, Remap, image_init};
use crate::verify::{Options as VerifyOptions, Status, model_runtime_call, run_jobs, verify};
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::sync::Arc;
use std::time::Instant;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Assumptions {
pub sp_aligned: bool,
pub ext_arity: bool,
pub ret32: bool,
pub void_r0: bool,
pub caller_stack: bool,
}
impl Default for Assumptions {
fn default() -> Self {
Assumptions {
sp_aligned: true,
ext_arity: false,
ret32: true,
void_r0: false,
caller_stack: true,
}
}
}
impl Assumptions {
pub fn list(&self) -> Vec<(&'static str, bool, &'static str)> {
vec![
(
"sp-aligned",
self.sp_aligned,
"the stack pointer is 8-byte aligned at function entry",
),
(
"ext-arity",
self.ext_arity,
"an argument register or stack word passed with different values to a function neither image defines is not one of its arguments (each use is listed)",
),
(
"ret32",
self.ret32,
"a function whose r1 differs at return does not return a 64-bit value, unless a caller in the images reads r1",
),
(
"void-r0",
self.void_r0,
"a function with the same effects whose r0 differs at return returns nothing, unless a caller in the images reads r0",
),
(
"caller-stack",
self.caller_stack,
"the stack at and above the entry stack pointer belongs to the caller (the number of stack arguments is unknown): a store there is a difference unless both versions leave the same value",
),
]
}
pub fn set(&mut self, name: &str, on: bool) -> Result<(), String> {
match name {
"sp-aligned" => self.sp_aligned = on,
"ext-arity" => self.ext_arity = on,
"ret32" => self.ret32 = on,
"void-r0" => self.void_r0 = on,
"caller-stack" => self.caller_stack = on,
_ => {
return Err(format!(
"unknown assumption `{name}` (known: sp-aligned, ext-arity, ret32, void-r0, caller-stack)"
));
}
}
Ok(())
}
}
pub const MODEL_ASSUMPTIONS: [&str; 7] = [
"a callee does not read an argument register that some caller leaves holding what an earlier call clobbered, nor a stack word some caller never wrote",
"a call that is the last instruction of a function does not return, nor does a function all of whose paths end in such a call or in an endless loop",
"results are returned in r0 (r0:r1); r4-r11 and sp are compared as outputs, r2, r3, r12 and the flags are not",
"pointers received from the caller do not point into the function's own stack frame or its stack arguments",
"behaviour does not depend on the numeric value of addresses: a value that designates the same symbol and offset in both images is the same pointer",
"an access whose address has a constant part inside an object is an access to that object",
"only constant addresses inside the peripheral ranges (--mmio) are volatile; other memory is compared by its contents at each call and at return",
];
#[derive(Clone, Debug, Default)]
pub struct Options {
pub verify: VerifyOptions,
pub assume: Assumptions,
pub explain: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Equivalent,
MayDiffer(String),
Different(String),
Bounded(String),
Inconclusive(String),
Unsupported(String),
Added,
Removed,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Route {
Source,
SameInstructions,
Machine,
None,
}
#[derive(Clone, Debug)]
pub struct FuncDiff {
pub name: String,
pub old: Option<(u32, u32)>,
pub new: Option<(u32, u32)>,
pub verdict: Verdict,
pub same_code: bool,
pub conditions: Vec<String>,
pub modulo: Vec<(String, String)>,
pub inlined: bool,
pub via_source: Option<String>,
pub route: Route,
pub replay: Option<replay::Replay>,
pub paths: usize,
pub millis: u128,
pub explanation: Option<String>,
}
impl FuncDiff {
pub fn label(&self) -> &'static str {
match &self.verdict {
Verdict::Equivalent if self.same_code && self.old.map(|o| o.0) != self.new.map(|n| n.0) => "MOVED",
Verdict::Equivalent if self.same_code => "IDENTICAL",
Verdict::Equivalent => "EQUIVALENT",
Verdict::MayDiffer(_) => "MAY-DIFFER",
Verdict::Different(_) => "DIFFERENT",
Verdict::Bounded(_) => "BOUNDED",
Verdict::Inconclusive(_) => "INCONCLUSIVE",
Verdict::Unsupported(_) => "UNSUPPORTED",
Verdict::Added => "ADDED",
Verdict::Removed => "REMOVED",
}
}
pub fn is_equivalent(&self) -> bool {
self.verdict == Verdict::Equivalent
}
pub fn detail(&self) -> String {
let mut parts: Vec<String> = Vec::new();
match &self.verdict {
Verdict::MayDiffer(s)
| Verdict::Different(s)
| Verdict::Bounded(s)
| Verdict::Inconclusive(s)
| Verdict::Unsupported(s) => parts.push(s.clone()),
_ => {}
}
if !self.modulo.is_empty() {
let l: Vec<String> = self.modulo.iter().map(|(n, s)| format!("{n} ({s})")).collect();
parts.push(format!("modulo {}", l.join(", ")));
}
if !self.conditions.is_empty() {
parts.push(format!("if {}", self.conditions.join("; ")));
}
if let Some(s) = &self.via_source {
parts.push(format!("[{s}]"));
}
parts.join(" ")
}
}
#[derive(Clone, Debug, Default)]
pub struct Comparison {
pub funcs: Vec<FuncDiff>,
pub data_checked: usize,
pub data: Vec<(String, String)>,
pub data_added: Vec<String>,
pub data_removed: Vec<String>,
pub assume: Assumptions,
pub with_source: bool,
pub source_changed: Vec<String>,
pub source_affected: Vec<String>,
pub source_unchecked: usize,
}
impl Comparison {
pub fn differs(&self) -> bool {
!self.data.is_empty() || self.funcs.iter().any(|f| matches!(f.verdict, Verdict::Different(_)))
}
pub fn may_differ(&self) -> bool {
self.funcs.iter().any(|f| matches!(f.verdict, Verdict::MayDiffer(_)))
}
pub fn func(&self, name: &str) -> Option<&FuncDiff> {
self.funcs.iter().find(|f| f.name == name)
}
pub fn count(&self, label: &str) -> usize {
self.funcs.iter().filter(|f| f.label() == label).count()
}
pub fn render(&self) -> String {
let mut o = String::new();
let width = self.funcs.iter().map(|f| f.name.len()).max().unwrap_or(8);
for f in &self.funcs {
let size = |x: Option<(u32, u32)>| x.map_or("-".to_string(), |x| x.1.to_string());
let mut line = format!(
"{:<12} {:<width$} {:>5} -> {:<5} bytes {:>4} paths {:>6} ms",
f.label(),
f.name,
size(f.old),
size(f.new),
f.paths,
f.millis
);
let d = f.detail();
if !d.is_empty() {
line.push_str(" ");
line.push_str(&d);
}
match &f.replay {
Some(replay::Replay::Reproduced(how)) => {
let _ = write!(line, " {{run on that input: {how}}}");
}
Some(replay::Replay::NotReproduced(_)) => {}
Some(replay::Replay::NotModelled(how)) => {
let _ = write!(line, " {{not run on that input: {how}}}");
}
None => {}
}
let _ = writeln!(o, "{}", line.trim_end());
if let Some(e) = &f.explanation {
for l in e.lines() {
let _ = writeln!(o, " {l}");
}
}
}
for (n, what) in &self.data {
let _ = writeln!(o, "{:<12} {n}: {what}", "DATA");
}
for n in &self.data_added {
let _ = writeln!(o, "{:<12} {n}: only in the new image", "DATA");
}
for n in &self.data_removed {
let _ = writeln!(o, "{:<12} {n}: only in the old image", "DATA");
}
let _ = writeln!(o);
let eq = self.funcs.iter().filter(|f| f.is_equivalent()).count();
let names = |l: &str| -> String {
let v: Vec<&str> = self
.funcs
.iter()
.filter(|f| f.label() == l)
.map(|f| f.name.as_str())
.collect();
if v.is_empty() {
String::new()
} else {
format!(": {}", v.join(", "))
}
};
let _ = writeln!(
o,
"functions: {eq} equivalent ({} identical, {} moved), {} different{}",
self.count("IDENTICAL"),
self.count("MOVED"),
self.count("DIFFERENT"),
names("DIFFERENT")
);
let _ = writeln!(
o,
" {} may differ (in a register or stack slot that may be dead){}",
self.count("MAY-DIFFER"),
names("MAY-DIFFER")
);
let _ = writeln!(
o,
" {} bounded, {} inconclusive, {} unsupported, {} added{}, {} removed{}",
self.count("BOUNDED"),
self.count("INCONCLUSIVE"),
self.count("UNSUPPORTED"),
self.count("ADDED"),
names("ADDED"),
self.count("REMOVED"),
names("REMOVED")
);
let _ = writeln!(
o,
"data objects: {} compared, {} differ, {} added, {} removed",
self.data_checked,
self.data.len(),
self.data_added.len(),
self.data_removed.len()
);
let _ = writeln!(
o,
"mode: {}",
if self.with_source {
"three-way (both images against the source, then against each other)"
} else {
"machine code against machine code, no source"
}
);
if self.funcs.iter().any(|f| f.replay.is_some()) {
let n =
|p: fn(&replay::Replay) -> bool| self.funcs.iter().filter(|f| f.replay.as_ref().is_some_and(p)).count();
let _ = writeln!(
o,
"counterexamples: {} reproduced by running both functions, {} not reproduced, {} not run",
n(|r| matches!(r, replay::Replay::Reproduced(_))),
n(|r| matches!(r, replay::Replay::NotReproduced(_))),
n(|r| matches!(r, replay::Replay::NotModelled(_)))
);
}
let by = |r: Route| self.funcs.iter().filter(|f| f.route == r).count();
let _ = writeln!(
o,
"decided by: {} through the source (both images match it, and it says the same in both versions), {} by having the same instructions, {} by comparing the machine code",
by(Route::Source),
by(Route::SameInstructions),
by(Route::Machine)
);
if self.source_unchecked > 0 {
let _ = writeln!(
o,
" {} pair(s) with the same instructions are equivalent whatever the source says, and were not checked against it (verify an image against its source for that)",
self.source_unchecked
);
}
if !self.source_changed.is_empty() {
let list = |v: &[String]| {
let mut s = v.iter().take(12).cloned().collect::<Vec<_>>().join(", ");
if v.len() > 12 {
let _ = write!(s, ", ... ({} in all)", v.len());
}
s
};
let _ = writeln!(
o,
"source: {} function(s) changed between the two sources: {}",
self.source_changed.len(),
list(&self.source_changed)
);
if !self.source_affected.is_empty() {
let _ = writeln!(
o,
" {} more depend on a change otherwise than through a call (the code of a changed function in place, a changed object, a changed interface): {}",
self.source_affected.len(),
list(&self.source_affected)
);
}
let _ = writeln!(
o,
" these are compared as machine code; a function that only calls a changed one depends on it through its interface, and is equivalent through the source if it matches its source in both images"
);
}
let _ = writeln!(o, "assumptions:");
for (name, on, what) in self.assume.list() {
let _ = writeln!(o, " {} {name:<10} {what}", if on { "[x]" } else { "[ ]" });
}
for what in MODEL_ASSUMPTIONS {
let _ = writeln!(o, " [x] {:<10} {what}", "(model)");
}
let _ = writeln!(
o,
"verdict: {}",
if self.differs() {
"DIFFERENT - the two images do not behave the same"
} else if self.may_differ() {
"MAY DIFFER - the images differ in registers or stack slots that nothing shows to be dead"
} else if self
.funcs
.iter()
.all(|f| f.is_equivalent() || matches!(f.verdict, Verdict::Added | Verdict::Removed))
{
"EQUIVALENT - every function both images define is proved equivalent"
} else {
"no difference proved"
}
);
o
}
pub fn json(&self, old: &str, new: &str) -> String {
let mut o = String::new();
let _ = writeln!(o, "{{");
let _ = writeln!(o, " \"type\": \"compare\",");
let _ = writeln!(o, " \"old\": {},", json_str(old));
let _ = writeln!(o, " \"new\": {},", json_str(new));
let _ = writeln!(o, " \"with_source\": {},", self.with_source);
let _ = writeln!(o, " \"different\": {},", self.differs());
let _ = writeln!(o, " \"may_differ\": {},", self.may_differ());
let _ = writeln!(o, " \"assumptions\": {{");
let l = self.assume.list();
for (i, (name, on, _)) in l.iter().enumerate() {
let _ = writeln!(
o,
" {}: {on}{}",
json_str(name),
if i + 1 < l.len() { "," } else { "" }
);
}
let _ = writeln!(o, " }},");
let list = |v: Vec<String>| format!("[{}]", v.join(", "));
let _ = writeln!(
o,
" \"model_assumptions\": {},",
list(MODEL_ASSUMPTIONS.iter().map(|s| json_str(s)).collect())
);
let _ = writeln!(o, " \"functions\": [");
for (i, f) in self.funcs.iter().enumerate() {
let at = |x: Option<(u32, u32)>| match x {
Some((a, s)) => format!("{{\"addr\": {a}, \"size\": {s}}}"),
None => "null".into(),
};
let reason = match &f.verdict {
Verdict::MayDiffer(s)
| Verdict::Different(s)
| Verdict::Bounded(s)
| Verdict::Inconclusive(s)
| Verdict::Unsupported(s) => json_str(s),
_ => "null".into(),
};
let _ = writeln!(
o,
" {{\"name\": {}, \"status\": {}, \"reason\": {reason}, \"old\": {}, \"new\": {}, \"same_code\": {}, \"inlined\": {}, \"conditions\": {}, \"modulo\": {}, \"source\": {}, \"route\": {}, \"explanation\": {}, \"paths\": {}, \"millis\": {}}}{}",
json_str(&f.name),
json_str(f.label()),
at(f.old),
at(f.new),
f.same_code,
f.inlined,
list(f.conditions.iter().map(|s| json_str(s)).collect()),
list(
f.modulo
.iter()
.map(|(n, s)| format!("{{\"name\": {}, \"status\": {}}}", json_str(n), json_str(s)))
.collect()
),
f.via_source.as_ref().map_or("null".into(), |s| json_str(s)),
match f.route {
Route::Source => "\"source\"",
Route::SameInstructions => "\"same-instructions\"",
Route::Machine => "\"machine\"",
Route::None => "null",
},
f.explanation.as_ref().map_or("null".into(), |s| json_str(s)),
f.paths,
f.millis,
if i + 1 < self.funcs.len() { "," } else { "" }
);
}
let _ = writeln!(o, " ],");
let _ = writeln!(
o,
" \"data\": {{\"compared\": {}, \"different\": {}, \"added\": {}, \"removed\": {}}},",
self.data_checked,
list(
self.data
.iter()
.map(|(n, w)| format!("{{\"name\": {}, \"what\": {}}}", json_str(n), json_str(w)))
.collect()
),
list(self.data_added.iter().map(|s| json_str(s)).collect()),
list(self.data_removed.iter().map(|s| json_str(s)).collect()),
);
let _ = writeln!(o, " \"summary\": {{");
let labels = [
"IDENTICAL",
"MOVED",
"EQUIVALENT",
"MAY-DIFFER",
"DIFFERENT",
"BOUNDED",
"INCONCLUSIVE",
"UNSUPPORTED",
"ADDED",
"REMOVED",
];
for (i, l) in labels.iter().enumerate() {
let _ = writeln!(
o,
" {}: {}{}",
json_str(l),
self.count(l),
if i + 1 < labels.len() { "," } else { "" }
);
}
let _ = writeln!(o, " }}");
let _ = writeln!(o, "}}");
o
}
}
fn json_str(s: &str) -> String {
let mut o = String::with_capacity(s.len() + 2);
o.push('"');
for c in s.chars() {
match c {
'"' => o.push_str("\\\""),
'\\' => o.push_str("\\\\"),
'\n' => o.push_str("\\n"),
'\r' => o.push_str("\\r"),
'\t' => o.push_str("\\t"),
c if (c as u32) < 0x20 => {
let _ = write!(o, "\\u{:04x}", c as u32);
}
c => o.push(c),
}
}
o.push('"');
o
}
#[derive(Clone, Debug)]
struct ObjMap {
start: u32,
size: u32,
to: Option<u32>,
direct: bool,
same: bool,
}
#[derive(Debug, Default)]
struct Layout {
objs: Vec<ObjMap>,
ext: Vec<(u32, u32)>,
segs: Vec<(u32, u32, bool)>,
delta: u32,
rom: Vec<(u32, u32)>,
}
const MAX_TABLE_VALUES: usize = 32;
const MAX_POINTER_PAIRS: usize = 400;
fn enumerate(ctx: &mut Ctx, t: T, max: usize) -> Option<Vec<u32>> {
if let Some(k) = ctx.tm.as_const(t) {
return Some(vec![k as u32]);
}
let mut values: Vec<u32> = Vec::new();
let mut known = ctx.tm.fals();
loop {
match ctx.check(known) {
Ok(()) => break,
Err(Some(env)) => {
let v = ctx.tm.eval(t, &env, &mut Default::default());
if values.contains(&(v as u32)) || values.len() >= max {
return None;
}
values.push(v as u32);
let k = ctx.tm.konst(32, v);
let e = ctx.tm.eq(t, k);
known = ctx.tm.or(known, e);
}
Err(None) => return None,
}
}
values.retain(|&v| {
let k = ctx.tm.konst(32, v as u64);
let ne = ctx.tm.ne(t, k);
!ctx.implied(ne)
});
values.sort_unstable();
Some(values)
}
const SMALL_OFFSET: u32 = 0x1000;
impl Layout {
fn access(&self, k: u32) -> Option<u32> {
for &(b, a) in &self.ext {
if k.wrapping_sub(b) < 16 {
return Some(a.wrapping_add(k - b));
}
}
if let Some(o) = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size) {
return Some(match o.to {
Some(a) if o.direct => a.wrapping_add(k - o.start),
_ => k.wrapping_add(self.delta),
});
}
let seg = self.segs.iter().find(|s| k.wrapping_sub(s.0) < s.1)?;
Some(if seg.2 { k } else { k.wrapping_add(self.delta) })
}
fn value(&self, k: u32) -> Option<u32> {
for &(b, a) in &self.ext {
if k.wrapping_sub(b) < 16 {
return Some(a.wrapping_add(k - b));
}
}
let o = self.objs.iter().find(|o| k.wrapping_sub(o.start) < o.size)?;
o.to.filter(|_| o.same).map(|a| a.wrapping_add(k - o.start))
}
fn translate(&self, ctx: &mut Ctx, addr: T) -> T {
if ctx.region(addr).is_some() {
return addr;
}
if let Node::Ite(c, x, y) = *ctx.tm.node(addr) {
let (x, y) = (self.translate(ctx, x), self.translate(ctx, y));
return ctx.tm.ite(c, x, y);
}
let (ts, k) = ctx.tm.linear(addr);
let k = k as u32;
if ts.is_empty() || k >= SMALL_OFFSET {
match self.access(k) {
Some(n) if n != k => return ctx.tm.add_const(addr, n.wrapping_sub(k) as u64),
Some(_) => return addr,
None => {}
}
}
if ts.is_empty() || !self.reads_rom(ctx, addr) {
return addr;
}
let Some(values) = enumerate(ctx, addr, MAX_TABLE_VALUES) else {
return addr;
};
let to = |k: u32| self.access(k).unwrap_or(k);
let Some((&last, rest)) = values.split_last() else {
return addr;
};
let mut out = ctx.tm.konst(32, to(last) as u64);
for &k in rest.iter().rev() {
let (kt, nt) = (ctx.tm.konst(32, k as u64), ctx.tm.konst(32, to(k) as u64));
let c = ctx.tm.eq(addr, kt);
out = ctx.tm.ite(c, nt, out);
}
out
}
fn reads_rom(&self, ctx: &Ctx, t: T) -> bool {
let mut seen = HashSet::new();
let mut stack = vec![t];
while let Some(x) = stack.pop() {
if !seen.insert(x) {
continue;
}
if seen.len() > 4000 {
return false;
}
let n = ctx.tm.node(x);
if let Node::Load(epoch, a) = n
&& *epoch < crate::sym::UNINIT_EPOCH
{
let k = ctx.tm.linear(*a).1 as u32;
if self.rom.iter().any(|r| k.wrapping_sub(r.0) < r.1) {
return true;
}
}
stack.extend(crate::bv::Prover::children_of(n));
}
false
}
}
#[derive(Clone, Debug)]
struct Named {
name: String,
file: Option<String>,
addr: u32,
size: u32,
writable: bool,
}
fn objects(img: &Image) -> Vec<Named> {
let mut syms: Vec<&crate::image::Symbol> = img
.symbols
.iter()
.filter(|s| s.kind != SymKind::Func && !s.name.is_empty() && !s.name.starts_with('$'))
.collect();
syms.sort_by_key(|s| s.addr);
let mut out = Vec::new();
for (i, s) in syms.iter().enumerate() {
let Some(seg) = img.segment_at(s.addr) else { continue };
let end = seg.addr + seg.data.len() as u32;
let size = if s.size > 0 {
s.size.min(end - s.addr)
} else if s.kind == SymKind::Object {
syms[i + 1..]
.iter()
.map(|n| n.addr)
.find(|&a| a > s.addr)
.unwrap_or(end)
.min(end)
- s.addr
} else {
continue;
};
if size > 0 {
out.push(Named {
name: s.name.clone(),
file: s.file.clone(),
addr: s.addr,
size,
writable: seg.writable,
});
}
}
out
}
fn pair_up(a: &[Named], b: &[Named]) -> Vec<(String, usize, usize)> {
let group = |l: &[Named]| {
let mut m: BTreeMap<String, Vec<usize>> = BTreeMap::new();
for (i, x) in l.iter().enumerate() {
m.entry(x.name.clone()).or_default().push(i);
}
for v in m.values_mut() {
v.sort_by_key(|&i| l[i].addr);
}
m
};
let (ga, gb) = (group(a), group(b));
let mut out = Vec::new();
for (name, va) in &ga {
let Some(vb) = gb.get(name) else { continue };
if va.len() == 1 && vb.len() == 1 {
out.push((name.clone(), va[0], vb[0]));
continue;
}
let base = |f: &Option<String>| f.as_ref().map(|f| f.rsplit('/').next().unwrap_or(f).to_string());
let once =
|l: &[Named], v: &[usize], f: &Option<String>| v.iter().filter(|&&i| base(&l[i].file) == *f).count() == 1;
let (mut ra, mut rb) = (va.clone(), vb.clone());
for &i in va {
let f = base(&a[i].file);
if f.is_some()
&& once(a, va, &f)
&& once(b, vb, &f)
&& let Some(&j) = vb.iter().find(|&&j| base(&b[j].file) == f)
{
out.push((format!("{name} ({})", f.unwrap()), i, j));
ra.retain(|&x| x != i);
rb.retain(|&x| x != j);
}
}
if ra.len() == rb.len() {
for (n, (&i, &j)) in ra.iter().zip(&rb).enumerate() {
out.push((format!("{name} (#{})", n + 1), i, j));
}
}
}
out
}
fn same_instructions(sp: &Space, ea: u32, eb: u32, size: u32) -> bool {
let (Some(x), Some(y)) = (sp.a.read(ea, size), sp.b.read(eb, size)) else {
return false;
};
if size == 0 || (ea ^ eb) & 3 != 0 {
return false;
}
let hw = |d: &[u8], i: usize| d.get(i..i + 2).map(|h| u16::from_le_bytes([h[0], h[1]]));
let branch = |d: &[u8], at: u32, i: usize| -> Option<u32> {
let (h1, h2) = (hw(d, i)? as u32, hw(d, i + 2)? as u32);
if h1 & 0xf800 != 0xf000 || h2 & 0x9000 != 0x9000 {
return None;
}
let s = h1 >> 10 & 1;
let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
let imm = s << 24 | i1 << 23 | i2 << 22 | (h1 & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
let imm = ((imm << 7) as i32 >> 7) as u32;
Some(at.wrapping_add(i as u32).wrapping_add(4).wrapping_add(imm))
};
let same_place = |ta: u32, tb: u32| match (sp.a.func_at(ta), sp.b.func_at(tb)) {
(Some(fa), Some(fb)) => {
fa.name == fb.name
&& ta - fa.addr == tb - fb.addr
&& sp.paired.get(&fa.name).is_some_and(|p| *p == [fa.addr, fb.addr])
}
_ => false,
};
let same_thing = |wa: u32, wb: u32| -> bool {
if sp.a.func_at(wa & !1).is_some() || sp.b.func_at(wb & !1).is_some() {
return (wa ^ wb) & 1 == 0 && same_place(wa & !1, wb & !1);
}
if let Some(m) = sp.layout.value(wb) {
return m == wa;
}
if sp.layout.objs.iter().any(|o| wb.wrapping_sub(o.start) < o.size) {
return false;
}
match (sp.a.segment_at(wa), sp.b.segment_at(wb)) {
(Some(p), Some(q)) if p.writable && q.writable => wa == wb,
(Some(p), Some(q)) if !p.writable && !q.writable => {
matches!((rom_str(sp.a, wa), rom_str(sp.b, wb)), (Some(s), Some(t)) if s == t && !s.is_empty())
}
_ => false,
}
};
let refs = |d: &[u8], at: u32, i: usize| -> Result<Option<u32>, ()> {
let h = hw(d, i).ok_or(())? as u32;
let pc = at.wrapping_add(i as u32).wrapping_add(4);
let inside = |t: u32, len: u32| t.wrapping_sub(at) < size && t.wrapping_sub(at) + len <= size;
let jump = |t: u32| if inside(t, 2) { Ok(None) } else { Ok(Some(t)) };
let sext = |v: u32, bits: u32| ((v << (32 - bits)) as i32 >> (32 - bits)) as u32;
if h < 0xe800 {
return match h {
0xe000..=0xe7ff => jump(pc.wrapping_add(sext(h & 0x7ff, 11) << 1)),
0xd000..=0xddff => jump(pc.wrapping_add(sext(h & 0xff, 8) << 1)),
_ if h & 0xf500 == 0xb100 => jump(pc + ((h >> 9 & 1) << 6 | (h >> 3 & 0x1f) << 1)),
0x4800..=0x4fff | 0xa000..=0xa7ff => {
if inside((pc & !3) + (h & 0xff) * 4, 4) {
Ok(None)
} else {
Err(())
}
}
_ if h & 0xff78 == 0x4478 || h & 0xff78 == 0x4678 || h & 0xff87 == 0x4487 => Err(()),
_ => Ok(None),
};
}
let h2 = hw(d, i + 2).ok_or(())? as u32;
if h & 0xf800 == 0xf000 && h2 & 0x8000 != 0 {
if h2 & 0x1000 != 0 {
return jump(branch(d, at, i).ok_or(())?);
}
if h2 & 0x4000 != 0 {
return Err(());
}
if h & 0x0380 != 0x0380 {
let s = h >> 10 & 1;
let imm = s << 20 | (h2 >> 11 & 1) << 19 | (h2 >> 13 & 1) << 18 | (h & 0x3f) << 12 | (h2 & 0x7ff) << 1;
let t = pc.wrapping_add(sext(imm, 21));
return if inside(t, 2) { Ok(None) } else { Err(()) };
}
return Ok(None);
}
if h & 0xff7f == 0xf85f {
let base = pc & !3;
let t = if h & 0x80 != 0 {
base.wrapping_add(h2 & 0xfff)
} else {
base.wrapping_sub(h2 & 0xfff)
};
return if inside(t, 4) { Ok(None) } else { Err(()) };
}
if h & 0xfff0 == 0xe8d0 && h & 0xf == 0xf && h2 & 0xffe0 == 0xf000 {
return Ok(None);
}
let mov = h & 0xfe00 == 0xea00 && matches!(h >> 5 & 0xf, 2 | 3);
let pc_operand = h & 0xf == 0xf
&& !mov
&& matches!(h & 0xfe00, 0xe800 | 0xe400 | 0xea00 | 0xec00 | 0xee00 | 0xf800 | 0xfa00);
if pc_operand || h & 0xfbff == 0xf20f || h & 0xfbff == 0xf2af || (h & 0xfe00 == 0xea00 && h2 & 0xf == 0xf) {
return Err(());
}
Ok(None)
};
if sp.a.data_ranges.is_empty() || sp.b.data_ranges.is_empty() {
return false;
}
let n = size as usize;
let mut i = 0usize;
while i + 2 <= n {
let (da, db) = (sp.a.is_data_in_code(ea + i as u32), sp.b.is_data_in_code(eb + i as u32));
if da != db {
return false;
}
if da {
if (ea as usize + i).is_multiple_of(4) && i + 4 <= n {
let word = |d: &[u8]| u32::from_le_bytes([d[i], d[i + 1], d[i + 2], d[i + 3]]);
let (wa, wb) = (word(x), word(y));
let ok = if sp.is_address(wa & !1) || sp.is_address(wb & !1) {
same_thing(wa, wb)
} else {
wa == wb
};
if !ok {
return false;
}
i += 4;
} else {
if x[i..i + 2] != y[i..i + 2] {
return false;
}
i += 2;
}
continue;
}
let len = if hw(x, i).is_some_and(|h| h >= 0xe800) { 4 } else { 2 };
if i + len > n || hw(x, i).map(|h| h >= 0xe800) != hw(y, i).map(|h| h >= 0xe800) {
return false;
}
match (refs(x, ea, i), refs(y, eb, i)) {
(Ok(None), Ok(None)) => {
if x[i..i + len] != y[i..i + len] {
return false;
}
}
(Ok(Some(ta)), Ok(Some(tb))) => {
let kind = |d: &[u8]| match len {
4 => (hw(d, i).map(|h| h & 0xf800), hw(d, i + 2).map(|h| h & 0xd000)),
_ => (
hw(d, i).map(|h| match h {
0xe000..=0xe7ff => h & 0xf800,
0xd000..=0xdfff => h & 0xff00,
_ => h & 0xfd07,
}),
None,
),
};
if kind(x) != kind(y) || !same_place(ta, tb) {
return false;
}
}
_ => return false,
}
i += len;
}
i == n
}
fn direct_targets(img: &Image, entry: u32, size: u32) -> BTreeSet<u32> {
let mut out = BTreeSet::new();
let Some(d) = img.read(entry, size) else {
return out;
};
let hw = |i: usize| d.get(i..i + 2).map(|h| u16::from_le_bytes([h[0], h[1]]) as u32);
let mut i = 0usize;
while let Some(h) = hw(i) {
let pc = entry.wrapping_add(i as u32).wrapping_add(4);
let mut target = None;
let mut len = 2;
if h >= 0xe800 {
len = 4;
if let Some(h2) = hw(i + 2)
&& h & 0xf800 == 0xf000
&& h2 & 0x9000 == 0x9000
{
let s = h >> 10 & 1;
let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
let imm = s << 24 | i1 << 23 | i2 << 22 | (h & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
target = Some(pc.wrapping_add(((imm << 7) as i32 >> 7) as u32));
}
} else if h & 0xf800 == 0xe000 {
target = Some(pc.wrapping_add((((h & 0x7ff) << 21) as i32 >> 20) as u32));
}
if let Some(t) = target
&& t.wrapping_sub(entry) >= size
{
out.insert(t & !1);
}
i += len;
}
out
}
fn is_fragment(name: &str) -> bool {
name.starts_with("OUTLINED_FUNCTION_")
|| [".constprop.", ".isra.", ".part.", ".cold", ".lto_priv.", ".localalias"]
.iter()
.any(|p| name.contains(p))
}
fn rom_str(img: &Image, k: u32) -> Option<&[u8]> {
let s = img.segment_at(k).filter(|s| !s.writable)?;
let rest = &s.data[(k - s.addr) as usize..];
let n = rest.iter().position(|&c| c == 0)?;
Some(&rest[..n])
}
fn same_const(a: &Image, b: &Image, layout: &Layout, ka: u32, kb: u32) -> bool {
if let Some(m) = layout.value(kb) {
return m == ka;
}
if let Some(fb) = b.func_at(kb & !1) {
return (ka ^ kb) & 1 == 0 && a.func_at(ka & !1).is_some_and(|fa| fa.name == fb.name);
}
if ka != kb
&& layout.objs.iter().any(|o| kb.wrapping_sub(o.start) < o.size)
&& b.segment_at(kb).is_some_and(|s| s.writable)
{
return false;
}
match (rom_str(a, ka), rom_str(b, kb)) {
(Some(x), Some(y)) => x == y,
(None, None) => ka == kb,
_ => false,
}
}
fn first_difference(a: &Image, b: &Image, layout: &Layout, x: &[u8], y: &[u8]) -> Option<(usize, u32, u32)> {
let mut off = 0usize;
while off < x.len().min(y.len()) {
let n = if off.is_multiple_of(4) && off + 4 <= x.len() {
4
} else {
1
};
let (xs, ys) = (&x[off..off + n], &y[off..off + n]);
if xs != ys {
let word = |s: &[u8]| s.iter().rev().fold(0u32, |v, &b| (v << 8) | b as u32);
let (wa, wb) = (word(xs), word(ys));
let pointers = n == 4
&& (a.segment_at(wa & !1).is_some() || a.externals.contains_key(&(wa & !1)))
&& same_const(a, b, layout, wa, wb);
if !pointers {
return Some((off, wa, wb));
}
}
off += n;
}
None
}
struct Space<'a> {
a: &'a Image,
b: &'a Image,
da: Arc<Image>,
db: Arc<Image>,
layout: Arc<Layout>,
values: Arc<Values>,
paired: BTreeMap<String, [u32; 2]>,
fn_key: [HashMap<u32, String>; 2],
folded: HashMap<String, String>,
obj_pairs: Vec<(String, Named, Named)>,
ext_names: [HashSet<String>; 2],
mmio: Vec<(u32, u32)>,
noreturn: HashSet<String>,
span: (u32, u32),
explain: bool,
notes: std::sync::Mutex<Vec<(String, String)>>,
}
fn funcs_of(img: &Image) -> Vec<Named> {
let mut v: Vec<Named> = img
.symbols
.iter()
.filter(|s| s.kind == SymKind::Func && !s.name.is_empty() && !is_fragment(&s.name))
.filter(|s| img.segment_at(s.addr).is_some_and(|g| g.exec))
.map(|s| Named {
name: s.name.clone(),
file: s.file.clone(),
addr: s.addr,
size: s.size,
writable: false,
})
.collect();
v.sort_by(|x, y| (&x.name, x.addr).cmp(&(&y.name, y.addr)));
v.dedup_by(|x, y| x.name == y.name && x.addr == y.addr);
v
}
struct Values {
layout: Arc<Layout>,
fns: HashMap<u32, u32>,
}
impl Values {
fn revalue(&self, ctx: &mut Ctx, t: T, seen: &mut usize) -> T {
let mut memo = HashMap::new();
self.revalue_in(ctx, t, seen, &mut memo)
}
fn revalue_in(&self, ctx: &mut Ctx, t: T, seen: &mut usize, memo: &mut HashMap<T, T>) -> T {
if let Some(&r) = memo.get(&t) {
return r;
}
*seen += 1;
if *seen > 4096 {
return t;
}
let w = ctx.tm.width(t);
let r = match *ctx.tm.node(t) {
Node::Const(k) if w == 32 => {
let k = k as u32;
let to = self.layout.value(k).or_else(|| {
let entry = self.fns.get(&(k & !1))?;
Some(entry | (k & 1))
});
match to {
Some(m) if m != k => ctx.tm.konst(32, m as u64),
_ => t,
}
}
Node::Ite(c, x, y) => {
let (x2, y2) = (self.revalue_in(ctx, x, seen, memo), self.revalue_in(ctx, y, seen, memo));
if (x2, y2) == (x, y) { t } else { ctx.tm.ite(c, x2, y2) }
}
Node::Concat(x, y) => {
let (x2, y2) = (self.revalue_in(ctx, x, seen, memo), self.revalue_in(ctx, y, seen, memo));
if (x2, y2) == (x, y) { t } else { ctx.tm.concat(x2, y2) }
}
Node::Extract(x, lo) => {
let x2 = self.revalue_in(ctx, x, seen, memo);
if x2 == x { t } else { ctx.tm.extract(x2, lo, w) }
}
Node::ZExt(x) => {
let x2 = self.revalue_in(ctx, x, seen, memo);
if x2 == x { t } else { ctx.tm.zext(x2, w) }
}
Node::LShr(x, n) => {
let x2 = self.revalue_in(ctx, x, seen, memo);
if x2 == x { t } else { ctx.tm.lshr(x2, n) }
}
Node::Shl(x, n) => {
let x2 = self.revalue_in(ctx, x, seen, memo);
if x2 == x { t } else { ctx.tm.shl(x2, n) }
}
_ => t,
};
memo.insert(t, r);
r
}
}
impl<'a> Space<'a> {
fn revalue(&self, ctx: &mut Ctx, t: T, seen: &mut usize) -> T {
self.values.revalue(ctx, t, seen)
}
fn new(a: &'a Image, b: &'a Image, mmio: &[(u32, u32)]) -> Space<'a> {
let (oa, ob) = (objects(a), objects(b));
let obj_pairs: Vec<(String, Named, Named)> = pair_up(&oa, &ob)
.into_iter()
.filter(|p| !p.0.starts_with(".L"))
.map(|(n, i, j)| (n, oa[i].clone(), ob[j].clone()))
.collect();
let mut layout = Layout::default();
for o in &ob {
let peer = obj_pairs
.iter()
.find(|p| p.2.addr == o.addr && p.2.name == o.name)
.map(|p| &p.1);
let same = peer.is_some_and(|p| p.size == o.size && a.read(p.addr, p.size) == b.read(o.addr, o.size));
let direct = peer.is_some_and(|p| (o.writable && p.writable) || (!o.writable && !p.writable && same));
layout.objs.push(ObjMap {
start: o.addr,
size: o.size,
to: peer.map(|p| p.addr),
direct,
same: direct || peer.is_some_and(|p| p.size == o.size && !o.writable && !p.writable),
});
}
layout.objs.sort_by_key(|o| (o.size, o.start));
loop {
let differ: Vec<usize> = (0..layout.objs.len())
.filter(|&i| {
let o = &layout.objs[i];
o.same
&& !o.direct
&& !o
.to
.is_some_and(|to| match (a.read(to, o.size), b.read(o.start, o.size)) {
(Some(x), Some(y)) => first_difference(a, b, &layout, x, y).is_none(),
_ => false,
})
})
.collect();
if differ.is_empty() {
break;
}
for i in differ {
if std::env::var_os("CVERIF_COMPARE_DEBUG").is_some() {
let o = &layout.objs[i];
let d = o
.to
.and_then(|to| first_difference(a, b, &layout, a.read(to, o.size)?, b.read(o.start, o.size)?));
eprintln!("compare: object at {:#x} (old {:x?}) differs: {d:x?}", o.start, o.to);
}
layout.objs[i].same = false;
}
}
let ext_a: HashMap<&str, u32> = a.externals.iter().map(|(a, n)| (n.as_str(), *a)).collect();
for (addr, name) in &b.externals {
if let Some(&to) = ext_a.get(name.as_str()) {
layout.ext.push((*addr, to));
}
}
layout.ext.sort();
layout.segs = b
.segments
.iter()
.map(|s| (s.addr, s.data.len() as u32, s.writable))
.collect();
let stored = |img: &Image| -> Vec<Segment> {
img.segments
.iter()
.filter_map(|s| {
let at = s.load_addr?;
let free = (0..s.data.len() as u32)
.step_by(4)
.all(|o| img.segment_at(at + o).is_none());
free.then(|| Segment {
name: format!("{} (load image)", s.name),
addr: at,
data: s.data.clone(),
writable: false,
exec: false,
load_addr: None,
})
})
.collect()
};
let (stored_a, stored_b) = (stored(a), stored(b));
layout
.segs
.extend(stored_b.iter().map(|s| (s.addr, s.data.len() as u32, false)));
let mut used: Vec<(u32, u32)> = mmio.to_vec();
for img in [a, b] {
used.extend(
img.segments
.iter()
.map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
);
used.extend(img.externals.keys().map(|&e| (e, e + 15)));
}
used.extend(
stored_a
.iter()
.chain(&stored_b)
.map(|s| (s.addr, s.addr + (s.data.len() as u32).saturating_sub(1))),
);
layout.delta = (1..256u32)
.map(|d| d << 24)
.find(|&d| {
b.segments.iter().all(|s| {
let lo = s.addr.wrapping_add(d);
let hi = lo.wrapping_add((s.data.len() as u32).saturating_sub(1));
hi >= lo && used.iter().all(|&(ulo, uhi)| hi < ulo || lo > uhi)
})
})
.unwrap_or(0x7000_0000);
let clone = |s: &Segment, shift: u32| Segment {
name: s.name.clone(),
addr: s.addr.wrapping_add(shift),
data: s.data.clone(),
writable: s.writable,
exec: s.exec,
load_addr: None,
};
let da = Image {
segments: a.segments.iter().chain(&stored_a).map(|s| clone(s, 0)).collect(),
..Default::default()
};
let mut db = Image {
segments: da.segments.iter().map(|s| clone(s, 0)).collect(),
..Default::default()
};
db.segments
.extend(b.segments.iter().chain(&stored_b).map(|s| clone(s, layout.delta)));
layout.rom = db
.segments
.iter()
.filter(|s| !s.writable)
.map(|s| (s.addr, s.data.len() as u32))
.collect();
let (fa, fb) = (funcs_of(a), funcs_of(b));
let mut paired = BTreeMap::new();
let mut fn_key = [HashMap::new(), HashMap::new()];
for (name, i, j) in pair_up(&fa, &fb) {
paired.insert(name, [fa[i].addr, fb[j].addr]);
}
let mut group: HashMap<String, String> = paired.keys().map(|n| (n.clone(), n.clone())).collect();
let mut folded: HashMap<String, String> = HashMap::new();
loop {
let mut changed = false;
for side in 0..2 {
let mut at: HashMap<u32, String> = HashMap::new();
for (n, e) in &paired {
let g = group[n].clone();
match at.get(&e[side]) {
Some(first) if *first != g => {
let (lo, hi) = if *first < g {
(first.clone(), g)
} else {
(g, first.clone())
};
for v in group.values_mut().filter(|v| **v == hi) {
*v = lo.clone();
}
at.insert(e[side], lo);
changed = true;
}
Some(_) => {}
None => {
at.insert(e[side], g);
}
}
}
}
if !changed {
break;
}
}
for (n, e) in &paired {
fn_key[0].insert(e[0], group[n].clone());
fn_key[1].insert(e[1], group[n].clone());
let others: Vec<&str> = (paired.iter())
.filter(|(m, x)| *m != n && (x[0] == e[0]) != (x[1] == e[1]))
.map(|(m, x)| (m.as_str(), x))
.filter(|(m, _)| group[*m] == group[n])
.map(|(m, _)| m)
.collect();
if !others.is_empty() {
folded.insert(
n.clone(),
format!(
"folded: one piece of code with {} in one of the images",
others.join(", ")
),
);
}
}
let stuck = |img: &Image| -> HashSet<u32> {
let d = crate::discover::discover(
img,
&crate::discover::Options {
no_vectors: true,
..Default::default()
},
);
(d.discovery.funcs.iter())
.filter(|f| f.noreturn)
.map(|f| f.addr)
.chain(never_return(img))
.collect()
};
let (na, nb) = (stuck(a), stuck(b));
let noreturn: HashSet<String> = (paired.iter())
.filter(|(_, e)| na.contains(&e[0]) || nb.contains(&e[1]))
.map(|(n, _)| n.clone())
.collect();
let layout = Arc::new(layout);
let values = Arc::new(Values {
layout: layout.clone(),
fns: paired.values().map(|e| (e[1], e[0])).collect(),
});
Space {
a,
b,
da: Arc::new(da),
db: Arc::new(db),
layout,
values,
paired,
folded,
fn_key,
obj_pairs,
ext_names: [
a.externals.values().cloned().collect(),
b.externals.values().cloned().collect(),
],
mmio: mmio.to_vec(),
noreturn,
span: a.segments.iter().chain(&b.segments).fold((u32::MAX, 0), |(lo, hi), s| {
(lo.min(s.addr), hi.max(s.addr + s.data.len() as u32))
}),
explain: false,
notes: Default::default(),
}
}
fn image(&self, side: usize) -> &'a Image {
if side == 0 { self.a } else { self.b }
}
fn data(&self, side: usize) -> &Arc<Image> {
if side == 0 { &self.da } else { &self.db }
}
fn translate(&self, side: usize, ctx: &mut Ctx, addr: T) -> T {
if side == 0 {
addr
} else {
self.layout.translate(ctx, addr)
}
}
fn is_address(&self, k: u32) -> bool {
self.span.0 <= k && k <= self.span.1 && (self.a.segment_at(k).is_some() || self.b.segment_at(k).is_some())
}
fn same_const(&self, ka: u32, kb: u32) -> bool {
same_const(self.a, self.b, &self.layout, ka, kb)
}
fn corr(&self, ctx: &Ctx, va: T, vb: T) -> bool {
if va == vb {
return match ctx.tm.as_const(va) {
Some(k) if ctx.tm.width(va) == 32 && self.is_address(k as u32) => self.same_const(k as u32, k as u32),
_ => true,
};
}
if ctx.tm.width(va) != 32 || ctx.tm.width(vb) != 32 {
return false;
}
if let (Node::Ite(c1, x1, y1), Node::Ite(c2, x2, y2)) = (ctx.tm.node(va), ctx.tm.node(vb))
&& c1 == c2
{
return self.corr(ctx, *x1, *x2) && self.corr(ctx, *y1, *y2);
}
let ((ta, ka), (tb, kb)) = (ctx.tm.linear(va), ctx.tm.linear(vb));
if ta != tb {
return false;
}
let (ka, kb) = (ka as u32, kb as u32);
if !ta.is_empty() && (ka < SMALL_OFFSET || kb < SMALL_OFFSET) {
return ka == kb;
}
self.same_const(ka, kb)
}
}
const NORETURN: &[&str] = &[
"abort",
"exit",
"_exit",
"_Exit",
"__assert_fail",
"__assert_func",
"__builtin_abort",
];
const ARG_WORDS: usize = 8;
struct Job<'a> {
sp: &'a Space<'a>,
entry: [u32; 2],
regs: [[T; 16]; 2],
lr0: T,
stack: Vec<(u32, T)>,
inline: bool,
follow: &'a HashSet<String>,
caller_stack: bool,
}
#[derive(Default)]
struct Facts {
calls: BTreeSet<String>,
stuck: BTreeSet<String>,
overlap: Option<String>,
culprits: BTreeSet<String>,
saw_internal: RefCell<bool>,
ret0_diff: Option<String>,
ret1_diff: bool,
needs: BTreeMap<String, (u8, BTreeMap<u8, String>)>,
dead: BTreeSet<(String, u8)>,
slot_diff: Option<String>,
in_always: u8,
in_r0: u8,
in_r1: u8,
in_arg: BTreeSet<(String, u8, u8)>,
ret_always: BTreeSet<u32>,
ret_r0: BTreeSet<u32>,
ret_r1: BTreeSet<u32>,
ret_arg: BTreeSet<(String, u8, u32)>,
ret_syms: HashMap<u32, (String, bool)>,
inputs: HashMap<T, u8>,
memo: HashMap<T, (u8, Arc<BTreeSet<u32>>)>,
}
impl Facts {
fn deps(&mut self, ctx: &Ctx, t: T) -> (u8, Arc<BTreeSet<u32>>) {
if let Some(d) = self.memo.get(&t) {
return d.clone();
}
let d = match ctx.tm.node(t) {
Node::Sym(id) => {
let mut s = BTreeSet::new();
if self.ret_syms.contains_key(id) {
s.insert(*id);
}
(self.inputs.get(&t).copied().unwrap_or(0), Arc::new(s))
}
n => {
let mut mask = 0u8;
let mut set: Option<Arc<BTreeSet<u32>>> = None;
for c in crate::bv::Prover::children_of(n) {
let (m, s) = self.deps(ctx, c);
mask |= m;
if !s.is_empty() {
set = Some(match set {
None => s,
Some(old) if s.is_subset(&old) => old,
Some(old) => Arc::new(old.union(&s).copied().collect()),
});
}
}
(mask, set.unwrap_or_default())
}
};
self.memo.insert(t, d.clone());
d
}
fn always(&mut self, ctx: &Ctx, t: T) {
let (m, s) = self.deps(ctx, t);
self.in_always |= m;
self.ret_always.extend(s.iter().copied());
}
}
thread_local! {
static MODELS: RefCell<Vec<replay::Model>> = const { RefCell::new(Vec::new()) };
}
fn witness(ctx: &Ctx, env: &Env) -> String {
let text = witness_text(ctx, env);
MODELS.with(|m| {
let mut m = m.borrow_mut();
if m.len() < 1024 && !m.iter().any(|x| x.text == text) {
m.push(replay::Model {
text: text.clone(),
syms: (env.syms.iter())
.map(|(id, v)| (ctx.tm.sym_name(*id).to_string(), *v))
.collect(),
mem: env.mem.clone(),
inline: false,
follow: Vec::new(),
});
}
});
text
}
fn witness_text(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() <= 3 && b[0] == b'r' && b[1..].iter().all(u8::is_ascii_digit))
|| n.starts_with("stk")
|| n.starts_with("ret")
|| n.starts_with("io")
})
.collect();
items.sort_by(|x, y| (x.0.len(), &x.0).cmp(&(y.0.len(), &y.0)));
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 difference(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<Option<String>> {
if sp.corr(ctx, va, vb) {
return Ok(None);
}
if ctx.tm.width(va) != ctx.tm.width(vb) {
return Ok(Some("different sizes".into()));
}
let vt = sp.revalue(ctx, vb, &mut 0);
if vt != vb {
let e = ctx.tm.eq(va, vt);
if ctx.check(e).is_ok() {
return Ok(None);
}
}
if ctx.tm.as_const(vb).is_none()
&& sp.layout.reads_rom(ctx, vb)
&& let Some(values) = enumerate(ctx, vb, MAX_TABLE_VALUES)
{
let mut all = true;
for k in values {
let kt = ctx.tm.konst(32, k as u64);
let c = ctx.tm.eq(vb, kt);
ctx.pc.push(c);
let ka = enumerate(ctx, va, 2).filter(|v| v.len() == 1).map(|v| v[0]);
ctx.pc.pop();
match ka {
Some(ka) if sp.same_const(ka, k) => {}
Some(ka) if sp.is_address(ka) || sp.is_address(k) => {
return Ok(Some(format!(
"old gives {ka:#x}, new gives {k:#x}, which do not designate the same thing in the two images"
)));
}
_ => {
all = false;
break;
}
}
}
if all {
return Ok(None);
}
}
if let (Some(x), Some(y)) = (ctx.tm.as_const(va), ctx.tm.as_const(vb))
&& (sp.is_address(x as u32) || sp.is_address(y as u32))
{
return Ok(Some(format!(
"old gives {x:#x}, new gives {y:#x}, which do not designate the same thing in the two images"
)));
}
let mut e = ctx.tm.eq(va, vb);
for round in 0.. {
let env = match ctx.check(e) {
Ok(()) => return Ok(None),
Err(Some(env)) => env,
Err(None) => break,
};
let mut memo = Default::default();
let (x, y) = (ctx.tm.eval(va, &env, &mut memo), ctx.tm.eval(vb, &env, &mut memo));
if ctx.tm.width(va) != 32 || x == y || !sp.same_const(x as u32, y as u32) {
break;
}
if round >= MAX_POINTER_PAIRS {
return Err(Stop::Truncated(format!(
"{what}: more than {MAX_POINTER_PAIRS} pairs of corresponding pointers"
)));
}
let (kx, ky) = (ctx.tm.konst(32, x), ctx.tm.konst(32, y));
let (ex, ey) = (ctx.tm.eq(va, kx), ctx.tm.eq(vb, ky));
let pair = ctx.tm.and(ex, ey);
e = ctx.tm.or(e, pair);
}
match ctx.check(e) {
Ok(()) => Ok(None),
Err(Some(env)) => {
let mut memo = Default::default();
let (x, y) = (ctx.tm.eval(va, &env, &mut memo), ctx.tm.eval(vb, &env, &mut memo));
let how = format!("old gives {x:#x}, new gives {y:#x} for {}", witness(ctx, &env));
if overlap_only(ctx, va, vb) {
if ctx.notes.len() < 4 {
ctx.notes.push(format!("{what}: {how}"));
}
return Ok(None);
}
if sp.explain {
let note = explain_terms(ctx, sp, va, vb, &env);
sp.notes
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((format!("{what}: {how}"), note));
}
Ok(Some(how))
}
Err(None) => Err(Stop::Inconclusive(format!("{what}: prover gave up"))),
}
}
fn overlap_only(ctx: &mut Ctx, va: T, vb: T) -> bool {
let base = ctx.pc.len();
if !assume_no_overlap(ctx) {
return false;
}
let f = ctx.tm.fals();
let e = ctx.tm.eq(va, vb);
let sat = ctx.check(f);
let same = ctx.check(e);
let only = sat.is_ok() || (matches!(sat, Err(Some(_))) && same.is_ok());
ctx.pc.truncate(base);
only
}
fn path_needs_overlap(ctx: &mut Ctx) -> bool {
let base = ctx.pc.len();
if !assume_no_overlap(ctx) {
return false;
}
let f = ctx.tm.fals();
let only = ctx.check(f).is_ok();
ctx.pc.truncate(base);
only
}
fn assume_no_overlap(ctx: &mut Ctx) -> bool {
let base = ctx.pc.len();
for c in ctx.overlaps.clone() {
let no = ctx.tm.not(c);
if !ctx.pc.contains(&no) {
ctx.pc.push(no);
}
}
ctx.pc.len() > base
}
fn explain_terms(ctx: &Ctx, sp: &Space, va: T, vb: T, env: &Env) -> String {
use crate::explain::{Dag, Names, Printer, Style, show_val};
let (dag, ids) = Dag::from_terms(&ctx.tm, &[va, vb], Some(env));
let names = Names::new(sp.a, None);
let pr = Printer::new(&dag, &names, &ids, Style::default());
let val = |n: u32| match dag.val(n) {
Some(v) => format!(" = {}", show_val(v, dag.width(n))),
None => String::new(),
};
let mut o = String::new();
let _ = writeln!(o, "old: {}{}", pr.expr(ids[0]), val(ids[0]));
let _ = writeln!(o, "new: {}{}", pr.expr(ids[1]), val(ids[1]));
let d = pr.diff(ids[0], ids[1]);
if !(d.holes.len() == 1 && d.skeleton == d.holes[0].label) {
let _ = writeln!(o, "differ in: {}", d.skeleton);
for h in &d.holes {
let v = |v: Option<u64>| v.map_or(String::new(), |v| format!(" = {}", show_val(v, h.width)));
let _ = writeln!(o, " {} old: {}{}", h.label, h.source, v(h.source_val));
let _ = writeln!(o, " {} new: {}{}", h.label, h.binary, v(h.binary_val));
}
}
let lets: Vec<_> = pr.lets().into_iter().filter(|l| o.contains(&l.name)).collect();
if !lets.is_empty() {
let _ = writeln!(o, "where:");
for l in lets {
let v = l
.value
.map_or(String::new(), |v| format!(" = {}", show_val(v, l.width)));
let _ = writeln!(o, " {} = {}{v}", l.name, l.text);
}
}
o
}
fn prove_same(ctx: &mut Ctx, sp: &Space, va: T, vb: T, what: &str) -> R<()> {
match difference(ctx, sp, va, vb, what)? {
None => Ok(()),
Some(how) => Err(Stop::Mismatch(format!("{what}: {how}"), None)),
}
}
fn classify(job: &Job, side: usize, facts: &Facts, addr: u32) -> Callee {
let (img, other) = (job.sp.image(side), 1 - side);
if let Some(name) = img.externals.get(&addr) {
return Callee::External(name.clone());
}
let Some(s) = img.func_at(addr) else {
return Callee::Internal;
};
if is_fragment(&s.name) {
return Callee::Internal;
}
if job.sp.ext_names[other].contains(&s.name) {
return Callee::External(s.name.clone());
}
if let Some(key) = job.sp.fn_key[side].get(&addr) {
if job.sp.noreturn.contains(key) {
return Callee::External(key.clone());
}
*facts.saw_internal.borrow_mut() = true;
if !job.inline && !job.follow.contains(key) {
return Callee::External(key.clone());
}
}
Callee::Internal
}
fn switch_helper(ctx: &mut Ctx, image: &Image, 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) = 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),
};
*count += 1;
m.resume_at(ctx, 1000 + *count, target);
Ok(true)
}
fn mem_call(ctx: &mut Ctx, job: &Job, side: usize, 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" | "__aeabi_memcpy" | "__aeabi_memcpy4" | "__aeabi_memcpy8" => (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;
let to = job.sp.translate(side, ctx, dst);
let periph = |ctx: &Ctx, t: T| {
ctx.tm.as_const(t).is_some_and(|a| {
let (a, end) = (a as u32, (a as u32).wrapping_add(n.max(1) - 1));
job.sp.mmio.iter().any(|&(lo, hi)| a <= hi && end >= lo)
})
};
if periph(ctx, to) {
return false;
}
if fill {
let byte = ctx.tm.trunc(arg, 8);
mem_fill(ctx, &mut m.mem, to, byte, n);
} else {
let from = job.sp.translate(side, ctx, arg);
if periph(ctx, from) {
return false;
}
let data = job.sp.data(side).clone();
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(from, off as u64);
let mut init = image_init(&data, 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(to, 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 run_side(ctx: &mut Ctx, job: &Job, facts: &Facts, side: usize, m: &mut Machine, helpers: &mut usize) -> R<Exit> {
let image = job.sp.image(side);
let cl = |addr: u32| classify(job, side, facts, addr);
let who = if side == 0 { "old image" } else { "new image" };
loop {
ctx.dead_garbage = true;
ctx.dead_hit = false;
let e = match m.run(ctx, image, job.lr0, &cl) {
Ok(e) => e,
Err(Stop::Halt) if ctx.dead_hit && side == 1 => {
return Err(Stop::Unsupported(format!(
"{who}: the code after a call decides on a register the call may clobber (the old code does not)"
)));
}
Err(Stop::Mismatch(why, env)) => {
let why = format!("{who}: {}", why.replacen("binary ", "", 1));
return Err(if side == 0 {
Stop::Unsupported(why)
} else {
Stop::Mismatch(why, env)
});
}
Err(Stop::Unsupported(why)) => return Err(Stop::Unsupported(format!("{who}: {why}"))),
Err(e) => return Err(e),
};
if let Exit::Call { name } = &e {
if switch_helper(ctx, image, m, name, helpers)? {
continue;
}
if model_runtime_call(ctx, m, name, helpers) || mem_call(ctx, job, side, m, name, helpers) {
continue;
}
}
return Ok(e);
}
}
fn last_insn(img: &Image, pc: u32) -> bool {
let site = pc.wrapping_sub(1);
let mut pc = pc;
while pc & 2 != 0 && matches!(img.read(pc, 2), Some([0x00, 0xbf] | [0xc0, 0x46])) {
pc += 2;
}
img.is_data_in_code(pc)
|| img.symbols.iter().any(|s| {
s.kind == SymKind::Func && s.size > 0 && site.wrapping_sub(s.addr) < s.size && pc - s.addr >= s.size
})
}
fn never_return(img: &Image) -> HashSet<u32> {
let mut out = HashSet::new();
for f in img.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size >= 4) {
let Some(d) = img.read(f.addr, f.size) else { continue };
let hw = |i: usize| u16::from_le_bytes([d[i], d[i + 1]]) as u32;
let mut i = 0usize;
while i + 2 <= d.len() {
let at = f.addr + i as u32;
if img.is_data_in_code(at) {
i += 2;
continue;
}
let h1 = hw(i);
if h1 < 0xe800 {
i += 2;
continue;
}
if i + 4 > d.len() {
break;
}
let h2 = hw(i + 2);
if h1 & 0xf800 == 0xf000 && h2 & 0xd000 == 0xd000 {
let s = h1 >> 10 & 1;
let (i1, i2) = (!(h2 >> 13 ^ s) & 1, !(h2 >> 11 ^ s) & 1);
let imm = s << 24 | i1 << 23 | i2 << 22 | (h1 & 0x3ff) << 12 | (h2 & 0x7ff) << 1;
let imm = ((imm << 7) as i32 >> 7) as u32;
let target = at.wrapping_add(4).wrapping_add(imm);
if last_insn(img, at + 4) {
out.insert(target);
}
}
i += 4;
}
}
out
}
fn describe(e: &Exit) -> String {
match e {
Exit::Return => "returns".into(),
Exit::Trap => "traps".into(),
Exit::Hang => "loops for ever".into(),
Exit::Call { name } => format!("calls {name}"),
Exit::Cut(a) => format!("stops at {a:#x}"),
Exit::Asm { name, .. } => format!("executes `{name}`"),
}
}
struct Pair {
m: [Machine; 2],
io_pos: usize,
escaped: Option<i64>,
}
fn compare_effects(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, what: &str) -> R<()> {
let sp = job.sp;
let n = p.m[0].io.len().max(p.m[1].io.len());
for i in p.io_pos..n {
let show = |ctx: &Ctx, a: &crate::thumb::exec::VolAccess| {
format!(
"{} {} byte(s) at {}",
if a.write { "writes" } else { "reads" },
a.size,
ctx.tm.show(a.addr)
)
};
match (p.m[0].io.get(i).cloned(), p.m[1].io.get(i).cloned()) {
(Some(x), Some(y)) => {
if x.write != y.write || x.size != y.size || x.addr != y.addr {
return Err(Stop::Mismatch(
format!(
"peripheral access #{} {what}: old {}, new {}",
i + 1,
show(ctx, &x),
show(ctx, &y)
),
None,
));
}
if x.write {
let at = ctx.tm.show(x.addr);
prove_same(
ctx,
sp,
x.val,
y.val,
&format!("value written to the peripheral register at {at} {what}"),
)?;
facts.always(ctx, x.val);
facts.always(ctx, y.val);
}
}
(Some(x), None) => {
return Err(Stop::Mismatch(
format!("peripheral access {what}: old {}, new does not", show(ctx, &x)),
None,
));
}
(None, Some(y)) => {
return Err(Stop::Mismatch(
format!("peripheral access {what}: new {}, old does not", show(ctx, &y)),
None,
));
}
(None, None) => {}
}
}
p.io_pos = n;
let mut revalued: Option<Vec<crate::sym::Write>> = None;
let mut seen: HashSet<(T, u8)> = HashSet::new();
let entries: Vec<(T, u8)> = p.m[0]
.mem
.world
.iter()
.chain(p.m[1].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 mut ia = image_init(&sp.da, p.m[0].mem.epoch, None);
let va = ctx.read_world(&p.m[0].mem.world, addr, size, &mut ia);
let mut ib = image_init(&sp.db, p.m[1].mem.epoch, None);
let vb = ctx.read_world(&p.m[1].mem.world, addr, size, &mut ib);
let at = ctx.tm.show(addr);
if va != vb && (ctx.mentions_private(va) || ctx.mentions_private(vb)) {
return Err(Stop::Unsupported(format!(
"{what}: a stack address is stored at {at} (the extent of stack objects is unknown without the source)"
)));
}
if !sp.corr(ctx, va, vb) {
let log = revalued.get_or_insert_with(|| {
let mut log = p.m[1].mem.world.clone();
for w in &mut log {
if w.havoc.is_none() && w.size == 4 {
w.val = sp.revalue(ctx, w.val, &mut 0);
}
}
log
});
let mut ib = image_init(&sp.db, p.m[1].mem.epoch, None);
let vr = ctx.read_world(log, addr, size, &mut ib);
if vr != vb && {
let e = ctx.tm.eq(va, vr);
va == vr || ctx.check(e).is_ok()
} {
for t in [addr, va, vb] {
facts.always(ctx, t);
}
continue;
}
}
prove_same(ctx, sp, va, vb, &format!("{what}: {size}-byte value stored at {at}"))?;
for t in [addr, va, vb] {
facts.always(ctx, t);
}
}
Ok(())
}
fn frame_slots(ctx: &mut Ctx, job: &Job, p: &Pair, from: i64) -> Vec<(T, u8)> {
let sp0 = job.regs[0][13];
let mut out: Vec<(T, u8)> = Vec::new();
for m in &p.m {
let Some(log) = m.mem.private.get(&sp0) else { continue };
for w in log {
let keep = match ctx.tm.const_diff(w.addr, sp0) {
Some(d) => d as u32 as i32 as i64 + w.size as i64 > from,
None => true,
};
if keep && !out.contains(&(w.addr, w.size)) {
out.push((w.addr, w.size));
}
}
}
out
}
fn compare_caller_stack(ctx: &mut Ctx, job: &Job, p: &Pair, what: &str) -> R<()> {
if !job.caller_stack {
return Ok(());
}
let sp0 = job.regs[0][13];
for (addr, size) in frame_slots(ctx, job, p, 0) {
let va = frame_read(ctx, job, p, 0, addr, size);
let vb = frame_read(ctx, job, p, 1, addr, size);
if va == vb {
continue;
}
let at = match ctx.tm.const_diff(addr, sp0) {
Some(d) => format!("entry sp+{}", d as u32 as i32),
None => ctx.tm.show(addr),
};
prove_same(
ctx,
job.sp,
va,
vb,
&format!("{what}: {size}-byte value in the caller's stack at {at} (assumption caller-stack)"),
)?;
}
Ok(())
}
fn saved_regs(job: &Job) -> Vec<T> {
(4..=11)
.flat_map(|r| [job.regs[0][r], job.regs[1][r]])
.chain([job.lr0])
.collect()
}
fn frame_read(ctx: &mut Ctx, job: &Job, p: &Pair, side: usize, addr: T, size: u8) -> T {
let data = job.sp.data(side).clone();
let mut init = image_init(&data, p.m[side].mem.epoch, None);
ctx.mem_read(&p.m[side].mem, addr, size, &mut init)
}
fn compare_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str) -> R<()> {
let sp = job.sp;
let sp0 = job.regs[0][13];
for i in 0..ARG_WORDS {
let (ta, tb) = if i < 4 {
(p.m[0].regs[i], p.m[1].regs[i])
} else {
let off = 4 * (i as u64 - 4);
let (aa, ab) = (
ctx.tm.add_const(p.m[0].regs[13], off),
ctx.tm.add_const(p.m[1].regs[13], off),
);
(frame_read(ctx, job, p, 0, aa, 4), frame_read(ctx, job, p, 1, ab, 4))
};
for t in [ta, tb] {
let (m, s) = facts.deps(ctx, t);
if m != 0 {
facts.in_arg.insert((name.to_string(), i as u8, m));
}
for &id in s.iter() {
facts.ret_arg.insert((name.to_string(), i as u8, id));
}
}
if i < 4 && (ctx.region(ta).is_some() || ctx.region(tb).is_some()) {
if ta == tb {
let off = match ctx.tm.const_diff(ta, sp0) {
Some(d) => d as u32 as i32 as i64,
None => i64::MIN,
};
p.escaped = Some(p.escaped.map_or(off, |e| e.min(off)));
continue;
}
if ctx.region(ta).is_some() && ctx.region(tb).is_some() {
return Err(Stop::Unsupported(format!(
"the address of a stack object is passed to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
)));
}
}
if sp.corr(ctx, ta, tb) {
continue;
}
let garbage = |ctx: &Ctx, t: T| match ctx.tm.node(t) {
Node::Sym(id) => ctx.tm.sym_name(*id).starts_with("clob"),
Node::Load(epoch, _) => *epoch == crate::sym::UNINIT_EPOCH,
_ => false,
};
if garbage(ctx, ta) || garbage(ctx, tb) {
for j in i..if i < 4 { i + 1 } else { ARG_WORDS } {
facts.dead.insert((name.to_string(), j as u8));
}
continue;
}
let word = if i < 4 {
format!("r{i}")
} else {
format!("sp[{}]", 4 * (i - 4))
};
let known = facts.needs.get(name).is_some_and(|n| n.0 >> i & 1 != 0);
if known {
continue;
}
let what = format!("{word} at the call to {name}");
if let Some(how) = difference(ctx, sp, ta, tb, &what)? {
let n = facts.needs.entry(name.to_string()).or_default();
n.0 |= 1 << i;
n.1.insert(i as u8, format!("{what}: {how}"));
}
}
while let Some(from) = p.escaped {
let mut lowest = from;
for (addr, size) in frame_slots(ctx, job, p, from) {
for side in 0..2 {
let v = frame_read(ctx, job, p, side, addr, size);
if size == 4 && ctx.region(v).is_some() {
lowest = lowest.min(match ctx.tm.const_diff(v, sp0) {
Some(d) => d as u32 as i32 as i64,
None => i64::MIN,
});
}
}
}
if lowest == from {
break;
}
p.escaped = Some(lowest);
}
if let Some(from) = p.escaped {
if p.m[0].regs[13] != p.m[1].regs[13] {
return Err(Stop::Unsupported(format!(
"the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
)));
}
let saved = saved_regs(job);
for (addr, size) in frame_slots(ctx, job, p, from) {
let (va, vb) = (
frame_read(ctx, job, p, 0, addr, size),
frame_read(ctx, job, p, 1, addr, size),
);
if sp.corr(ctx, va, vb) {
continue;
}
if saved.contains(&va) != saved.contains(&vb) {
return Err(Stop::Unsupported(format!(
"the address of a stack object is known to {name} and the two frames are laid out differently (the extent of stack objects is unknown without the source)"
)));
}
if facts.slot_diff.is_some() {
continue;
}
let what = format!(
"{size} byte(s) of the frame at {} that {name} can reach",
ctx.tm.show(addr)
);
if let Some(how) = difference(ctx, sp, va, vb, &what)? {
facts.slot_diff = Some(format!("{what}: {how}"));
}
}
}
Ok(())
}
fn after_call(ctx: &mut Ctx, job: &Job, facts: &mut Facts, p: &mut Pair, name: &str, k: usize) {
let lo = ctx.named_sym(&format!("ret{k}:lo:{name}"), 32);
let hi = ctx.named_sym(&format!("ret{k}:hi:{name}"), 32);
for (t, high) in [(lo, false), (hi, true)] {
if let Node::Sym(id) = *ctx.tm.node(t) {
facts.ret_syms.insert(id, (name.to_string(), high));
}
}
let slots = match p.escaped {
Some(from) => frame_slots(ctx, job, p, from),
None => Vec::new(),
};
for (side, m) in p.m.iter_mut().enumerate() {
m.finish_call(ctx, 2000 * side + k, Some(lo), Some(hi));
m.mem.world.clear();
m.mem.epoch = k as u32 + 1;
}
let saved = saved_regs(job);
for (n, (addr, size)) in slots.into_iter().enumerate() {
let cur = frame_read(ctx, job, p, 0, addr, size);
if saved.contains(&cur) {
continue;
}
let v = ctx.named_sym(&format!("esc{k}.{n}w{size}"), size * 8);
for m in p.m.iter_mut() {
ctx.mem_write(&mut m.mem, addr, size, v);
}
}
}
fn run_path(ctx: &mut Ctx, job: &Job, facts: &mut Facts) -> R<()> {
let sp = job.sp;
let mk = |ctx: &mut Ctx, side: usize| {
let mut m = Machine::new(ctx, job.entry[side], job.regs[side]);
let layout = sp.layout.clone();
let values = sp.values.clone();
m.remap = Some(Remap {
value: if side == 0 {
Arc::new(|_: &mut Ctx, t: T| t)
} else {
Arc::new(move |ctx: &mut Ctx, t: T| values.revalue(ctx, t, &mut 0))
},
addr: if side == 0 {
Arc::new(|_: &mut Ctx, t: T| t)
} else {
Arc::new(move |ctx: &mut Ctx, t: T| layout.translate(ctx, t))
},
data: sp.data(side).clone(),
});
m.mmio = sp.mmio.clone();
m.stack_top = job.stack.iter().map(|a| a.0 + 4).max().unwrap_or(0);
m.clobbers = (side as u32) << 20;
for &(off, v) in &job.stack {
let a = ctx.tm.add_const(job.regs[side][13], off as u64);
ctx.mem_write(&mut m.mem, a, 4, v);
}
m
};
let mut p = Pair {
m: [mk(ctx, 0), mk(ctx, 1)],
io_pos: 0,
escaped: None,
};
let mut helpers = [0usize, 2000];
let mut k = 0usize;
let mut last: Option<String> = None;
loop {
let [ma, mb] = &mut p.m;
let ea = match run_side(ctx, job, facts, 0, ma, &mut helpers[0]) {
Err(Stop::Halt) if ctx.dead_hit => {
if let Some(callee) = last.take() {
facts.stuck.insert(callee);
}
return Err(Stop::Halt);
}
r => r?,
};
let eb = run_side(ctx, job, facts, 1, mb, &mut helpers[1])?;
match (&ea, &eb) {
(Exit::Return, Exit::Return) => {
compare_effects(ctx, job, facts, &mut p, "at return")?;
compare_caller_stack(ctx, job, &p, "at return")?;
for r in (4..=11).chain([13]) {
let (fa, fb) = (p.m[0].regs[r], p.m[1].regs[r]);
if fa == job.regs[0][r] && fb == job.regs[1][r] {
continue;
}
let name = if r == 13 { "sp".to_string() } else { format!("r{r}") };
prove_same(ctx, sp, fa, fb, &format!("callee-saved register {name} at return"))?;
}
let garbage = |ctx: &Ctx, t: T| matches!(ctx.tm.node(t), Node::Sym(id) if ctx.tm.sym_name(*id).starts_with("clob"));
let (a0, b0) = (p.m[0].regs[0], p.m[1].regs[0]);
if facts.ret0_diff.is_none()
&& !(garbage(ctx, a0) && garbage(ctx, b0))
&& let Some(how) = difference(ctx, sp, a0, b0, "r0 at return")?
{
facts.ret0_diff = Some(format!("r0 at return: {how}"));
}
let (a1, b1) = (p.m[0].regs[1], p.m[1].regs[1]);
if !facts.ret1_diff && !(garbage(ctx, a1) && garbage(ctx, b1)) && !sp.corr(ctx, a1, b1) {
let e = ctx.tm.eq(a1, b1);
facts.ret1_diff = !ctx.implied(e);
}
for t in [a0, b0] {
let (m, s) = facts.deps(ctx, t);
facts.in_r0 |= m;
facts.ret_r0.extend(s.iter().copied());
}
for t in [a1, b1] {
let (m, s) = facts.deps(ctx, t);
facts.in_r1 |= m;
facts.ret_r1.extend(s.iter().copied());
}
break;
}
(Exit::Trap, Exit::Trap) => {
compare_effects(ctx, job, facts, &mut p, "at trap")?;
compare_caller_stack(ctx, job, &p, "at trap")?;
break;
}
(Exit::Hang, Exit::Hang) => {
compare_effects(ctx, job, facts, &mut p, "at the endless loop")?;
compare_caller_stack(ctx, job, &p, "at the endless loop")?;
break;
}
(Exit::Call { name: na }, Exit::Call { name: nb }) if na == nb => {
let what = format!("at call #{} ({na})", k + 1);
if let (Some(ta), Some(tb)) = (p.m[0].indirect.take(), p.m[1].indirect.take()) {
if ctx.mentions_garbage(ta) && last.is_some() {
facts.stuck.extend(last.take());
return Err(Stop::Halt);
}
prove_same(ctx, sp, ta, tb, &format!("target of the call through a pointer {what}"))?;
facts.always(ctx, ta);
facts.always(ctx, tb);
}
compare_effects(ctx, job, facts, &mut p, &what)?;
compare_call(ctx, job, facts, &mut p, na)?;
if sp.paired.contains_key(na.as_str()) {
facts.calls.insert(na.clone());
}
if NORETURN.contains(&na.as_str())
|| sp.noreturn.contains(na.as_str())
|| (0..2).any(|s| last_insn(sp.image(s), p.m[s].resume_pc()))
{
break;
}
after_call(ctx, job, facts, &mut p, na, k);
last = Some(na.clone());
k += 1;
}
(
Exit::Asm {
name: na,
arg: aa,
out: oa,
},
Exit::Asm {
name: nb,
arg: ab,
out: ob,
},
) if na == nb && aa.is_some() == ab.is_some() && oa.is_some() == ob.is_some() => {
let what = format!("at `{na}` (event #{})", k + 1);
compare_effects(ctx, job, facts, &mut p, &what)?;
if let (Some(va), Some(vb)) = (*aa, *ab) {
prove_same(ctx, sp, va, vb, &format!("value written {what}"))?;
}
if let (Some(ra), Some(rb)) = (*oa, *ob) {
let v = ctx.named_sym(&format!("ret{k}:asm:{na}"), 32);
p.m[0].regs[ra as usize] = v;
p.m[1].regs[rb as usize] = v;
}
k += 1;
}
_ => {
if path_needs_overlap(ctx) {
if ctx.notes.len() < 4 {
ctx.notes.push(format!(
"after {k} matching call(s): old {}, new {}",
describe(&ea),
describe(&eb)
));
}
return Err(Stop::Halt);
}
for e in [&ea, &eb] {
if let Exit::Call { name } = e
&& sp.paired.contains_key(name.as_str())
{
facts.culprits.insert(name.clone());
}
}
let f = ctx.tm.fals();
let on = match ctx.check(f) {
Err(Some(env)) => format!(" for {}", witness(ctx, &env)),
_ => String::new(),
};
return Err(Stop::Mismatch(
format!(
"after {k} matching call(s): old {}, new {}{on}",
describe(&ea),
describe(&eb)
),
None,
));
}
}
}
for c in ctx.pc.clone() {
facts.always(ctx, c);
}
Ok(())
}
struct Raw {
verdict: Verdict,
facts: Facts,
inline: bool,
paths: usize,
millis: u128,
models: Vec<(replay::Model, bool)>,
}
type SrcRefs = (BTreeSet<String>, BTreeSet<String>);
struct SrcDelta {
changed: BTreeMap<String, &'static str>,
objects: BTreeSet<String>,
interface: BTreeSet<String>,
refs: [HashMap<String, SrcRefs>; 2],
obj_refs: [HashMap<String, BTreeSet<String>>; 2],
}
const CHANGED: &str = "CHANGED IN SOURCE";
const CHANGED_LINES: &str = "CHANGED IN SOURCE (line numbers and file names only)";
impl SrcDelta {
fn through_source(&self, name: &str, events: [&HashSet<&str>; 2]) -> Result<(), String> {
for side in 0..2 {
let mut seen: BTreeSet<&str> = BTreeSet::new();
let mut objs: BTreeSet<&str> = BTreeSet::new();
let mut work = vec![name];
while let Some(f) = work.pop() {
if !seen.insert(f) {
continue;
}
if self.interface.contains(f) {
return Err(if f == name {
"what its callers may rely on differs between the sources".to_string()
} else {
format!("what the callers of {f} may rely on differs between the sources")
});
}
if f != name && events[side].contains(f) {
continue;
}
if let Some(how) = self.changed.get(f) {
return Err(if f == name {
how.to_string()
} else {
format!("has the code of {f} in place, which is changed in the source")
});
}
let Some((callees, globals)) = self.refs[side].get(f) else {
continue;
};
work.extend(callees.iter().map(|c| c.as_str()));
objs.extend(globals.iter().map(|g| g.as_str()));
}
let mut work: Vec<&str> = objs.into_iter().collect();
let mut seen: BTreeSet<&str> = BTreeSet::new();
while let Some(g) = work.pop() {
if !seen.insert(g) {
continue;
}
if self.objects.contains(g) {
return Err(format!("uses {g}, which is defined differently in the two sources"));
}
if let Some(next) = self.obj_refs[side].get(g) {
work.extend(next.iter().map(|c| c.as_str()));
}
}
}
Ok(())
}
}
fn source_text(p: &Program, f: &crate::c::ast::Func) -> Option<String> {
let file = p.files.get(f.loc.file as usize)?;
let text = std::fs::read_to_string(file).ok()?;
let next = (p.funcs.iter().map(|g| g.loc))
.chain(p.globals.iter().map(|g| g.loc))
.filter(|l| l.file == f.loc.file && l.line > f.loc.line)
.map(|l| l.line)
.min();
let mut o = String::new();
let mut in_comment = false;
for (i, line) in text.lines().enumerate() {
let n = i as u32 + 1;
if n < f.loc.line || next.is_some_and(|e| n >= e) {
continue;
}
let mut rest = line;
loop {
if in_comment {
match rest.find("*/") {
Some(j) => {
rest = &rest[j + 2..];
in_comment = false;
}
None => break,
}
}
let (a, b) = (rest.find("/*"), rest.find("//"));
match (a, b) {
(Some(a), b) if b.is_none_or(|b| a < b) => {
o.push_str(&rest[..a]);
o.push(' ');
rest = &rest[a + 2..];
in_comment = true;
}
(_, Some(b)) => {
o.push_str(&rest[..b]);
break;
}
_ => {
o.push_str(rest);
break;
}
}
}
o.push(' ');
}
Some(o.split_whitespace().collect::<Vec<_>>().join(" "))
}
fn source_delta(pa: &Program, pb: &Program) -> SrcDelta {
fn type_shape(p: &Program, t: u32, depth: u8, memo: &mut HashMap<(u32, u8), String>) -> String {
use crate::c::ast::Type;
let key = (t, depth.min(2));
if let Some(s) = memo.get(&key) {
return s.clone();
}
let s = match p.ty(t) {
Type::Ptr(u) => format!("*{}", type_shape(p, *u, depth + 1, memo)),
Type::Array(u, n) => format!("[{n:?}]{}", type_shape(p, *u, depth, memo)),
Type::Func(ft) => {
let ps: Vec<String> = ft.params.iter().map(|&x| type_shape(p, x, depth + 1, memo)).collect();
format!(
"fn({};{}{})",
type_shape(p, ft.ret, depth + 1, memo),
ps.join(","),
if ft.variadic { ",..." } else { "" }
)
}
Type::Record(r) => {
let rec = &p.records[*r as usize];
let mut o = format!("rec {:?} {} {}", rec.name, rec.size, rec.align);
if depth < 2 {
for f in &rec.fields {
let _ = write!(
o,
" {}@{}{:?}:{}",
f.name,
f.offset,
f.bits,
type_shape(p, f.ty, depth + 1, memo)
);
}
}
format!("{{{o}}}")
}
other => format!("{other:?}"),
};
memo.insert(key, s.clone());
s
}
let spell = |p: &Program, text: &str, lines: Option<(u32, u32)>, memo: &mut HashMap<(u32, u8), String>| -> String {
let mut o = String::new();
let b = text.as_bytes();
let mut i = 0;
let id = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
'scan: while i < b.len() {
if text[i..].starts_with("Loc {") {
i += text[i..].find('}').map_or(text.len() - i, |j| j + 1);
continue;
}
if i == 0 || !id(b[i - 1]) {
for key in ["ty: ", "term_cov: ", "cov: ", "Str(", "Global(", "Func("] {
if !text[i..].starts_with(key) {
continue;
}
let from = i + key.len();
let n = b[from..].iter().take_while(|c| c.is_ascii_digit()).count();
let Ok(v) = text[from..from + n].parse::<usize>() else {
continue;
};
o.push_str(key);
match key {
"ty: " => o.push_str(&type_shape(p, v as u32, 0, memo)),
"Str(" => match p.strings.get(v) {
Some(s) if lines.is_some() && p.files.iter().any(|f| f.as_bytes() == &**s) => {
o.push_str("<file>")
}
s => {
let _ = write!(o, "{s:?}");
}
},
"Global(" => o.push_str(p.globals.get(v).map_or("?", |g| &g.name)),
"Func(" => o.push_str(p.funcs.get(v).map_or("?", |g| &g.name)),
_ => {}
}
i = from + n;
continue 'scan;
}
}
let c = text[i..].chars().next().unwrap();
o.push(c);
i += c.len_utf8();
}
o
};
let extent = |text: &str, first: u32| -> (u32, u32) {
let mut last = first;
let mut rest = text;
while let Some(i) = rest.find("line: ") {
rest = &rest[i + 6..];
let n = rest.bytes().take_while(|c| c.is_ascii_digit()).count();
if let Ok(v) = rest[..n].parse::<u32>() {
last = last.max(v);
}
}
(first, last)
};
let shape = |p: &Program, f: &crate::c::ast::Func, memo: &mut HashMap<(u32, u8), String>| -> (String, String) {
let params: Vec<String> = f.ty.params.iter().map(|&x| type_shape(p, x, 0, memo)).collect();
let head = format!(
"fn({};{};{}) {} {} {} {} {} ",
type_shape(p, f.ty.ret, 0, memo),
params.join(","),
f.ty.variadic,
f.is_static,
f.is_inline,
f.nparams,
f.variadic_def,
f.opaque
);
let body = format!("{:?} {:?}", f.locals, f.body);
if f.opaque || f.unsupported.is_some() {
let text = source_text(p, f).unwrap_or_else(|| {
let why = f.unsupported.as_deref().unwrap_or("");
format!("{body} {}", why.split_once(": ").map_or(why, |w| w.1))
});
let s = format!("{head}{text}");
return (s.clone(), s);
}
let lines = extent(&body, f.loc.line);
let exact = format!("{head}{}", spell(p, &body, None, memo));
let loose = spell(p, &body, Some(lines), memo);
let mut blank = String::with_capacity(loose.len());
let b = loose.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i].is_ascii_digit() && (i == 0 || !(b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_')) {
let n = b[i..].iter().take_while(|c| c.is_ascii_digit()).count();
let end = i + n;
let word = end < b.len() && (b[end].is_ascii_alphanumeric() || b[end] == b'_');
match loose[i..end].parse::<u32>() {
Ok(v) if !word && v >= lines.0 && v <= lines.1 => blank.push_str("<line>"),
_ => blank.push_str(&loose[i..end]),
}
i = end;
} else {
let c = loose[i..].chars().next().unwrap();
blank.push(c);
i += c.len_utf8();
}
}
(exact, format!("{head}{blank}"))
};
type Defs = BTreeMap<String, (Vec<String>, Vec<String>)>;
let defs = |p: &Program| -> Defs {
let mut m: Defs = BTreeMap::new();
let mut memo = HashMap::new();
for f in p.funcs.iter().filter(|f| f.body.is_some() || f.opaque) {
let (exact, loose) = shape(p, f, &mut memo);
let e = m.entry(f.name.to_string()).or_default();
e.0.push(exact);
e.1.push(loose);
}
for v in m.values_mut() {
v.0.sort();
v.0.dedup();
v.1.sort();
v.1.dedup();
}
m
};
let (da, db) = (defs(pa), defs(pb));
let mut changed: BTreeMap<String, &'static str> = BTreeMap::new();
for n in da.keys().chain(db.keys()) {
match (da.get(n), db.get(n)) {
(Some(x), Some(y)) if x.0 == y.0 => {}
(Some(x), Some(y)) if x.1 == y.1 => {
changed.insert(n.clone(), CHANGED_LINES);
}
_ => {
changed.insert(n.clone(), CHANGED);
}
}
}
let objects_of = |p: &Program| -> BTreeMap<String, Vec<String>> {
let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut memo = HashMap::new();
for g in p.globals.iter().filter(|g| g.defined) {
let text = format!(
"{} {} {} {} {} {:?}",
type_shape(p, g.ty, 0, &mut memo),
g.is_static,
g.is_local_static,
g.is_const,
g.is_volatile,
g.init
);
let text = spell(p, &text, None, &mut memo);
m.entry(g.name.to_string()).or_default().push(text);
}
for v in m.values_mut() {
v.sort();
v.dedup();
}
m
};
let (oa, ob) = (objects_of(pa), objects_of(pb));
let objects: BTreeSet<String> = (oa.keys().chain(ob.keys()))
.filter(|n| oa.get(*n) != ob.get(*n))
.cloned()
.collect();
let interface_of = |p: &Program| -> BTreeMap<String, Vec<String>> {
let borrowed = crate::c::borrow::borrowed_params(p);
let callers = crate::c::callers::callers(p);
let mut m: BTreeMap<String, Vec<String>> = BTreeMap::new();
let mut memo = HashMap::new();
for (i, f) in p.funcs.iter().enumerate() {
let params: Vec<String> = f.ty.params.iter().map(|&x| type_shape(p, x, 0, &mut memo)).collect();
let mut restrict: Vec<u32> = (p.restrict_params.iter())
.filter(|r| r.0 == i as u32)
.map(|r| r.1)
.collect();
restrict.sort();
let mut who: Vec<&str> = (callers.callers.get(i).into_iter().flatten())
.map(|c| &*p.funcs[*c as usize].name)
.collect();
who.sort();
who.dedup();
let private = callers.private.get(i).copied().unwrap_or(false);
let text = format!(
"fn({};{};{}) body {} static {} opaque {} noreturn {} twice {} restrict {restrict:?} borrowed {:?} given {:?} private {private} callers {:?} unused {:?} returns {:?}",
type_shape(p, f.ty.ret, 0, &mut memo),
params.join(","),
f.ty.variadic,
f.body.is_some(),
f.is_static,
f.opaque,
p.noreturn.contains(&f.name),
p.returns_twice.contains(&f.name),
borrowed.get(i),
callers.given.get(i),
if private { who } else { Vec::new() },
callers.result_unused.get(i),
p.returns_param(i as u32),
);
m.entry(f.name.to_string()).or_default().push(text);
}
for v in m.values_mut() {
v.sort();
v.dedup();
}
m
};
let (ia, ib) = (interface_of(pa), interface_of(pb));
let interface: BTreeSet<String> = (ia.keys().chain(ib.keys()))
.filter(|n| ia.get(*n) != ib.get(*n))
.cloned()
.collect();
let refs_of = |p: &Program| {
let mut m: HashMap<String, SrcRefs> = HashMap::new();
for (i, f) in p.funcs.iter().enumerate() {
let sig = crate::discover::matcher::refs(p, i as u32);
let e = m.entry(f.name.to_string()).or_default();
e.0.extend(sig.callees.iter().map(|c| p.funcs[*c as usize].name.to_string()));
e.1.extend(sig.globals.iter().map(|g| p.globals[*g as usize].name.to_string()));
}
m
};
let obj_refs_of = |p: &Program| {
let mut m: HashMap<String, BTreeSet<String>> = HashMap::new();
for g in &p.globals {
let e = m.entry(g.name.to_string()).or_default();
for (_, t, _) in g.init.iter().flat_map(|i| &i.relocs) {
if let crate::c::ast::SymRef::Global(x) = t {
e.insert(p.globals[*x as usize].name.to_string());
}
}
}
m
};
SrcDelta {
changed,
objects,
interface,
refs: [refs_of(pa), refs_of(pb)],
obj_refs: [obj_refs_of(pa), obj_refs_of(pb)],
}
}
const MAX_FOLLOWED: usize = 8;
fn analyse_calls(sp: &Space, entry: [u32; 2], opts: &Options) -> Raw {
let mut follow: HashSet<String> = HashSet::new();
loop {
let r = analyse(sp, entry, false, &follow, opts);
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!("compare: {:#x} following {follow:?}: {:?}", entry[0], r.verdict);
}
let more: Vec<String> = match &r.verdict {
Verdict::Different(_) => r
.facts
.culprits
.iter()
.filter(|c| !follow.contains(*c))
.cloned()
.collect(),
_ => Vec::new(),
};
if more.is_empty() || follow.len() + more.len() > MAX_FOLLOWED {
return r;
}
follow.extend(more);
}
}
fn analyse(sp: &Space, entry: [u32; 2], inline: bool, follow: &HashSet<String>, opts: &Options) -> Raw {
let v = &opts.verify;
let start = Instant::now();
MODELS.with(|m| m.borrow_mut().clear());
let mut ctx = Ctx::new(v.limits);
if v.check_solver {
ctx.prover = crate::bv::Prover::new_checked();
}
let mut deadline = start + v.time_limit;
if let Some(d) = v.deadline {
deadline = deadline.min(d);
}
ctx.set_budget(v.work_limit, v.max_terms, Some(deadline));
ctx.track_overlaps = true;
ctx.prover.rom = sp
.db
.segments
.iter()
.filter(|s| !s.writable)
.map(|s| (s.addr, s.data.clone()))
.collect();
let mut facts = Facts::default();
let mut shared = [0 as T; 16];
for (i, r) in shared.iter_mut().enumerate().take(13) {
*r = ctx.named_sym(&format!("r{i}"), 32);
if i < 4 {
facts.inputs.insert(*r, 1 << i);
}
}
shared[13] = ctx.private_base("SP0");
shared[14] = ctx.named_sym("LR0", 32);
shared[15] = ctx.tm.konst(32, 0);
let mut regs = [shared, shared];
for (side, r) in regs.iter_mut().enumerate() {
if let Some(sb) = sp.image(side).static_base {
r[9] = ctx.tm.konst(32, sb as u64);
}
}
let mut stack = Vec::new();
for i in 0..8u32 {
let s = ctx.named_sym(&format!("stk{}", 4 * i), 32);
if i < 4 {
facts.inputs.insert(s, 1 << (4 + i));
}
stack.push((4 * i, s));
}
let bits = if opts.assume.sp_aligned { 3 } else { 2 };
let low = ctx.tm.extract(shared[13], 0, bits);
let z = ctx.tm.konst(bits, 0);
let pre = vec![ctx.tm.eq(low, z)];
let job = Job {
sp,
entry,
regs,
lr0: shared[14],
stack,
inline,
follow,
caller_stack: opts.assume.caller_stack,
};
let mut verdict = Verdict::Equivalent;
let mut bounded: Option<String> = None;
let mut inconclusive: Option<String> = None;
let mut explored = 0usize;
let mut paths = 0usize;
let mut best_paths = 0usize;
let mut steps = 0u64;
let step_budget = v.work_limit.saturating_mul(10).max(200_000);
let max_depth = v.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);
'rounds: for (round, &depth) in schedule.iter().enumerate() {
ctx.limits.max_depth = depth;
ctx.decisions.clear();
let mut depth_hit = false;
inconclusive = None;
paths = 0;
loop {
ctx.restart(&pre);
explored += 1;
match run_path(&mut ctx, &job, &mut facts) {
Ok(()) => paths += 1,
Err(Stop::Undefined) | Err(Stop::Halt) => {}
Err(Stop::Truncated(why)) => {
if why == "branch depth limit" {
depth_hit = true;
} else {
bounded.get_or_insert(why);
}
}
Err(Stop::Inconclusive(why)) => match ctx.check_deadline() {
Err(Stop::Truncated(limit)) => {
bounded.get_or_insert(limit);
}
_ => {
inconclusive.get_or_insert(why);
}
},
Err(Stop::Mismatch(why, _)) => {
verdict = Verdict::Different(why);
break 'rounds;
}
Err(Stop::Unsupported(why)) => {
verdict = Verdict::Unsupported(why);
break 'rounds;
}
}
best_paths = best_paths.max(paths);
steps += ctx.steps;
if steps > step_budget {
bounded.get_or_insert_with(|| "step budget".into());
break 'rounds;
}
if let Err(Stop::Truncated(limit)) = ctx.check_deadline() {
bounded.get_or_insert(limit);
break 'rounds;
}
if explored >= v.limits.max_paths {
bounded.get_or_insert_with(|| "path limit".into());
break 'rounds;
}
if !ctx.next_path() {
break;
}
}
if !depth_hit {
break;
}
if round + 1 == schedule.len() {
bounded.get_or_insert_with(|| format!("loop bound ({depth} branches per path)"));
}
}
let paths = paths.max(best_paths);
if verdict == Verdict::Equivalent {
if let Some(why) = inconclusive {
verdict = Verdict::Inconclusive(why);
} else if let Some(why) = bounded {
verdict = Verdict::Bounded(format!("{why}; {paths} paths compared"));
}
}
facts.overlap = ctx.notes.first().cloned();
Raw {
verdict,
facts,
inline,
paths,
millis: start.elapsed().as_millis(),
models: MODELS.with(|m| {
(m.borrow_mut().drain(..))
.map(|mut m| {
m.inline = inline;
m.follow = follow.iter().cloned().collect();
(m, inline)
})
.collect()
}),
}
}
fn complete(v: &Verdict) -> bool {
matches!(v, Verdict::Equivalent)
}
fn compare_data(sp: &Space, out: &mut Comparison) {
let local = |n: &str| {
n.starts_with(".L") || n.starts_with("__") || n.starts_with("CSWTCH.") || n.starts_with("switch.table")
};
for (name, x, y) in &sp.obj_pairs {
if local(name) {
continue;
}
out.data_checked += 1;
if x.size != y.size {
out.data.push((
name.clone(),
format!("size {} in the old image, {} in the new", x.size, y.size),
));
continue;
}
let (Some(xs), Some(ys)) = (sp.a.read(x.addr, x.size), sp.b.read(y.addr, y.size)) else {
continue;
};
if let Some((off, wa, wb)) = first_difference(sp.a, sp.b, &sp.layout, xs, ys) {
out.data.push((
name.clone(),
format!("initial contents differ at offset {off}: old {wa:#x}, new {wb:#x}"),
));
}
}
let (oa, ob) = (objects(sp.a), objects(sp.b));
let only = |l: &[Named], other: &[Named]| -> Vec<String> {
let mut v: Vec<String> = l
.iter()
.filter(|o| !local(&o.name) && !other.iter().any(|p| p.name == o.name))
.map(|o| o.name.clone())
.collect();
v.sort();
v.dedup();
v
};
out.data_removed = only(&oa, &ob);
out.data_added = only(&ob, &oa);
}
thread_local! {
static REPLAY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn compare_replayed(a: &Image, b: &Image, src: Option<(&Program, &Program)>, opts: &Options) -> Comparison {
REPLAY.with(|r| r.set(true));
let c = compare(a, b, src, opts);
REPLAY.with(|r| r.set(false));
c
}
pub fn compare(a: &Image, b: &Image, src: Option<(&Program, &Program)>, opts: &Options) -> Comparison {
let mut sp = Space::new(a, b, &opts.verify.mmio);
sp.explain = opts.explain;
let mut out = Comparison {
assume: opts.assume.clone(),
with_source: src.is_some(),
..Default::default()
};
compare_data(&sp, &mut out);
let wanted = |n: &str| opts.verify.only.is_empty() || opts.verify.only.iter().any(|o| o == n);
let mut by_source: HashMap<String, (Verdict, String)> = HashMap::new();
let mut voids: HashMap<String, bool> = HashMap::new();
let mut in_source: HashMap<String, (bool, bool)> = HashMap::new();
let mut src_diff: HashMap<String, (String, &'static str)> = HashMap::new();
let delta = src.map(|(pa, pb)| source_delta(pa, pb));
let same_code: HashSet<&String> = (sp.paired.iter())
.filter(|(_, [ea, eb])| {
let size = |img: &Image, e: u32| img.func_at(e).map_or(0, |s| s.size);
let (sa, sb) = (size(a, *ea), size(b, *eb));
sa == sb && same_instructions(&sp, *ea, *eb, sa)
})
.map(|(n, _)| n)
.collect();
let lazy = std::env::var_os("CVERIF_COMPARE_FULL").is_none();
let mut src_status: HashMap<String, String> = HashMap::new();
let mut src_events: HashMap<String, Vec<String>> = HashMap::new();
if let (Some((pa, pb)), Some(delta)) = (src, &delta) {
out.source_changed = delta.changed.keys().cloned().collect();
let mut vopts = opts.verify.clone();
let mut none = false;
if lazy && vopts.only.is_empty() {
let (mut rest, mut left_out) = (BTreeSet::new(), 0);
for f in pa.funcs.iter().chain(pb.funcs.iter()).filter(|f| f.body.is_some()) {
if same_code.contains(&f.name.to_string()) {
left_out += 1;
} else {
rest.insert(f.name.to_string());
}
}
if left_out > 0 {
none = rest.is_empty();
vopts.only = rest.into_iter().collect();
out.source_unchecked = same_code.len();
}
}
let (ra, rb) = if none {
Default::default()
} else {
(verify(pa, a, &vopts), verify(pb, b, &vopts))
};
for f in pa.funcs.iter().filter(|f| f.body.is_some()) {
voids.insert(f.name.to_string(), f.ty.ret == VOID);
}
for fa in &ra.funcs {
let Some(fb) = rb.funcs.iter().find(|f| f.name == fa.name) else {
continue;
};
fn events(r: &crate::verify::FuncReport) -> HashSet<&str> {
r.modulo.iter().map(|m| m.0.as_str()).collect()
}
let (ea, eb) = (events(fa), events(fb));
if let Err(how) = delta.through_source(&fa.name, [&ea, &eb]) {
let word = |s: &Status| match s {
Status::Proved => "PROVED".to_string(),
Status::Bounded(_) => "BOUNDED".to_string(),
Status::Mismatch(why) => format!("MISMATCH ({why})"),
_ => "not established".to_string(),
};
if !delta.changed.contains_key(&fa.name) {
out.source_affected.push(fa.name.clone());
}
src_status.insert(
fa.name.clone(),
format!(
"{how}; against its own source the old image is {}, the new image is {}",
word(&fa.status),
word(&fb.status)
),
);
continue;
}
let mut called: Vec<String> = ea.union(&eb).map(|c| c.to_string()).collect();
called.sort();
src_events.insert(fa.name.clone(), called);
let r = match (&fa.status, &fb.status) {
(Status::Proved, Status::Proved) => (
Verdict::Equivalent,
if delta.changed.is_empty() {
"both match the source".to_string()
} else {
"both match the source, which says the same in both versions".to_string()
},
),
(Status::Proved, Status::Mismatch(why)) => {
src_diff.insert(
fa.name.clone(),
(
format!("the new image does not match the source: {why}"),
"old matches the source",
),
);
continue;
}
(Status::Mismatch(why), Status::Proved) => {
src_diff.insert(
fa.name.clone(),
(
format!("the old image does not match the source: {why}"),
"new matches the source",
),
);
continue;
}
(x, y) => {
let mismatch = matches!(x, Status::Mismatch(_)) || matches!(y, Status::Mismatch(_));
let ok = |s: &Status| matches!(s, Status::Proved | Status::Bounded(_));
in_source.insert(fa.name.clone(), (!mismatch, ok(x) && ok(y)));
continue;
}
};
by_source.insert(fa.name.clone(), r);
}
}
let names: Vec<&String> = sp
.paired
.keys()
.filter(|n| wanted(n) && !by_source.contains_key(*n))
.collect();
let run = |which: &[u32], inline: bool| -> Vec<Raw> {
run_jobs(which, opts.verify.jobs, |i| {
let n = names[i as usize];
crate::verify::caught(|| {
if std::env::var("CVERIF_TEST_PANIC").is_ok_and(|v| v == *n) {
panic!("requested by CVERIF_TEST_PANIC");
}
if inline {
analyse(&sp, sp.paired[n], true, &HashSet::new(), opts)
} else {
analyse_calls(&sp, sp.paired[n], opts)
}
})
.unwrap_or_else(|what| Raw {
verdict: Verdict::Inconclusive(crate::verify::internal_error(&what)),
facts: Facts::default(),
inline,
paths: 0,
millis: 0,
models: Vec::new(),
})
})
};
let all: Vec<u32> = (0..names.len() as u32).collect();
let same: Vec<bool> = names.iter().map(|n| same_code.contains(*n)).collect();
let mut skipped: Vec<bool> = same.iter().map(|s| *s && lazy).collect();
let direct: Vec<BTreeSet<String>> = (names.iter())
.map(|n| {
let ea = sp.paired[*n][0];
let size = a.func_at(ea).map_or(0, |s| s.size);
direct_targets(a, ea, size)
.into_iter()
.filter_map(|t| sp.fn_key[0].get(&t).cloned())
.collect()
})
.collect();
let mut raw: Vec<Raw> = (0..names.len())
.map(|i| Raw {
verdict: Verdict::Equivalent,
facts: Facts {
calls: if skipped[i] { direct[i].clone() } else { BTreeSet::new() },
..Default::default()
},
inline: false,
paths: 0,
millis: 0,
models: Vec::new(),
})
.collect();
let active: Vec<u32> = all.iter().copied().filter(|&i| !skipped[i as usize]).collect();
for (i, r) in active.iter().zip(run(&active, false)) {
raw[*i as usize] = r;
}
let mut notes: Vec<Option<String>> = vec![None; names.len()];
let redo = |raw: &mut Vec<Raw>, notes: &mut Vec<Option<String>>, which: Vec<u32>| {
let again = run(&which, true);
for (i, r) in which.into_iter().zip(again) {
let i = i as usize;
let decisive = complete(&r.verdict) || matches!(r.verdict, Verdict::Different(_));
notes[i] = Some(String::new());
if decisive {
let own = match (&raw[i].verdict, &r.verdict) {
(Verdict::Different(why), Verdict::Different(_)) => Some(why.clone()),
_ => None,
};
let mut models = std::mem::take(&mut raw[i].models);
raw[i] = r;
raw[i].models.append(&mut models);
if let Some(why) = own {
raw[i].verdict = Verdict::Different(why);
}
} else if !matches!(raw[i].verdict, Verdict::Different(_)) {
} else {
let Verdict::Different(old) = &raw[i].verdict else {
unreachable!()
};
let why = match &r.verdict {
Verdict::Bounded(w) | Verdict::Inconclusive(w) | Verdict::Unsupported(w) => w.clone(),
_ => String::new(),
};
let msg =
format!("differs when calls are matched one to one ({old}); with the callees followed: {why}");
raw[i].verdict = match &r.verdict {
Verdict::Bounded(_) => Verdict::Bounded(msg),
Verdict::Unsupported(_) => Verdict::Unsupported(msg),
_ => Verdict::Inconclusive(msg),
};
raw[i].inline = true;
}
}
};
let first: Vec<u32> = all
.iter()
.copied()
.filter(|&i| {
let r = &raw[i as usize];
!complete(&r.verdict) && *r.facts.saw_internal.borrow()
})
.collect();
if std::env::var_os("CVERIF_DEBUG").is_some() {
for &i in &first {
eprintln!(
"compare: {} call by call: {:?}",
names[i as usize], raw[i as usize].verdict
);
}
}
if !first.is_empty() {
redo(&mut raw, &mut notes, first);
}
let index: HashMap<&str, usize> = names.iter().enumerate().map(|(i, n)| (n.as_str(), i)).collect();
let solve_with = |raw: &[Raw], skipped: &[bool], passed_on: bool| -> (Vec<u8>, Vec<[bool; 2]>) {
let n = raw.len();
let mut uses = vec![0u8; n];
let mut read = vec![[false; 2]; n];
let reads = |uses: &[u8], callee: &str, word: u8| match index.get(callee) {
Some(&j) => uses[j] >> word & 1 != 0,
None => true,
};
loop {
let mut changed = false;
for (i, r) in raw.iter().enumerate() {
let f = &r.facts;
let mut u = if complete(&r.verdict) && !skipped[i] {
f.in_always | f.in_r0
} else {
0xff
};
if read[i][1] {
u |= f.in_r1;
}
for (callee, word, mask) in &f.in_arg {
if reads(&uses, callee, *word) {
u |= mask;
}
}
if u != uses[i] {
uses[i] = u;
changed = true;
}
let mut hit: Vec<u32> = f.ret_always.iter().copied().collect();
if read[i][0] {
hit.extend(f.ret_r0.iter().copied());
}
if read[i][1] {
hit.extend(f.ret_r1.iter().copied());
}
for (callee, word, id) in &f.ret_arg {
if passed_on
&& index
.get(callee.as_str())
.is_some_and(|&j| complete(&raw[j].verdict) && uses[j] >> word & 1 != 0)
{
hit.push(*id);
}
}
for id in hit {
let (callee, high) = &f.ret_syms[&id];
if let Some(&j) = index.get(callee.as_str())
&& !read[j][*high as usize]
{
read[j][*high as usize] = true;
changed = true;
}
}
}
if !changed {
return (uses, read);
}
}
};
let solve = |raw: &[Raw], skipped: &[bool]| solve_with(raw, skipped, true);
loop {
let mut wanted: BTreeSet<usize> = BTreeSet::new();
let mut differs: BTreeSet<&str> = BTreeSet::new();
let uses = solve(&raw, &skipped).0;
for (i, r) in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]) {
let f = &r.facts;
if f.ret0_diff.is_some() || f.ret1_diff {
differs.insert(names[i].as_str());
}
let mut work: Vec<(usize, u8)> = (f.needs.iter())
.filter_map(|(c, (mask, _))| Some((*index.get(c.as_str())?, *mask)))
.collect();
let mut seen: BTreeSet<(usize, u8)> = BTreeSet::new();
while let Some((j, mask)) = work.pop() {
if mask & uses[j] == 0 || !seen.insert((j, mask)) {
continue;
}
if skipped[j] {
wanted.insert(j);
continue;
}
for (h, word, m) in &raw[j].facts.in_arg {
if m & mask != 0
&& let Some(&k) = index.get(h.as_str())
{
work.push((k, 1 << word));
}
}
}
}
loop {
let before = differs.len();
for (i, r) in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]) {
let f = &r.facts;
if (f.ret_r0.iter().chain(f.ret_r1.iter())).any(|id| differs.contains(f.ret_syms[id].0.as_str())) {
differs.insert(names[i].as_str());
}
}
if differs.len() == before {
break;
}
}
for r in raw.iter().enumerate().filter(|(i, _)| !skipped[*i]).map(|x| x.1) {
let f = &r.facts;
for (callee, _, id) in &f.ret_arg {
if differs.contains(f.ret_syms[id].0.as_str())
&& let Some(&j) = index.get(callee.as_str())
&& skipped[j]
{
wanted.insert(j);
}
}
}
for (i, d) in direct.iter().enumerate() {
if skipped[i] && d.iter().any(|c| differs.contains(c.as_str())) {
wanted.insert(i);
}
}
if wanted.is_empty() {
break;
}
let which: Vec<u32> = wanted.iter().map(|&i| i as u32).collect();
for (i, r) in which.iter().zip(run(&which, false)) {
raw[*i as usize] = r;
skipped[*i as usize] = false;
}
let again: Vec<u32> = which
.iter()
.copied()
.filter(|&i| {
let r = &raw[i as usize];
!complete(&r.verdict) && *r.facts.saw_internal.borrow()
})
.collect();
if !again.is_empty() {
redo(&mut raw, &mut notes, again);
}
}
let skipped = skipped;
if std::env::var_os("CVERIF_DEBUG").is_some() {
eprintln!(
"compare: {} pairs, {} with the same instructions, {} of them analysed all the same",
names.len(),
same.iter().filter(|s| **s).count(),
(0..names.len()).filter(|&i| same[i] && !skipped[i]).count()
);
for (i, n) in names.iter().enumerate() {
if !same[i] {
eprintln!("compare: {n}: not the same instructions");
}
}
}
let (mut uses, mut read) = solve(&raw, &skipped);
let dead_of = |raw: &[Raw], callee: &str| -> u8 {
let m = raw
.iter()
.flat_map(|r| r.facts.dead.iter())
.filter(|d| d.0 == callee)
.fold(0u8, |m, d| m | 1 << d.1);
if m & 1 != 0 {
0xff
} else if m & 4 != 0 {
m | 0xf8
} else {
m
}
};
let live = |raw: &[Raw], uses: &[u8], callee: &str, mask: u8| -> u8 {
let mask = mask & !dead_of(raw, callee);
match index.get(callee) {
Some(&j) => mask & uses[j],
None => mask,
}
};
if std::env::var_os("CVERIF_DEBUG").is_some() {
for (i, r) in raw.iter().enumerate() {
let f = &r.facts;
let who = |ids: &BTreeSet<u32>| -> Vec<String> {
ids.iter()
.map(|id| format!("{}{}", f.ret_syms[id].0, if f.ret_syms[id].1 { ":hi" } else { "" }))
.collect()
};
eprintln!(
"compare: {} inputs {:#x}/{:#x}/{:#x} {:?} complete={} reads results always {:?}, if its r0 is read {:?}, if its r1 is read {:?}",
names[i],
f.in_always,
f.in_r0,
f.in_r1,
f.in_arg,
complete(&r.verdict),
who(&f.ret_always),
who(&f.ret_r0),
who(&f.ret_r1)
);
}
}
for _ in 0..names.len() {
let again: Vec<u32> = all
.iter()
.copied()
.filter(|&i| {
let r = &raw[i as usize];
!r.inline
&& notes[i as usize].is_none()
&& complete(&r.verdict)
&& r.facts.needs.iter().any(|(callee, (mask, _))| {
index.contains_key(callee.as_str()) && live(&raw, &uses, callee, *mask) != 0
})
})
.collect();
if again.is_empty() {
break;
}
redo(&mut raw, &mut notes, again);
(uses, read) = solve(&raw, &skipped);
}
let used = solve_with(&raw, &skipped, false).1;
let mut diffs: Vec<FuncDiff> = Vec::new();
let mut r0_only: HashSet<String> = HashSet::new();
for (i, n) in names.iter().enumerate() {
let r = &raw[i];
let [ea, eb] = sp.paired[*n];
let size = |img: &Image, e: u32| img.func_at(e).map_or(0, |s| s.size);
let (sa, sb) = (size(a, ea), size(b, eb));
let mut d = FuncDiff {
name: (*n).clone(),
old: Some((ea, sa)),
new: Some((eb, sb)),
verdict: r.verdict.clone(),
same_code: sa == sb && sa > 0 && a.read(ea, sa) == b.read(eb, sb),
conditions: Vec::new(),
modulo: Vec::new(),
inlined: r.inline,
via_source: None,
route: Route::Machine,
replay: None,
paths: r.paths,
millis: r.millis,
explanation: None,
};
if complete(&r.verdict) || matches!(r.verdict, Verdict::Bounded(_)) {
let f = &r.facts;
let mut hard: Option<String> = None;
let mut weak: Vec<String> = Vec::new();
for (callee, (mask, whys)) in &f.needs {
let mask = live(&raw, &uses, callee, *mask);
if mask == 0 {
continue;
}
let why = &whys[&(mask.trailing_zeros() as u8)];
let words: Vec<String> = (0..ARG_WORDS)
.filter(|w| mask >> w & 1 != 0)
.map(|w| {
if w < 4 {
format!("r{w}")
} else {
format!("sp[{}]", 4 * (w - 4))
}
})
.collect();
if opts.assume.ext_arity {
d.conditions
.push(format!("{callee} does not read {}", words.join(", ")));
} else {
weak.push(format!(
"{why} (not a difference if {callee} does not read {})",
words.join(", ")
));
}
}
for callee in &f.stuck {
d.conditions.push(format!(
"{callee} does not return here (the old code after the call decides on a register the call may clobber)"
));
}
if let Some(why) = &f.overlap {
weak.push(format!(
"{why}, only when a load overlaps a store made through another address (not a difference if the two are distinct objects)"
));
}
if let Some(why) = &f.slot_diff {
weak.push(format!("{why} (not a difference outside the object it was given)"));
}
if let Some(why) = &f.ret0_diff {
let known = voids.get(n.as_str()).copied();
if read[i][0] {
hard = Some(format!("{why} (callers read the result)"));
} else if known == Some(true) {
d.via_source = Some("returns void in the source".into());
} else if known == Some(false) {
hard = Some(why.clone());
} else if opts.assume.void_r0 {
d.conditions.push("it returns nothing (r0 differs at return)".into());
} else {
if weak.is_empty() {
r0_only.insert((*n).clone());
}
weak.push(format!("{why} (not a difference if it returns nothing)"));
}
}
if f.ret1_diff && hard.is_none() {
if used[i][1] {
hard = Some("r1 differs at return and callers read it".into());
} else if read[i][1] {
weak.push(
"r1 differs at return, and some caller leaves it in place for its next call (not a difference unless it returns a 64-bit value or a caller relies on the registers it keeps)"
.into(),
);
} else if !opts.assume.ret32 {
weak.push("r1 differs at return (not a difference unless it returns a 64-bit value)".into());
} else if !voids.contains_key(n.as_str()) {
d.conditions
.push("it does not return a 64-bit value (r1 differs at return)".into());
}
}
if let Some(why) = hard {
d.verdict = Verdict::Different(why);
} else if !weak.is_empty() {
d.verdict = Verdict::MayDiffer(weak.join("; "));
}
}
match in_source.get(n.as_str()) {
Some(&(true, bounded)) => match &d.verdict {
Verdict::Different(why) | Verdict::MayDiffer(why) => {
let why = format!(
"the machine code differs ({why}), possibly only where the source is undefined: neither image is shown to differ from the source"
);
d.verdict = if bounded {
Verdict::Bounded(format!("{why}; both match it as far as explored"))
} else {
Verdict::Inconclusive(why)
};
}
Verdict::Equivalent => {}
_ if bounded => {
d.verdict = Verdict::Bounded("both images match the source as far as explored".into());
}
_ => {}
},
Some(&(false, _)) => d.via_source = Some("differs from the source".into()),
None => {}
}
if same[i] && (skipped[i] || !matches!(d.verdict, Verdict::Equivalent)) {
d.route = Route::SameInstructions;
d.verdict = Verdict::Equivalent;
d.conditions.clear();
d.modulo.clear();
d.via_source = Some(
"the same instructions; the functions they call and the addresses they hold designate the same things"
.into(),
);
}
diffs.push(d);
}
for d in diffs.iter_mut() {
if let Some(how) = src_status.get(&d.name) {
d.via_source = Some(how.clone());
} else if let (Some(how), None) = (sp.folded.get(&d.name), &d.via_source) {
d.via_source = Some(how.clone());
}
}
let status: HashMap<String, &'static str> = diffs
.iter()
.map(|d| (d.name.clone(), d.label()))
.chain(by_source.iter().map(|(n, v)| {
(
n.clone(),
if v.0 == Verdict::Equivalent {
"EQUIVALENT"
} else {
"DIFFERENT"
},
)
}))
.chain(src_diff.keys().map(|n| (n.clone(), "DIFFERENT")))
.collect();
for (i, d) in diffs.iter_mut().enumerate() {
let f = &raw[i].facts;
if !matches!(d.verdict, Verdict::Equivalent | Verdict::MayDiffer(_)) || !complete(&raw[i].verdict) {
continue;
}
let forwarded: BTreeSet<&str> = f
.ret_r0
.iter()
.chain(f.ret_r1.iter())
.chain(f.ret_arg.iter().map(|x| &x.2))
.filter(|id| !f.ret_syms[*id].1)
.map(|id| f.ret_syms[id].0.as_str())
.collect();
for callee in &f.calls {
if *callee == d.name {
continue;
}
match status.get(callee.as_str()).copied() {
Some("EQUIVALENT" | "IDENTICAL" | "MOVED") | None => {}
Some("MAY-DIFFER") if r0_only.contains(callee) && !forwarded.contains(callee.as_str()) => {}
Some(s) => d.modulo.push((callee.clone(), s.to_string())),
}
}
}
for d in diffs.iter_mut() {
let Some((why, how)) = src_diff.get(&d.name) else {
continue;
};
if d.verdict == Verdict::Equivalent && d.modulo.iter().any(|m| m.1 == "DIFFERENT") {
d.via_source = Some("differs from the source only through what it calls".into());
} else {
d.verdict = Verdict::Different(why.clone());
d.via_source = Some(how.to_string());
d.modulo.clear();
d.conditions.clear();
}
}
for (n, (v, how)) in by_source {
let [ea, eb] = sp.paired.get(&n).copied().unwrap_or([0, 0]);
let at = |img: &Image, e: u32| img.func_at(e).or_else(|| img.func(&n)).map(|s| (s.addr, s.size));
let (old, new) = (at(a, ea), at(b, eb));
let modulo: Vec<(String, String)> = (src_events.get(&n).into_iter().flatten())
.filter(|c| **c != n)
.filter_map(|c| match status.get(c.as_str()).copied() {
Some("EQUIVALENT" | "IDENTICAL" | "MOVED" | "MAY-DIFFER") | None => None,
Some(s) => Some((c.clone(), s.to_string())),
})
.collect();
diffs.push(FuncDiff {
same_code: match (old, new) {
(Some(x), Some(y)) => x.1 == y.1 && x.1 > 0 && a.read(x.0, x.1) == b.read(y.0, y.1),
_ => false,
},
name: n,
old,
new,
verdict: v,
conditions: Vec::new(),
modulo,
inlined: false,
via_source: Some(how),
route: Route::Source,
replay: None,
paths: 0,
millis: 0,
explanation: None,
});
}
let (fa, fb) = (funcs_of(a), funcs_of(b));
for (side, list) in [(0, &fa), (1, &fb)] {
for f in list.iter() {
if !wanted(&f.name) || sp.fn_key[side].contains_key(&f.addr) {
continue;
}
let at = Some((f.addr, f.size));
diffs.push(FuncDiff {
name: f.name.clone(),
old: if side == 0 { at } else { None },
new: if side == 1 { at } else { None },
verdict: if side == 0 { Verdict::Removed } else { Verdict::Added },
same_code: false,
conditions: Vec::new(),
modulo: Vec::new(),
inlined: false,
via_source: None,
route: Route::None,
replay: None,
paths: 0,
millis: 0,
explanation: None,
});
}
}
let show = REPLAY.with(|r| r.get()) || std::env::var_os("CVERIF_REPLAY").is_some();
{
for d in diffs.iter_mut() {
let Verdict::Different(why) = &d.verdict else { continue };
let Some(&i) = index.get(d.name.as_str()) else { continue };
let found = (raw[i].models.iter())
.filter(|(m, _)| m.text != "any input" && why.contains(&m.text))
.max_by_key(|(m, inline)| (m.text.len(), *inline == d.inlined))
.or_else(|| raw[i].models.iter().find(|(m, _)| why.contains(&m.text)));
d.replay = Some(match found {
_ if src_diff.contains_key(&d.name) => replay::Replay::NotModelled(
"the verdict and its counterexample come from the comparison with the source".into(),
),
Some((m, _)) => replay::replay(&sp, sp.paired[&d.name], m, why),
None => replay::Replay::NotModelled("the verdict has no counterexample of the machine code".into()),
});
if let Some(replay::Replay::NotReproduced(how)) = &d.replay {
d.verdict = Verdict::Inconclusive(format!(
"the prover finds a difference ({why}) that running the old and the new code on that input does not show: {how}"
));
d.modulo.clear();
d.conditions.clear();
}
if !show && !matches!(d.replay, Some(replay::Replay::NotReproduced(_))) {
d.replay = None;
}
}
}
diffs.sort_by(|x, y| {
let key = |d: &FuncDiff| (d.old.or(d.new).map_or(0, |x| x.0), d.old.is_none());
key(x).cmp(&key(y)).then(x.name.cmp(&y.name))
});
if opts.explain {
let notes = std::mem::take(&mut *sp.notes.lock().unwrap_or_else(|e| e.into_inner()));
let (na, nb) = (crate::explain::Names::new(a, None), crate::explain::Names::new(b, None));
for d in diffs.iter_mut() {
let (Verdict::Different(why) | Verdict::MayDiffer(why)) = &d.verdict else {
continue;
};
let mut o = String::new();
if let Some((_, note)) = notes.iter().find(|n| why.contains(&n.0)) {
o.push_str(note);
}
for (label, image, names, at) in [("old", a, &na, d.old), ("new", b, &nb, d.new)] {
if let Some((addr, size)) = at {
let _ = writeln!(o, "{label} code:");
o.push_str(&crate::explain::binary::listing(
image,
names,
addr & !1,
(addr & !1) + size,
));
}
}
d.explanation = Some(o);
}
}
out.funcs = diffs;
out
}