use std::collections::{BTreeMap, BTreeSet};
use crate::cfg::{Block, FunctionId, Program};
use binbun_loader::{
Catch, CxxTable, FrameHandler, FuncletKind, HandlerTable, Image, Machine, Scope, ScopeAction,
SehFilter,
};
use binbun_semantics::RegisterId;
use binbun_semantics::ir::Binary;
use binbun_ssa::ir::Definition;
use binbun_ssa::{FuncletReturn, Op, Resume, Terminator, Unwind, Value};
use binbun_x86_lift::X86;
use crate::lift::lift_function;
use crate::summary::Summaries;
use crate::target::Abi;
const HOME: i64 = 32;
const RETURNED: i64 = 8 - HOME;
#[derive(Clone, Debug, PartialEq, Eq)]
enum Step {
Except(u64),
Cleanup(u64),
Dispatch {
catches: Vec<u64>,
all: Option<u64>,
cleanup: Option<u64>,
},
}
#[derive(Clone, Debug)]
struct Registers {
rsp: RegisterId,
rax: RegisterId,
rcx: RegisterId,
rdx: RegisterId,
kept: Vec<RegisterId>,
}
#[derive(Clone, Debug)]
pub struct Funclets {
runtime: u64,
establisher: u64,
table: HandlerTable,
own: BTreeMap<u64, CxxTable>,
starts: Vec<u64>,
registers: Registers,
returns: Vec<(u64, u64, u64, FuncletReturn)>,
continuations: Vec<u64>,
parts: Vec<FunctionId>,
blocks: Vec<Block>,
}
impl Funclets {
pub fn of(image: &Image<'_>, program: &Program, function: FunctionId) -> Option<Self> {
if image.machine != Machine::X86_64 {
return None;
}
let f = program.functions.get(function)?;
let handler = image
.frame_handlers
.iter()
.find(|handler| handler.function == f.entry)?;
let runtime = handler.data;
let establisher = handler.establisher?;
let abi = Abi::of(image).ok()?;
let find = |name| X86.find(name);
let kept = (0..abi.declarations.registers.len())
.filter_map(|index| u16::try_from(index).ok().map(RegisterId))
.filter(|®ister| {
register != abi.stack_pointer && !abi.call.changes.contains(®ister)
})
.collect();
let mut model = Self {
runtime,
establisher,
table: handler.table.clone(),
own: BTreeMap::new(),
starts: vec![f.entry],
registers: Registers {
rsp: abi.stack_pointer,
rax: find("rax")?,
rcx: find("rcx")?,
rdx: find("rdx")?,
kept,
},
returns: Vec::new(),
continuations: Vec::new(),
parts: Vec::new(),
blocks: Vec::new(),
};
let roles = model.roles(image, program, handler)?;
for &address in roles.keys() {
model.starts.push(address);
if let Some(HandlerTable::Cxx(cxx)) = image
.frame_handlers
.iter()
.find(|handler| handler.function == address)
.map(|handler| &handler.table)
{
model.own.insert(address, cxx.clone());
}
}
model.starts.sort_unstable();
let mut covered: Vec<(u64, u64)> = Vec::new();
let own = blocks(program, function)?;
covered.extend(own.iter().map(|block| (block.start, block.end)));
let overlaps = |covered: &[(u64, u64)], block: &Block| {
covered
.iter()
.any(|&(start, end)| start < block.end && block.start < end)
};
for (address, resumed) in roles {
let part = program.function_at(address)?;
let code = blocks(program, part)?;
if code.iter().any(|block| overlaps(&covered, block)) {
return None;
}
for block in &code {
covered.push((block.start, block.end));
model
.returns
.push((block.start, block.end, address, resumed.clone()));
}
model.parts.push(part);
model.blocks.extend(code);
}
for &continuation in &model.continuations.clone() {
if covered
.iter()
.any(|&(start, end)| (start..end).contains(&continuation))
{
continue;
}
let part = program.function_at(continuation)?;
let code = blocks(program, part)?;
let code: Vec<Block> = code
.into_iter()
.filter(|block| !overlaps(&covered, block))
.collect();
if !code
.iter()
.any(|block| (block.start..block.end).contains(&continuation))
{
return None;
}
covered.extend(code.iter().map(|block| (block.start, block.end)));
model.parts.push(part);
model.blocks.extend(code);
}
Some(model)
}
fn roles(
&mut self,
image: &Image<'_>,
program: &Program,
handler: &FrameHandler,
) -> Option<BTreeMap<u64, FuncletReturn>> {
let mut roles: BTreeMap<u64, FuncletReturn> = BTreeMap::new();
let add = |roles: &mut BTreeMap<u64, FuncletReturn>, address, resumed| {
if let Some(known) = roles.get(&address) {
return *known == resumed;
}
roles.insert(address, resumed);
true
};
match &handler.table {
HandlerTable::Scopes(scopes) => {
for (index, scope) in scopes.iter().enumerate() {
let ScopeAction::Finally(funclet) = scope.action else {
continue;
};
let rest = Self::scope_chain(scopes.get(index + 1..)?, |other| {
other.start <= scope.start && scope.end <= other.end
});
let resumed = FuncletReturn::Resume(self.resume(&rest, RETURNED));
if !add(&mut roles, funclet, resumed) {
return None;
}
}
}
HandlerTable::Cxx(cxx) => {
for (state, entry) in cxx.unwind.iter().enumerate() {
let Some(funclet) = entry.action else {
continue;
};
let state = i32::try_from(state).ok()?;
let rest = Self::cxx_chain(cxx, entry.next, state);
let resumed = FuncletReturn::Resume(self.resume(&rest, RETURNED));
if !add(&mut roles, funclet, resumed) {
return None;
}
}
for catch in cxx.tries.iter().flat_map(|block| &block.catches) {
let targets = if catch.continuations.is_empty() {
continuations(image, program, catch.funclet, self.registers.rax)?
} else {
catch.continuations.clone()
};
self.continuations.extend(&targets);
let resumed = FuncletReturn::Continue {
register: self.registers.rax,
targets,
frames: vec![(
self.registers.rsp,
self.registers.rsp,
0i64.checked_sub_unsigned(self.establisher)?,
)],
};
if !add(&mut roles, catch.funclet, resumed) {
return None;
}
}
}
}
self.continuations.sort_unstable();
self.continuations.dedup();
let all = handler
.funclets()
.filter(|&(_, kind)| kind != FuncletKind::Filter)
.all(|(address, _)| roles.contains_key(&address));
all.then_some(roles)
}
fn scope_chain(scopes: &[Scope], holds: impl Fn(&Scope) -> bool) -> Vec<Step> {
scopes
.iter()
.filter(|scope| holds(scope))
.map(|scope| match scope.action {
ScopeAction::Except { target, .. } => Step::Except(target),
ScopeAction::Finally(funclet) => Step::Cleanup(funclet),
})
.collect()
}
fn cxx_chain(cxx: &CxxTable, mut state: i32, origin: i32) -> Vec<Step> {
let mut steps = Vec::new();
for _ in 0..=cxx.unwind.len() {
let Some(entry) = usize::try_from(state)
.ok()
.and_then(|index| cxx.unwind.get(index))
else {
break;
};
let mut catches: Vec<u64> = Vec::new();
let mut all = None;
for catch in cxx
.tries
.iter()
.filter(|block| block.low == state && block.low <= origin && origin <= block.high)
.flat_map(|block| &block.catches)
{
if catch_all(catch) {
all = Some(catch.funclet);
break;
}
catches.push(catch.funclet);
}
if all.is_some() {
steps.push(Step::Dispatch {
catches,
all,
cleanup: None,
});
break;
}
if !catches.is_empty() {
steps.push(Step::Dispatch {
catches,
all: None,
cleanup: entry.action,
});
} else if let Some(funclet) = entry.action {
steps.push(Step::Cleanup(funclet));
}
state = entry.next;
}
steps
}
fn chain(&self, ip: u64) -> Vec<Step> {
match &self.table {
HandlerTable::Scopes(scopes) => {
Self::scope_chain(scopes, |scope| scope.start <= ip && ip < scope.end)
}
HandlerTable::Cxx(cxx) => {
let part = self
.starts
.partition_point(|&start| start <= ip)
.checked_sub(1)
.and_then(|at| self.starts.get(at))
.copied()
.unwrap_or(0);
let cxx = self.own.get(&part).unwrap_or(cxx);
let at = cxx.states.partition_point(|range| range.start <= ip);
let state = at
.checked_sub(1)
.and_then(|at| cxx.states.get(at))
.filter(|range| range.start >= part)
.map_or(-1, |range| range.state);
Self::cxx_chain(cxx, state, state)
}
}
}
fn resume(&self, chain: &[Step], from: i64) -> Resume {
Resume {
runtime: self.runtime,
unwind: self.pad(chain, from).map(Box::new),
}
}
fn pad(&self, chain: &[Step], from: i64) -> Option<Unwind> {
let (first, rest) = chain.split_first()?;
let r = &self.registers;
let frames = vec![(r.rdx, r.rsp, 0i64.checked_sub_unsigned(self.establisher)?)];
let entry = -HOME - from;
Some(match first {
&Step::Except(target) => Unwind {
pad: target,
kept: r.kept.clone(),
stack: Some((r.rsp, 8 - from)),
receives: vec![r.rax],
..Unwind::default()
},
&Step::Cleanup(funclet) => Unwind {
pad: funclet,
kept: r.kept.clone(),
stack: Some((r.rsp, entry)),
receives: vec![r.rcx],
frames,
..Unwind::default()
},
Step::Dispatch {
catches,
all,
cleanup,
} => Unwind {
pad: all.or(*cleanup).or_else(|| catches.first().copied())?,
kept: r.kept.clone(),
stack: Some((r.rsp, entry)),
receives: vec![r.rcx, r.rax],
frames,
choices: (1..)
.zip(catches)
.map(|(selector, &funclet)| (selector, funclet))
.collect(),
resume: (all.is_none() && cleanup.is_none()).then(|| self.resume(rest, -HOME)),
},
})
}
pub fn unwind(&self, return_address: u64) -> Option<Unwind> {
self.pad(&self.chain(return_address.checked_sub(1)?), 0)
}
pub fn funclet_return(&self, site: u64) -> Option<(u64, FuncletReturn)> {
self.returns
.iter()
.find(|&&(start, end, _, _)| (start..end).contains(&site))
.map(|(_, _, entry, resumed)| (*entry, resumed.clone()))
}
pub fn entries(&self) -> Vec<(u64, Vec<RegisterId>)> {
let mut entries: Vec<u64> = self.returns.iter().map(|&(_, _, entry, _)| entry).collect();
entries.dedup();
entries
.into_iter()
.map(|entry| (entry, self.registers.kept.clone()))
.collect()
}
pub fn continuations(&self) -> &[u64] {
&self.continuations
}
pub fn parts(&self) -> &[FunctionId] {
&self.parts
}
pub fn blocks(&self) -> &[Block] {
&self.blocks
}
}
pub fn built_in(image: &Image<'_>, program: &Program) -> BTreeSet<u64> {
let mut entries = BTreeSet::new();
for handler in &image.frame_handlers {
let Some(function) = program.function_at(handler.function) else {
continue;
};
let Some(model) = Funclets::of(image, program, function) else {
continue;
};
entries.extend(
model
.parts()
.iter()
.filter_map(|&part| program.functions.get(part))
.map(|part| part.entry),
);
}
entries
}
pub fn named(image: &Image<'_>) -> BTreeSet<u64> {
let mut entries = BTreeSet::new();
for handler in &image.frame_handlers {
match &handler.table {
HandlerTable::Scopes(scopes) => {
entries.extend(scopes.iter().filter_map(|scope| match scope.action {
ScopeAction::Finally(funclet)
| ScopeAction::Except {
filter: SehFilter::Funclet(funclet),
..
} => Some(funclet),
ScopeAction::Except {
filter: SehFilter::Constant(_),
..
} => None,
}));
}
HandlerTable::Cxx(cxx) => {
entries.extend(cxx.unwind.iter().filter_map(|state| state.action));
entries.extend(
cxx.tries
.iter()
.flat_map(|t| &t.catches)
.map(|catch| catch.funclet),
);
}
}
}
entries
}
pub fn catch_all(catch: &Catch) -> bool {
catch.adjectives & 0x40 != 0 || catch.ty.is_none()
}
fn blocks(program: &Program, function: FunctionId) -> Option<Vec<Block>> {
let function = program.functions.get(function)?;
function
.blocks
.iter()
.map(|&id| program.blocks.get(id).copied())
.collect()
}
fn continuations(
image: &Image<'_>,
program: &Program,
funclet: u64,
rax: RegisterId,
) -> Option<Vec<u64>> {
let id = program.function_at(funclet)?;
let l1 = lift_function(image, program, id, &Summaries::new()).ok()?;
let mut targets = Vec::new();
for block in &l1.blocks {
if let Terminator::Return { state, .. } = &block.terminator {
let &value = state.registers.get(usize::from(rax.0))?;
targets.push(constant(&l1, value, 8)?);
}
}
targets.sort_unstable();
targets.dedup();
Some(targets)
}
fn constant(function: &binbun_ssa::Function, value: Value, depth: u32) -> Option<u64> {
let depth = depth.checked_sub(1)?;
let Definition::Result { inst, .. } = function.value(value)?.definition else {
return None;
};
let op = &function.inst(inst)?.op;
if let Op::Const(bits) = op {
return Some(bits.low_u64());
}
let &Op::Binary(binary, a, b) = op else {
return None;
};
let (a, b) = (constant(function, a, depth)?, constant(function, b, depth)?);
match binary {
Binary::Add => Some(a.wrapping_add(b)),
Binary::Sub => Some(a.wrapping_sub(b)),
Binary::Mul
| Binary::UDiv
| Binary::URem
| Binary::SDiv
| Binary::SRem
| Binary::And
| Binary::Or
| Binary::Xor
| Binary::Shl
| Binary::LShr
| Binary::AShr
| Binary::Rol
| Binary::Ror
| Binary::Eq
| Binary::Ne
| Binary::ULt
| Binary::ULe
| Binary::SLt
| Binary::SLe => None,
}
}