pub mod aarch64;
mod arm32;
mod convention;
pub use arm32::disassembly as arm32_disassembly;
pub use arm32::fold_literals;
pub use arm32::literal as arm32_literal;
pub use arm32::position_independent_instruction as arm32_position_independent_instruction;
#[cfg(test)]
mod atomic_tests;
mod build;
mod calls;
mod carry;
mod constants;
pub mod execution;
mod exits;
mod flags;
#[cfg(test)]
mod hardware;
mod machine;
pub mod mips32;
pub mod pairs32;
pub mod riscv64;
mod scan;
pub use scan::scan;
mod stack_results;
mod windows;
mod x86_64;
use build::lift_continuing;
use calls::tail_call;
pub(crate) use calls::{
arguments, call, call_through, call_through_as, import_called, pointer_target,
};
use carry::flag_predecessors;
#[cfg(test)]
use carry::{Carried, Exit, carry_flags, carry_zero, condition_values};
pub(crate) use exits::stack_heights;
#[cfg(test)]
use machine::recover_operand;
use machine::{Decoded, Emitter, Machine, Write};
pub(crate) use stack_results::stack_results;
use stack_results::take_stack_results;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use vlk_base::error::LiftError;
use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Expr, RegRef, Stmt};
use vlk_loader::loader::{Image, Summary};
use vlk_program::program::Program;
pub use convention::callee_cleanup;
pub use convention::convention_of;
#[derive(Clone, Copy, Debug)]
pub enum ReferenceKind {
Branch,
Memory,
LiteralPool,
IndirectControlFlow,
Address,
}
#[derive(Clone, Copy, Debug)]
pub struct Reference {
pub address: u64,
pub kind: ReferenceKind,
}
#[derive(Debug)]
pub struct RawInstruction {
pub addr: u64,
pub end: u64,
pub text: String,
pub reference: Option<Reference>,
}
pub fn load(path: &std::path::Path) -> vlk_base::error::Result<Image> {
load_with_arch(path, None)
}
pub fn load_with_arch(
path: &std::path::Path,
arch: Option<vlk_loader::loader::Architecture>,
) -> vlk_base::error::Result<Image> {
vlk_loader::loader::load(path, arch, None, &scan, |_| false)
}
pub type Summaries<'a> = &'a dyn Fn(u64) -> Summary;
pub fn lift(
program: &Program,
addr: u64,
size: u64,
extra_targets: &HashSet<u64>,
) -> Result<Vec<Block>, LiftError> {
let summaries = |target| crate::analysis::summary(program, target);
if extra_targets.is_empty() {
return lift_shared(program, addr, size, &summaries).map(Arc::unwrap_or_clone);
}
lift_with(program, addr, size, extra_targets, &summaries)
}
pub fn lift_shared(
program: &Program,
addr: u64,
size: u64,
summaries: Summaries<'_>,
) -> Result<Arc<Vec<Block>>, LiftError> {
lift_shared_with_targets(program, addr, size, &HashSet::new(), summaries)
}
#[expect(
clippy::rc_buffer,
reason = "Shared blocks retain Vec ownership so an unshared lift can be taken without cloning its blocks."
)]
pub(crate) fn lift_shared_with_targets(
program: &Program,
addr: u64,
size: u64,
extra_targets: &HashSet<u64>,
summaries: Summaries<'_>,
) -> Result<Arc<Vec<Block>>, LiftError> {
if let Some(found) = program
.lifts
.find(addr, size, extra_targets, |target, summary| {
call_summary(summaries(target)) == summary
})
{
return found;
}
let answers = std::cell::RefCell::new(Vec::new());
let blocks = lift_with(program, addr, size, extra_targets, &|target| {
let summary = summaries(target);
answers.borrow_mut().push((target, call_summary(summary)));
summary
})
.map(|mut blocks| {
for block in &mut blocks {
block.stmts.shrink_to_fit();
}
blocks.shrink_to_fit();
Arc::new(blocks)
});
let mut answers = answers.into_inner();
answers.sort_unstable_by_key(|(target, _)| *target);
answers.dedup_by_key(|(target, _)| *target);
let unknown = call_summary(Summary::default());
let without_summaries = answers.iter().all(|(_, answer)| *answer == unknown);
program.lifts.record(
addr,
size,
extra_targets,
answers,
without_summaries,
blocks,
)
}
pub(crate) fn call_summary(summary: Summary) -> Summary {
Summary {
promoted_parameters: None,
pointers: 0,
indirect_result: false,
narrow_return: false,
float_return: 0,
..summary
}
}
pub fn lift_with(
program: &Program,
addr: u64,
size: u64,
extra_targets: &HashSet<u64>,
summaries: Summaries<'_>,
) -> Result<Vec<Block>, LiftError> {
let image = &program.image;
let lifted = lift_unpaired(program, addr, size, extra_targets, summaries);
lifted.map(|mut blocks| {
if vlk_arch::arch::pointer_bytes(image.isa) == 4 {
for block in &mut blocks {
let mut statements = Vec::new();
for mut stmt in std::mem::take(&mut block.stmts) {
let target = match &stmt {
Stmt::Call { target, .. } => *target,
_ => None,
};
let pair = pairs32::call(program, target, &mut stmt);
let word_remainder = pairs32::word_remainder(image, target, &mut stmt);
let remainder = if (pair || word_remainder) && image.isa == Isa::Arm32 {
pairs32::remainder_arguments(image, target, &mut stmt)
} else {
None
};
let has_remainder = remainder.is_some();
if let Some(captures) = remainder {
statements.extend(captures);
}
statements.push(stmt);
if has_remainder {
statements.push(pairs32::remainder_value());
}
if pair {
statements
.extend(pairs32::split_result(image.isa, pairs32::high_first(image)));
}
if word_remainder {
statements.extend(pairs32::split_word_result());
} else if has_remainder {
statements.extend(pairs32::split_remainder());
}
}
block.stmts = statements;
}
}
drop_stack_probes(&mut blocks, image);
blocks
})
}
pub fn lift_for_execution(
program: &Program,
addr: u64,
size: u64,
targets: &HashSet<u64>,
) -> Result<Vec<Block>, LiftError> {
lift_in_mode(
program,
addr,
size,
targets,
&|_| Summary::default(),
execution::Mode::Execution,
)
}
pub(super) fn lift_unpaired(
program: &Program,
addr: u64,
size: u64,
extra_targets: &HashSet<u64>,
summaries: Summaries<'_>,
) -> Result<Vec<Block>, LiftError> {
lift_in_mode(
program,
addr,
size,
extra_targets,
summaries,
execution::Mode::Analysis,
)
}
fn lift_in_mode(
program: &Program,
addr: u64,
size: u64,
extra_targets: &HashSet<u64>,
summaries: Summaries<'_>,
mode: execution::Mode,
) -> Result<Vec<Block>, LiftError> {
let image = &program.image;
let addr = image.code_address(addr);
let Some(bytes) = image.read_vaddr(addr, size) else {
return Err(LiftError::Unreadable);
};
lift_bytes(program, addr, bytes, extra_targets, summaries, mode)
}
pub fn lift_written_for_execution(
program: &Program,
addr: u64,
bytes: &[u8],
) -> Result<Vec<Block>, LiftError> {
lift_bytes(
program,
addr,
bytes,
&HashSet::new(),
&|_| Summary::default(),
execution::Mode::Execution,
)
}
fn lift_bytes(
program: &Program,
addr: u64,
bytes: &[u8],
extra_targets: &HashSet<u64>,
summaries: Summaries<'_>,
mode: execution::Mode,
) -> Result<Vec<Block>, LiftError> {
let image = &program.image;
let summaries: Summaries<'_> = &|target| call_summary(summaries(target));
match image.isa {
Isa::Arm32 => match mode {
execution::Mode::Analysis => {
arm32::lift(program, addr, bytes, extra_targets, summaries)
}
execution::Mode::Execution => {
arm32::lift_in_mode(program, addr, bytes, extra_targets, summaries, mode)
}
},
Isa::AArch64 => {
let mut blocks = match lift_continuing(
program,
summaries,
|| execution::Located::new(aarch64::Lifter::new(image, addr), mode),
addr,
bytes,
&aarch64::decode,
extra_targets,
) {
Ok(blocks) => blocks,
Err(error) => return Err(error),
};
if mode == execution::Mode::Analysis {
aarch64::recover_atomic_loops(image, &mut blocks);
if image.go {
take_stack_results(&mut blocks, image, summaries);
}
}
Ok(blocks)
}
Isa::I386 | Isa::X86_64 => {
let mut blocks = match lift_continuing(
program,
summaries,
|| execution::Located::new(x86_64::Lifter::new(image), mode),
addr,
bytes,
&if image.isa == Isa::I386 {
x86_64::decode32
} else {
x86_64::decode
},
extra_targets,
) {
Ok(result) => result,
Err(error) => return Err(error),
};
if mode == execution::Mode::Execution {
return Ok(blocks);
}
let direction = blocks.iter().flat_map(|block| &block.stmts).any(|stmt| {
matches!(stmt, Stmt::Assign { dest, value, .. } if dest.index == x86_64::DIRECTION && *value != Expr::constant(0))
});
if !direction {
for stmt in blocks.iter_mut().flat_map(|block| &mut block.stmts) {
vlk_ir::ir::visit::replace_reads(
stmt,
&[(x86_64::DIRECTION, Expr::constant(0))],
);
}
for block in &mut blocks {
block.stmts.retain(|stmt| {
!matches!(stmt, Stmt::Assign { dest, .. } if dest.index == x86_64::DIRECTION)
});
}
}
if direction && let Some(entry) = blocks.first_mut() {
entry.stmts.insert(
0,
Stmt::Assign {
dest: RegRef {
index: x86_64::DIRECTION,
width: 64,
},
value: Expr::constant(0),
at: None,
},
);
}
if image.go {
take_stack_results(&mut blocks, image, summaries);
}
Ok(blocks)
}
Isa::RiscV64 => lift_continuing(
program,
summaries,
|| execution::Located::new(riscv64::Lifter::new(image), mode),
addr,
bytes,
&riscv64::decode,
extra_targets,
),
Isa::Mips32 => lift_continuing(
program,
summaries,
|| execution::Located::new(mips32::Lifter::new(image, addr), mode),
addr,
bytes,
if image.byte_order() == Some(object::Endianness::Big) {
&mips32::decode_big
} else {
&mips32::decode
},
extra_targets,
),
Isa::Unsupported => Err(LiftError::UnsupportedIsa),
}
}
fn drop_stack_probes(blocks: &mut [Block], image: &Image) {
if !matches!(
image.format,
vlk_base::target::Format::MachO | vlk_base::target::Format::Pe
) {
return;
}
let sp = vlk_arch::arch::stack_pointer(image.isa);
for block in blocks {
let mut slots: HashMap<u16, u64> = HashMap::new();
let mut addresses: HashMap<u16, u64> = HashMap::new();
let mut probes = Vec::new();
for (position, stmt) in block.stmts.iter().enumerate() {
let name = match stmt {
Stmt::Call {
through: Some(Expr::Reg { index, width: 64 }),
..
} => slots
.get(index)
.filter(|slot| {
image
.import_addends
.get(slot)
.is_none_or(|addend| *addend == 0)
})
.and_then(|slot| image.imports.get(slot))
.map(String::as_str),
Stmt::Call {
through: Some(through),
..
} => vlk_prototypes::prototypes::import_name(image, through),
Stmt::Call {
target: Some(target),
through: None,
..
} => image
.functions
.get(target)
.filter(|function| {
function
.sources
.contains(&vlk_loader::loader::NameSource::Plt)
})
.and_then(|function| function.name.as_deref()),
_ => None,
};
let probe = match image.format {
vlk_base::target::Format::MachO => match image.isa {
Isa::X86_64 => name == Some("____chkstk_darwin"),
Isa::AArch64 => name == Some("___chkstk_darwin"),
Isa::Arm32 | Isa::I386 | Isa::RiscV64 | Isa::Mips32 | Isa::Unsupported => false,
},
vlk_base::target::Format::Pe if image.isa == vlk_base::target::Isa::X86_64 => {
name == Some("__chkstk")
}
_ => false,
};
if probe {
probes.push(position);
}
let mut slot = None;
let mut address = None;
if let Stmt::Assign { dest, value, .. } = stmt
&& dest.width == 64
{
match value {
Expr::Load { addr, width: 8, .. } => {
slot = known_address(addr, &addresses)
.filter(|slot| image.imports.contains_key(slot))
.map(|slot| (dest.index, slot));
}
value => {
address = known_address(value, &addresses).map(|value| (dest.index, value));
}
}
}
for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
slots.remove(®ister);
addresses.remove(®ister);
}
if let Some((register, slot)) = slot {
slots.insert(register, slot);
}
if let Some((register, value)) = address {
addresses.insert(register, value);
}
}
let mut dropped = Vec::new();
for position in probes {
dropped.push(position);
if image.isa == Isa::AArch64
&& let Some(restore) = link_restore(&block.stmts, position, sp)
&& let Some(save) = link_save(&block.stmts, position, sp)
{
dropped.push(restore);
dropped.push(save);
}
}
dropped.sort_unstable();
dropped.dedup();
for position in dropped.into_iter().rev() {
if image.format == vlk_base::target::Format::Pe {
block.stmts.splice(
position..=position,
[10, 11].map(|index| Stmt::Assign {
dest: vlk_ir::ir::RegRef { index, width: 64 },
value: Expr::apply(vlk_ir::ir::Operation::Undefined, Vec::new()),
at: None,
}),
);
} else {
block.stmts.remove(position);
}
}
}
}
const LINK_REGISTER: u16 = 30;
fn link_restore(stmts: &[Stmt], call: usize, sp: u16) -> Option<usize> {
let position = call.checked_add(1)?;
match stmts.get(position)? {
Stmt::Assign {
dest,
value: Expr::Load { addr, width: 8, .. },
..
} if dest.index == LINK_REGISTER
&& matches!(addr.as_ref(), Expr::Reg { index, width: 64 } if *index == sp) =>
{
Some(position)
}
_ => None,
}
}
fn link_save(stmts: &[Stmt], call: usize, sp: u16) -> Option<usize> {
let position = stmts[..call].iter().rposition(|stmt| {
matches!(stmt, Stmt::Store { value: Expr::Reg { index, width: 64 }, width: 8, .. }
if *index == LINK_REGISTER)
})?;
let Stmt::Store { addr, .. } = &stmts[position] else {
return None;
};
let from_sp = match addr {
Expr::Reg { index, width: 64 } => *index == sp,
Expr::Bin { lhs, rhs, .. } => {
matches!(lhs.as_ref(), Expr::Reg { index, width: 64 } if *index == sp)
&& matches!(rhs.as_ref(), Expr::Const(_))
}
_ => false,
};
from_sp.then_some(position)
}
fn known_address(expr: &Expr, addresses: &HashMap<u16, u64>) -> Option<u64> {
match expr {
Expr::Const(value) => Some(*value),
Expr::Reg { index, width: 64 } => addresses.get(index).copied(),
Expr::Bin {
op: vlk_ir::ir::BinOp::Add,
lhs,
rhs,
} => match (known_address(lhs, addresses), known_address(rhs, addresses)) {
(Some(lhs), Some(rhs)) => Some(lhs.wrapping_add(rhs)),
_ => None,
},
_ => None,
}
}
#[cfg(test)]
mod smt_tests;
fn rotate(value: Expr, amount: Expr, width: u8, right: bool) -> Expr {
use vlk_ir::ir::BinOp;
let bits = u64::from(width);
let (amount, back) = match amount {
Expr::Const(amount) => match amount % bits {
0 => return value,
amount => (Expr::constant(amount), Expr::constant(bits - amount)),
},
amount => {
let amount = Expr::bin(BinOp::And, amount, Expr::constant(bits - 1));
let back = Expr::bin(
BinOp::And,
Expr::bin(BinOp::Sub, Expr::constant(bits), amount.clone()),
Expr::constant(bits - 1),
);
(amount, back)
}
};
let (towards, from) = if right {
(BinOp::Shr, BinOp::Shl)
} else {
(BinOp::Shl, BinOp::Shr)
};
Expr::bin(
BinOp::Or,
Expr::bin(towards, value.clone(), amount),
Expr::bin(from, value, back),
)
}
fn reverse_bytes(value: Expr, width: u8, chunk: u8) -> Expr {
use vlk_ir::ir::BinOp;
let bytes = width / 8;
(0..bytes)
.map(|byte| {
let start = byte - byte % chunk;
let target = start + (chunk - 1 - byte % chunk);
let field = Expr::bin(
BinOp::And,
Expr::bin(
BinOp::Shr,
value.clone(),
Expr::constant(8 * u64::from(byte)),
),
Expr::constant(0xff),
);
Expr::bin(BinOp::Shl, field, Expr::constant(8 * u64::from(target)))
})
.reduce(|all, field| Expr::bin(BinOp::Or, all, field))
.unwrap_or(value)
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod i386_tests;