vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! The calling convention each function of an image follows.

mod i386;

use vlk_base::target::Isa;
use vlk_loader::loader::Image;

/// The calling convention the function at `addr` follows.
pub fn convention_of(image: &Image, addr: u64) -> vlk_types::types::Convention {
    if image.isa == Isa::I386 {
        return i386::properties(image, addr).0;
    }
    if image.go
        && matches!(image.isa, Isa::X86_64 | Isa::AArch64)
        && image
            .go_abi0
            .get_or_init(|| assembly_callees(image))
            .contains(&addr)
    {
        return if image.isa == Isa::AArch64 {
            vlk_types::types::Convention::GoAbi0Arm64
        } else {
            vlk_types::types::Convention::GoAbi0
        };
    }
    vlk_types::types::Convention::of(image.isa, image.format, image.go)
}

pub fn callee_cleanup(image: &Image, addr: u64) -> Option<u16> {
    if image.isa == Isa::I386 {
        i386::properties(image, addr).1
    } else {
        Some(0)
    }
}

/// The targets of the direct calls `xorps xmm15, xmm15` follows: Go
/// zeroes xmm15 again after calling into the assembly ABI, which uses it.
/// On `AArch64`, the functions written in assembly that reach their
/// caller's frame.
fn assembly_callees(image: &Image) -> std::collections::HashSet<u64> {
    if image.isa == Isa::AArch64 {
        return arm64_assembly_callees(image);
    }
    let mut callees = std::collections::HashSet::new();
    // ABI0-to-register wrappers initialize the fixed registers before
    // their call, rather than restoring them after an assembly call.
    for function in image.functions.values() {
        let Some(size) = function.size else {
            continue;
        };
        let Some(bytes) = image.read_vaddr(function.addr, size.min(128)) else {
            continue;
        };
        let mut decoder =
            iced_x86::Decoder::with_ip(64, bytes, function.addr, iced_x86::DecoderOptions::NONE);
        while decoder.can_decode() {
            let at = decoder.position();
            let instruction = decoder.decode();
            if instruction.is_invalid() {
                break;
            }
            if bytes.get(at..at.saturating_add(18)).is_some_and(|window| {
                window[..14]
                    == [
                        0x45, 0x0f, 0x57, 0xff, // xorps xmm15, xmm15
                        0x64, 0x4c, 0x8b, 0x34, 0x25, 0xf8, 0xff, 0xff,
                        0xff, // mov r14, fs:[-8]
                        0xe8,
                    ]
            }) {
                callees.insert(function.addr);
                break;
            }
            if matches!(
                instruction.flow_control(),
                iced_x86::FlowControl::Return
                    | iced_x86::FlowControl::UnconditionalBranch
                    | iced_x86::FlowControl::IndirectBranch
            ) {
                break;
            }
        }
    }
    for section in image.sections.iter().filter(|section| section.executable) {
        let Some(bytes) = image.read_vaddr(section.vaddr, section.size) else {
            continue;
        };
        for at in 0..bytes.len().saturating_sub(8) {
            if bytes[at] != 0xe8 || bytes[at + 5..at + 9] != [0x45, 0x0f, 0x57, 0xff] {
                continue;
            }
            let displacement =
                i32::from_le_bytes(bytes[at + 1..at + 5].try_into().expect("four bytes"));
            callees
                .insert((section.vaddr + at as u64 + 5).wrapping_add(displacement as i64 as u64));
        }
    }
    callees
}

/// The functions the pclntab flags as written in assembly whose code
/// loads or stores past the stack pointer it found on entry: arguments
/// and results, which Go's assembly ABI passes on the stack. The others,
/// such as `memmove`, take Go's register ABI, which leaves the caller's
/// frame to the caller, or take nothing.
fn arm64_assembly_callees(image: &Image) -> std::collections::HashSet<u64> {
    use yaxpeax_arch::Decoder;
    use yaxpeax_arm::armv8::a64::{InstDecoder, Opcode, Operand};
    let Some(assembly) = vlk_loader::loader::go::assembly_functions(image) else {
        return std::collections::HashSet::new();
    };
    let decoder = InstDecoder::default();
    assembly
        .into_iter()
        .filter(|addr| {
            let Some(size) = image.functions.get(addr).and_then(|function| function.size) else {
                return false;
            };
            let Some(bytes) = image.read_vaddr(*addr, size) else {
                return false;
            };
            // How far the code moved the stack pointer down, counting
            // each move down and none back up: code after a return may
            // still run in the frame the return left.
            let mut frame: i64 = 0;
            for word in bytes.as_chunks::<4>().0 {
                let mut reader = yaxpeax_arch::U8Reader::new(word);
                let Ok(instruction) = decoder.decode(&mut reader) else {
                    continue;
                };
                let operands = &instruction.operands;
                if instruction.opcode == Opcode::SUB
                    && matches!(operands[0], Operand::RegisterOrSP(_, 31))
                    && matches!(operands[1], Operand::RegisterOrSP(_, 31))
                {
                    match operands[2] {
                        Operand::Immediate(value) => frame += i64::from(value),
                        Operand::ImmShift(value, shift) => {
                            frame += i64::from(value) << shift;
                        }
                        _ => {}
                    }
                    continue;
                }
                for operand in operands {
                    match *operand {
                        Operand::RegPreIndex(31, offset, true) if offset < 0 => {
                            frame -= i64::from(offset);
                        }
                        Operand::RegPreIndex(31, offset, false)
                            if i64::from(offset) >= frame + 8 =>
                        {
                            return true;
                        }
                        _ => {}
                    }
                }
            }
            false
        })
        .collect()
}

#[cfg(test)]
mod tests;