mod decode;
mod disassembly;
mod instruction_fallback;
mod literals;
pub use disassembly::{disassembly, position_independent_instruction};
pub(super) use literals::resolve_internal_pc_loads;
pub use literals::{fold_literals, literal};
use std::collections::HashSet;
use yaxpeax_arm::armv7::{Instruction, Opcode, Operand, RegShiftStyle, ShiftStyle};
use decode::{Step, decode};
use disassembly::unsupported_declaration;
use super::flags::{Flags, Test};
use super::{Machine, Summaries, Write};
use vlk_base::error::LiftError;
use vlk_base::target::Isa;
use vlk_ir::ir::{BinOp, Block, Cond, Expr, RegRef, Stmt};
#[cfg(test)]
use vlk_loader::loader::ArmMode;
use vlk_loader::loader::Image;
use vlk_program::program::Program;
use vlk_types::types::CallKind;
#[cfg(test)]
use yaxpeax_arm::armv7;
pub(super) fn lift(
program: &Program,
addr: u64,
bytes: &[u8],
targets: &HashSet<u64>,
summaries: Summaries<'_>,
) -> Result<Vec<Block>, LiftError> {
lift_in_mode(
program,
addr,
bytes,
targets,
summaries,
super::execution::Mode::Analysis,
)
}
pub(super) fn lift_in_mode(
program: &Program,
addr: u64,
bytes: &[u8],
targets: &HashSet<u64>,
summaries: Summaries<'_>,
mode: super::execution::Mode,
) -> Result<Vec<Block>, LiftError> {
let image = &program.image;
if !matches!(
image.format,
vlk_base::target::Format::Elf | vlk_base::target::Format::Raw
) || image.byte_order() != Some(object::Endianness::Little)
|| addr > u64::from(u32::MAX)
|| addr
.checked_add(bytes.len() as u64)
.is_none_or(|end| end > u64::from(u32::MAX) + 1)
{
return Err(LiftError::UnsupportedIsa);
}
let mut targets = targets.clone();
let (decoded, _) = decode(image, bytes, addr);
let starts: HashSet<u64> = decoded.iter().map(|instruction| instruction.pc).collect();
let blocks = loop {
let blocks = super::lift_continuing(
program,
summaries,
|| {
super::execution::Located::new(
Lifter {
image,
out: super::Emitter::default(),
float_comparison: false,
},
mode,
)
},
addr,
bytes,
&|bytes, address| decode(image, bytes, address),
&targets,
);
let mut blocks = match blocks {
Ok(blocks) => blocks,
Err(error) => return Err(error),
};
let found = resolve_internal_pc_loads(program, &mut blocks, &starts);
let split = !found.is_subset(&targets);
targets.extend(found);
for block in &mut blocks {
if !matches!(block.stmts.last(), Some(Stmt::BrIndirect { target, .. })
if *target == Expr::reg(vlk_ir::ir::EXCHANGE, 64))
{
continue;
}
if mode == super::execution::Mode::Analysis
&& matches!(block.stmts.iter().rev().nth(1),
Some(Stmt::Assign { dest, .. }) if dest.index > 3)
{
*block.stmts.last_mut().expect("indirect branch") = Stmt::unsupported(
"ARM PC load with writeback requires a proven internal target",
);
block.stmts.push(Stmt::Trap { at: None });
}
}
if !split {
break Ok(blocks);
}
};
match blocks {
Ok(mut blocks) => {
if unsupported_declaration(image, addr)
&& let Some(entry) = blocks.first_mut()
{
entry.stmts.insert(
0,
Stmt::unsupported("AAPCS32 multiword, floating-point or aggregate declaration"),
);
}
Ok(blocks)
}
Err(error) => Err(error),
}
}
struct Lifter<'a> {
image: &'a Image,
out: super::Emitter,
float_comparison: bool,
}
pub(super) fn low(value: Expr) -> Expr {
Expr::bin(BinOp::And, value, Expr::constant(0xffff_ffff))
}
fn extend(value: Expr, width: u8, signed: bool, rotation: u8) -> Expr {
let value = super::rotate(
value,
Expr::constant(u64::from(rotation)),
32,
true,
);
if signed {
Expr::SignExtend {
value: Box::new(value),
width,
}
} else {
Expr::bin(BinOp::And, value, Expr::constant((1u64 << (width * 8)) - 1))
}
}
fn bitfield(value: Expr, start: u64, width: u64) -> Expr {
let shifted = Expr::bin(BinOp::Shr, value, Expr::constant(start));
Expr::bin(BinOp::And, shifted, Expr::constant((1u64 << width) - 1))
}
fn divide(left: Expr, right: Expr, signed: bool) -> Expr {
let operand = |value| {
if signed {
Expr::SignExtend {
value: Box::new(value),
width: 4,
}
} else {
low(value)
}
};
let right = operand(right);
Expr::Select {
cond: Cond::Eq,
lhs: Box::new(right.clone()),
rhs: Box::new(Expr::constant(0)),
then: Box::new(Expr::constant(0)),
els: Box::new(Expr::bin(
if signed { BinOp::DivS } else { BinOp::DivU },
operand(left),
right,
)),
}
}
impl Lifter<'_> {
fn read(index: u8, pc: u64, thumb: bool) -> Expr {
if index == 15 {
Expr::constant((pc as u32).wrapping_add(if thumb { 4 } else { 8 }) as u64)
} else {
Expr::reg(u16::from(index), if index == 13 { 64 } else { 32 })
}
}
fn operand(&self, op: Operand, pc: u64, thumb: bool) -> Option<Expr> {
let carry = self
.out
.flags
.pending
.as_ref()
.map_or(Test::Unknown, |flags| flags.test(Cond::Cs, Isa::Arm32))
.select(Expr::constant(1), Expr::constant(0));
Self::operand_value(op, pc, thumb, carry.as_ref())
}
fn operand_value(op: Operand, pc: u64, thumb: bool, carry: Option<&Expr>) -> Option<Expr> {
match op {
Operand::Reg(reg) => Some(Self::read(reg.number(), pc, thumb)),
Operand::Imm12(value) => Some(Expr::constant(u64::from(value))),
Operand::Imm32(value) => Some(Expr::constant(u64::from(value))),
Operand::RegShift(shift) => {
let (reg, style, amount) = match shift.into_shift() {
RegShiftStyle::RegImm(shift) => (
shift.shiftee(),
shift.stype(),
Expr::constant(u64::from(shift.imm())),
),
RegShiftStyle::RegReg(shift) => (
shift.shiftee(),
shift.stype(),
Expr::bin(
BinOp::And,
Self::read(shift.shifter().number(), pc, thumb),
Expr::constant(255),
),
),
};
let value = Self::read(reg.number(), pc, thumb);
if style == ShiftStyle::RRX {
let Some(carry) = carry else { return None };
Some(Expr::bin(
BinOp::Or,
Expr::bin(BinOp::Shr, value, Expr::constant(1)),
Expr::bin(BinOp::Shl, carry.clone(), Expr::constant(31)),
))
} else {
shift_value(value, style, amount)
}
}
_ => None,
}
}
fn assign(&mut self, index: u8, value: Expr) {
let index = u16::from(index);
self.out.preserve(Write::Register(index, Some(&value)));
let frame = matches!(index, 7 | 11)
&& match &value {
Expr::Reg {
index: 13,
width: 64,
} => true,
Expr::Bin { lhs, .. } => matches!(
lhs.as_ref(),
Expr::Reg {
index: 13,
width: 64
}
),
_ => false,
};
let value = if index == 13 || frame {
value
} else {
low(value)
};
self.out.stmts.push(Stmt::Assign {
dest: RegRef { index, width: 64 },
value,
at: None,
});
}
fn memory(&self, op: Operand, pc: u64, thumb: bool) -> Option<(Expr, Option<(u8, Expr)>)> {
let (base, offset, add, pre, back) = match op {
Operand::RegDeref(reg) => (reg, Expr::constant(0), true, true, false),
Operand::RegDerefPreindexOffset(reg, offset, add, back) => {
(reg, Expr::constant(u64::from(offset)), add, true, back)
}
Operand::RegDerefPostindexOffset(reg, offset, add, _) => {
(reg, Expr::constant(u64::from(offset)), add, false, true)
}
Operand::RegDerefPreindexReg(reg, offset, add, back) => {
(reg, Self::read(offset.number(), pc, thumb), add, true, back)
}
Operand::RegDerefPostindexReg(reg, offset, add, _) => (
reg,
Self::read(offset.number(), pc, thumb),
add,
false,
true,
),
Operand::RegDerefPreindexRegShift(reg, offset, add, back) => {
let Some(offset) = self.operand(Operand::RegShift(offset), pc, thumb) else {
return None;
};
(reg, offset, add, true, back)
}
Operand::RegDerefPostindexRegShift(reg, offset, add, _) => {
let Some(offset) = self.operand(Operand::RegShift(offset), pc, thumb) else {
return None;
};
(reg, offset, add, false, true)
}
_ => return None,
};
let number = base.number();
let base = if matches!(number, 7 | 11 | 13) {
Expr::reg(u16::from(number), 64)
} else if number == 15 && thumb {
Expr::constant(u64::from((pc as u32).wrapping_add(4) & !3))
} else {
Self::read(number, pc, thumb)
};
let adjusted = Expr::bin(
if add { BinOp::Add } else { BinOp::Sub },
base.clone(),
offset,
);
let adjusted = if matches!(number, 7 | 11 | 13) {
adjusted
} else {
low(adjusted)
};
Some((
if pre { adjusted.clone() } else { base },
back.then_some((number, adjusted)),
))
}
fn execute(
&mut self,
instruction: &Instruction,
pc: u64,
next: u64,
target: Option<u64>,
) -> Option<bool> {
if matches!(instruction.opcode, Opcode::BL | Opcode::BLX) {
self.float_comparison = false;
}
let [a, b, c, d] = instruction.operands;
let carry = self
.out
.flags
.pending
.as_ref()
.map_or(Test::Unknown, |flags| flags.test(Cond::Cs, Isa::Arm32))
.select(Expr::constant(1), Expr::constant(0));
let overflow = self
.out
.flags
.pending
.as_ref()
.map_or(Test::Unknown, |flags| flags.test(Cond::Vs, Isa::Arm32))
.select(Expr::constant(1), Expr::constant(0));
let operand = |op| Self::operand_value(op, pc, instruction.thumb, carry.as_ref());
match instruction.opcode {
Opcode::NOP | Opcode::IT => {}
Opcode::B => {
self.out.stmts.push(Stmt::Br { target, at: None });
return Some(true);
}
Opcode::CBZ | Opcode::CBNZ => {
let (Some(lhs), Some(target)) = (operand(a), target) else {
return None;
};
self.out.stmts.push(Stmt::Brif {
cond: if instruction.opcode == Opcode::CBZ {
Cond::Eq
} else {
Cond::Ne
},
lhs,
rhs: Expr::constant(0),
target,
at: None,
});
return Some(true);
}
Opcode::BX if matches!(a, Operand::Reg(reg) if reg.number() == 14) => {
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(0, 32),
at: None,
});
return Some(true);
}
Opcode::TBB => {
let Operand::RegDerefPreindexReg(base, index, true, false) = a else {
return None;
};
if base.number() != 15 || index.number() == 15 {
return None;
}
let table = Expr::constant(u64::from((pc as u32).wrapping_add(4)));
let entry = Expr::Load {
addr: Box::new(low(Expr::bin(
BinOp::Add,
table.clone(),
low(Self::read(index.number(), pc, instruction.thumb)),
))),
width: 1,
signed: false,
};
self.out.stmts.push(Stmt::BrIndirect {
target: low(Expr::bin(
BinOp::Add,
table,
Expr::bin(BinOp::Shl, entry, Expr::constant(1)),
)),
at: None,
});
return Some(true);
}
Opcode::BX => {
let Some(value) = operand(a) else {
return None;
};
self.out.stmts.push(Stmt::BrIndirect {
target: low(value),
at: None,
});
return Some(true);
}
Opcode::BL | Opcode::BLX => {
if target.is_some_and(|target| unsupported_declaration(self.image, target)) {
self.out
.stmts
.push(Stmt::unsupported("AAPCS32 callee declaration"));
}
let through = if target.is_none() {
let Some(value) = operand(a) else {
return None;
};
Some(low(value))
} else {
None
};
if let Some(through) = through {
self.assign_temp(through);
self.assign(14, Expr::constant(next | u64::from(instruction.thumb)));
self.out.stmts.push(super::call_through(
CallKind::Invoke,
self.image,
Expr::reg(vlk_ir::ir::EXCHANGE, 64),
));
} else {
self.assign(14, Expr::constant(next | u64::from(instruction.thumb)));
self.out
.stmts
.push(super::calls::bare(CallKind::Invoke, self.image, target));
}
self.out.flags.pending = None;
self.out.flags.touched = true;
}
Opcode::MOV | Opcode::MVN | Opcode::MOVT => {
let Operand::Reg(reg) = a else {
return None;
};
if reg.number() == 15 {
if matches!(b, Operand::Reg(reg) if reg.number() == 14)
&& instruction.opcode == Opcode::MOV
&& !instruction.s
{
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(0, 32),
at: None,
});
return Some(true);
}
return None;
}
let source = if instruction.opcode == Opcode::MVN && c != Operand::Nothing {
c
} else {
b
};
let Some(mut value) = operand(source) else {
return None;
};
if instruction.opcode == Opcode::MVN {
value = Expr::bin(BinOp::Xor, value, Expr::constant(0xffff_ffff));
}
if instruction.opcode == Opcode::MOVT {
value = Expr::bin(
BinOp::Or,
Expr::bin(
BinOp::And,
Self::read(reg.number(), pc, instruction.thumb),
Expr::constant(65535),
),
Expr::bin(BinOp::Shl, value, Expr::constant(16)),
);
}
if instruction.s {
let shifted_carry = match source {
Operand::RegShift(shift) => match shift.into_shift() {
RegShiftStyle::RegImm(shift) => shifted_carry(
Self::read(shift.shiftee().number(), pc, instruction.thumb),
shift.stype(),
&Expr::constant(u64::from(shift.imm())),
carry.clone(),
),
_ => None,
},
_ => None,
};
let flags = match shifted_carry {
Some(shifted_carry) => shift_flags(value.clone(), shifted_carry, overflow),
None => Flags::result(low(value.clone())),
};
self.set_flags(flags);
}
self.assign(reg.number(), value);
}
Opcode::ADR => {
let (Operand::Reg(reg), Some(Expr::Const(offset))) =
(a, operand(if c == Operand::Nothing { b } else { c }))
else {
return None;
};
if reg.number() == 15 {
return None;
}
let base = (pc as u32).wrapping_add(if instruction.thumb { 4 } else { 8 });
let add = if instruction.thumb {
true
} else {
let Some(bytes) = self.image.read_vaddr(pc, 4) else {
return None;
};
let [a, b, c, d] = bytes else { return None };
u32::from_le_bytes([*a, *b, *c, *d]) & (1 << 23) != 0
};
let address = if add {
(base & !3).wrapping_add(offset as u32)
} else {
(base & !3).wrapping_sub(offset as u32)
};
self.assign(reg.number(), Expr::constant(u64::from(address)));
}
Opcode::ADD
| Opcode::SUB
| Opcode::RSB
| Opcode::AND
| Opcode::ORR
| Opcode::ORN
| Opcode::EOR
| Opcode::BIC
| Opcode::MUL
| Opcode::CMP
| Opcode::CMN
| Opcode::TST
| Opcode::TEQ
| Opcode::LSL
| Opcode::LSR
| Opcode::ASR
| Opcode::ROR => return self.arithmetic(instruction, pc, carry, overflow),
Opcode::ADC | Opcode::SBC | Opcode::RSC => {
return self.carry_arithmetic(instruction, pc, carry);
}
Opcode::SDIV | Opcode::UDIV => {
let Operand::Reg(reg) = a else {
return None;
};
if reg.number() == 15 {
return None;
}
let (Some(lhs), Some(rhs)) = (operand(b), operand(c)) else {
return None;
};
let value = divide(lhs, rhs, instruction.opcode == Opcode::SDIV);
self.assign(reg.number(), value);
}
Opcode::UMULL | Opcode::SMULL | Opcode::UMLAL | Opcode::SMLAL => {
let (Operand::Reg(lo), Operand::Reg(hi), Some(left), Some(right)) =
(a, b, operand(c), operand(d))
else {
return None;
};
if lo.number() == 15 || hi.number() == 15 || lo == hi || instruction.s {
return None;
}
let signed = matches!(instruction.opcode, Opcode::SMULL | Opcode::SMLAL);
let extend = |value| {
if signed {
Expr::SignExtend {
value: Box::new(value),
width: 4,
}
} else {
low(value)
}
};
let mut value = Expr::bin(BinOp::Mul, extend(left), extend(right));
if matches!(instruction.opcode, Opcode::UMLAL | Opcode::SMLAL) {
value = Expr::bin(
BinOp::Add,
value,
super::pairs32::join(
Self::read(lo.number(), pc, instruction.thumb),
Self::read(hi.number(), pc, instruction.thumb),
),
);
}
self.assign_temp(value);
self.assign(lo.number(), Expr::reg(vlk_ir::ir::EXCHANGE, 64));
self.assign(
hi.number(),
Expr::bin(
BinOp::Shr,
Expr::reg(vlk_ir::ir::EXCHANGE, 64),
Expr::constant(32),
),
);
}
Opcode::MLA | Opcode::MLS => {
let Operand::Reg(reg) = a else {
return None;
};
if reg.number() == 15 || instruction.s {
return None;
}
let (Some(left), Some(right), Some(addend)) = (operand(b), operand(c), operand(d))
else {
return None;
};
let product = Expr::bin(BinOp::Mul, left, right);
let value = Expr::bin(
if instruction.opcode == Opcode::MLS {
BinOp::Sub
} else {
BinOp::Add
},
addend,
product,
);
self.assign(reg.number(), value);
}
Opcode::UXTB | Opcode::UXTH | Opcode::SXTB | Opcode::SXTH => {
let Operand::Reg(reg) = a else {
return None;
};
if reg.number() == 15 {
return None;
}
let rotation = match c {
Operand::Nothing => 0,
Operand::Ror(rotation) if rotation <= 24 && rotation % 8 == 0 => rotation,
_ => return None,
};
let width = if matches!(instruction.opcode, Opcode::UXTB | Opcode::SXTB) {
1
} else {
2
};
let Some(value) = operand(b) else {
return None;
};
let value = extend(
value,
width,
matches!(instruction.opcode, Opcode::SXTB | Opcode::SXTH),
rotation,
);
self.assign(reg.number(), value);
}
Opcode::REV => {
let Operand::Reg(destination) = a else {
return None;
};
let Some(value) = operand(b) else {
return None;
};
if destination.number() == 15 {
return None;
}
self.assign(destination.number(), super::reverse_bytes(value, 32, 4));
}
Opcode::UBFX => {
let Operand::Reg(destination) = a else {
return None;
};
let (Some(value), Some(Expr::Const(start)), Some(Expr::Const(width))) =
(operand(b), operand(c), operand(d))
else {
return None;
};
if destination.number() == 15 || width == 0 || width > 32 || start > 32 - width {
return None;
}
self.assign(destination.number(), bitfield(value, start, width));
}
Opcode::LDRD | Opcode::STRD => {
let (Operand::Reg(first), Operand::Reg(second)) = (a, b) else {
return None;
};
let load = instruction.opcode == Opcode::LDRD;
if first.number() == 15 || second.number() == 15 || (load && first == second) {
return None;
}
let Some((mut addr, writeback)) = self.memory(c, pc, instruction.thumb) else {
return None;
};
if load {
let mut reads = HashSet::new();
if let Some((base, value)) = &writeback {
vlk_ir::ir::visit::collect_reads(value, &mut reads);
if *base == first.number()
|| *base == second.number()
|| reads.contains(&u16::from(first.number()))
|| reads.contains(&u16::from(second.number()))
{
return None;
}
}
reads.clear();
vlk_ir::ir::visit::collect_reads(&addr, &mut reads);
if reads.contains(&u16::from(first.number())) {
self.assign_temp(addr);
addr = Expr::reg(vlk_ir::ir::EXCHANGE, 64);
}
}
let registers = [first, second].into_iter().enumerate();
for (position, register) in registers {
let address = Expr::bin(
BinOp::Add,
addr.clone(),
Expr::constant(position as u64 * 4),
);
if load {
let value =
literal(self.image, &address, 4, false).unwrap_or_else(|| Expr::Load {
addr: Box::new(address),
width: 4,
signed: false,
});
self.assign(register.number(), value);
} else {
self.out.preserve(Write::Memory);
self.out.stmts.push(Stmt::Store {
addr: address,
value: Self::read(register.number(), pc, instruction.thumb),
width: 4,
at: None,
});
}
}
if let Some((base, value)) = writeback {
self.assign(base, value);
}
}
Opcode::LDR
| Opcode::LDRB
| Opcode::LDRH
| Opcode::LDRSB
| Opcode::LDRSH
| Opcode::STR
| Opcode::STRB
| Opcode::STRH => {
let Operand::Reg(reg) = a else {
return None;
};
let Some((addr, back)) = self.memory(b, pc, instruction.thumb) else {
return None;
};
let load = matches!(
instruction.opcode,
Opcode::LDR | Opcode::LDRB | Opcode::LDRH | Opcode::LDRSB | Opcode::LDRSH
);
let width = match instruction.opcode {
Opcode::LDRB | Opcode::LDRSB | Opcode::STRB => 1,
Opcode::LDRH | Opcode::LDRSH | Opcode::STRH => 2,
_ => 4,
};
if load {
if reg.number() == 15 {
return self.load_program_counter(instruction, addr, back);
}
if let Some((_, value)) = &back {
let mut reads = HashSet::new();
vlk_ir::ir::visit::collect_reads(value, &mut reads);
if reads.contains(&u16::from(reg.number())) {
return None;
}
}
let signed = matches!(instruction.opcode, Opcode::LDRSB | Opcode::LDRSH);
let value =
literal(self.image, &addr, width, signed).unwrap_or_else(|| Expr::Load {
addr: Box::new(addr),
width,
signed,
});
self.assign(reg.number(), value);
if let Some((base, value)) = back {
self.assign(base, value);
}
} else {
let Some(value) = operand(a) else {
return None;
};
self.out.preserve(Write::Memory);
self.out.stmts.push(Stmt::Store {
addr,
value,
width,
at: None,
});
if let Some((base, value)) = back {
self.assign(base, value);
}
}
}
Opcode::PUSH | Opcode::POP | Opcode::LDM(..) | Opcode::STM(..) => {
return self.transfer_multiple(instruction, pc, next);
}
Opcode::RRX => {
let (Operand::Reg(dest), Some(value), Some(carry)) = (a, operand(b), carry) else {
return None;
};
if dest.number() == 15 {
return None;
}
let result = Expr::bin(
BinOp::Or,
Expr::bin(BinOp::Shr, value.clone(), Expr::constant(1)),
Expr::bin(BinOp::Shl, carry, Expr::constant(31)),
);
if instruction.s {
self.set_flags(shift_flags(
result.clone(),
Expr::bin(BinOp::And, value, Expr::constant(1)),
overflow,
));
}
self.assign(dest.number(), result);
}
Opcode::CLZ => {
let (Operand::Reg(dest), Some(value)) = (a, operand(b)) else {
return None;
};
if dest.number() == 15 {
return None;
}
self.assign(
dest.number(),
Expr::Select {
cond: Cond::Eq,
lhs: Box::new(value.clone()),
rhs: Box::new(Expr::constant(0)),
then: Box::new(Expr::constant(32)),
els: Box::new(Expr::apply(
vlk_ir::ir::Operation::CountLeadingZeros(32),
vec![value],
)),
},
);
}
Opcode::UDF | Opcode::BKPT => {
self.out.stmts.push(Stmt::Trap { at: None });
return Some(true);
}
_ => return None,
}
Some(false)
}
fn arithmetic(
&mut self,
instruction: &Instruction,
pc: u64,
carry: Option<Expr>,
overflow: Option<Expr>,
) -> Option<bool> {
let [a, b, c, _] = instruction.operands;
let operand = |op| Self::operand_value(op, pc, instruction.thumb, carry.as_ref());
let compare = matches!(
instruction.opcode,
Opcode::CMP | Opcode::CMN | Opcode::TST | Opcode::TEQ
);
let (left, right) = if compare || c == Operand::Nothing {
(a, b)
} else {
(b, c)
};
let Some(mut lhs) = operand(left) else {
return None;
};
if instruction.thumb
&& matches!(left, Operand::Reg(reg) if reg.number() == 15)
&& matches!(instruction.opcode, Opcode::ADD | Opcode::SUB)
{
lhs = Expr::constant(u64::from((pc as u32).wrapping_add(4) & !3));
}
let frame = matches!(a, Operand::Reg(reg) if matches!(reg.number(), 7 | 11 | 13))
&& matches!(left, Operand::Reg(reg) if reg.number() == 13)
&& matches!(instruction.opcode, Opcode::ADD | Opcode::SUB);
let lhs = if frame { Expr::reg(13, 64) } else { low(lhs) };
let Some(rhs) = operand(right) else {
return None;
};
let rhs = if matches!(
instruction.opcode,
Opcode::LSL | Opcode::LSR | Opcode::ASR | Opcode::ROR
) && matches!(right, Operand::Reg(_))
{
Expr::bin(BinOp::And, rhs, Expr::constant(255))
} else {
low(rhs)
};
let op = match instruction.opcode {
Opcode::ADD | Opcode::CMN => BinOp::Add,
Opcode::SUB | Opcode::CMP | Opcode::RSB => BinOp::Sub,
Opcode::AND | Opcode::BIC | Opcode::TST => BinOp::And,
Opcode::ORR | Opcode::ORN => BinOp::Or,
Opcode::EOR | Opcode::TEQ => BinOp::Xor,
Opcode::MUL => BinOp::Mul,
Opcode::LSL => BinOp::Shl,
Opcode::LSR => BinOp::Shr,
Opcode::ASR => BinOp::Sar,
_ => BinOp::Or,
};
let (lhs, rhs) = if instruction.opcode == Opcode::RSB {
(rhs, lhs)
} else {
(lhs, rhs)
};
let value = match instruction.opcode {
Opcode::LSL | Opcode::LSR | Opcode::ASR | Opcode::ROR => {
let Some(value) = shift_value(
lhs.clone(),
match instruction.opcode {
Opcode::LSL => ShiftStyle::LSL,
Opcode::LSR => ShiftStyle::LSR,
Opcode::ASR => ShiftStyle::ASR,
_ => ShiftStyle::ROR,
},
rhs.clone(),
) else {
return None;
};
value
}
Opcode::BIC | Opcode::ORN => Expr::bin(
op,
lhs.clone(),
Expr::bin(BinOp::Xor, rhs.clone(), Expr::constant(0xffff_ffff)),
),
_ => Expr::bin(op, lhs.clone(), rhs.clone()),
};
if instruction.s || compare {
let flags = match op {
BinOp::Add => Flags::sum(lhs.clone(), rhs.clone()),
BinOp::Sub => Flags::difference(lhs.clone(), rhs.clone()),
_ => Flags::result(low(value.clone())),
};
let shifted = match instruction.opcode {
Opcode::LSL | Opcode::LSR | Opcode::ASR => {
let style = match instruction.opcode {
Opcode::LSL => ShiftStyle::LSL,
Opcode::LSR => ShiftStyle::LSR,
_ => ShiftStyle::ASR,
};
shifted_carry(lhs, style, &rhs, carry.clone())
.map(|out| shift_flags(value.clone(), out, overflow.clone()))
}
_ => None,
};
self.set_flags(shifted.unwrap_or(flags));
}
if !compare {
let Operand::Reg(reg) = a else {
return None;
};
if reg.number() == 15 {
if instruction.opcode != Opcode::ADD || instruction.s || instruction.thumb {
return None;
}
self.out.stmts.push(Stmt::BrIndirect {
target: low(value),
at: None,
});
return Some(true);
}
let value = if frame || (reg.number() == 13 && matches!(op, BinOp::Add | BinOp::Sub)) {
let left = if matches!(left, Operand::Reg(reg) if reg.number() == 13) {
Expr::reg(13, 64)
} else {
let Some(value) = operand(left) else {
return None;
};
value
};
let Some(right) = operand(right) else {
return None;
};
Expr::bin(op, left, right)
} else {
value
};
self.assign(reg.number(), value);
}
Some(false)
}
fn carry_arithmetic(
&mut self,
instruction: &Instruction,
pc: u64,
carry: Option<Expr>,
) -> Option<bool> {
let [a, b, c, _] = instruction.operands;
let operand = |op| Self::operand_value(op, pc, instruction.thumb, carry.as_ref());
let Operand::Reg(destination) = a else {
return None;
};
if destination.number() == 15 {
return None;
}
let (left, right) = if c == Operand::Nothing {
(a, b)
} else {
(b, c)
};
let (Some(left), Some(right)) = (operand(left), operand(right)) else {
return None;
};
let Some(carry) = carry else {
return None;
};
self.assign_temp(carry);
let carry = Expr::reg(vlk_ir::ir::EXCHANGE, 64);
let (left, right) = if instruction.opcode == Opcode::RSC {
(low(right), low(left))
} else {
(low(left), low(right))
};
let subtract = instruction.opcode != Opcode::ADC;
let value = if subtract {
Expr::bin(
BinOp::Sub,
Expr::bin(BinOp::Sub, left.clone(), right.clone()),
Expr::bin(BinOp::Xor, carry.clone(), Expr::constant(1)),
)
} else {
Expr::bin(
BinOp::Add,
Expr::bin(BinOp::Add, left.clone(), right.clone()),
carry.clone(),
)
};
if instruction.s {
let addend = if subtract {
Expr::bin(BinOp::Xor, right.clone(), Expr::constant(0xffff_ffff))
} else {
right.clone()
};
let carry_out = super::flags::carry_out(&left, &addend, carry, 32);
let result = low(value.clone());
let zero = Test::Compare(Cond::Eq, result.clone(), Expr::constant(0))
.select(Expr::constant(64), Expr::constant(0))
.expect("a comparison is decided");
let sign = Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, result.clone(), Expr::constant(24)),
Expr::constant(128),
);
let first = Expr::bin(
BinOp::Xor,
left.clone(),
if subtract {
right.clone()
} else {
result.clone()
},
);
let second = Expr::bin(BinOp::Xor, if subtract { left } else { right }, result);
let overflow = Expr::bin(
BinOp::Shr,
Expr::bin(BinOp::And, first, second),
Expr::constant(31),
);
let byte = Expr::bin(
BinOp::Or,
Expr::bin(BinOp::Or, zero, sign),
Expr::bin(BinOp::Xor, carry_out, Expr::constant(1)),
);
self.set_flags(Flags::stored(byte, Some(overflow)));
}
self.assign(destination.number(), value);
Some(false)
}
fn load_program_counter(
&mut self,
instruction: &Instruction,
addr: Expr,
back: Option<(u8, Expr)>,
) -> Option<bool> {
if instruction.opcode != Opcode::LDR {
return None;
}
if addr == Expr::reg(13, 64)
&& let Some((13, value)) = &back
&& *value == Expr::bin(BinOp::Add, Expr::reg(13, 64), Expr::constant(4))
{
self.assign(13, value.clone());
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(0, 32),
at: None,
});
return Some(true);
}
if matches!(
instruction.operands[1],
Operand::RegDerefPreindexOffset(..)
| Operand::RegDerefPreindexReg(..)
| Operand::RegDerefPreindexRegShift(..)
) && let Some((base, value)) = back
&& base != 15
{
let target = literal(self.image, &addr, 4, false).unwrap_or_else(|| Expr::Load {
addr: Box::new(addr),
width: 4,
signed: false,
});
self.assign_temp(target);
self.assign(base, value);
self.out.stmts.push(Stmt::BrIndirect {
target: Expr::reg(vlk_ir::ir::EXCHANGE, 64),
at: None,
});
return Some(true);
}
None
}
fn transfer_multiple(&mut self, instruction: &Instruction, pc: u64, next: u64) -> Option<bool> {
let [a, b, _, _] = instruction.operands;
let (base, list, load, add, pre, back) = match instruction.opcode {
Opcode::PUSH | Opcode::POP => {
let Operand::RegList(list) = a else {
return None;
};
(
13,
list,
instruction.opcode == Opcode::POP,
instruction.opcode == Opcode::POP,
instruction.opcode == Opcode::PUSH,
true,
)
}
Opcode::LDM(add, pre, _, user) | Opcode::STM(add, pre, _, user)
if instruction.thumb || !user =>
{
let (Operand::RegWBack(reg, back), Operand::RegList(list)) = (a, b) else {
return None;
};
(
reg.number(),
list,
matches!(instruction.opcode, Opcode::LDM(..)),
add,
if instruction.thumb
&& next - pc == 2
&& matches!(instruction.opcode, Opcode::STM(..))
{
false
} else {
pre
},
back,
)
}
_ => return None,
};
if list == 0
|| base == 15
|| (list & (1 << base) != 0 && back)
|| (!load && list & 0x8000 != 0)
{
return None;
}
let count = i64::from(list.count_ones()) * 4;
let first = if add {
if pre { 4 } else { 0 }
} else {
-count + if pre { 0 } else { 4 }
};
let mut address = if base == 13 {
Expr::reg(13, 64)
} else {
Self::read(base, pc, instruction.thumb)
};
if list & (1 << base) != 0 {
self.assign_temp(address);
address = Expr::reg(vlk_ir::ir::EXCHANGE, 64);
}
let mut offset = first;
for index in 0..16u8 {
if list & (1 << index) == 0 {
continue;
}
let addr = Expr::bin(BinOp::Add, address.clone(), Expr::constant(offset as u64));
if load {
if index != 15 {
self.assign(
index,
Expr::Load {
addr: Box::new(addr),
width: 4,
signed: false,
},
);
}
} else {
self.out.preserve(Write::Memory);
self.out.stmts.push(Stmt::Store {
addr,
value: Self::read(index, pc, instruction.thumb),
width: 4,
at: None,
});
}
offset += 4;
}
if back {
self.assign(
base,
Expr::bin(
BinOp::Add,
address,
Expr::constant(if add { count } else { -count } as u64),
),
);
}
if load && list & 0x8000 != 0 {
if base != 13 {
return None;
}
self.out.stmts.push(Stmt::Ret {
value: Expr::reg(0, 32),
at: None,
});
return Some(true);
}
Some(false)
}
fn assign_temp(&mut self, value: Expr) {
self.out
.preserve(Write::Register(vlk_ir::ir::EXCHANGE, Some(&value)));
self.out.stmts.push(Stmt::Assign {
dest: RegRef {
index: vlk_ir::ir::EXCHANGE,
width: 64,
},
value,
at: None,
});
}
fn set_flags(&mut self, mut flags: Flags) {
for operand in flags.operands_mut() {
if matches!(operand, Expr::Const(_)) {
*operand = Expr::Bin {
op: BinOp::And,
lhs: Box::new(operand.clone()),
rhs: Box::new(Expr::constant(0xffff_ffff)),
};
}
}
flags.width = Some(32);
self.out.set_flags(Some(flags));
}
}
fn shifted_carry(value: Expr, style: ShiftStyle, amount: &Expr, old: Option<Expr>) -> Option<Expr> {
if style == ShiftStyle::RRX {
return Some(Expr::bin(BinOp::And, value, Expr::constant(1)));
}
let Expr::Const(amount) = amount else {
return None;
};
let shift = match (style, *amount) {
(_, 0) => return old,
(ShiftStyle::LSL, 1..=32) => 32 - amount,
(ShiftStyle::LSR, 1..=32) | (ShiftStyle::ASR, 1..=31) => amount - 1,
(ShiftStyle::ASR, _) => 31,
(ShiftStyle::ROR, _) => (amount - 1) & 31,
_ => return Some(Expr::constant(0)),
};
Some(Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, value, Expr::constant(shift)),
Expr::constant(1),
))
}
fn shift_flags(value: Expr, carry: Expr, overflow: Option<Expr>) -> Flags {
let result = low(value);
let zero = Test::Compare(Cond::Eq, result.clone(), Expr::constant(0))
.select(Expr::constant(64), Expr::constant(0))
.expect("a comparison is decided");
let sign = Expr::bin(
BinOp::And,
Expr::bin(BinOp::Shr, result, Expr::constant(24)),
Expr::constant(128),
);
Flags::stored(
Expr::bin(
BinOp::Or,
Expr::bin(BinOp::Or, sign, zero),
Expr::bin(BinOp::Xor, carry, Expr::constant(1)),
),
overflow,
)
}
fn shift_value(value: Expr, style: ShiftStyle, amount: Expr) -> Option<Expr> {
let value = if style == ShiftStyle::ASR {
Expr::SignExtend {
value: Box::new(value),
width: 4,
}
} else {
value
};
match style {
ShiftStyle::LSL | ShiftStyle::LSR | ShiftStyle::ASR => {
let op = match style {
ShiftStyle::LSL => BinOp::Shl,
ShiftStyle::LSR => BinOp::Shr,
_ => BinOp::Sar,
};
let beyond = if style == ShiftStyle::ASR {
Expr::bin(BinOp::Sar, value.clone(), Expr::constant(31))
} else {
Expr::constant(0)
};
if let Expr::Const(count) = amount {
return Some(if count >= 32 {
beyond
} else {
Expr::bin(op, value, amount)
});
}
Some(Expr::Select {
cond: Cond::Cs,
lhs: Box::new(amount.clone()),
rhs: Box::new(Expr::constant(32)),
then: Box::new(beyond),
els: Box::new(Expr::bin(op, value, amount)),
})
}
ShiftStyle::ROR => Some(super::rotate(value, amount, 32, true)),
ShiftStyle::RRX => None,
}
}
impl Machine for Lifter<'_> {
type Instruction = Step;
fn out(&mut self) -> &mut super::Emitter {
&mut self.out
}
fn branch_target(&self, instruction: &Step, _: u64) -> Option<u64> {
match instruction {
Step::Guard { target, .. } => Some(*target),
Step::Execute {
target,
instruction,
..
} if matches!(instruction.opcode, Opcode::B | Opcode::CBZ | Opcode::CBNZ) => *target,
_ => None,
}
}
fn step(&mut self, instruction: &Step, _: u64) -> bool {
self.step_instruction(instruction)
}
fn origin(&self, instruction: &Step, pc: u64) -> u64 {
match instruction {
Step::Execute { pc, .. } => *pc,
Step::Guard { .. } => pc,
}
}
fn enter_block(&mut self) {
self.float_comparison = false;
}
}
impl Lifter<'_> {
fn step_instruction(&mut self, instruction: &Step) -> bool {
match instruction {
Step::Guard { condition, target } => {
let test = self
.out
.flags
.pending
.as_ref()
.map_or(Test::Unknown, |flags| flags.test(*condition, Isa::Arm32));
if let Some(branch) = test.branch(*condition, *target) {
self.out.stmts.push(branch);
return true;
}
false
}
Step::Execute {
instruction,
additional,
pc,
next,
target,
} => {
if let Some(extra) = additional {
extra.execute(self, *pc, instruction.thumb);
return false;
}
let first = self.out.stmts.len();
match self.execute(instruction, *pc, *next, *target) {
Some(ended) => ended,
None => {
self.out.stmts.truncate(first);
self.out
.stmts
.push(Stmt::unsupported(format!("ARM {instruction} at 0x{pc:x}")));
self.out.flags.pending = None;
self.float_comparison = false;
self.out.flags.touched = true;
false
}
}
}
}
}
}
#[cfg(test)]
mod smt_tests;
#[cfg(test)]
mod tests;