vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Values that code reads from the literal pools between its functions.

use std::collections::HashSet;

use yaxpeax_arm::armv7::{self, Instruction, Opcode, Operand};

use super::instruction_fallback;
use vlk_ir::ir::{Block, Expr, Stmt};
use vlk_loader::loader::{ArmMode, Image};
use vlk_program::program::Program;

/// Resolves only destinations decoded in the instruction mode selected by the load.
pub(in crate::lift) fn resolve_internal_pc_loads(
    program: &Program,
    blocks: &mut [Block],
    starts: &HashSet<u64>,
) -> HashSet<u64> {
    let image = &program.image;
    if !blocks.iter().any(|block| {
        matches!(block.stmts.last(),
        Some(Stmt::BrIndirect { target, .. }) if *target == Expr::reg(vlk_ir::ir::EXCHANGE, 64))
    }) {
        return HashSet::new();
    }
    let proven = crate::analysis::constant_branch_targets(blocks, program);
    let mut targets = HashSet::new();
    for block in blocks {
        if !matches!(block.stmts.last(), Some(Stmt::BrIndirect { target, .. })
            if *target == Expr::reg(vlk_ir::ir::EXCHANGE, 64))
        {
            continue;
        }
        let Some(&value) = proven.get(&block.start) else {
            continue;
        };
        let destination = value & !1;
        let mode = if value & 1 != 0 {
            ArmMode::Thumb
        } else {
            ArmMode::Arm
        };
        if starts.contains(&destination)
            && image.arm_mode(destination) == mode
            && (mode == ArmMode::Thumb || destination & 3 == 0)
        {
            targets.insert(destination);
            *block.stmts.last_mut().expect("indirect branch") = Stmt::Br {
                target: Some(destination),
                at: block.stmts.last().and_then(Stmt::origin),
            };
        }
    }
    targets
}

pub fn literal(image: &Image, addr: &Expr, width: u8, signed: bool) -> Option<Expr> {
    if !matches!(width, 1 | 2 | 4 | 8) {
        return None;
    }
    let Expr::Const(address) = addr else {
        return None;
    };
    let Some(end) = address.checked_add(u64::from(width)) else {
        return None;
    };
    if !image
        .literal_sections
        .iter()
        .any(|section| section.contains(address) && end <= section.end)
        || image
            .literal_relocations
            .range(address.saturating_sub(7)..end)
            .next()
            .is_some()
    {
        return None;
    }
    let Some(bytes) = image.read_vaddr(*address, u64::from(width)) else {
        return None;
    };
    let mut value = 0;
    for (index, byte) in bytes.iter().enumerate() {
        value |= u64::from(*byte) << (index * 8);
    }
    Some(if signed {
        Expr::SignExtend {
            value: Box::new(Expr::constant(value)),
            width,
        }
    } else {
        Expr::constant(value)
    })
}

pub(super) fn double_literal(bytes: &[u8]) -> Option<Instruction> {
    let [a, b, c, d, ..] = bytes else { return None };
    let word = u32::from_le_bytes([*a, *b, *c, *d]);
    let register = ((word >> 12) & 15) as u8;
    if word >> 28 >= 15 || word & 0x0f7f_00f0 != 0x014f_00d0 || register & 1 != 0 || register >= 14
    {
        return None;
    }
    Some(Instruction {
        condition: instruction_fallback::condition((word >> 28) as u8),
        opcode: Opcode::LDRD,
        operands: [
            Operand::Reg(armv7::Reg::from_u8(register)),
            Operand::Reg(armv7::Reg::from_u8(register + 1)),
            Operand::RegDerefPreindexOffset(
                armv7::Reg::from_u8(15),
                (((word >> 4) & 0xf0) | (word & 15)) as u16,
                word & (1 << 23) != 0,
                false,
            ),
            Operand::Nothing,
        ],
        ..Instruction::default()
    })
}

pub fn fold_literals(ir: &mut vlk_ir::ir::FunctionIr, image: &Image) {
    if image.literal_sections.is_empty() {
        return;
    }
    fn fold(expr: &mut Expr, image: &Image) {
        for child in vlk_ir::ir::visit::children_mut(expr) {
            fold(child, image);
        }
        if let Expr::Load {
            addr,
            width,
            signed,
        } = expr
            && let Some(value) = literal(image, addr, *width, *signed)
        {
            *expr = value;
        }
    }
    for block in &mut ir.blocks {
        for stmt in &mut block.stmts {
            match stmt {
                Stmt::Assign { value, .. } | Stmt::Ret { value, .. } => fold(value, image),
                Stmt::Store { addr, value, .. } => {
                    fold(addr, image);
                    fold(value, image);
                }
                Stmt::Brif { lhs, rhs, .. } => {
                    fold(lhs, image);
                    fold(rhs, image);
                }
                Stmt::Call { through, args, .. } => {
                    if let Some(through) = through {
                        fold(through, image);
                    }
                    for arg in args.iter_mut().flatten() {
                        fold(arg, image);
                    }
                }
                _ => {}
            }
        }
    }
}