use std::collections::HashSet;
use vlk_base::error::LiftError;
use vlk_base::target::Isa;
use vlk_ir::ir::{Block, Expr, FunctionIr, Operation, Stmt};
use vlk_loader::loader::{Function, Image, NameSource};
use vlk_program::program::Program;
use vlk_types::types::{
AbiLocation, CType, Convention, Passing, Precision, SignatureAbi, StackParam, Structure,
ValueAbi,
};
use super::dead_code::drop_unreached;
use super::exceptions::{exception_starts, receive_exceptions};
use super::float_result::{float_result_of, float_return_slot};
use super::go_entry::{drop_stack_growth_check, initialize_go_registers};
use super::mips_calls::keep_registers_read_after_calls;
use super::{UNKNOWN_SIZE, abi, go_types, indirect, jump_table, results, signature, summary};
use crate::lift;
pub(super) struct Lifted {
pub(super) ir: FunctionIr,
pub(super) has_jump_tables: bool,
pub(super) types: Option<vlk_loader::loader::dwarf::FunctionTypes>,
}
pub fn absorb_jump_table_cases(program: &mut Program) {
for _ in 0..4 {
let functions: Vec<_> = program
.image
.functions
.values()
.filter(|function| {
function
.sources
.contains(&vlk_loader::loader::NameSource::Prologue)
})
.collect();
let found = vlk_base::parallel::map(&functions, |function| {
let mut cases = HashSet::new();
let size = function.size.unwrap_or(UNKNOWN_SIZE);
let Ok(blocks) =
lift::lift_with(program, function.addr, size, &HashSet::new(), &|_| {
vlk_loader::loader::Summary::default()
})
else {
return cases;
};
let reach = function.addr..function.addr.saturating_add(0x1_0000);
for table in jump_table::recover(&blocks, program, reach) {
cases.extend(
table
.targets()
.into_iter()
.filter(|target| *target != function.addr),
);
}
cases
});
let mut cases = HashSet::new();
for found in found {
cases.extend(found);
}
if !program
.image
.drop_scanned_starts(&cases, crate::lift::scan(program.image.isa))
{
return;
}
}
}
pub(super) fn stack_results(program: &Program, addr: u64) -> Vec<vlk_ir::ir::Expr> {
let image = &program.image;
let convention = crate::lift::convention_of(image, addr);
let Some(start) = convention.stack_arguments() else {
return Vec::new();
};
let sp = vlk_arch::arch::stack_pointer(image.isa);
summary::summary(program, addr)
.stack_results
.iter()
.take_while(|(_, width)| *width != 0)
.map(|(offset, width)| vlk_ir::ir::Expr::Load {
addr: Box::new(vlk_ir::ir::Expr::bin(
vlk_ir::ir::BinOp::Add,
vlk_ir::ir::Expr::reg(sp, 64),
vlk_ir::ir::Expr::Const(start as u64 + u64::from(*offset)),
)),
width: *width,
signed: false,
})
.collect()
}
pub(super) fn tail_calls_through_pointers(
blocks: &mut [vlk_ir::ir::Block],
switched: &HashSet<u64>,
image: &Image,
) {
let heights = crate::lift::stack_heights(blocks, image.isa);
for (block, height) in blocks.iter_mut().zip(heights) {
if switched.contains(&block.start) || height.is_some_and(|height| height != 0) {
continue;
}
let Some(Stmt::BrIndirect { target, .. }) = block.stmts.last() else {
continue;
};
let mut pointer = matches!(target, Expr::Load { .. });
let mut copied = target;
let mut earlier = block.stmts.iter().rev().skip(1);
loop {
if image.isa == vlk_base::target::Isa::Arm32
&& let Expr::Bin {
op: vlk_ir::ir::BinOp::And,
lhs,
rhs,
} = copied
&& matches!(rhs.as_ref(), Expr::Const(0xffff_ffff | 0xffff_fffe))
{
copied = lhs;
continue;
}
let Expr::Reg { index, .. } = copied else {
break;
};
match earlier.find_map(|stmt| match stmt {
Stmt::Assign { dest, value, .. } if dest.index == *index => Some(value),
_ => None,
}) {
None | Some(Expr::Load { .. }) => {
pointer = true;
break;
}
Some(value) => copied = value,
}
}
if !pointer {
continue;
}
let through = target.clone();
let at = block.stmts.pop().and_then(|stmt| stmt.origin());
block.stmts.push(Stmt::Call {
kind: vlk_types::types::CallKind::Tail,
target: None,
through: Some(through),
convention: vlk_types::types::Convention::of(image.isa, image.format, image.go),
args: None,
floats_named: false,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(
vlk_types::types::Convention::of(image.isa, image.format, image.go),
None,
),
via: None,
at,
});
block.stmts.push(Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 64),
at: None,
});
}
}
pub(super) fn recover_tables(
program: &Program,
blocks: &mut [vlk_ir::ir::Block],
extent: std::ops::Range<u64>,
) -> Vec<jump_table::Recovered> {
let image = &program.image;
let mut tables = jump_table::recover(blocks, program, extent.clone());
if image.isa == vlk_base::target::Isa::Mips32 {
for _ in 0..4 {
let known: Vec<(u64, Vec<u64>)> = tables
.iter()
.map(|table| (table.block_start, table.targets()))
.collect();
if !lift::mips32::fold_table_slots(image, blocks, &HashSet::new(), &known) {
break;
}
tables = jump_table::recover(blocks, program, extent.clone());
}
}
tables
}
fn lift_with_tables(
program: &Program,
function: &Function,
size: u64,
starts: HashSet<u64>,
) -> Result<(Vec<Block>, Vec<jump_table::Recovered>), LiftError> {
let extent = function.addr..function.addr.saturating_add(size);
let mut blocks = match lift::lift(program, function.addr, size, &starts) {
Ok(blocks) => blocks,
Err(error) => return Err(error),
};
let mut tables = recover_tables(program, &mut blocks, extent.clone());
let mut targets = starts;
for _ in 0..4 {
let found: HashSet<u64> = tables
.iter()
.flat_map(jump_table::Recovered::targets)
.collect();
if found.is_subset(&targets) {
break;
}
targets.extend(found);
blocks = match lift::lift(program, function.addr, size, &targets) {
Ok(blocks) => blocks,
Err(error) => return Err(error),
};
tables = recover_tables(program, &mut blocks, extent.clone());
}
Ok((blocks, tables))
}
pub(super) fn set_returns(blocks: &mut [Block], returned: &Expr) {
for stmt in blocks.iter_mut().flat_map(|block| &mut block.stmts) {
if let Stmt::Ret { value, .. } = stmt {
*value = returned.clone();
}
}
}
struct RegisterReturn {
float: Option<Precision>,
ignored: bool,
}
fn settle_register_return(
program: &Program,
function: &Function,
blocks: &mut [Block],
declared: Option<&CType>,
stack_results: bool,
) -> RegisterReturn {
let image = &program.image;
if vlk_arch::arch::pointer_bytes(image.isa) == 4 && declared.is_some_and(lift::pairs32::wide) {
let (low, high) = lift::pairs32::result_registers(image);
set_returns(
blocks,
&lift::pairs32::join(Expr::reg(low, 32), Expr::reg(high, 32)),
);
}
let float = match declared {
Some(ret) => ret.precision(),
None if stack_results => None,
None => float_result_of(blocks, program, function.addr, &|target| {
summary::summary(program, target).float_return
}),
};
let further = if (image.go || declared.is_none()) && float.is_none() && !stack_results {
results::further_results(program, function.addr)
} else {
0
};
let listed = if float.is_none() && !stack_results {
results::method_results(image, function.addr)
} else {
None
};
let ignored = declared.is_none()
&& float.is_none()
&& !stack_results
&& further == 0
&& !function.sources.contains(&NameSource::Plt)
&& match listed {
Some(results) => results == 0,
None => {
results::ignored_by_callers(program, function.addr)
|| results::returns_unset(blocks, lift::convention_of(image, function.addr))
}
};
if declared == Some(&CType::Void) || ignored {
set_returns(blocks, &Expr::constant(0));
}
if let (Some(precision), Some(slot)) = (float, float_return_slot(image.isa)) {
set_returns(blocks, &Expr::reg(slot, precision.bits()));
}
if further > 0 {
let convention = Convention::of(image.isa, image.format, image.go);
let returned: Vec<Expr> = convention.results()[..=further]
.iter()
.map(|register| Expr::reg(*register, 64))
.collect();
for stmt in blocks.iter_mut().flat_map(|block| &mut block.stmts) {
if let Stmt::Ret { value, .. } = stmt
&& matches!(value, Expr::Reg { .. })
{
*value = Expr::Apply {
op: Operation::Results,
args: returned.clone(),
};
}
}
}
RegisterReturn { float, ignored }
}
fn declared_return(binding: &SignatureAbi) -> Option<Expr> {
match binding.result.as_ref().map(|value| &value.passing) {
Some(Passing::Direct(pieces)) => {
let values: Option<Vec<_>> = pieces
.iter()
.map(|piece| match piece.location {
AbiLocation::Register(register) => Some(Expr::reg(register, 64)),
AbiLocation::Stack(_) => None,
})
.collect();
values.map(|args| Expr::Apply {
op: Operation::Results,
args,
})
}
Some(Passing::Indirect {
returned_pointer, ..
}) => Some(
returned_pointer.map_or_else(|| Expr::constant(0), |register| Expr::reg(register, 64)),
),
None => Some(Expr::constant(0)),
}
}
fn recover_signature(
image: &Image,
function: &Function,
blocks: &[Block],
landing_pads: &[(u64, Vec<(u64, u64)>)],
) -> signature::Signature {
let mut signature = signature::recover_for(image, function, blocks, landing_pads);
if let Some(listed) = vlk_loader::loader::go::argument_registers(image, function.addr) {
let arguments = lift::convention_of(image, function.addr).arguments();
signature.params.retain(|param| {
param.name == "closure"
|| arguments
.iter()
.position(|register| *register == param.index)
.is_none_or(|position| position < listed)
});
}
signature
}
fn stack_parameters(
signature: &signature::Signature,
function: &Function,
isa: Isa,
) -> (Vec<StackParam>, Vec<Structure>) {
match (signature.aggregate, signature.stack.first()) {
(true, Some(first)) => {
let position = signature.params.len();
let name = format!(
"{}_a{position}",
vlk_types::types::structure_prefix(function.name.as_deref(), function.addr)
);
let structure = Structure {
name: name.clone(),
fields: signature
.stack
.iter()
.map(|offset| ((offset - first) as u64, CType::I64))
.collect(),
size: None,
elements: Vec::new(),
};
let stack_param = StackParam {
offset: *first,
size: 8 * signature.stack.len() as u64,
name: format!("a{position}"),
ty: CType::Named(format!("struct {name}")),
position,
};
(vec![stack_param], vec![structure])
}
_ => {
let stack_params = signature
.stack
.iter()
.enumerate()
.map(|(slot, offset)| {
let position = signature.params.len() + slot;
let ty = match signature.stack_widths.get(slot) {
Some(width) if *width < 8 => CType::int(*width, false),
_ => CType::I64,
};
StackParam {
offset: *offset,
size: u64::from(vlk_arch::arch::pointer_bytes(isa)),
name: format!("a{position}"),
ty,
position,
}
})
.collect();
(stack_params, Vec::new())
}
}
}
fn add_indirect_result_parameter(ir: &mut FunctionIr) {
let Some(Ok(binding)) = ir
.declared_signature
.as_ref()
.map(|signature| &signature.abi)
else {
return;
};
let Some(ValueAbi {
passing:
Passing::Indirect {
pointer: AbiLocation::Register(register),
returned_pointer,
},
..
}) = &binding.result
else {
return;
};
let (register, returns_pointer) = (*register, returned_pointer.is_some());
if !ir.params.iter().any(|param| param.index == register) {
let mut position = ir.params.len();
while ir
.params
.iter()
.any(|param| param.name == format!("a{position}"))
{
position += 1;
}
ir.params.push(vlk_types::types::Param {
index: register,
name: format!("a{position}"),
ty: CType::U64,
});
}
if !returns_pointer {
ir.ret_type = CType::Void;
}
}
pub(super) fn lift_function(program: &Program, function: &Function) -> Result<Lifted, LiftError> {
let image = &program.image;
let size = function.size.unwrap_or(UNKNOWN_SIZE);
let extent = function.addr..function.addr.saturating_add(size);
let landing_pads = image.landing_pads_of(extent.clone());
let pads: HashSet<u64> = landing_pads.iter().map(|(pad, _)| *pad).collect();
let starts = exception_starts(&landing_pads, extent);
let (mut blocks, tables) = match lift_with_tables(program, function, size, starts) {
Ok(lifted) => lifted,
Err(error) => return Err(error),
};
if image.go {
drop_stack_growth_check(&mut blocks, image);
initialize_go_registers(&mut blocks, image.isa);
}
receive_exceptions(&mut blocks, &pads, image.isa);
let switched: HashSet<u64> = tables.iter().map(|table| table.block_start).collect();
tail_calls_through_pointers(&mut blocks, &switched, image);
indirect::resolve(&mut blocks, &landing_pads, program);
if image.isa == Isa::Mips32 {
keep_registers_read_after_calls(&mut blocks);
}
let types = vlk_loader::loader::dwarf::function_types(image, function.addr);
let declared_signature = types.as_ref().and_then(abi::declaration);
let inferred = if types.is_none() {
lift::pairs32::definition_types(program, function.addr)
} else {
None
};
let runtime = go_types::runtime(image, function.addr);
let declared = types
.as_ref()
.and_then(|types| types.ret.as_ref())
.or_else(|| inferred.as_ref().map(|(_, ret)| ret))
.or_else(|| runtime.map(|prototype| &prototype.ret));
let stack_results = stack_results(program, function.addr);
let RegisterReturn {
float: float_return,
ignored,
} = settle_register_return(
program,
function,
&mut blocks,
declared,
!stack_results.is_empty(),
);
if let Some(Ok(binding)) = declared_signature.as_ref().map(|signature| &signature.abi)
&& let Some(returned) = declared_return(binding)
{
set_returns(&mut blocks, &returned);
}
jump_table::apply(&mut blocks, &tables);
jump_table::drop_data(&mut blocks, &tables, &landing_pads);
if image.go
|| (landing_pads.is_empty() && image.exception_handlers.is_empty())
|| function.sources.contains(&NameSource::Plt)
{
drop_unreached(&mut blocks);
}
let mut signature = recover_signature(image, function, &blocks, &landing_pads);
if let Some(first) = stack_results.first() {
let returned = match stack_results.as_slice() {
[only] => only.clone(),
all => Expr::Apply {
op: Operation::Results,
args: all.to_vec(),
},
};
set_returns(&mut blocks, &returned);
if let Expr::Load { width, .. } = first {
signature.ret = CType::int(*width, *width > 1);
}
}
let (stack_params, structures) = stack_parameters(&signature, function, image.isa);
let mut ir = FunctionIr {
isa: image.isa,
convention: lift::convention_of(image, function.addr),
params: signature.params,
declared_signature,
stack_params,
stack_spills: vlk_loader::loader::go::stack_spills(image, function.addr),
debug_globals: types
.as_ref()
.map(|types| types.globals.clone())
.unwrap_or_default(),
debug_registers: types
.as_ref()
.map(|types| types.registers.clone())
.unwrap_or_default(),
debug_locals: types
.as_ref()
.map(|types| types.locals.clone())
.unwrap_or_default(),
variadic: false,
ret_type: match float_return {
_ if ignored => CType::Void,
Some(precision) => CType::Named(
match precision {
Precision::Single => "float",
Precision::Double => "double",
}
.to_owned(),
),
None => inferred.map_or(signature.ret, |(_, ret)| ret),
},
accesses: signature.accesses,
members: Vec::new(),
definitions: Vec::new(),
structures,
signed_params: signature.signed.into_iter().collect(),
landing_pads,
pointer_values: Vec::new(),
saved_slots: Vec::new(),
frame_bottom: 0,
entry_alignment: entry_alignment(image, function.addr),
callee_signatures: Default::default(),
big_endian: image.byte_order() == Some(object::Endianness::Big),
callee_results: Default::default(),
callee_named_arguments: Default::default(),
callee_float_returns: Default::default(),
listed_callees: Default::default(),
callee_floats: Default::default(),
value_types: std::collections::BTreeMap::new(),
variable_registers: std::collections::BTreeMap::new(),
addr: function.addr,
name: function.name.clone(),
size,
blocks,
};
add_indirect_result_parameter(&mut ir);
go_types::apply_runtime_signature(&mut ir, image);
Ok(Lifted {
ir,
has_jump_tables: !tables.is_empty(),
types,
})
}
pub(super) fn entry_alignment(
image: &vlk_loader::loader::Image,
addr: u64,
) -> Option<vlk_types::types::EntryAlignment> {
use vlk_base::target::{Format, Isa};
if image.entry == Some(addr) {
match image.format {
Format::Raw => return None,
Format::Elf if image.isa == Isa::X86_64 => {
return Some(vlk_types::types::EntryAlignment {
residue: 0,
modulus: 16,
});
}
_ => {}
}
}
crate::lift::convention_of(image, addr).entry_alignment()
}