use std::sync::{Arc, LazyLock};
use binbun_loader::{Image, Machine};
use binbun_semantics::ir::SiteId;
use binbun_semantics::rule::Rule;
use binbun_ssa::ir::{Function, Op, Unknown};
use binbun_x86_lift::profiles;
pub use binbun_semantics::profile::{Choice, Choices, Measured, Profile};
static EMBEDDED: LazyLock<Vec<Arc<Profile>>> =
LazyLock::new(|| profiles::embedded().into_iter().map(Arc::new).collect());
pub fn embedded() -> &'static [Arc<Profile>] {
&EMBEDDED
}
pub fn resolve(name: &str) -> Result<Arc<Profile>, String> {
if let Some(profile) = embedded().iter().find(|profile| profile.id == name) {
return Ok(Arc::clone(profile));
}
profiles::resolve(name).map(Arc::new)
}
pub fn fits(profile: &Profile, image: &Image<'_>) -> Result<(), String> {
if image.machine == Machine::X86_64 {
Ok(())
} else {
Err(format!(
"{} describes an x86-64 processor; the image is {:?}",
profile.id, image.machine
))
}
}
pub fn label(profile: Option<&Profile>) -> String {
profile.map_or_else(|| "architecture (any processor)".to_owned(), Profile::label)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Agreement {
Agree,
Differ,
Unknown,
}
pub fn agreement(site: SiteId) -> Agreement {
let rules: Option<Vec<&str>> = embedded()
.iter()
.map(|profile| profile.rule(site).map(Rule::text))
.collect();
match rules {
None => Agreement::Unknown,
Some(rules) if rules.windows(2).all(|pair| pair.first() == pair.last()) => Agreement::Agree,
Some(_) => Agreement::Differ,
}
}
pub fn sites(l1: &Function) -> Vec<(u64, SiteId)> {
let mut sites: Vec<(u64, SiteId)> = l1
.insts
.iter()
.filter_map(|inst| {
if let Op::Undefined(
Unknown::Architecture {
address,
site: Some(site),
..
},
_,
) = &inst.op
{
Some((*address, *site))
} else {
None
}
})
.collect();
sites.sort_unstable();
sites.dedup();
sites
}