vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Decoding ARM and Thumb code into the steps the lifter takes: an
//! instruction, and before a conditional one the branch that guards it.

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

use super::instruction_fallback;
use super::literals::double_literal;
use crate::lift::Decoded;
use vlk_ir::ir::Cond;
use vlk_loader::loader::{ArmMode, Image};

pub(in crate::lift) enum Step {
    Guard {
        condition: Cond,
        target: u64,
    },
    Execute {
        instruction: Instruction,
        additional: Option<instruction_fallback::Instruction>,
        pc: u64,
        next: u64,
        target: Option<u64>,
    },
}

pub(super) fn signed(value: u32, bits: u32) -> i64 {
    i64::from((value << (32 - bits)) as i32 >> (32 - bits))
}

pub(super) fn target(instruction: &Instruction, bytes: &[u8], pc: u64) -> Option<u64> {
    if !matches!(
        instruction.opcode,
        Opcode::B | Opcode::BL | Opcode::BLX | Opcode::CBZ | Opcode::CBNZ
    ) {
        return None;
    }
    if matches!(instruction.operands[0], Operand::Reg(_))
        && !matches!(instruction.opcode, Opcode::CBZ | Opcode::CBNZ)
    {
        return None;
    }
    let [first, second, ..] = bytes else {
        return None;
    };
    let half = u32::from(u16::from_le_bytes([*first, *second]));
    let offset = if !instruction.thumb {
        let [a, b, c, d, ..] = bytes else {
            return None;
        };
        let word = u32::from_le_bytes([*a, *b, *c, *d]);
        signed((word & 0xffffff) << 2, 26)
            + 8
            + if instruction.opcode == Opcode::BLX {
                i64::from((word >> 23) & 2)
            } else {
                0
            }
    } else if !instruction.wide {
        if matches!(instruction.opcode, Opcode::CBZ | Opcode::CBNZ) {
            i64::from(((half >> 3) & 0x1f) * 2 + ((half >> 9) & 1) * 64) + 4
        } else if half & 0xf000 == 0xd000 {
            signed((half & 255) << 1, 9) + 4
        } else {
            signed((half & 2047) << 1, 12) + 4
        }
    } else {
        let [_, _, third, fourth, ..] = bytes else {
            return None;
        };
        let low = u32::from(u16::from_le_bytes([*third, *fourth]));
        let s = (half >> 10) & 1;
        let j1 = (low >> 13) & 1;
        let j2 = (low >> 11) & 1;
        if low & 0xd000 == 0x8000 {
            signed(
                s << 20 | j2 << 19 | j1 << 18 | (half & 63) << 12 | (low & 2047) << 1,
                21,
            ) + 4
        } else {
            signed(
                s << 24
                    | (1 ^ j1 ^ s) << 23
                    | (1 ^ j2 ^ s) << 22
                    | (half & 1023) << 12
                    | (low & 2047) << 1,
                25,
            ) + 4
        }
    };
    let base = if instruction.thumb && instruction.opcode == Opcode::BLX {
        pc & !3
    } else {
        pc
    };
    Some((base as u32).wrapping_add(offset as u32) as u64 & !1)
}

pub(super) fn decode(
    image: &Image,
    bytes: &[u8],
    addr: u64,
) -> (Vec<Decoded<Step>>, Option<String>) {
    use yaxpeax_arch::{Decoder, ReaderBuilder};

    let mut decoded = Vec::new();
    let mut offset = 0;
    let mut it = 0u8;
    while offset < bytes.len() {
        let Some(pc) = addr.checked_add(offset as u64) else {
            return (decoded, Some("ARM instruction address overflow".into()));
        };
        let mode = image.arm_mode(pc & !1);
        if mode == ArmMode::Data {
            offset += 1;
            continue;
        }
        let decoder = armv7::InstDecoder::default()
            .allow_nonconforming(false)
            .with_thumb_mode(mode == ArmMode::Thumb);
        let mut reader = ReaderBuilder::<u32, u8>::read_at(&bytes[offset..], 0);
        let fallback_instruction = instruction_fallback::decode(&bytes[offset..], mode);
        let mut instruction = match decoder.decode(&mut reader) {
            Ok(instruction) => instruction,
            Err(_) if mode == ArmMode::Arm && double_literal(&bytes[offset..]).is_some() => {
                double_literal(&bytes[offset..]).expect("validated double-word literal encoding")
            }
            Err(_) if fallback_instruction.is_some() => Instruction {
                condition: if mode == ArmMode::Thumb {
                    armv7::ConditionCode::AL
                } else {
                    instruction_fallback::condition(bytes[offset + 3] >> 4)
                },
                thumb: mode == ArmMode::Thumb,
                wide: mode == ArmMode::Thumb,
                ..Instruction::default()
            },
            Err(error) => {
                return (
                    decoded,
                    Some(format!("undecodable ARM instruction at 0x{pc:x}: {error}")),
                );
            }
        };
        let len = if instruction.thumb && !instruction.wide {
            2
        } else {
            4
        };
        let Some(next) = pc.checked_add(len as u64) else {
            return (
                decoded,
                Some(format!("ARM instruction address overflow at 0x{pc:x}")),
            );
        };
        let mut condition = Cond::from_code(instruction.condition as u8);
        if instruction.opcode == Opcode::IT {
            if it != 0 {
                return (decoded, Some(format!("nested IT at 0x{pc:x}")));
            }
            let [Operand::Imm32(cond), Operand::Imm32(mask), ..] = instruction.operands else {
                return (decoded, Some(format!("invalid IT at 0x{pc:x}")));
            };
            it = ((cond << 4) | mask) as u8;
        } else if it != 0 {
            condition = Cond::from_code(it >> 4);
            // Narrow Thumb arithmetic implicitly sets flags only outside IT.
            if !instruction.wide
                && !matches!(instruction.opcode, Opcode::CMP | Opcode::CMN | Opcode::TST)
            {
                instruction.s = false;
            }
            it = if it & 7 == 0 {
                0
            } else {
                (it & 0xe0) | ((it << 1) & 0x1f)
            };
        }
        let destination = image
            .relocations
            .get(&pc)
            .map(|value| value & !1)
            .or_else(|| target(&instruction, &bytes[offset..], pc));
        let body = if let Some(cond) = condition {
            decoded.push(Decoded {
                pc,
                next: pc + 1,
                instruction: Step::Guard {
                    condition: cond.invert(),
                    target: next,
                },
            });
            pc + 1
        } else {
            pc
        };
        decoded.push(Decoded {
            pc: body,
            next,
            instruction: Step::Execute {
                instruction,
                additional: fallback_instruction,
                pc,
                next,
                target: destination,
            },
        });
        offset += len;
    }
    let stop = (it != 0).then(|| "truncated ARM IT block".into());
    (decoded, stop)
}