vlk-analysis 0.3.0

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

use super::{decode, function_starts, text};
use vlk_base::target::Isa;
use vlk_eval::eval;
use vlk_ir::ir::{FunctionIr, Stmt};
use vlk_loader::loader::Image;

const RET: u32 = 0x0000_8067;
const NOP: u32 = 0x0000_0013;

fn jal(rd: u32, offset: i32) -> u32 {
    let offset = offset as u32;
    (offset >> 20 & 1) << 31
        | (offset >> 1 & 0x3ff) << 21
        | (offset >> 11 & 1) << 20
        | (offset >> 12 & 0xff) << 12
        | rd << 7
        | 0x6f
}

fn beqz(rs1: u32, offset: i32) -> u32 {
    let offset = offset as u32;
    (offset >> 12 & 1) << 31
        | (offset >> 5 & 0x3f) << 25
        | rs1 << 15
        | (offset >> 1 & 0xf) << 8
        | (offset >> 11 & 1) << 7
        | 0x63
}

fn addi(rd: u32, rs1: u32, immediate: i32) -> u32 {
    (immediate as u32 & 0xfff) << 20 | rs1 << 15 | rd << 7 | 0x13
}

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

fn lifted(bytes: Vec<u8>) -> FunctionIr {
    let size = bytes.len() as u64;
    let program = vlk_program::program::Program::new(Image::from_code(Isa::RiscV64, 0x1000, bytes));
    let mut ir = FunctionIr::single_block(Isa::RiscV64, Vec::new());
    ir.blocks = crate::lift::lift(&program, 0x1000, size, &HashSet::new()).unwrap();
    ir
}

#[test]
fn instructions_decode_to_their_usual_text() {
    for (bytes, expected) in [
        (&[0x33, 0x85, 0xa5, 0x00][..], "add a0, a1, a0"),
        (&[0x82, 0x80], "ret"),
        (&[0x01, 0x00], "nop"),
        (&[0x41, 0x11], "addi sp, sp, -0x10"),
        (&[0x06, 0xe4], "sd ra, 0x8(sp)"),
        (&[0x13, 0x05, 0xb0, 0x07], "li a0, 0x7b"),
        (&[0x3b, 0x05, 0xb5, 0x00], "addw a0, a0, a1"),
        (&[0x53, 0x75, 0xb5, 0x02], "fadd.d fa0, fa0, fa1"),
        (&[0x73, 0x00, 0x00, 0x00], "ecall"),
        (&[0x2f, 0xa5, 0xc5, 0x00], "amoadd.w a0, a2, (a1)"),
    ] {
        let instruction = decode::decode(bytes).unwrap();
        assert_eq!(usize::from(instruction.length), bytes.len());
        assert_eq!(text::text(&instruction, 0x1000), expected);
    }
    assert_eq!(
        text::text(&decode::decode(&jal(0, -8).to_le_bytes()).unwrap(), 0x1000),
        "j 0xff8"
    );
    assert_eq!(
        text::text(
            &decode::decode(&beqz(10, 12).to_le_bytes()).unwrap(),
            0x1000
        ),
        "beqz a0, 0x100c"
    );
}

#[test]
fn words_no_extension_defines_do_not_decode() {
    for bytes in [
        &[0x00, 0x00][..],
        // A rounding mode that is reserved.
        &[0x53, 0x55, 0xb5, 0x02],
        // A longer encoding.
        &[0x1f, 0x00, 0x00, 0x00, 0x00, 0x00],
        // Half of a 32-bit instruction.
        &[0x33, 0x85],
        &[0x33],
        &[],
    ] {
        assert_eq!(decode::decode(bytes), None, "{bytes:x?}");
    }
}

#[test]
fn a_function_starts_after_a_return_unless_its_own_branch_goes_there() {
    // 0x00 f: beqz a0, +12; ret; nop; [0x0c] addi; ret
    // 0x14 g: addi; ret
    let bytes = code(&[
        beqz(10, 12),
        RET,
        NOP,
        addi(10, 10, 1),
        RET,
        addi(10, 10, 2),
        RET,
    ]);
    assert_eq!(function_starts(&bytes, 0x1000), [0x1014]);
}

#[test]
fn a_tail_called_function_starts_where_another_function_jumps() {
    // 0x00 f: j h
    // 0x04 g: addi; ret
    // 0x0c h: addi; ret, reached only by the jump in f
    // 0x14 k: jal ra, m; ret
    // 0x1c m: beqz a0, +8; j +8 (to 0x28, in m); [0x24] ret; [0x28] ret
    let bytes = code(&[
        jal(0, 0x0c),
        addi(10, 10, 1),
        RET,
        addi(10, 10, 2),
        RET,
        jal(1, 0x08),
        RET,
        beqz(10, 8),
        jal(0, 8),
        RET,
        RET,
    ]);
    assert_eq!(
        function_starts(&bytes, 0x1000),
        [0x1004, 0x100c, 0x1014, 0x101c]
    );
}

#[test]
fn a_frame_opened_after_a_call_starts_a_function() {
    // f: jal ra, +16 (a call that does not return); g: addi sp, sp, -16;
    // addi sp, sp, 16; ret; h: ret
    let bytes = code(&[jal(1, 16), addi(2, 2, -16), addi(2, 2, 16), RET, RET]);
    assert_eq!(function_starts(&bytes, 0x1000), [0x1004, 0x1010]);
    // After a call that returns, the frame is closed, not opened.
    let bytes = code(&[jal(1, 16), addi(2, 2, 16), RET, NOP, RET]);
    assert_eq!(function_starts(&bytes, 0x1000), [0x1010]);
}

#[test]
fn a_jump_table_dispatch_does_not_end_its_function() {
    // add a5, a5, a4; jr a5; the cases follow.
    let dispatch = code(&[0x00e7_87b3, 0x0007_8067, addi(10, 0, 1), RET]);
    assert_eq!(function_starts(&dispatch, 0x1000), [0u64; 0]);
    // ld a5, 0(a0); jr a5 is a tail call.
    let tail = code(&[0x0005_3783, 0x0007_8067, addi(10, 0, 1), RET]);
    assert_eq!(function_starts(&tail, 0x1000), [0x1008]);
}

#[test]
fn a_far_jump_goes_to_a_block_of_the_function() {
    // auipc t1, 0; jr 12(t1); li a0, 9; [0x0c] addi a0, a0, 1; ret
    let ir = lifted(code(&[
        0x0000_0317,
        0x00c3_0067,
        addi(10, 0, 9),
        addi(10, 10, 1),
        RET,
    ]));
    assert!(
        ir.blocks.iter().any(|block| block.start == 0x100c),
        "{}",
        ir.render()
    );
    assert!(matches!(
        ir.blocks[0].stmts.last(),
        Some(Stmt::Br {
            target: Some(0x100c),
            ..
        })
    ));
    let setup = eval::Setup {
        seed: 0,
        convention: eval::Convention {
            arguments: &[],
            clobbered: &[],
        },
        registers: &[(0, 5)],
        memory: &[],
        step_limit: 100,
    };
    assert!(matches!(
        eval::run(&ir, &setup),
        eval::Outcome::Return { value: 6, .. }
    ));
}

#[test]
fn a_far_call_names_its_target() {
    // auipc ra, 0; jalr ra, 16(ra); ret
    let ir = lifted(code(&[0x0000_0097, 0x0100_80e7, RET]));
    assert!(
        ir.blocks[0].stmts.iter().any(|stmt| matches!(
            stmt,
            Stmt::Call {
                target: Some(0x1010),
                ..
            }
        )),
        "{}",
        ir.render()
    );
}

#[test]
fn the_global_pointer_is_read_from_the_startup_code() {
    // auipc gp, 0x2; addi gp, gp, -0x800; ret
    let mut image = Image::from_code(Isa::RiscV64, 0x1000, code(&[0x0000_2197, 0x8001_8193, RET]));
    assert_eq!(super::global_pointer_at_entry(&image), None);
    image.entry = Some(0x1000);
    assert_eq!(super::global_pointer_at_entry(&image), Some(0x2800));
    // addi a0, gp, 16 reads the address it names.
    image.global_pointer = Some(0x2800);
    let mut later = Image::from_code(Isa::RiscV64, 0x1000, code(&[0x0101_8513, RET]));
    later.global_pointer = Some(0x2800);
    let mut ir = FunctionIr::single_block(Isa::RiscV64, Vec::new());
    ir.blocks = crate::lift::lift(
        &vlk_program::program::Program::new(later),
        0x1000,
        8,
        &HashSet::new(),
    )
    .unwrap();
    assert!(ir.render().contains("#0x2810"), "{}", ir.render());
}

#[test]
fn control_register_accesses_are_machine_statements() {
    use vlk_ir::ir::MachineInstruction;
    // frcsr a0; fsrm a0, a1; csrci fflags, 1; ret
    let ir = lifted(code(&[0x0030_2573, 0x0025_9573, 0x0010_f073, RET]));
    let machine: Vec<_> = ir.blocks[0]
        .stmts
        .iter()
        .filter_map(|stmt| match stmt {
            Stmt::Machine {
                instruction,
                inputs,
                outputs,
                ..
            } => Some((*instruction, inputs.len(), outputs.len())),
            _ => None,
        })
        .collect();
    assert_eq!(
        machine,
        [
            (
                MachineInstruction::RiscvCsr {
                    register: 3,
                    change: 2
                },
                0,
                1
            ),
            (
                MachineInstruction::RiscvCsr {
                    register: 2,
                    change: 1
                },
                1,
                1
            ),
            (
                MachineInstruction::RiscvCsr {
                    register: 1,
                    change: 3
                },
                1,
                0
            ),
        ],
        "{}",
        ir.render()
    );
    assert!(
        !ir.blocks[0]
            .stmts
            .iter()
            .any(|stmt| matches!(stmt, Stmt::Unsupported { .. }))
    );
    let printed = vlk_render::render::render(&ir, &[], &Default::default(), &[]);
    for expected in ["csrr %0, 0x3", "csrrw %0, 0x2, %1", "csrc 0x1, %0"] {
        assert!(printed.contains(expected), "{printed}");
    }
}

#[test]
fn a_static_rounding_mode_makes_a_machine_statement() {
    use vlk_ir::ir::MachineInstruction;
    // fadd.d fa0, fa0, fa1, rtz; fcvt.s.w fa0, a0, rup; fadd.d fa0, fa0, fa1; ret
    let ir = lifted(code(&[0x02b5_1553, 0xd005_3553, 0x02b5_7553, RET]));
    let machine: Vec<_> = ir.blocks[0]
        .stmts
        .iter()
        .filter_map(|stmt| match stmt {
            Stmt::Machine {
                instruction,
                inputs,
                ..
            } => Some((*instruction, inputs.len())),
            _ => None,
        })
        .collect();
    assert_eq!(
        machine,
        [
            (
                MachineInstruction::RiscvRounded {
                    mnemonic: "fadd.d",
                    mode: 1
                },
                2
            ),
            (
                MachineInstruction::RiscvRounded {
                    mnemonic: "fcvt.s.w",
                    mode: 3
                },
                1
            ),
        ],
        "{}",
        ir.render()
    );
    assert!(
        !ir.blocks[0]
            .stmts
            .iter()
            .any(|stmt| matches!(stmt, Stmt::Unsupported { .. }))
    );
    let printed = vlk_render::render::render(&ir, &[], &Default::default(), &[]);
    for expected in [
        "fmv.d.x ft0, %1; fmv.d.x ft1, %2; fadd.d ft0, ft0, ft1, rtz; fmv.x.d %0, ft0",
        "fcvt.s.w ft0, %1, rup; fmv.x.w %0, ft0",
    ] {
        assert!(printed.contains(expected), "{printed}");
    }
}