use std::collections::HashMap;
use vlk_base::target::Isa;
use vlk_ir::ir::{BinOp, Expr, Stmt, Table, Via};
use vlk_loader::loader::Image;
use vlk_types::types::{CallKind, Convention};
use super::Summaries;
use super::constants::{Facts, Rules, apply, frame_load, value, word};
pub(super) fn bare(kind: CallKind, image: &Image, target: Option<u64>) -> Stmt {
Stmt::Call {
kind,
target,
through: None,
convention: Convention::of(image.isa, image.format, image.go),
args: None,
floats_named: false,
abi: None,
clobbers: None,
outputs: Vec::new(),
via: None,
at: None,
}
}
fn cleanup(image: &Image, target: u64) -> Option<Stmt> {
let Some(bytes) = crate::lift::callee_cleanup(image, target).filter(|bytes| *bytes != 0) else {
return None;
};
let sp = vlk_arch::arch::stack_pointer(image.isa);
let moved = Expr::bin(
BinOp::Add,
Expr::reg(sp, 64),
Expr::constant(u64::from(bytes)),
);
let value = if vlk_arch::arch::pointer_bytes(image.isa) == 4 {
Expr::bin(BinOp::And, moved, Expr::constant(0xffff_ffff))
} else {
moved
};
Some(Stmt::Assign {
dest: vlk_ir::ir::RegRef {
index: sp,
width: 64,
},
value,
at: None,
})
}
pub(super) struct Calls {
rules: Rules,
start: u64,
known: Facts,
loaded: HashMap<u16, u64>,
}
fn slot_word(slot: u64) -> Expr {
Expr::Load {
addr: Box::new(Expr::Const(slot)),
width: 4,
signed: false,
}
}
impl Calls {
pub(super) fn new(rules: Rules, start: u64) -> Self {
Self {
rules,
start,
known: Facts::default(),
loaded: HashMap::new(),
}
}
pub(super) fn enter(&mut self, address: u64, known: Option<&Facts>) {
self.known = match known {
Some(known) => known.clone(),
None if address == self.start => Facts::of(&self.rules.at_entry),
None => Facts::default(),
};
self.loaded.clear();
}
fn fold(&mut self, image: &Image, stmts: &mut Vec<Stmt>, index: usize) -> bool {
let fixed: Vec<(u16, Expr)> = self
.rules
.fixed
.iter()
.chain(self.rules.saved)
.filter_map(|register| {
self.known
.registers
.get(register)
.map(|value| (*register, Expr::Const(*value)))
})
.collect();
if let Stmt::Assign { dest, value, .. } = &stmts[index]
&& self.rules.fixed.contains(&dest.index)
&& self.known.registers.contains_key(&dest.index)
&& frame_load(self.rules.frame, value)
{
stmts.remove(index);
return true;
}
let stmt = &mut stmts[index];
vlk_ir::ir::visit::replace_reads(stmt, &fixed);
match stmt {
Stmt::Assign {
value: assigned, ..
} => {
if let Some(constant) = value(&self.known, assigned, image, &self.rules) {
*assigned = Expr::Const(constant);
} else if let Expr::Load { addr, width: 4, .. } = word(assigned)
&& let Some(address) = value(&self.known, addr, image, &self.rules)
{
if let Some(entry) = image.fixed_table_entry(address) {
*assigned = Expr::Const(entry);
} else if image.imports.contains_key(&address) {
*assigned =
Expr::bin(BinOp::And, slot_word(address), Expr::Const(0xffff_ffff));
}
}
}
Stmt::Call {
through: Some(through),
..
}
| Stmt::BrIndirect {
target: through, ..
} => {
if let Expr::Reg { index, .. } = through
&& let Some(slot) = self.loaded.get(index)
{
*through = slot_word(*slot);
}
}
_ => {}
}
false
}
fn load(&mut self, image: &Image, stmt: &Stmt) {
match stmt {
Stmt::Assign { dest, value, .. } => {
let slot = match word(value) {
Expr::Load { addr, width: 4, .. } => match addr.as_ref() {
Expr::Const(slot) if image.imports.contains_key(slot) => Some(*slot),
_ => None,
},
Expr::Reg { index, .. } => self.loaded.get(index).copied(),
_ => None,
};
match slot {
Some(slot) => self.loaded.insert(dest.index, slot),
None => self.loaded.remove(&dest.index),
};
}
Stmt::Call { .. } => self.loaded.clear(),
stmt => {
for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
self.loaded.remove(®ister);
}
}
}
}
fn complete(
&mut self,
image: &Image,
summaries: Summaries<'_>,
stmts: &mut Vec<Stmt>,
index: usize,
) -> Option<usize> {
let Stmt::Call {
kind,
target,
through,
..
} = &stmts[index]
else {
return Some(index + 1);
};
let through_known = target.is_none();
let target = target.or_else(|| {
through
.as_ref()
.and_then(|expr| value(&self.known, expr, image, &self.rules))
});
if let (None, Some(through)) = (target, through) {
if self.rules.folds {
let mut made = super::call_through_as(
*kind,
image,
through.clone(),
Convention::of(image.isa, image.format, image.go),
);
made.set_origin(stmts[index].origin());
stmts[index] = made;
}
apply(&mut self.known, &stmts[index], image, &self.rules);
self.loaded.clear();
return Some(index + 1);
}
let kind = *kind;
let mut call = super::call(kind, image, summaries, target);
if let (true, Some(_), false, Stmt::Call { via, .. }) = (
through_known,
target,
self.rules.calls_through_registers,
&mut call,
) {
*via = Some(Box::new(Via {
table: Table::Register,
slot: 0,
candidates: Vec::new(),
}));
}
if image.isa == Isa::Mips32 && kind == CallKind::Invoke {
super::mips32::count_format(image, summaries, &mut call, |register| {
self.known.registers.get(®ister).copied()
});
}
apply(&mut self.known, &call, image, &self.rules);
self.loaded.clear();
let mut made = vec![call];
let ends =
kind == CallKind::Invoke && target.is_some_and(|target| summaries(target).noreturn);
let tail_ends =
kind == CallKind::Tail && target.is_some_and(|target| summaries(target).noreturn);
if ends {
made.push(Stmt::Trap { at: None });
} else if let (CallKind::Invoke, Some(target)) = (kind, target) {
made.extend(cleanup(image, target));
made.extend(super::stack_results(image, summaries, target));
}
for stmt in &made[1..] {
apply(&mut self.known, stmt, image, &self.rules);
}
let count = made.len();
stmts.splice(index..=index, made);
if ends {
stmts.truncate(index + count);
return None;
}
if kind == CallKind::Tail
&& let Some(after @ Stmt::Ret { .. }) = stmts.get_mut(index + count)
{
let at = after.origin();
if tail_ends {
*after = Stmt::Trap { at };
} else if through_known {
*after = Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 64),
at,
};
}
}
Some(index + count)
}
pub(super) fn settle(
&mut self,
image: &Image,
summaries: Summaries<'_>,
stmts: &mut Vec<Stmt>,
from: usize,
) -> bool {
let mut index = from;
while index < stmts.len() {
if self.rules.folds && self.fold(image, stmts, index) {
continue;
}
match &stmts[index] {
Stmt::Call { kind, .. } if *kind != CallKind::Syscall => {
match self.complete(image, summaries, stmts, index) {
Some(next) => index = next,
None => return true,
}
continue;
}
Stmt::BrIndirect { target, at } if self.rules.folds => {
if let Some(target) = value(&self.known, target, image, &self.rules) {
stmts[index] = Stmt::Br {
target: Some(target),
at: *at,
};
}
}
stmt => {
apply(&mut self.known, stmt, image, &self.rules);
if self.rules.folds {
self.load(image, stmt);
}
}
}
index += 1;
}
false
}
}
pub(super) fn count_tail_formats(
image: &Image,
summaries: Summaries<'_>,
rules: &Rules,
start: u64,
begins: &HashMap<u64, Facts>,
blocks: &mut [vlk_ir::ir::Block],
) {
for block in blocks {
let mut known = match begins.get(&block.start) {
Some(known) => known.clone(),
None if block.start == start => Facts::of(&rules.at_entry),
None => Facts::default(),
};
for stmt in &mut block.stmts {
if matches!(
stmt,
Stmt::Call {
kind: CallKind::Tail,
..
}
) {
super::mips32::count_format(image, summaries, stmt, |register| {
known.registers.get(®ister).copied()
});
}
apply(&mut known, stmt, image, rules);
}
}
}
pub(crate) fn arguments(
kind: CallKind,
convention: Convention,
isa: vlk_base::target::Isa,
count: Option<usize>,
stack: usize,
) -> Option<Vec<Expr>> {
let Some(count) = count else {
return None;
};
if kind.push_bytes(isa, convention).is_none() {
return None;
}
let word = i64::from(vlk_arch::arch::pointer_bytes(isa));
let stack = if isa == Isa::I386 {
stack.max(count.saturating_sub(convention.arguments().len()))
} else {
stack
};
let mut args: Vec<Expr> = convention.arguments()[..count.min(convention.arguments().len())]
.iter()
.map(|register| Expr::reg(*register, vlk_arch::arch::pointer_bytes(isa) * 8))
.collect();
if let Some(start) = convention.stack_arguments() {
let sp = vlk_arch::arch::stack_pointer(isa);
for slot in 0..stack {
let Some(offset) = i64::try_from(slot)
.ok()
.and_then(|slot| slot.checked_mul(word))
.and_then(|slot| start.checked_add(slot))
.and_then(|callee| kind.stack_offset(isa, convention, callee))
else {
return None;
};
args.push(Expr::Load {
addr: Box::new(Expr::bin(
vlk_ir::ir::BinOp::Add,
Expr::reg(sp, 64),
Expr::Const(offset as u64),
)),
width: word as u8,
signed: false,
});
}
}
Some(args)
}
pub(crate) fn call(
kind: CallKind,
image: &Image,
summaries: Summaries<'_>,
target: Option<u64>,
) -> Stmt {
let name = target
.and_then(|target| image.functions.get(&target))
.and_then(|function| function.name.as_deref());
if image.go && name.is_some_and(|name| name.starts_with("runtime.gcWriteBarrier")) {
return Stmt::Call {
kind,
target,
through: None,
convention: Convention::GoWriteBarrier,
args: Some(Vec::new()),
floats_named: false,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(Convention::GoWriteBarrier, None),
via: None,
at: None,
};
}
let convention = match target {
Some(target) => crate::lift::convention_of(image, target),
None => Convention::of(image.isa, image.format, image.go),
};
let variadic = target.is_some_and(|target| {
image
.functions
.get(&target)
.and_then(|function| function.name.as_deref())
.and_then(|name| vlk_prototypes::prototypes::for_image(name, image))
.is_some_and(|prototype| prototype.format.is_some())
});
let summary = target.filter(|_| !variadic).map(summaries);
let cleanup_slots = if convention == Convention::Stdcall {
target
.and_then(|target| crate::lift::callee_cleanup(image, target))
.filter(|bytes| bytes.is_multiple_of(4))
.map(|bytes| usize::from(bytes / 4))
} else {
None
};
let arity = summary.and_then(|summary| summary.arity).or(cleanup_slots);
let stack = summary
.map_or(0, |summary| summary.stack)
.max(cleanup_slots.unwrap_or(0));
let mut args = arguments(kind, convention, image.isa, arity, stack);
if let (true, Some(args), Some(summary)) = (convention.go_assembly(), &mut args, summary) {
for (arg, read) in args.iter_mut().zip(summary.stack_widths) {
if let Expr::Load { width, .. } = arg
&& read != 0
{
*width = read;
}
}
}
let floats_named = append_float_arguments(
&mut args,
convention,
summary.and_then(|summary| summary.floats),
);
if let (Some(args), Some(inputs)) = (&mut args, summary.and_then(|summary| summary.inputs)) {
let unread = |arg: &Expr| {
matches!(arg, Expr::Reg { index, .. }
if convention.arguments().contains(index) && !inputs.contains(*index))
};
let floats = summary
.and_then(|summary| summary.floats)
.is_some_and(|floats| floats != 0);
if convention == Convention::O32 && floats {
args.retain(|arg| !unread(arg));
} else {
for arg in args {
if unread(arg) {
*arg = Expr::constant(0);
}
}
}
}
if (image.isa == vlk_base::target::Isa::I386
|| target
.and_then(|target| image.functions.get(&target))
.is_some_and(|function| {
function
.sources
.contains(&vlk_loader::loader::NameSource::Call)
}))
&& let (Some(args), Some(inputs)) = (&mut args, summary.and_then(|summary| summary.inputs))
{
for register in inputs.iter() {
if register < 16
&& register != vlk_arch::arch::stack_pointer(image.isa)
&& !convention.arguments().contains(®ister)
{
args.push(Expr::reg(
register,
if image.isa == vlk_base::target::Isa::I386 {
32
} else {
64
},
));
}
}
}
let clobbers = summary.and_then(|summary| summary.clobbers);
Stmt::Call {
kind,
target,
through: None,
convention,
args,
floats_named,
abi: None,
outputs: vlk_ir::ir::fallback_call_outputs(convention, clobbers),
clobbers,
via: None,
at: None,
}
}
pub(crate) fn pointer_target(image: &Image, through: &Expr) -> Option<u64> {
let Some(slot) = vlk_prototypes::prototypes::pointer_slot(image, through) else {
return None;
};
let Some(section) = image.section_at(slot) else {
return None;
};
if section.executable || !section.read_only {
return None;
}
let word = vlk_arch::arch::pointer_bytes(image.isa);
let Some(bytes) = image.read_vaddr(slot, u64::from(word)) else {
return None;
};
let target = if word == 4 {
let Ok(bytes) = bytes.try_into() else {
return None;
};
u64::from(u32::from_le_bytes(bytes))
} else {
let Ok(bytes) = bytes.try_into() else {
return None;
};
u64::from_le_bytes(bytes)
};
image.functions.contains_key(&target).then_some(target)
}
pub(crate) fn import_called(image: &Image, through: &Expr) -> Option<vlk_loader::loader::Summary> {
vlk_prototypes::prototypes::import_name(image, through)
.map(|name| crate::analysis::summary::import(image, name))
}
fn append_float_arguments(
args: &mut Option<Vec<Expr>>,
convention: Convention,
floats: Option<usize>,
) -> bool {
let (Some(args), Some(floats)) = (args, floats) else {
return false;
};
let registers = convention.float_arguments();
args.extend(
registers[..floats.min(registers.len())]
.iter()
.map(|register| Expr::reg(*register, 64)),
);
true
}
pub(crate) fn call_through(kind: CallKind, image: &Image, through: Expr) -> Stmt {
call_through_as(
kind,
image,
through,
Convention::of(image.isa, image.format, image.go),
)
}
pub(crate) fn call_through_as(
kind: CallKind,
image: &Image,
through: Expr,
default: Convention,
) -> Stmt {
let convention = vlk_prototypes::prototypes::import_name(image, &through)
.and_then(|name| vlk_prototypes::prototypes::i386_import(image, name))
.map_or(default, |properties| properties.0);
let variadic = vlk_prototypes::prototypes::import_name(image, &through)
.and_then(|name| vlk_prototypes::prototypes::for_image(name, image))
.is_some_and(|prototype| {
prototype.format.is_some() || (kind == CallKind::Tail && prototype.variadic)
});
let summary = import_called(image, &through).filter(|_| !variadic);
let arity = summary.as_ref().and_then(|summary| summary.arity);
let mut args = arguments(kind, convention, image.isa, arity, 0);
let floats_named = append_float_arguments(
&mut args,
convention,
summary
.as_ref()
.and_then(|summary| summary.floats)
.filter(|count| *count != 0),
);
Stmt::Call {
kind,
target: None,
through: Some(through),
convention,
args,
floats_named,
abi: None,
clobbers: None,
outputs: vlk_ir::ir::fallback_call_outputs(convention, None),
via: None,
at: None,
}
}
pub(super) fn tail_call(image: &Image, summaries: Summaries<'_>, target: Option<u64>) -> [Stmt; 2] {
if target.is_some_and(|target| summaries(target).noreturn) {
return [
call(CallKind::Tail, image, summaries, target),
Stmt::Trap { at: None },
];
}
[
call(CallKind::Tail, image, summaries, target),
Stmt::Ret {
value: Expr::reg(vlk_arch::arch::RETURN, 64),
at: None,
},
]
}
#[cfg(test)]
mod tests;