vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Scanning `AArch64` code: where functions start and what the startup
//! code passes to the C runtime.

use vlk_loader::loader::Image;
use vlk_loader::loader::discover::read_word;

/// Function starts in a stripped `AArch64` image: the first non-padding
/// instruction after a return, trap or tail call, unless a branch targets it.
pub(super) fn function_starts(
    bytes: &[u8],
    base: u64,
    relocated: &std::collections::HashSet<u64>,
) -> Vec<u64> {
    let targets = branch_targets(bytes, base);
    let mut starts = Vec::new();
    let mut offset = 0usize;
    let mut closed = false;
    while offset + 4 <= bytes.len() {
        let Some(word) = read_word(bytes, offset) else {
            offset += 4;
            continue;
        };
        let padding = is_padding(word);
        if closed && !padding {
            // A branch target after a return is still part of the same function.
            if !targets.contains(&(base + offset as u64)) {
                starts.push(base + offset as u64);
            }
            closed = false;
        }
        if padding {
            offset += 4;
            continue;
        }
        // `ret`, `retaa` and `brk #0` end a function. So does `br`, an
        // indirect tail call, unless it dispatches a jump table, whose cases
        // follow it.
        if matches!(word, 0xd65f_03c0 | 0xd65f_0bff | 0xd420_0000) {
            closed = true;
        } else if word & 0xffff_fc1f == 0xd61f_0000 {
            let previous = offset.checked_sub(4).and_then(|at| read_word(bytes, at));
            closed = !previous.is_some_and(|previous| table_dispatch(previous, word))
                || read_word(bytes, offset + 4).is_none_or(is_padding);
        } else if let Some(target) = tail_jump(word, base + offset as u64) {
            let pc = base + offset as u64;
            // A branch to itself or one with a pending relocation is an
            // unresolved call; one leaving the section is a tail call.
            if target == pc
                || !(base..base + bytes.len() as u64).contains(&target)
                || relocated.contains(&pc)
            {
                closed = true;
            }
        }
        offset += 4;
    }
    starts.dedup();
    starts
}

/// A jump table's `br` takes the address the instruction before computes as
/// a base plus a scaled entry: `add xd, xbase, xentry, lsl #k` or with an
/// extended register.
fn table_dispatch(previous: u32, br: u32) -> bool {
    let added = previous & 0xff20_0000 == 0x8b00_0000 || previous & 0xffe0_0000 == 0x8b20_0000;
    added && previous & 0x1f == (br >> 5) & 0x1f
}

/// The target of a `b` instruction (unconditional, no link).
fn tail_jump(word: u32, pc: u64) -> Option<u64> {
    // `b`: bits 31..26 = 000101
    if word >> 26 != 0b000101 {
        return None;
    }
    let imm26 = (word & 0x03ff_ffff) as i64;
    let signed = (imm26 << 6) >> 6;
    Some(pc.wrapping_add((signed * 4) as u64))
}

fn branch_targets(bytes: &[u8], base: u64) -> std::collections::HashSet<u64> {
    use yaxpeax_arch::Decoder;
    use yaxpeax_arm::armv8::a64::{self, Opcode, Operand};
    let decoder = a64::InstDecoder::default();
    let mut targets = std::collections::HashSet::new();
    let mut offset = 0usize;
    while offset + 4 <= bytes.len() {
        let mut reader = yaxpeax_arch::U8Reader::new(&bytes[offset..]);
        let Ok(instruction) = decoder.decode(&mut reader) else {
            offset += 4;
            continue;
        };
        let pc = base + offset as u64;
        let branch = match instruction.opcode {
            Opcode::B | Opcode::Bcc(_) => Some(instruction.operands[0]),
            Opcode::CBZ | Opcode::CBNZ => Some(instruction.operands[1]),
            Opcode::TBZ | Opcode::TBNZ => Some(instruction.operands[2]),
            _ => None,
        };
        if let Some(operand) = branch
            && let Operand::PCOffset(delta) = operand
        {
            targets.insert(pc.wrapping_add(delta as u64));
        }
        // Every AArch64 instruction is one word.
        offset += 4;
    }
    targets
}

pub(super) fn is_padding(word: u32) -> bool {
    matches!(
        word,
        0xd503_201f // nop
            | 0xd503_233f // paciasp
            | 0xd503_237f // pacibsp
            | 0xd503_245f // bti c
            | 0xd503_249f // bti j
            | 0x0000_0000
    )
}

/// The address `AArch64` startup code passes to `__libc_start_main` as `main`.
pub(super) fn startup_main(image: &Image) -> Option<u64> {
    if image.byte_order() != Some(object::Endianness::Little) {
        return None;
    }
    let Some(mut pc) = image.entry else {
        return None;
    };
    let read = |image: &Image, address: u64| {
        if image
            .section_at(address)
            .filter(|section| section.executable)
            .is_none()
        {
            return None;
        }
        let Some(bytes) = image.read_vaddr(address, 4) else {
            return None;
        };
        let Some(value) = bytes.try_into().ok() else {
            return None;
        };
        Some(u32::from_le_bytes(value))
    };
    if read(image, pc) == Some(0xd503201f) {
        let Some(next) = pc.checked_add(4) else {
            return None;
        };
        pc = next;
    }
    for expected in [
        0xd280001d, 0xd280001e, 0xaa0003e5, 0xf94003e1, 0x910023e2, 0x910003e6,
    ] {
        if read(image, pc) != Some(expected) {
            return None;
        }
        let Some(next) = pc.checked_add(4) else {
            return None;
        };
        pc = next;
    }
    let Some(adrp) = read(image, pc) else {
        return None;
    };
    if adrp & 0x9f00_001f != 0x9000_0000 {
        return None;
    }
    let immediate = (((adrp >> 5) & 0x7ffff) << 2 | (adrp >> 29) & 3) as i64;
    let pages = (immediate << 43) >> 43;
    let Some(page) = (pc & !0xfff).checked_add_signed(pages << 12) else {
        return None;
    };
    let Some(next) = pc.checked_add(4) else {
        return None;
    };
    pc = next;
    let Some(load) = read(image, pc) else {
        return None;
    };
    let argument = if load & 0xffc0_03ff == 0xf940_0000 {
        let Some(slot) = page.checked_add(u64::from((load >> 10) & 0xfff) * 8) else {
            return None;
        };
        if image.imports.contains_key(&slot) {
            return None;
        }
        let Some(bytes) = image.read_vaddr(slot, 8) else {
            return None;
        };
        let Ok(bytes) = bytes.try_into() else {
            return None;
        };
        u64::from_le_bytes(bytes)
    } else if load & 0xffc0_03ff == 0x9100_0000 {
        let Some(address) = page.checked_add(u64::from((load >> 10) & 0xfff)) else {
            return None;
        };
        address
    } else {
        return None;
    };
    for expected in [0xd2800003, 0xd2800004] {
        let Some(next) = pc.checked_add(4) else {
            return None;
        };
        pc = next;
        if read(image, pc) != Some(expected) {
            return None;
        }
    }
    let Some(next) = pc.checked_add(4) else {
        return None;
    };
    pc = next;
    let Some(call) = read(image, pc) else {
        return None;
    };
    if call & 0xfc00_0000 != 0x9400_0000 {
        return None;
    }
    Some(argument)
}