use std::collections::HashSet;
use vlk_ir::ir::{FunctionIr, Stmt};
use vlk_loader::loader::Image;
pub(super) fn drop_stack_protector(ir: &mut FunctionIr, image: &Image) {
use vlk_ir::ir::Expr;
let fails = |block: &vlk_ir::ir::Block| {
block.stmts.iter().any(|stmt| {
matches!(stmt, Stmt::Call { target: Some(target), .. }
if image.functions.get(target).and_then(|function| function.name.as_deref())
.is_some_and(|name| name.trim_start_matches('_') == "stack_chk_fail"))
})
};
let failing: HashSet<u64> = ir
.blocks
.iter()
.filter(|block| fails(block))
.map(|block| block.start)
.collect();
if failing.is_empty() {
return;
}
let sp = vlk_arch::arch::stack_pointer(ir.isa);
let in_frame = |expr: &Expr| match expr {
Expr::Load { addr, .. } => {
let mut read = HashSet::new();
vlk_ir::ir::visit::collect_reads(addr, &mut read);
read.contains(&sp)
}
_ => false,
};
let mut guarded: Vec<(Expr, Expr)> = Vec::new();
for index in 0..ir.blocks.len() {
let next = ir.blocks.get(index + 1).map(|block| block.start);
let Some(Stmt::Brif {
cond,
lhs,
rhs,
target,
..
}) = ir.blocks[index].stmts.last()
else {
continue;
};
let (copy, guard) = match (in_frame(lhs), in_frame(rhs)) {
(true, false) => (lhs.clone(), rhs.clone()),
(false, true) => (rhs.clone(), lhs.clone()),
_ => continue,
};
let continues = match cond {
vlk_ir::ir::Cond::Ne if failing.contains(target) => next,
vlk_ir::ir::Cond::Eq if next.is_some_and(|next| failing.contains(&next)) => {
Some(*target)
}
_ => continue,
};
let Some(continues) = continues else {
continue;
};
*ir.blocks[index].stmts.last_mut().expect("a branch") = Stmt::Br {
target: Some(continues),
at: None,
};
guarded.push((copy, guard));
}
if guarded.is_empty() {
return;
}
for block in &mut ir.blocks {
block.stmts.retain(|stmt| {
!matches!(stmt, Stmt::Store { addr, value, .. }
if guarded.iter().any(|(copy, guard)| {
matches!(copy, Expr::Load { addr: slot, .. } if slot.as_ref() == addr)
&& guard == value
}))
});
}
loop {
let reached: HashSet<usize> = (0..ir.blocks.len())
.flat_map(|from| vlk_ir::ir::cfg::block_successors(&ir.blocks, from))
.collect();
let before = ir.blocks.len();
let mut position = 0;
ir.blocks.retain(|block| {
position += 1;
position == 1 || reached.contains(&(position - 1)) || !failing.contains(&block.start)
});
if ir.blocks.len() == before {
break;
}
}
}