mod parts;
mod recover;
use std::collections::BTreeMap;
use binbun_isa::Target;
use binbun_semantics::core::{Arena, Id, Memory};
pub use recover::{Options, recover};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Id)]
pub struct BlockId(u32);
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Id)]
pub struct FunctionId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Returns {
Yes,
No,
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Callee {
Import(u64),
Address(u64),
}
pub trait Callees {
fn is_import(&self, slot: u64) -> bool;
fn slot(&self, slot: u64, size: u8) -> Option<u64> {
let _ = (slot, size);
None
}
fn returns(&self, callee: Callee) -> Returns;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NothingKnown;
impl Callees for NothingKnown {
fn is_import(&self, _: u64) -> bool {
false
}
fn returns(&self, _: Callee) -> Returns {
Returns::Unknown
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Table {
pub targets: Vec<u64>,
pub inferred: bool,
}
pub trait Resolver {
fn target(&mut self, entry: u64, blocks: &[Block], jump: Block) -> Option<Target> {
let _ = (entry, blocks, jump);
None
}
fn table(&mut self, entry: u64, blocks: &[Block], jump: Block) -> Option<Table>;
fn data(&mut self, address: u64) -> Option<u64> {
let _ = address;
None
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NoResolver;
impl Resolver for NoResolver {
fn table(&mut self, _: u64, _: &[Block], _: Block) -> Option<Table> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SeedKind {
Entry,
Symbol,
Export,
Unwind,
Call,
Pointer,
Reference,
User,
}
impl SeedKind {
const fn bit(self) -> u8 {
match self {
Self::Entry => 1,
Self::Symbol => 2,
Self::Unwind => 4,
Self::Call => 8,
Self::Pointer => 16,
Self::Reference => 32,
Self::Export => 64,
Self::User => 128,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Seed {
Function(u64, SeedKind),
Code {
function: u64,
address: u64,
},
Extent {
function: u64,
end: u64,
frame: Frame,
},
Split {
start: u64,
end: u64,
owner: Option<u64>,
},
Unwind {
start: u64,
end: u64,
pad: u64,
},
Funclet {
function: u64,
address: u64,
},
Flow(u64),
NotCode {
start: u64,
end: u64,
},
End {
function: u64,
end: u64,
},
NoFunction(u64),
}
impl Seed {
const fn pointer(&self) -> Option<u64> {
match *self {
Self::Function(address, SeedKind::Pointer) => Some(address),
Self::Function(..)
| Self::Code { .. }
| Self::Extent { .. }
| Self::Split { .. }
| Self::Unwind { .. }
| Self::Funclet { .. }
| Self::Flow(_)
| Self::NotCode { .. }
| Self::End { .. }
| Self::NoFunction(_) => None,
}
}
pub const fn address(&self) -> u64 {
match *self {
Self::Function(address, _)
| Self::Code { address, .. }
| Self::Extent {
function: address, ..
}
| Self::Split { start: address, .. }
| Self::Unwind { start: address, .. }
| Self::Funclet { address, .. }
| Self::Flow(address)
| Self::NotCode { start: address, .. }
| Self::End {
function: address, ..
}
| Self::NoFunction(address) => address,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Frame {
Call,
Inside,
Outermost,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct SeedKinds(u8);
impl SeedKinds {
pub const fn contains(self, kind: SeedKind) -> bool {
self.0 & kind.bit() != 0
}
pub const fn insert(&mut self, kind: SeedKind) {
self.0 |= kind.bit();
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Destination {
Address(u64),
Import(u64),
Pointer(u64),
Indirect,
Far,
}
impl Destination {
pub const fn is_unresolved(self) -> bool {
matches!(self, Self::Pointer(_) | Self::Indirect | Self::Far)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Exit {
Next,
Jump(Destination),
Branch(Destination),
Call {
callee: Destination,
returns: Returns,
},
Return,
Stop,
Invalid,
Limit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Block {
pub start: u64,
pub end: u64,
pub instructions: u32,
pub exit: Exit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EdgeKind {
Next,
Jump,
Taken,
NotTaken,
CallReturn,
Table,
Unwind,
}
fn static_successors(block: Block) -> impl Iterator<Item = (EdgeKind, u64)> {
let (first, second) = match block.exit {
Exit::Next => (Some((EdgeKind::Next, block.end)), None),
Exit::Jump(Destination::Address(target)) => (Some((EdgeKind::Jump, target)), None),
Exit::Branch(Destination::Address(target)) => (
Some((EdgeKind::Taken, target)),
Some((EdgeKind::NotTaken, block.end)),
),
Exit::Branch(_) => (Some((EdgeKind::NotTaken, block.end)), None),
Exit::Call {
returns: Returns::Yes | Returns::Unknown,
..
} => (Some((EdgeKind::CallReturn, block.end)), None),
Exit::Jump(_)
| Exit::Call {
returns: Returns::No,
..
}
| Exit::Return
| Exit::Stop
| Exit::Invalid
| Exit::Limit => (None, None),
};
first.into_iter().chain(second)
}
pub(crate) type Unwind = BTreeMap<u64, (u64, u64)>;
fn landing_pad(unwind: &Unwind, return_address: u64) -> Option<u64> {
let at = return_address.checked_sub(1)?;
let (_, &(end, pad)) = unwind.range(..=at).next_back()?;
(at < end).then_some(pad)
}
fn unwind_successor(unwind: &Unwind, block: Block) -> Option<(EdgeKind, u64)> {
match block.exit {
Exit::Call { .. } => landing_pad(unwind, block.end).map(|pad| (EdgeKind::Unwind, pad)),
Exit::Next
| Exit::Jump(_)
| Exit::Branch(_)
| Exit::Return
| Exit::Stop
| Exit::Invalid
| Exit::Limit => None,
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Function {
pub entry: u64,
pub seeds: SeedKinds,
pub blocks: Vec<BlockId>,
pub returns: bool,
pub parts: Vec<u64>,
pub landing_pads: Vec<u64>,
pub part_of: Option<u64>,
pub funclets: Vec<u64>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Conflict {
pub instruction: u64,
pub block: u64,
}
#[derive(Clone, Debug, Default)]
pub struct Program {
pub blocks: Arena<BlockId, Block>,
pub functions: Arena<FunctionId, Function>,
pub conflicts: Vec<Conflict>,
by_start: BTreeMap<u64, BlockId>,
by_entry: BTreeMap<u64, FunctionId>,
tables: BTreeMap<BlockId, Table>,
unwind: Unwind,
data: BTreeMap<u64, u64>,
}
impl Program {
pub fn data(&self) -> &BTreeMap<u64, u64> {
&self.data
}
pub fn block_at(&self, address: u64) -> Option<BlockId> {
self.by_start.get(&address).copied()
}
pub fn block_containing(&self, address: u64) -> Option<BlockId> {
let (_, &id) = self.by_start.range(..=address).next_back()?;
self.blocks.get(id).filter(|b| address < b.end).map(|_| id)
}
pub fn function_at(&self, address: u64) -> Option<FunctionId> {
self.by_entry.get(&address).copied()
}
pub fn blocks_by_address(&self) -> impl Iterator<Item = (u64, BlockId)> + '_ {
self.by_start.iter().map(|(&start, &id)| (start, id))
}
pub fn table(&self, block: BlockId) -> Option<&Table> {
self.tables.get(&block)
}
pub fn successors(&self, block: BlockId) -> impl Iterator<Item = (EdgeKind, u64)> + '_ {
let table = self
.table(block)
.into_iter()
.flat_map(|table| &table.targets)
.map(|&target| (EdgeKind::Table, target));
let block = self.blocks.get(block).copied();
let unwind = block.and_then(|block| unwind_successor(&self.unwind, block));
block
.into_iter()
.flat_map(static_successors)
.chain(table)
.chain(unwind)
}
pub fn landing_pad(&self, return_address: u64) -> Option<u64> {
landing_pad(&self.unwind, return_address)
}
pub fn unresolved(&self) -> impl Iterator<Item = (BlockId, Destination)> + '_ {
self.blocks
.iter()
.filter_map(|(id, block)| match block.exit {
Exit::Jump(destination)
| Exit::Branch(destination)
| Exit::Call {
callee: destination,
..
} if destination.is_unresolved() && !self.tables.contains_key(&id) => {
Some((id, destination))
}
Exit::Jump(_)
| Exit::Branch(_)
| Exit::Call { .. }
| Exit::Next
| Exit::Return
| Exit::Stop
| Exit::Invalid
| Exit::Limit => None,
})
}
}
fn program(
blocks: Arena<BlockId, Block>,
by_start: BTreeMap<u64, BlockId>,
functions: Arena<FunctionId, Function>,
conflicts: Vec<Conflict>,
tables: BTreeMap<BlockId, Table>,
unwind: Unwind,
data: BTreeMap<u64, u64>,
) -> Program {
let by_entry = functions.iter().map(|(id, f)| (f.entry, id)).collect();
Program {
blocks,
functions,
conflicts,
by_start,
by_entry,
tables,
unwind,
data,
}
}
pub fn recover_function<A: binbun_isa::Architecture, M: Memory>(
architecture: &A,
mode: A::Mode,
memory: &M,
entry: u64,
callees: &impl Callees,
resolver: &mut dyn Resolver,
) -> Program {
let options = Options {
follow_calls: false,
..Options::default()
};
recover(
architecture,
mode,
memory,
&[Seed::Function(entry, SeedKind::Symbol)],
callees,
resolver,
&options,
)
}