use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub use binbun_decompile::validate::{Decider, Output, Stored};
use binbun_decompile::validate::{
Differing as Found, OnProcessor, Oracle, State, compare_processors, random_states,
shaped_states,
};
use binbun_semantics::Declarations;
use binbun_semantics::ir::SiteId;
use super::verify::{SHAPED, STATES};
use super::{Lowered, lower, lower_prepared};
use crate::Database;
use crate::cfg::FunctionId;
use crate::decompile::{Interfaces, Prepared, View, stream_parallel};
use crate::memory::ImageOracle;
use crate::profile::{Choice, Profile, embedded, fits};
use crate::run::state::{Region, RegisterValue, format_value};
use crate::run::{ExampleState, Fill};
use crate::target::setup;
pub const KEPT: usize = 4;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
pub profiles: Vec<Arc<Profile>>,
pub states: usize,
pub shaped: usize,
pub seed: Option<u64>,
pub fuel: Option<u64>,
}
impl Default for Options {
fn default() -> Self {
Self {
profiles: embedded().to_vec(),
states: STATES,
shaped: SHAPED,
seed: None,
fuel: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Differing {
pub index: usize,
pub state: State,
pub example: ExampleState,
pub what: String,
pub outputs: Vec<Output>,
pub stored: Option<Stored>,
pub decider: Option<Decider>,
pub rules: Vec<String>,
pub way: usize,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Same,
NotReached,
Differs(Vec<Differing>),
NotCheckable(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comparison {
pub entry: u64,
pub profiles: Vec<String>,
pub seed: u64,
pub states: usize,
pub same: usize,
pub skipped: usize,
pub reaching: usize,
pub reached: BTreeMap<SiteId, usize>,
pub ways: Vec<usize>,
pub verdict: Verdict,
}
impl Comparison {
fn not_checkable(entry: u64, options: &Options, why: String) -> Self {
Self {
entry,
profiles: options.profiles.iter().map(|p| p.label()).collect(),
seed: options.seed.unwrap_or(entry),
states: 0,
same: 0,
skipped: 0,
reaching: 0,
reached: BTreeMap::new(),
ways: Vec::new(),
verdict: Verdict::NotCheckable(why),
}
}
}
pub fn compare(database: &Database<'_>, id: FunctionId, options: &Options) -> Comparison {
let never = AtomicBool::new(false);
let entry = database.function(id).map_or(0, |function| function.entry);
compare_cancellable(database, id, options, &never)
.unwrap_or_else(|| Comparison::not_checkable(entry, options, String::new()))
}
pub fn compare_cancellable(
database: &Database<'_>,
id: FunctionId,
options: &Options,
cancel: &AtomicBool,
) -> Option<Comparison> {
let entry = database.function(id).map_or(0, |function| function.entry);
match lower(database, id, View::Exact, &[]) {
Ok((lowered, _)) => compare_lowered(database, &lowered, options, cancel),
Err(why) => Some(Comparison::not_checkable(entry, options, why)),
}
}
pub fn compare_all(
database: &Database<'_>,
options: &Options,
threads: usize,
ready: impl FnMut(Comparison),
) {
let callers = database.callers(&[]);
stream_parallel(
database.image(),
database.program(),
database.summaries(),
&callers,
&[],
threads,
|id, prepared, interfaces| compare_prepared(database, id, prepared, interfaces, options),
ready,
);
}
fn compare_prepared(
database: &Database<'_>,
id: FunctionId,
prepared: Result<Prepared, String>,
interfaces: &Interfaces,
options: &Options,
) -> Comparison {
let entry = database.function(id).map_or(0, |function| function.entry);
let never = AtomicBool::new(false);
match prepared
.and_then(|prepared| lower_prepared(database, prepared, interfaces, View::Exact, &[]))
{
Ok(lowered) => compare_lowered(database, &lowered, options, &never)
.unwrap_or_else(|| Comparison::not_checkable(entry, options, String::new())),
Err(why) => Comparison::not_checkable(entry, options, why),
}
}
fn compare_lowered(
database: &Database<'_>,
lowered: &Lowered,
options: &Options,
cancel: &AtomicBool,
) -> Option<Comparison> {
let entry = lowered.entry;
let failed = |why: String| Some(Comparison::not_checkable(entry, options, why));
if options.profiles.len() < 2 {
return failed("two processors or more are compared".to_owned());
}
let image = database.image();
for profile in &options.profiles {
if let Err(why) = fits(profile, image) {
return failed(why);
}
}
let mut setup = match setup(image, entry) {
Ok(setup) => setup,
Err(why) => return failed(why),
};
setup.fuel = options.fuel.unwrap_or(setup.fuel);
let seed = options.seed.unwrap_or(entry);
let mut states = random_states(&setup, options.states, seed);
states.extend(shaped_states(
&setup,
&lowered.l2,
&lowered.mapping,
options.shaped,
seed,
));
let memory = ImageOracle::new(image);
let processors: Vec<OnProcessor<'_>> = options
.profiles
.iter()
.map(|profile| OnProcessor {
oracle: &memory,
profile,
})
.collect();
let oracles: Vec<&dyn Oracle> = processors.iter().map(|p| p as &dyn Oracle).collect();
let found = compare_processors(
&lowered.prepared.l1,
&lowered.l2,
&lowered.mapping,
&setup,
&oracles,
&states,
cancel,
)?;
if cancel.load(Ordering::Relaxed) {
return None;
}
let (ways, way_of) = ways(&found.differing);
let kept = kept(&way_of, ways.len());
let differing: Vec<Differing> = found
.differing
.into_iter()
.zip(way_of)
.enumerate()
.filter(|(position, _)| kept.contains(position))
.filter_map(|(_, (differing, way))| {
let state = states.get(differing.state)?.clone();
let name = format!("differs-{}", differing.state);
let example = example_state(setup.declarations, &state, &name, database.name(entry));
Some(kept_state(
differing,
state,
example,
way,
&options.profiles,
))
})
.collect();
let verdict = if !differing.is_empty() {
Verdict::Differs(differing)
} else if found.reaching == 0 {
Verdict::NotReached
} else if found.same == 0 {
Verdict::NotCheckable(format!(
"{} states reached a site, none compared ({} skipped)",
found.reaching, found.skipped
))
} else {
Verdict::Same
};
Some(Comparison {
entry,
profiles: options.profiles.iter().map(|p| p.label()).collect(),
seed,
states: found.runs,
same: found.same,
skipped: found.skipped,
reaching: found.reaching,
reached: found.reached,
ways,
verdict,
})
}
pub fn example_state(
declarations: &Declarations,
state: &State,
name: &str,
function: Option<&str>,
) -> ExampleState {
let registers = declarations
.registers
.iter()
.zip(&state.registers)
.filter(|(_, value)| value.is_defined())
.map(|(info, value)| RegisterValue {
name: info.name.to_owned(),
value: format_value(value),
})
.collect();
let regions = state
.memory
.iter()
.map(|(start, bytes)| Region {
address: format!("{start:#x}"),
bytes: Some(bytes.iter().fold(String::new(), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})),
..Region::default()
})
.collect();
ExampleState {
function: function.map(str::to_owned),
fill: Fill::Hashed,
registers,
regions,
..ExampleState::scratch(name)
}
}
fn kept_state(
found: Found,
state: State,
example: ExampleState,
way: usize,
profiles: &[Arc<Profile>],
) -> Differing {
let rules = found
.decider
.as_ref()
.map_or_else(Vec::new, |decider| rules(profiles, decider.site));
Differing {
index: found.state,
state,
example,
what: found.what,
outputs: found.outputs,
stored: found.stored,
decider: found.decider,
rules,
way,
}
}
fn rules(profiles: &[Arc<Profile>], site: SiteId) -> Vec<String> {
profiles
.iter()
.map(|profile| {
profile
.choice(site)
.map_or("unknown", Choice::text)
.to_owned()
})
.collect()
}
fn ways(differing: &[Found]) -> (Vec<usize>, Vec<usize>) {
let mut keys: Vec<(&str, Option<&Decider>)> = Vec::new();
let mut ways: Vec<usize> = Vec::new();
let mut way_of: Vec<usize> = Vec::with_capacity(differing.len());
for state in differing {
let key = (state.what.as_str(), state.decider.as_ref());
let way = keys.iter().position(|k| *k == key).unwrap_or_else(|| {
keys.push(key);
ways.push(0);
keys.len() - 1
});
if let Some(count) = ways.get_mut(way) {
*count += 1;
}
way_of.push(way);
}
(ways, way_of)
}
fn kept(way_of: &[usize], ways: usize) -> Vec<usize> {
let mut kept: Vec<usize> = (0..ways)
.take(KEPT)
.filter_map(|way| way_of.iter().position(|&w| w == way))
.collect();
for position in 0..way_of.len() {
if kept.len() >= KEPT {
break;
}
if !kept.contains(&position) {
kept.push(position);
}
}
kept.sort_unstable();
kept
}