vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
use std::collections::HashSet;

use crate::lift::lift;
use vlk_base::target::Isa;
use vlk_eval::eval;
use vlk_ir::ir::{Block, FunctionIr, Stmt};
use vlk_loader::loader::{Function, Image};

/// The code, holding the functions at the given starts and sizes.
fn image(isa: Isa, code: Vec<u8>, functions: &[(u64, u64)]) -> Image {
    let mut image = Image::from_code(isa, 0, code);
    for (addr, size) in functions {
        image.functions.insert(
            *addr,
            Function {
                addr: *addr,
                size: Some(*size),
                size_estimated: false,
                name: None,
                aliases: Vec::new(),
                library: None,
                sources: Vec::new(),
            },
        );
    }
    image
}

fn lifted(program: &vlk_program::program::Program) -> Vec<Block> {
    let size = program.image.functions[&0].size.expect("sized");
    lift(program, 0, size, &HashSet::new()).expect("lifts")
}

fn calls(blocks: &[Block]) -> Vec<Option<u64>> {
    blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .filter_map(|stmt| match stmt {
            Stmt::Call { target, .. } => Some(*target),
            _ => None,
        })
        .collect()
}

/// What the lifted code returns with the given registers.
fn returns(isa: Isa, blocks: Vec<Block>, registers: &[(u16, u64)]) -> u64 {
    let mut ir = FunctionIr::single_block(isa, Vec::new());
    ir.blocks = blocks;
    let setup = eval::Setup {
        seed: 0,
        convention: eval::Convention {
            arguments: &[],
            clobbered: &[],
        },
        registers,
        memory: &[],
        step_limit: 100,
    };
    match eval::run(&ir, &setup) {
        eval::Outcome::Return { value, .. } => value,
        other => panic!("{other:?}\n{}", ir.render()),
    }
}

/// The code, followed at 0x10 by `mov eax, 7; ret`.
fn returning_seven(mut code: Vec<u8>) -> Vec<u8> {
    code.resize(0x10, 0xcc);
    code.extend([0xb8, 7, 0, 0, 0, 0xc3]);
    code
}

#[test]
fn a_jump_to_a_function_with_the_stack_as_on_entry_is_a_tail_call() {
    // jmp 0x10
    let program = vlk_program::program::Program::new(image(
        Isa::X86_64,
        returning_seven(vec![0xeb, 0x0e]),
        &[(0, 2), (0x10, 6)],
    ));
    let blocks = lifted(&program);
    assert_eq!(calls(&blocks), [Some(0x10)]);
    assert_eq!(blocks.len(), 1, "{blocks:?}");
}

#[test]
fn a_jump_after_the_frame_pointer_restores_the_stack_is_a_tail_call() {
    // push rbp; mov rbp, rsp; sub rsp, 16; mov rsp, rbp; pop rbp; jmp 0x10
    let code = vec![
        0x55, 0x48, 0x89, 0xe5, 0x48, 0x83, 0xec, 0x10, 0x48, 0x89, 0xec, 0x5d, 0xeb, 0x02,
    ];
    let program = vlk_program::program::Program::new(image(
        Isa::X86_64,
        returning_seven(code),
        &[(0, 14), (0x10, 6)],
    ));
    assert_eq!(calls(&lifted(&program)), [Some(0x10)]);
}

#[test]
fn a_jump_to_a_function_with_a_value_still_pushed_continues_in_it() {
    // push rbx; jmp 0x10; 0x10: pop rbx; mov eax, 7; ret
    let mut code = vec![0x53, 0xeb, 0x0d];
    code.resize(0x10, 0xcc);
    code.extend([0x5b, 0xb8, 7, 0, 0, 0, 0xc3]);
    let program =
        vlk_program::program::Program::new(image(Isa::X86_64, code, &[(0, 3), (0x10, 7)]));
    let blocks = lifted(&program);
    assert_eq!(calls(&blocks), []);
    assert_eq!(returns(Isa::X86_64, blocks, &[]), 7);
}

#[test]
fn a_conditional_branch_with_a_value_still_pushed_continues_in_its_target() {
    // push rbx; test edi, edi; jne 0x10; pop rbx; xor eax, eax; ret;
    // 0x10: pop rbx; mov eax, 7; ret
    let mut code = vec![0x53, 0x85, 0xff, 0x75, 0x0b, 0x5b, 0x31, 0xc0, 0xc3];
    code.resize(0x10, 0xcc);
    code.extend([0x5b, 0xb8, 7, 0, 0, 0, 0xc3]);
    let program =
        vlk_program::program::Program::new(image(Isa::X86_64, code, &[(0, 9), (0x10, 7)]));
    let blocks = lifted(&program);
    assert_eq!(calls(&blocks), []);
    assert_eq!(returns(Isa::X86_64, blocks.clone(), &[(7, 1)]), 7);
    assert_eq!(returns(Isa::X86_64, blocks, &[(7, 0)]), 0);
}

#[test]
fn a_jump_into_another_function_s_body_continues_there() {
    // jmp 0x12; 0x10: xor eax, eax; mov eax, 7; ret
    let mut code = vec![0xeb, 0x10];
    code.resize(0x10, 0xcc);
    code.extend([0x31, 0xc0, 0xb8, 7, 0, 0, 0, 0xc3]);
    let program =
        vlk_program::program::Program::new(image(Isa::X86_64, code, &[(0, 2), (0x10, 8)]));
    let blocks = lifted(&program);
    assert_eq!(calls(&blocks), []);
    assert_eq!(returns(Isa::X86_64, blocks, &[]), 7);
}

#[test]
fn a_branch_to_padding_goes_on_to_the_code_after_it() {
    // test edi, edi; jne 7; jmp 6; 6: nop; 7: mov eax, 2; ret
    let code = vec![
        0x85, 0xff, 0x75, 0x03, 0xeb, 0x00, 0x90, 0xb8, 2, 0, 0, 0, 0xc3,
    ];
    let program = vlk_program::program::Program::new(image(Isa::X86_64, code, &[(0, 13)]));
    let blocks = lifted(&program);
    assert_eq!(calls(&blocks), []);
    assert_eq!(returns(Isa::X86_64, blocks, &[(7, 0)]), 2);
}

fn words(words: &[u32]) -> Vec<u8> {
    words.iter().flat_map(|word| word.to_le_bytes()).collect()
}

#[test]
fn an_aarch64_branch_is_a_tail_call_only_once_the_frame_is_gone() {
    const NOP: u32 = 0xd503_201f;
    // stp x29, x30, [sp, #-16]!; b 0x10;
    // 0x10: ldp x29, x30, [sp], #16; mov w0, #7; ret
    let framed = words(&[
        0xa9bf_7bfd,
        0x1400_0003,
        NOP,
        NOP,
        0xa8c1_7bfd,
        0x5280_00e0,
        0xd65f_03c0,
    ]);
    let framed_image =
        vlk_program::program::Program::new(image(Isa::AArch64, framed, &[(0, 8), (0x10, 12)]));
    let blocks = lifted(&framed_image);
    assert_eq!(calls(&blocks), []);
    assert_eq!(returns(Isa::AArch64, blocks, &[]), 7);
    // b 0x10; 0x10: mov w0, #7; ret
    let bare = words(&[0x1400_0004, NOP, NOP, NOP, 0x5280_00e0, 0xd65f_03c0]);
    let bare_image =
        vlk_program::program::Program::new(image(Isa::AArch64, bare, &[(0, 4), (0x10, 8)]));
    assert_eq!(calls(&lifted(&bare_image)), [Some(0x10)]);
}