vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
use super::{Calls, bare};
use crate::lift::call_through_as;
use crate::lift::constants::{Known, Rules};
use vlk_arch::arch::mips32::{FP, GP, SP};
use vlk_base::target::Isa;
use vlk_ir::ir::{BinOp, Expr, RegRef, Stmt, Table};
use vlk_loader::loader::{Image, Summary};
use vlk_types::types::{CallKind, Convention};

const START: u64 = 0x1000;
const CALLEE: u64 = 0x2000;
/// t9, as the IR numbers it.
const T9: u16 = 15;

fn image(isa: Isa) -> Image {
    Image::from_code(isa, START, vec![0; 64])
}

fn mips() -> Rules {
    Rules {
        at_entry: Known::from([(T9, START)]),
        fixed: &[GP],
        frame: &[SP, FP],
        saved: &[16],
        folds: true,
        calls_through_registers: true,
    }
}

fn assign(index: u16, value: Expr) -> Stmt {
    Stmt::Assign {
        dest: RegRef { index, width: 64 },
        value,
        at: None,
    }
}

fn returns() -> Stmt {
    Stmt::Ret {
        value: Expr::reg(vlk_arch::arch::RETURN, 32),
        at: None,
    }
}

/// Settles `stmts` as the statements of one instruction that begins a
/// function, and says whether they end the block.
fn settle(image: &Image, rules: Rules, summary: Summary, stmts: &mut Vec<Stmt>) -> bool {
    let mut calls = Calls::new(rules, START);
    calls.enter(START, None);
    calls.settle(image, &|_| summary, stmts, 0)
}

#[test]
fn a_bare_call_takes_its_arguments_from_the_callee() {
    let image = image(Isa::X86_64);
    let summary = Summary {
        arity: Some(2),
        ..Summary::default()
    };
    let mut stmts = vec![bare(CallKind::Invoke, &image, Some(CALLEE))];
    assert!(!settle(&image, Rules::default(), summary, &mut stmts));
    let [
        Stmt::Call {
            target: Some(CALLEE),
            args: Some(args),
            via: None,
            ..
        },
    ] = stmts.as_slice()
    else {
        panic!("{stmts:?}");
    };
    assert_eq!(args.len(), 2);
}

#[test]
fn a_call_through_a_register_with_a_known_address_is_direct() {
    let image = image(Isa::X86_64);
    let through = |image: &Image| {
        call_through_as(CallKind::Invoke, image, Expr::reg(3, 64), Convention::SysV)
    };
    let mut stmts = vec![assign(3, Expr::Const(CALLEE)), through(&image)];
    assert!(!settle(
        &image,
        Rules::default(),
        Summary::default(),
        &mut stmts
    ));
    // The call says that the code made it through a register.
    assert!(
        matches!(&stmts[1], Stmt::Call { target: Some(CALLEE), through: None, via: Some(via), .. }
            if via.table == Table::Register),
        "{stmts:?}"
    );
    // A register whose value the block does not give stays the way to it.
    let mut stmts = vec![through(&image)];
    settle(&image, Rules::default(), Summary::default(), &mut stmts);
    assert!(
        matches!(
            &stmts[0],
            Stmt::Call {
                target: None,
                through: Some(_),
                ..
            }
        ),
        "{stmts:?}"
    );
    // Where the convention calls through a register, nothing is noted.
    let image = self::image(Isa::Mips32);
    let mut stmts = vec![
        assign(T9, Expr::Const(CALLEE)),
        call_through_as(CallKind::Invoke, &image, Expr::reg(T9, 32), Convention::O32),
    ];
    settle(&image, mips(), Summary::default(), &mut stmts);
    assert!(
        matches!(
            &stmts[1],
            Stmt::Call {
                target: Some(CALLEE),
                via: None,
                ..
            }
        ),
        "{stmts:?}"
    );
}

#[test]
fn a_call_that_does_not_return_ends_the_block() {
    let image = image(Isa::X86_64);
    let summary = Summary {
        noreturn: true,
        ..Summary::default()
    };
    let mut stmts = vec![
        bare(CallKind::Invoke, &image, Some(CALLEE)),
        assign(5, Expr::Const(0)),
    ];
    assert!(settle(&image, Rules::default(), summary, &mut stmts));
    // Nothing of the instruction is left after the trap.
    assert!(
        matches!(stmts.as_slice(), [Stmt::Call { .. }, Stmt::Trap { .. }]),
        "{stmts:?}"
    );
}

#[test]
fn a_jump_to_a_function_ends_as_the_function_does() {
    let image = image(Isa::Mips32);
    let jump = |image: &Image| {
        vec![
            assign(T9, Expr::Const(CALLEE)),
            call_through_as(CallKind::Tail, image, Expr::reg(T9, 32), Convention::O32),
            returns(),
        ]
    };
    let mut stmts = jump(&image);
    assert!(!settle(&image, mips(), Summary::default(), &mut stmts));
    assert!(
        matches!(
            &stmts[1],
            Stmt::Call {
                kind: CallKind::Tail,
                target: Some(CALLEE),
                ..
            }
        ),
        "{stmts:?}"
    );
    assert!(
        matches!(
            &stmts[2],
            Stmt::Ret {
                value: Expr::Reg { width: 64, .. },
                ..
            }
        ),
        "{stmts:?}"
    );
    let never = Summary {
        noreturn: true,
        ..Summary::default()
    };
    let mut stmts = jump(&image);
    settle(&image, mips(), never, &mut stmts);
    assert!(matches!(&stmts[2], Stmt::Trap { .. }), "{stmts:?}");
}

#[test]
fn what_is_known_is_written_into_the_statements_where_the_rules_fold() {
    let image = image(Isa::Mips32);
    let gp = 0x5a_4c90u64;
    let frame = Expr::bin(BinOp::Add, Expr::reg(SP, 64), Expr::Const(16));
    let mut stmts = vec![
        // gp from its two halves and the function's address in t9.
        assign(GP, Expr::Const(gp - START)),
        assign(
            GP,
            Expr::bin(BinOp::Add, Expr::reg(GP, 32), Expr::reg(T9, 32)),
        ),
        // A read of gp inside an address.
        assign(
            2,
            Expr::Load {
                addr: Box::new(Expr::bin(BinOp::Add, Expr::reg(GP, 32), Expr::Const(8))),
                width: 1,
                signed: false,
            },
        ),
        // The reload of gp from the frame.
        assign(
            GP,
            Expr::Load {
                addr: Box::new(frame),
                width: 4,
                signed: false,
            },
        ),
        Stmt::BrIndirect {
            target: Expr::reg(T9, 32),
            at: None,
        },
    ];
    settle(&image, mips(), Summary::default(), &mut stmts);
    assert!(
        matches!(&stmts[1], Stmt::Assign { value: Expr::Const(value), .. } if *value == gp),
        "{stmts:?}"
    );
    assert!(
        matches!(&stmts[2], Stmt::Assign { value: Expr::Load { addr, .. }, .. }
            if **addr == Expr::Const(gp + 8)),
        "{stmts:?}"
    );
    // The reload is left out, and the jump goes to the address t9 holds.
    assert_eq!(stmts.len(), 4, "{stmts:?}");
    assert!(
        matches!(
            &stmts[3],
            Stmt::Br {
                target: Some(START),
                ..
            }
        ),
        "{stmts:?}"
    );
    // Without folding the statements stay as the lifter wrote them.
    let plain = vec![
        assign(1, Expr::Const(4)),
        assign(2, Expr::bin(BinOp::Add, Expr::reg(1, 64), Expr::Const(4))),
    ];
    let mut stmts = plain.clone();
    settle(&image, Rules::default(), Summary::default(), &mut stmts);
    assert_eq!(stmts, plain);
}

#[test]
fn a_call_through_an_import_slot_names_the_slot() {
    let mut image = image(Isa::Mips32);
    let slot = 0x3000;
    image.imports.insert(slot, "puts".to_owned());
    let mut stmts = vec![
        assign(GP, Expr::Const(slot - 8)),
        assign(
            T9,
            Expr::bin(
                BinOp::And,
                Expr::Load {
                    addr: Box::new(Expr::bin(BinOp::Add, Expr::reg(GP, 32), Expr::Const(8))),
                    width: 4,
                    signed: false,
                },
                Expr::Const(0xffff_ffff),
            ),
        ),
        call_through_as(CallKind::Invoke, &image, Expr::reg(T9, 32), Convention::O32),
    ];
    settle(&image, mips(), Summary::default(), &mut stmts);
    let Stmt::Call {
        target: None,
        through: Some(Expr::Load { addr, width: 4, .. }),
        ..
    } = &stmts[2]
    else {
        panic!("{stmts:?}");
    };
    assert_eq!(**addr, Expr::Const(slot));
}