vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Scanning x86 code: where functions start, how control leaves an
//! instruction, and what the startup code passes to the C runtime.

use iced_x86::{
    Decoder, DecoderOptions, FlowControl, InstructionInfoFactory, Mnemonic, OpAccess, OpKind,
    Register,
};
use vlk_loader::loader::Image;
use vlk_loader::loader::discover::{Step, Transfer};

/// The instruction at the start of `bytes`.
pub(super) fn step(bytes: &[u8], address: u64, bitness: u32) -> Option<Step> {
    let instruction = Decoder::with_ip(bitness, bytes, address, DecoderOptions::NONE).decode();
    if instruction.is_invalid() {
        return None;
    }
    let target = instruction.near_branch_target();
    let transfer = match instruction.flow_control() {
        FlowControl::Call => Transfer::Call(target),
        FlowControl::ConditionalBranch => Transfer::Branch(target),
        FlowControl::UnconditionalBranch => Transfer::Jump(target),
        FlowControl::IndirectBranch => Transfer::IndirectJump,
        FlowControl::Return => Transfer::Return,
        FlowControl::Exception => Transfer::Fault,
        _ if matches!(instruction.mnemonic(), Mnemonic::Int3 | Mnemonic::Hlt) => Transfer::Stop,
        _ => Transfer::Next,
    };
    Some(Step {
        next: instruction.next_ip(),
        transfer,
    })
}

/// True when `target` decodes to padding, where an unresolved jump lands.
fn is_padding(bytes: &[u8], base: u64, target: u64, bitness: u32) -> bool {
    use iced_x86::{Decoder, DecoderOptions, Mnemonic};
    if target < base {
        return false;
    }
    let offset = (target - base) as usize;
    let Some(rest) = bytes.get(offset..) else {
        return false;
    };
    let mut decoder = Decoder::with_ip(bitness, rest, target, DecoderOptions::NONE);
    if !decoder.can_decode() {
        return false;
    }
    matches!(decoder.decode().mnemonic(), Mnemonic::Nop | Mnemonic::Int3)
}

/// Function starts in a stripped x86 image: the first non-padding
/// instruction after a return or tail jump, unless a branch targets it.
/// An indirect jump ends a function unless it dispatches a jump table.
pub(super) fn function_starts(bytes: &[u8], base: u64, bitness: u32) -> Vec<u64> {
    use iced_x86::{Decoder, DecoderOptions, FlowControl};
    // Every conditional branch target, wherever the branch: a later loop
    // may jump back into code an earlier return seemed to end.
    let mut targets = std::collections::HashSet::new();
    // Call targets are function starts, so a jump to one is a tail call.
    let mut called = std::collections::HashSet::new();
    let mut decoder = Decoder::with_ip(bitness, bytes, base, DecoderOptions::NONE);
    while decoder.can_decode() {
        let instruction = decoder.decode();
        match instruction.flow_control() {
            FlowControl::ConditionalBranch => {
                targets.insert(instruction.near_branch_target());
            }
            FlowControl::Call => {
                called.insert(instruction.near_branch_target());
            }
            _ => {}
        }
    }
    let mut decoder = Decoder::with_ip(bitness, bytes, base, DecoderOptions::NONE);
    let mut starts = Vec::new();
    let mut closed = false;
    let mut previous: Option<iced_x86::Instruction> = None;
    while decoder.can_decode() {
        let instruction = decoder.decode();
        let ip = instruction.ip();
        let continued = targets.contains(&ip) && !called.contains(&ip);
        if closed && !continued && ip != base && !is_padding(bytes, base, ip, bitness) {
            starts.push(ip);
            closed = false;
        } else if closed && continued && !is_padding(bytes, base, ip, bitness) {
            // A branch target of the previous function: it continues here.
            closed = false;
        }
        match instruction.flow_control() {
            FlowControl::UnconditionalBranch => {
                let target = instruction.near_branch_target();
                if !is_padding(bytes, base, target, bitness) {
                    targets.insert(target);
                }
                // A jump to itself or to padding is unresolved; one leaving
                // the section or to a called function is a tail call. All
                // end the function.
                if target == ip
                    || !(base..base.saturating_add(bytes.len() as u64)).contains(&target)
                    || is_padding(bytes, base, target, bitness)
                    || called.contains(&target)
                {
                    closed = true;
                }
            }
            // A jump through a table, or to a register just computed as a
            // table's base plus an entry, dispatches cases that follow.
            FlowControl::IndirectBranch => {
                let through_table = instruction.op0_kind() == iced_x86::OpKind::Memory
                    && instruction.memory_index() != iced_x86::Register::None;
                let computed = instruction.op0_kind() == iced_x86::OpKind::Register
                    && previous.is_some_and(|previous| {
                        previous.mnemonic() == iced_x86::Mnemonic::Add
                            && previous.op0_kind() == iced_x86::OpKind::Register
                            && previous.op0_register() == instruction.op0_register()
                    });
                // Padding after it ends the function all the same: the
                // table held functions, as for a call through a table.
                closed = !(through_table || computed)
                    || is_padding(bytes, base, instruction.next_ip(), bitness);
            }
            FlowControl::Return => closed = true,
            // A trap or halt ends a function, as after a call that does not
            // return.
            _ if matches!(
                instruction.mnemonic(),
                iced_x86::Mnemonic::Int3 | iced_x86::Mnemonic::Ud2 | iced_x86::Mnemonic::Hlt
            ) =>
            {
                closed = true
            }
            _ => {}
        }
        previous = Some(instruction);
    }
    starts
}

/// The address x86-64 startup code passes to `__libc_start_main` as `main`.
pub(super) fn startup_main_64(image: &Image) -> Option<u64> {
    let Some(mut decoder) = entry_decoder(image, 64) else {
        return None;
    };
    let mut info = InstructionInfoFactory::new();
    let mut argument = None;
    let mut startup_arguments = 0u8;
    while decoder.can_decode() {
        let instruction = decoder.decode();
        if instruction.is_invalid() {
            break;
        }
        if matches!(
            instruction.flow_control(),
            FlowControl::Call | FlowControl::IndirectCall
        ) {
            let name = if instruction.flow_control() == FlowControl::Call {
                image
                    .functions
                    .get(&instruction.near_branch_target())
                    .and_then(|function| function.name.as_deref())
            } else if instruction.is_ip_rel_memory_operand()
                && !matches!(instruction.segment_prefix(), Register::FS | Register::GS)
                && image
                    .import_addends
                    .get(&instruction.ip_rel_memory_address())
                    .is_none_or(|addend| *addend == 0)
            {
                image
                    .imports
                    .get(&instruction.ip_rel_memory_address())
                    .map(String::as_str)
            } else {
                None
            };
            if name == Some("__libc_start_main") || startup_arguments == 0b1_1111 {
                return argument;
            }
            break;
        }
        if instruction.flow_control() != FlowControl::Next {
            break;
        }
        for used in info.info(&instruction).used_registers() {
            if used.register().full_register() == Register::RDI
                && matches!(
                    used.access(),
                    OpAccess::Write
                        | OpAccess::CondWrite
                        | OpAccess::ReadWrite
                        | OpAccess::ReadCondWrite
                )
            {
                argument = None;
            }
        }
        if instruction.op0_kind() != OpKind::Register {
            continue;
        }
        if instruction.mnemonic() == Mnemonic::Lea
            && instruction.op0_register() == Register::RDI
            && instruction.is_ip_rel_memory_operand()
        {
            argument = Some(instruction.ip_rel_memory_address());
        } else if instruction.mnemonic() == Mnemonic::Mov
            && matches!(instruction.op0_register(), Register::RDI | Register::EDI)
            && matches!(
                instruction.op1_kind(),
                OpKind::Immediate64 | OpKind::Immediate32to64 | OpKind::Immediate32
            )
        {
            argument = Some(instruction.immediate(1));
        }
        if instruction.mnemonic() == Mnemonic::Mov
            && instruction.op0_kind() == OpKind::Register
            && instruction.op1_kind() == OpKind::Register
        {
            match (instruction.op0_register(), instruction.op1_register()) {
                (Register::R9, Register::RDX) => startup_arguments |= 1,
                (Register::RDX, Register::RSP) => startup_arguments |= 4,
                _ => {}
            }
        } else if instruction.mnemonic() == Mnemonic::Pop
            && instruction.op0_kind() == OpKind::Register
            && instruction.op0_register() == Register::RSI
        {
            startup_arguments |= 2;
        } else if instruction.mnemonic() == Mnemonic::Xor
            && instruction.op0_kind() == OpKind::Register
            && instruction.op1_kind() == OpKind::Register
            && instruction.op0_register() == instruction.op1_register()
        {
            match instruction.op0_register() {
                Register::ECX | Register::RCX => startup_arguments |= 8,
                Register::R8D | Register::R8 => startup_arguments |= 16,
                _ => {}
            }
        }
    }
    None
}

/// The address i386 startup code pushes for `__libc_start_main` as `main`.
pub(super) fn startup_main_32(image: &Image) -> Option<u64> {
    let Some(mut decoder) = entry_decoder(image, 32) else {
        return None;
    };
    let mut info = InstructionInfoFactory::new();
    let mut argument = None;
    let mut startup_arguments = 0u8;
    let mut startup_pushes = 0u8;
    while decoder.can_decode() {
        let instruction = decoder.decode();
        if instruction.is_invalid() {
            return None;
        }
        if instruction.flow_control() == FlowControl::Call {
            let name = image
                .functions
                .get(&instruction.near_branch_target())
                .and_then(|function| function.name.as_deref());
            if name == Some("__libc_start_main") || (startup_arguments == 3 && startup_pushes >= 6)
            {
                return argument;
            }
            return None;
        }
        if instruction.flow_control() != FlowControl::Next {
            return None;
        }
        let used = info.info(&instruction);
        if instruction.mnemonic() == Mnemonic::Push {
            startup_pushes = startup_pushes.saturating_add(1);
            argument = match instruction.op0_kind() {
                OpKind::Immediate32 | OpKind::Immediate8to32 => {
                    Some(instruction.immediate(0) as u32 as u64)
                }
                _ => None,
            };
        } else if used.used_registers().iter().any(|register| {
            register.register().full_register() == Register::RSP
                && matches!(
                    register.access(),
                    OpAccess::Write
                        | OpAccess::CondWrite
                        | OpAccess::ReadWrite
                        | OpAccess::ReadCondWrite
                )
        }) || used.used_memory().iter().any(|memory| {
            matches!(
                memory.access(),
                OpAccess::Write
                    | OpAccess::CondWrite
                    | OpAccess::ReadWrite
                    | OpAccess::ReadCondWrite
            )
        }) {
            argument = None;
        }
        if instruction.mnemonic() != Mnemonic::Push {
            startup_pushes = 0;
        }
        if instruction.mnemonic() == Mnemonic::Pop
            && instruction.op0_kind() == OpKind::Register
            && instruction.op0_register() == Register::ESI
        {
            startup_arguments |= 1;
        } else if instruction.mnemonic() == Mnemonic::Mov
            && instruction.op0_kind() == OpKind::Register
            && instruction.op0_register() == Register::ECX
            && instruction.op1_kind() == OpKind::Register
            && instruction.op1_register() == Register::ESP
        {
            startup_arguments |= 2;
        }
    }
    None
}

fn entry_decoder(image: &Image, bitness: u32) -> Option<Decoder<'_>> {
    let Some(entry) = image.entry else {
        return None;
    };
    let Some(section) = image.section_at(entry).filter(|section| section.executable) else {
        return None;
    };
    let size = section.file_size.saturating_sub(entry - section.vaddr);
    let Some(bytes) = image.read_vaddr(entry, size) else {
        return None;
    };
    Some(Decoder::with_ip(
        bitness,
        bytes,
        entry,
        DecoderOptions::NONE,
    ))
}