use super::{Dag, Importer, Names, Printer, Style, json_str, show_val};
use crate::c::ast::{Program, Type};
use crate::c::exec::CExec;
use crate::sym::{Ctx, R, Stop, WordLoc, arg_words};
use crate::term::{Env, Node, T};
use crate::thumb::exec::Machine;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt::Write as _;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Origin {
None,
Src(u32),
Bin(u32),
}
type RawWrite = (T, u8, T);
#[derive(Default)]
struct RawCall {
name: String,
args: Vec<T>,
ret: Option<T>,
writes: Vec<RawWrite>,
}
#[derive(Default)]
struct RawSide {
calls: Vec<RawCall>,
writes: Vec<RawWrite>,
vol: Vec<(bool, T, u8, T, usize)>,
ret: Vec<(String, T)>,
returned: bool,
cov: Vec<u32>,
insns: Vec<(u32, u8)>,
}
struct Track {
marks: Vec<(usize, usize, Origin)>,
cur: Origin,
cur_len: usize,
pre_len: usize,
last_src: Option<u32>,
last_bin: Option<u32>,
goal: Option<(T, T)>,
addr: Option<T>,
dump: usize,
src: Option<RawSide>,
bin: Option<RawSide>,
paths: Vec<PathDump>,
skipped: usize,
}
impl Track {
const fn new() -> Track {
Track {
marks: Vec::new(),
cur: Origin::None,
cur_len: 0,
pre_len: 0,
last_src: None,
last_bin: None,
goal: None,
addr: None,
dump: 0,
src: None,
bin: None,
paths: Vec::new(),
skipped: 0,
}
}
#[inline]
fn mark(&mut self, len: usize, o: Origin) {
if len > self.cur_len {
self.marks.push((self.cur_len, len, self.cur));
}
self.cur_len = len;
self.cur = o;
}
fn origin(&self, i: usize) -> Origin {
if i < self.pre_len {
return Origin::None;
}
match self.marks.iter().find(|m| m.0 <= i && i < m.1) {
Some(m) => m.2,
None if i >= self.cur_len => self.cur,
None => Origin::None,
}
}
}
thread_local! {
static TRACK: RefCell<Track> = const { RefCell::new(Track::new()) };
}
pub(crate) fn begin_function(dump: usize) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
*t = Track::new();
t.dump = dump;
});
}
pub(crate) fn begin_round() {
TRACK.with(|t| {
let mut t = t.borrow_mut();
t.paths.clear();
t.skipped = 0;
});
}
pub(crate) fn begin_path(pre_len: usize) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
t.marks.clear();
t.cur = Origin::None;
t.cur_len = pre_len;
t.pre_len = pre_len;
t.last_src = None;
t.last_bin = None;
t.goal = None;
t.addr = None;
t.src = None;
t.bin = None;
});
}
#[inline]
pub(crate) fn at_src(pc_len: usize, cov: u32) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
t.mark(pc_len, Origin::Src(cov));
t.last_src = Some(cov);
});
}
#[inline]
pub(crate) fn at_bin(pc_len: usize, addr: u32) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
t.mark(pc_len, Origin::Bin(addr));
t.last_bin = Some(addr);
});
}
#[inline]
pub(crate) fn note_addr(addr: T) {
TRACK.with(|t| t.borrow_mut().addr = Some(addr));
}
pub(crate) fn note_goal(source: T, binary: T) {
TRACK.with(|t| t.borrow_mut().goal = Some((source, binary)));
}
#[inline]
pub(crate) fn dumping() -> bool {
TRACK.with(|t| t.borrow().dump > 0)
}
pub(crate) fn note_source(cx: &CExec, ret: Option<T>, halted: bool) {
if !dumping() {
return;
}
let mut s = RawSide {
returned: !halted,
cov: cx.cov.clone(),
..Default::default()
};
for ev in &cx.events {
s.calls.push(RawCall {
name: ev.name.clone(),
args: ev.args.iter().map(|a| a.0).collect(),
ret: ev.ret.map(|r| r.0),
writes: ev.writes.iter().map(|w| (w.addr, w.size, w.val)).collect(),
});
if ev.noreturn {
s.returned = false;
}
}
s.writes = cx.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect();
s.vol = cx
.volatile
.iter()
.map(|v| (v.write, v.addr, v.size, v.val, v.event))
.collect();
if let Some(r) = ret {
s.ret.push(("return".into(), r));
}
TRACK.with(|t| t.borrow_mut().src = Some(s));
}
pub(crate) fn note_call(m: &Machine, name: &str, nargs: Option<usize>) {
if !dumping() {
return;
}
TRACK.with(|t| {
let mut t = t.borrow_mut();
let b = t.bin.get_or_insert_with(RawSide::default);
b.calls.push(RawCall {
name: name.to_string(),
args: m.regs[..nargs.unwrap_or(4).min(4)].to_vec(),
ret: None,
writes: m.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect(),
});
b.insns = m.covered.clone();
});
}
pub(crate) fn note_return(m: &Machine, width: Option<u8>) {
if !dumping() {
return;
}
TRACK.with(|t| {
let mut t = t.borrow_mut();
let b = t.bin.get_or_insert_with(RawSide::default);
b.returned = true;
match width {
None => {}
Some(64) => {
b.ret.push(("r0".into(), m.regs[0]));
b.ret.push(("r1".into(), m.regs[1]));
}
Some(_) => b.ret.push(("r0".into(), m.regs[0])),
}
b.writes = m.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect();
b.insns = m.covered.clone();
});
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Side {
Pre,
Source,
Binary,
Compare,
}
impl Side {
pub fn label(self) -> &'static str {
match self {
Side::Pre => "precondition",
Side::Source => "source",
Side::Binary => "binary",
Side::Compare => "comparison",
}
}
}
#[derive(Clone, Debug)]
pub struct Decision {
pub cond: u32,
pub side: Side,
pub line: Option<(String, u32)>,
pub addr: Option<u32>,
}
#[derive(Clone, Debug)]
pub struct Input {
pub label: String,
pub name: String,
pub value: u64,
pub width: u8,
}
#[derive(Clone, Debug, Default)]
pub struct Explanation {
pub outcome: String,
pub goal: String,
pub what: String,
pub reason: String,
pub dag: Dag,
pub source: Option<u32>,
pub binary: Option<u32>,
pub address: Option<u32>,
pub path: Vec<Decision>,
pub assumptions: Vec<u32>,
pub inputs: Vec<Input>,
pub memory: Vec<(u32, u32, Vec<u8>)>,
pub has_model: bool,
pub src_loc: Option<(String, u32)>,
pub bin_addr: Option<u32>,
pub induction: Option<bool>,
pub induction_code: String,
pub induction_detail: String,
}
#[derive(Clone, Debug)]
pub enum Effect {
Write {
addr: u32,
size: u8,
val: u32,
},
Volatile {
write: bool,
addr: u32,
size: u8,
val: u32,
},
Call {
index: usize,
name: String,
args: Vec<u32>,
ret: Option<u32>,
},
Return(Vec<(String, u32)>),
NoReturn,
}
#[derive(Clone, Debug, Default)]
pub struct SideDump {
pub trace: String,
pub effects: Vec<Effect>,
}
#[derive(Clone, Debug, Default)]
pub struct PathDump {
pub dag: Dag,
pub outcome: String,
pub conds: Vec<Decision>,
pub assumptions: Vec<u32>,
pub source: Option<SideDump>,
pub binary: Option<SideDump>,
}
#[derive(Clone, Debug, Default)]
pub struct FuncDetail {
pub explanation: Option<Explanation>,
pub paths: Vec<PathDump>,
pub skipped_paths: usize,
}
fn aliases(prog: &Program, fid: u32) -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
let f = &prog.funcs[fid as usize];
let record = |t| matches!(prog.ty(t), Type::Record(_)) && prog.size_of(t).is_some_and(|s| s > 0);
let first = (record(f.ty.ret) && prog.size_of(f.ty.ret).unwrap_or(0) > 4) as u8;
let shapes: Vec<(u32, bool)> =
f.ty.params
.iter()
.map(|&t| (prog.size_of(t).unwrap_or(4), prog.align_of(t) == 8))
.collect();
for (i, locs) in arg_words(&shapes, first).into_iter().enumerate() {
let Some(l) = f.locals.get(i).filter(|_| i < f.nparams) else {
continue;
};
let rec = record(f.ty.params[i]);
if rec {
m.insert(format!("&arg{i}"), format!("&{}", l.name));
}
for (j, loc) in locs.iter().enumerate() {
let sym = match loc {
WordLoc::Reg(n) => format!("r{n}"),
WordLoc::Stack(off) => format!("stk{off}"),
};
let name = match (locs.len(), rec, j) {
(1, false, _) => l.name.to_string(),
(2, false, 0) => format!("{}.lo", l.name),
(2, false, _) => format!("{}.hi", l.name),
_ => format!("{}.word{j}", l.name),
};
let ty = f.ty.params[i];
let bits = prog.bits(ty);
if locs.len() == 1 && !rec && bits < 32 {
let vw = if ty == crate::c::ast::BOOL { 1 } else { bits };
m.insert(format!("{sym}:{vw}"), name.clone());
}
m.insert(sym, name);
}
}
for (s, bytes) in prog.strings.iter().enumerate() {
m.insert(format!("&str#{s}"), string_label(bytes));
}
m
}
pub(crate) fn string_label(bytes: &[u8]) -> String {
let mut o = String::from("\"");
let body = bytes.strip_suffix(&[0]).unwrap_or(bytes);
for (i, &b) in body.iter().enumerate() {
if i >= 24 {
o.push('\u{2026}');
break;
}
match b {
b'"' => o.push_str("\\\""),
b'\\' => o.push_str("\\\\"),
b'\n' => o.push_str("\\n"),
b'\t' => o.push_str("\\t"),
0x20..=0x7e => o.push(b as char),
_ => {
let _ = write!(o, "\\x{b:02x}");
}
}
}
o.push('"');
o
}
fn loc_of(prog: Option<&Program>, cov: u32) -> Option<(String, u32)> {
let p = prog?;
let (_, loc) = p.cov_info.get(cov as usize)?;
Some((p.files.get(loc.file as usize).cloned().unwrap_or_default(), loc.line))
}
fn decisions(ctx: &Ctx, t: &Track, prog: Option<&Program>, dag: &mut Dag, imp: &mut Importer) -> Vec<Decision> {
ctx.pc
.iter()
.enumerate()
.map(|(i, &c)| {
let cond = dag.import(imp, c);
let (side, line, addr) = if i < t.pre_len {
(Side::Pre, None, None)
} else {
match t.origin(i) {
Origin::Src(cov) => (Side::Source, loc_of(prog, cov), None),
Origin::Bin(a) => (Side::Binary, None, Some(a)),
Origin::None => (Side::Compare, None, None),
}
};
Decision { cond, side, line, addr }
})
.collect()
}
fn calls_from_syms(dag: &Dag) -> Vec<String> {
let mut calls: Vec<String> = Vec::new();
for s in &dag.syms {
let Some(rest) = s.strip_prefix("ret") else { continue };
let Some((k, name)) = rest.split_once(':') else {
continue;
};
let Ok(k) = k.parse::<usize>() else { continue };
if k < 4096 {
if calls.len() <= k {
calls.resize(k + 1, String::new());
}
calls[k] = name.to_string();
}
}
if let Some(i) = calls.iter().position(|c| c.is_empty()) {
calls.truncate(i);
}
calls
}
fn goal_kind(what: &str) -> &'static str {
let w = what;
if w.starts_with("return value") || w.contains("returned structure") {
"return_value"
} else if w.starts_with("memory") {
"memory"
} else if w.contains("argument") || w.contains("passed to") {
"argument"
} else if w.starts_with("target of call") {
"call_target"
} else if w.contains("register") || w.starts_with("stack pointer") {
"register"
} else if w.contains("volatile") {
"volatile"
} else if w.starts_with("binary ") {
"call_sequence"
} else {
"other"
}
}
pub(crate) fn capture(
ctx: &Ctx,
prog: Option<&Program>,
fid: u32,
outcome: &str,
why: &str,
env: Option<&Env>,
) -> Explanation {
TRACK.with(|t| {
let t = t.borrow();
let mut e = Explanation {
outcome: outcome.to_string(),
..Default::default()
};
let (what, reason) = match outcome {
"bounded" => ("", why),
_ => match why.find(": source gives").or_else(|| why.find(": prover gave up")) {
Some(i) => (&why[..i], &why[i + 2..]),
None => (why, why),
},
};
e.what = what.to_string();
e.reason = reason.to_string();
e.goal = if outcome == "bounded" { "limit" } else { goal_kind(what) }.to_string();
if let Some(p) = prog {
e.dag.alias = aliases(p, fid);
}
let mut imp = Importer::new(&ctx.tm, env);
if let Some((c, b)) = t.goal.filter(|_| outcome != "bounded" || why.contains("limit")) {
e.source = Some(e.dag.import(&mut imp, c));
e.binary = Some(e.dag.import(&mut imp, b));
if e.goal == "memory"
&& let Some(a) = t.addr
{
e.address = Some(e.dag.import(&mut imp, a));
}
}
e.path = decisions(ctx, &t, prog, &mut e.dag, &mut imp);
e.assumptions = ctx.ub.iter().map(|&u| e.dag.import(&mut imp, u)).collect();
e.dag.calls = calls_from_syms(&e.dag);
e.src_loc = t.last_src.and_then(|c| loc_of(prog, c));
e.bin_addr = t.last_bin;
if let Some(env) = env {
e.has_model = true;
let pr = Printer::new(&e.dag, &NO_NAMES, &[], Style::default());
let mut seen = std::collections::HashSet::new();
for (i, (n, w)) in e.dag.nodes.iter().enumerate() {
let Node::Sym(s) = n else { continue };
let name = &e.dag.syms[*s as usize];
if name == super::ELIDED
|| name.starts_with('&')
|| matches!(name.as_str(), "SP0" | "LR0" | "RET0")
|| !seen.insert(name.clone())
{
continue;
}
e.inputs.push(Input {
label: pr.sym_label(name),
name: name.clone(),
value: e.dag.vals[i].unwrap_or(0),
width: *w,
});
}
e.inputs
.sort_by_key(|i| (!e.dag.alias.contains_key(&i.name), i.name.clone()));
let mut cells: Vec<(u32, u32, u8)> = env.mem.iter().map(|(&(m, a), &v)| (m, a as u32, v)).collect();
cells.sort();
cells.truncate(512);
for (m, a, v) in cells {
match e.memory.last_mut() {
Some(run) if run.0 == m && run.1.wrapping_add(run.2.len() as u32) == a && run.2.len() < 8 => {
run.2.push(v)
}
_ => e.memory.push((m, a, vec![v])),
}
}
}
e
})
}
static NO_NAMES: Names = Names { objs: Vec::new() };
pub(crate) fn limit_only(why: &str) -> Explanation {
Explanation {
outcome: "bounded".into(),
goal: "limit".into(),
reason: why.to_string(),
..Default::default()
}
}
fn src_trace(prog: Option<&Program>, cov: &[u32]) -> String {
let mut files: Vec<(String, Vec<u32>)> = Vec::new();
for &c in cov {
let Some((f, l)) = loc_of(prog, c) else { continue };
match files.iter_mut().find(|x| x.0 == f) {
Some(x) => x.1.push(l),
None => files.push((f, vec![l])),
}
}
let mut o = Vec::new();
for (f, mut lines) in files {
lines.sort();
lines.dedup();
let mut runs: Vec<(u32, u32)> = Vec::new();
for l in lines {
match runs.last_mut() {
Some(r) if r.1 + 1 == l => r.1 = l,
_ => runs.push((l, l)),
}
}
let runs: Vec<String> = runs
.iter()
.map(|&(a, b)| if a == b { a.to_string() } else { format!("{a}-{b}") })
.collect();
let short = f.rsplit('/').next().unwrap_or(&f).to_string();
o.push(format!("{short}:{}", runs.join(",")));
}
o.join(" ")
}
fn bin_trace(insns: &[(u32, u8)]) -> String {
let mut v: Vec<(u32, u32)> = insns.iter().map(|&(a, n)| (a, a + n as u32)).collect();
v.sort();
let mut runs: Vec<(u32, u32)> = Vec::new();
for (a, b) in v {
match runs.last_mut() {
Some(r) if r.1 >= a => r.1 = r.1.max(b),
_ => runs.push((a, b)),
}
}
let runs: Vec<String> = runs.iter().map(|&(a, b)| format!("{a:#x}-{b:#x}")).collect();
runs.join(" ")
}
fn side_dump(raw: &RawSide, source: bool, trace: String, dag: &mut Dag, imp: &mut Importer) -> SideDump {
let mut d = SideDump {
trace,
effects: Vec::new(),
};
let mut shown: std::collections::HashSet<RawWrite> = std::collections::HashSet::new();
let mut writes = |ws: &[RawWrite], d: &mut SideDump, dag: &mut Dag, imp: &mut Importer| {
let mut last: Vec<RawWrite> = Vec::new();
for &w in ws {
if source && !shown.insert(w) {
continue;
}
last.retain(|x| !(x.0 == w.0 && x.1 == w.1));
last.push(w);
}
for (a, size, v) in last {
let (addr, val) = (dag.import(imp, a), dag.import(imp, v));
d.effects.push(Effect::Write { addr, size, val });
}
};
let vols = |k: usize, d: &mut SideDump, dag: &mut Dag, imp: &mut Importer| {
for &(write, a, size, v, ev) in &raw.vol {
if ev == k {
let (addr, val) = (dag.import(imp, a), dag.import(imp, v));
d.effects.push(Effect::Volatile { write, addr, size, val });
}
}
};
for (k, c) in raw.calls.iter().enumerate() {
writes(&c.writes, &mut d, dag, imp);
vols(k, &mut d, dag, imp);
let args = c.args.iter().map(|&a| dag.import(imp, a)).collect();
let ret = c.ret.map(|r| dag.import(imp, r));
d.effects.push(Effect::Call {
index: k + 1,
name: c.name.clone(),
args,
ret,
});
}
if raw.returned {
writes(&raw.writes, &mut d, dag, imp);
vols(raw.calls.len(), &mut d, dag, imp);
let ret = raw.ret.iter().map(|(l, t)| (l.clone(), dag.import(imp, *t))).collect();
d.effects.push(Effect::Return(ret));
} else {
d.effects.push(Effect::NoReturn);
}
d
}
pub(crate) fn end_path<V>(ctx: &Ctx, prog: Option<&Program>, fid: u32, res: &R<V>) {
if !dumping() {
return;
}
let outcome = match res {
Ok(_) => "proved".to_string(),
Err(Stop::Undefined) => "the source has undefined behaviour here (nothing to prove)".into(),
Err(Stop::Halt) => "does not return".into(),
Err(Stop::Truncated(w)) => format!("not explored to the end: {w}"),
Err(Stop::Mismatch(w, _)) => format!("MISMATCH: {w}"),
Err(Stop::Inconclusive(w)) => format!("inconclusive: {w}"),
Err(Stop::Unsupported(w)) => format!("unsupported: {w}"),
};
end_path_as(ctx, prog, fid, outcome);
}
pub(crate) fn end_path_as(ctx: &Ctx, prog: Option<&Program>, fid: u32, outcome: String) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
if t.paths.len() >= t.dump {
t.skipped += 1;
return;
}
let mut p = PathDump {
outcome,
..Default::default()
};
if let Some(pg) = prog {
p.dag.alias = aliases(pg, fid);
}
let mut imp = Importer::new(&ctx.tm, None);
p.conds = decisions(ctx, &t, prog, &mut p.dag, &mut imp);
p.assumptions = ctx.ub.iter().map(|&u| p.dag.import(&mut imp, u)).collect();
if let Some(s) = &t.src {
p.dag.calls = s.calls.iter().map(|c| c.name.clone()).collect();
p.source = Some(side_dump(s, true, src_trace(prog, &s.cov), &mut p.dag, &mut imp));
}
if let Some(b) = &t.bin {
if p.dag.calls.is_empty() {
p.dag.calls = b.calls.iter().map(|c| c.name.clone()).collect();
}
p.binary = Some(side_dump(b, false, bin_trace(&b.insns), &mut p.dag, &mut imp));
}
t.paths.push(p);
});
}
pub(crate) fn take_paths() -> (Vec<PathDump>, usize) {
TRACK.with(|t| {
let mut t = t.borrow_mut();
let skipped = t.skipped;
(std::mem::take(&mut t.paths), skipped)
})
}
fn used_lets(lets: Vec<super::Let>, body: &str) -> Vec<super::Let> {
let mentions = |text: &str, name: &str| {
text.match_indices(name).any(|(i, _)| {
!text[i + name.len()..].starts_with(|c: char| c.is_ascii_digit())
&& !text[..i].ends_with(|c: char| c.is_alphanumeric() || c == '_')
})
};
let mut keep = vec![false; lets.len()];
for i in (0..lets.len()).rev() {
keep[i] = mentions(body, &lets[i].name)
|| (i + 1..lets.len()).any(|j| keep[j] && mentions(&lets[j].text, &lets[i].name));
}
lets.into_iter().zip(keep).filter(|x| x.1).map(|x| x.0).collect()
}
fn pad(s: &str, w: usize) -> String {
let n = s.chars().count();
if n >= w {
s.to_string()
} else {
format!("{s}{}", " ".repeat(w - n))
}
}
fn decision_origin(d: &Decision, names: &Names) -> String {
match (&d.line, d.addr) {
(Some((f, l)), _) => format!("source {}:{l}", f.rsplit('/').next().unwrap_or(f)),
(None, Some(a)) => match names.locate(a) {
Some(s) => format!("binary {a:#x} <{s}>"),
None => format!("binary {a:#x}"),
},
_ => d.side.label().to_string(),
}
}
fn mem_label(names: &Names, snapshot: u32, addr: u32, calls: &[String]) -> String {
let mut s = match names.locate(addr) {
Some(n) => format!("{n} ({addr:#x})"),
None => format!("{addr:#x}"),
};
if snapshot & super::UNINIT != 0 {
s.push_str(" {never written}");
} else if snapshot > 0 {
match calls.get(snapshot as usize - 1) {
Some(c) => {
let _ = write!(s, " {{after call #{snapshot} to {c}}}");
}
None => {
let _ = write!(s, " {{after call #{snapshot}}}");
}
}
}
s
}
impl Explanation {
fn roots(&self) -> Vec<u32> {
let mut r: Vec<u32> = self.source.into_iter().chain(self.binary).chain(self.address).collect();
r.extend(self.path.iter().filter(|d| d.side != Side::Pre).map(|d| d.cond));
r.extend(self.assumptions.iter().copied());
r
}
pub fn text(&self, names: &Names, style: Style) -> String {
let mut roots = self.roots();
if style.full {
roots.extend(self.path.iter().filter(|d| d.side == Side::Pre).map(|d| d.cond));
}
let pr = Printer::new(&self.dag, names, &roots, style);
let mut o = String::new();
let val = |n: u32| match self.dag.val(n) {
Some(v) => format!(" = {}", show_val(v, self.dag.width(n))),
None => String::new(),
};
match self.outcome.as_str() {
"bounded" => {
let _ = writeln!(o, " limit: {}", self.reason);
match self.induction {
Some(true) => {
let _ = writeln!(
o,
" induction: attempted, no proof found (no loop invariant strong enough within half the budget)"
);
}
Some(false) => {
let _ = writeln!(o, " induction: not attempted (the limit was hit first)");
}
None => {}
}
match (self.induction_code.as_str(), self.induction_detail.as_str()) {
("", _) => {}
(code, "") => {
let _ = writeln!(o, " obstacle: {code}");
}
(code, detail) => {
let _ = writeln!(o, " obstacle: {code}: {detail}");
}
}
if !self.what.is_empty() {
let _ = writeln!(o, " undecided: {}", self.what);
}
}
_ => {
let _ = writeln!(o, " compared: {}", self.what);
if let Some(a) = self.address {
let _ = writeln!(o, " address: {}", pr.addr(a));
}
if self.reason != self.what {
let _ = writeln!(o, " result: {}", self.reason);
}
}
}
let mut at = Vec::new();
if let Some((f, l)) = &self.src_loc {
at.push(format!("source {f}:{l}"));
}
if let Some(a) = self.bin_addr {
at.push(match names.locate(a) {
Some(s) => format!("binary {a:#x} <{s}>"),
None => format!("binary {a:#x}"),
});
}
if !at.is_empty() {
let _ = writeln!(o, " at: {}", at.join(", "));
}
let shown: Vec<&Decision> = self.path.iter().filter(|d| style.full || d.side != Side::Pre).collect();
let pre = self.path.len() - self.path.iter().filter(|d| d.side != Side::Pre).count();
if self.path.is_empty() {
} else if shown.is_empty() {
let _ = writeln!(o, " path: every input (no branch decision)");
} else {
let _ = writeln!(o, " path: taken when");
let texts: Vec<String> = shown.iter().map(|d| pr.expr(d.cond)).collect();
let w = texts.iter().map(|t| t.chars().count()).max().unwrap_or(0).min(48);
for (i, (d, t)) in shown.iter().zip(&texts).enumerate() {
let _ = writeln!(o, " {:>2}. {} [{}]", i + 1, pad(t, w), decision_origin(d, names));
}
}
if pre > 0 && !style.full {
let _ = writeln!(
o,
" (+ {pre} calling-convention preconditions; --full lists them)"
);
}
if !self.assumptions.is_empty() {
let _ = writeln!(o, " assuming: the source has no undefined behaviour, that is");
for &a in &self.assumptions {
let _ = writeln!(o, " - {}", pr.expr(a));
}
}
let mut tail = String::new();
if let (Some(s), Some(b)) = (self.source, self.binary) {
let (st, bt) = (pr.expr(s), pr.expr(b));
let w = st.chars().count().max(bt.chars().count()).min(60);
let _ = writeln!(tail, "{}", format!(" source: {}{}", pad(&st, w), val(s)).trim_end());
let _ = writeln!(tail, "{}", format!(" binary: {}{}", pad(&bt, w), val(b)).trim_end());
let d = pr.diff(s, b);
if !(d.holes.len() == 1 && d.skeleton == d.holes[0].label) {
let _ = writeln!(tail, " differ in: {}", d.skeleton);
for h in &d.holes {
let w = h.source.chars().count().max(h.binary.chars().count()).min(60);
let v = |v: Option<u64>| match v {
Some(v) => format!(" = {}", show_val(v, h.width)),
None => String::new(),
};
let _ = writeln!(tail, " {} source: {}{}", h.label, pad(&h.source, w), v(h.source_val));
let _ = writeln!(tail, " binary: {}{}", pad(&h.binary, w), v(h.binary_val));
}
}
}
let lets = used_lets(pr.lets(), &format!("{o}{tail}"));
if !lets.is_empty() {
let _ = writeln!(o, " where:");
for l in &lets {
let v = match l.value {
Some(v) => format!(" = {}", show_val(v, l.width)),
None => String::new(),
};
let _ = writeln!(o, " {} = {}{v}", l.name, l.text);
}
}
o.push_str(&tail);
if self.has_model {
if self.inputs.is_empty() && self.memory.is_empty() {
let _ = writeln!(o, " counterexample: any input");
} else {
let _ = writeln!(o, " counterexample:");
}
let w = self.inputs.iter().map(|i| i.label.chars().count()).max().unwrap_or(0);
for i in &self.inputs {
let raw = if i.label == i.name {
String::new()
} else {
format!(" ({})", i.name)
};
let _ = writeln!(o, " {} = {}{raw}", pad(&i.label, w), show_val(i.value, i.width));
}
let limit = if style.full { usize::MAX } else { 16 };
for (m, a, bytes) in self.memory.iter().take(limit) {
let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
let _ = writeln!(
o,
" memory at {}: {}",
mem_label(names, *m, *a, &self.dag.calls),
hex.join(" ")
);
}
if self.memory.len() > limit {
let _ = writeln!(o, " ... {} more memory cells (--full)", self.memory.len() - limit);
}
}
o
}
pub fn json(&self, names: &Names) -> String {
let mut roots = self.roots();
roots.extend(self.path.iter().filter(|d| d.side == Side::Pre).map(|d| d.cond));
let pr = Printer::new(&self.dag, names, &roots, Style::default());
let hex = |v: u64| format!("\"{v:#x}\"");
let term = |n: u32| {
let mut s = format!("{{\"text\":{},\"node\":{n}", json_str(&pr.expr(n)));
if let Some(v) = self.dag.val(n) {
let _ = write!(s, ",\"value\":{}", hex(v));
}
s.push('}');
s
};
let mut o = format!(
"{{\"outcome\":{},\"goal\":{},\"what\":{},\"reason\":{}",
json_str(&self.outcome),
json_str(&self.goal),
json_str(&self.what),
json_str(&self.reason)
);
if let Some(i) = self.induction {
let _ = write!(o, ",\"induction_attempted\":{i}");
if !self.induction_code.is_empty() {
let _ = write!(
o,
",\"induction\":{},\"induction_detail\":{}",
json_str(&self.induction_code),
json_str(&self.induction_detail)
);
}
}
o.push_str(",\"location\":{");
let mut loc = Vec::new();
if let Some((f, l)) = &self.src_loc {
loc.push(format!("\"file\":{},\"line\":{l}", json_str(f)));
}
if let Some(a) = self.bin_addr {
loc.push(format!("\"address\":{a}"));
}
o.push_str(&loc.join(","));
o.push('}');
if let Some(a) = self.address {
let _ = write!(o, ",\"address\":{}", term(a));
}
o.push_str(",\"path\":[");
for (i, d) in self.path.iter().enumerate() {
let _ = write!(
o,
"{}{{\"side\":{},\"condition\":{},\"node\":{}",
if i > 0 { "," } else { "" },
json_str(d.side.label()),
json_str(&pr.expr(d.cond)),
d.cond
);
if let Some((f, l)) = &d.line {
let _ = write!(o, ",\"file\":{},\"line\":{l}", json_str(f));
}
if let Some(a) = d.addr {
let _ = write!(o, ",\"address\":{a}");
}
o.push('}');
}
o.push_str("],\"assumptions\":[");
for (i, &a) in self.assumptions.iter().enumerate() {
let _ = write!(o, "{}{}", if i > 0 { "," } else { "" }, term(a));
}
o.push(']');
if let (Some(s), Some(b)) = (self.source, self.binary) {
let _ = write!(o, ",\"source\":{},\"binary\":{}", term(s), term(b));
let d = pr.diff(s, b);
let _ = write!(o, ",\"diff\":{{\"skeleton\":{},\"holes\":[", json_str(&d.skeleton));
for (i, h) in d.holes.iter().enumerate() {
let _ = write!(
o,
"{}{{\"label\":{},\"source\":{},\"binary\":{}",
if i > 0 { "," } else { "" },
json_str(&h.label),
json_str(&h.source),
json_str(&h.binary)
);
if let (Some(sv), Some(bv)) = (h.source_val, h.binary_val) {
let _ = write!(o, ",\"source_value\":{},\"binary_value\":{}", hex(sv), hex(bv));
}
o.push('}');
}
o.push_str("]}");
}
o.push_str(",\"lets\":[");
for (i, l) in pr.lets().iter().enumerate() {
let _ = write!(
o,
"{}{{\"name\":{},\"text\":{},\"node\":{}",
if i > 0 { "," } else { "" },
json_str(&l.name),
json_str(&l.text),
l.node
);
if let Some(v) = l.value {
let _ = write!(o, ",\"value\":{}", hex(v));
}
o.push('}');
}
o.push(']');
if self.has_model {
o.push_str(",\"counterexample\":{\"inputs\":[");
for (i, inp) in self.inputs.iter().enumerate() {
let _ = write!(
o,
"{}{{\"name\":{},\"symbol\":{},\"value\":{},\"width\":{}}}",
if i > 0 { "," } else { "" },
json_str(&inp.label),
json_str(&inp.name),
hex(inp.value),
inp.width
);
}
o.push_str("],\"memory\":[");
for (i, (m, a, bytes)) in self.memory.iter().enumerate() {
let list: Vec<String> = bytes.iter().map(|b| b.to_string()).collect();
let _ = write!(
o,
"{}{{\"snapshot\":{m},\"address\":{a},\"bytes\":[{}]",
if i > 0 { "," } else { "" },
list.join(",")
);
if let Some(s) = names.locate(*a) {
let _ = write!(o, ",\"symbol\":{}", json_str(&s));
}
o.push('}');
}
o.push_str("]}");
}
let _ = write!(o, ",\"nodes\":{}}}", self.dag.json(&roots, names));
o
}
}
impl PathDump {
fn roots(&self) -> Vec<u32> {
let mut r: Vec<u32> = self
.conds
.iter()
.filter(|d| d.side != Side::Pre)
.map(|d| d.cond)
.collect();
for s in self.source.iter().chain(&self.binary) {
for e in &s.effects {
match e {
Effect::Write { addr, val, .. } | Effect::Volatile { addr, val, .. } => r.extend([*addr, *val]),
Effect::Call { args, ret, .. } => {
r.extend(args.iter().copied());
r.extend(*ret);
}
Effect::Return(v) => r.extend(v.iter().map(|x| x.1)),
Effect::NoReturn => {}
}
}
}
r
}
pub fn text(&self, names: &Names, style: Style, index: usize, total: usize) -> String {
let pr = Printer::new(&self.dag, names, &self.roots(), style);
let mut o = String::new();
let _ = writeln!(o, " path {index} of {total}: {}", self.outcome);
let conds: Vec<&Decision> = self.conds.iter().filter(|d| d.side != Side::Pre).collect();
if conds.is_empty() {
let _ = writeln!(o, " when: always");
}
let texts: Vec<String> = conds.iter().map(|d| pr.expr(d.cond)).collect();
let w = texts.iter().map(|t| t.chars().count()).max().unwrap_or(0).min(48);
for (i, (d, t)) in conds.iter().zip(&texts).enumerate() {
let _ = writeln!(
o,
" {} {} [{}]",
if i == 0 { "when: " } else { " and:" },
pad(t, w),
decision_origin(d, names)
);
}
if !self.assumptions.is_empty() && style.full {
for &a in &self.assumptions {
let _ = writeln!(o, " assuming (no undefined behaviour): {}", pr.expr(a));
}
}
for (label, side) in [("source", &self.source), ("binary", &self.binary)] {
let Some(s) = side else { continue };
let _ = writeln!(o, " {label}: {}", s.trace);
for e in &s.effects {
match e {
Effect::Write { addr, size, val } => {
let _ = writeln!(
o,
" store {} \u{2190} {}",
pr.lvalue(*addr, *size),
pr.expr(*val)
);
}
Effect::Volatile { write, addr, size, val } => {
if *write {
let _ = writeln!(
o,
" volatile write {} \u{2190} {}",
pr.lvalue(*addr, *size),
pr.expr(*val)
);
} else {
let _ = writeln!(
o,
" volatile read {} \u{2192} {}",
pr.lvalue(*addr, *size),
pr.expr(*val)
);
}
}
Effect::Call { index, name, args, ret } => {
let list: Vec<String> = if label == "binary" {
args.iter()
.enumerate()
.map(|(i, &a)| format!("r{i} = {}", pr.expr(a)))
.collect()
} else {
args.iter().map(|&a| pr.expr(a)).collect()
};
let r = match ret {
Some(r) => format!(" \u{2192} {}", pr.expr(*r)),
None => String::new(),
};
let _ = writeln!(o, " call #{index} {name}({}){r}", list.join(", "));
}
Effect::Return(v) => {
let list: Vec<String> = v
.iter()
.map(|(l, t)| {
if l == "return" {
pr.expr(*t)
} else {
format!("{l} = {}", pr.expr(*t))
}
})
.collect();
let _ = writeln!(o, " {}", format!("return {}", list.join(", ")).trim_end());
}
Effect::NoReturn => {
let _ = writeln!(o, " (does not return on this path)");
}
}
}
}
let lets = used_lets(pr.lets(), &o);
if !lets.is_empty() {
let _ = writeln!(o, " where:");
for l in &lets {
let _ = writeln!(o, " {} = {}", l.name, l.text);
}
}
o
}
}
impl FuncDetail {
pub fn dump_text(&self, names: &Names, style: Style) -> String {
let mut o = String::new();
let total = self.paths.len() + self.skipped_paths;
for (i, p) in self.paths.iter().enumerate() {
o.push_str(&p.text(names, style, i + 1, total));
}
if self.skipped_paths > 0 {
let _ = writeln!(
o,
" ... {} more paths not shown (--full shows every path)",
self.skipped_paths
);
}
o
}
}