vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
use super::*;
use vlk_types::types::Convention;

#[test]
fn arm64_assembly_functions_that_reach_the_callers_frame_take_the_assembly_abi() {
    let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
        .join("tests/fixtures/go_probe_arm64");
    let program = vlk_program::program::Program::new(crate::lift::load(&path).unwrap());
    let at = |name: &str| {
        program
            .image
            .functions
            .values()
            .find(|function| function.name.as_deref() == Some(name))
            .map(|function| function.addr)
            .unwrap()
    };
    // Arguments on the stack, a result on the stack, and Go's register
    // ABI in assembly and in Go.
    for (name, convention) in [
        ("runtime.usleep", Convention::GoAbi0Arm64),
        ("runtime.nanotime1", Convention::GoAbi0Arm64),
        ("runtime.walltime", Convention::GoAbi0Arm64),
        ("runtime.memmove", Convention::GoArm64),
        ("runtime.send", Convention::GoArm64),
    ] {
        assert_eq!(
            convention_of(&program.image, at(name)),
            convention,
            "{name}"
        );
    }
    assert_eq!(
        crate::analysis::summary::summary(&program, at("runtime.usleep")).stack,
        1
    );
    // The goroutine in x28 survives an assembly call, except one whose
    // code sets it.
    let changes_g = |name: &str| {
        let summary = crate::analysis::summary::summary(&program, at(name));
        let convention = convention_of(&program.image, at(name));
        convention.clobbered_by(summary.clobbers).contains(&28)
    };
    assert!(changes_g("runtime.setg"));
    assert!(!changes_g("runtime.usleep"));
    assert!(!changes_g("runtime.systemstack"));
    // The function table gives bootstrapRand no argument bytes: calls
    // pass it nothing, whatever registers its body reads.
    let random = crate::analysis::summary::summary(&program, at("runtime.bootstrapRand"));
    assert_eq!((random.arity, random.floats), (Some(0), Some(0)));
    let nanotime = at("runtime.nanotime1");
    assert_eq!(
        crate::analysis::summary::summary(&program, nanotime).stack_results[0],
        (0, 8)
    );
    // runtime.send stores what nanotime1 returns on the stack.
    let send = program.image.functions.get(&at("runtime.send")).unwrap();
    let analysis = crate::analysis::analyze(&program, send, None).unwrap();
    let stored = analysis.ir.blocks.iter().any(|block| {
        let Some(call) = block.stmts.iter().position(|stmt| {
            matches!(stmt, vlk_ir::ir::Stmt::Call { target: Some(target), .. } if *target == nanotime)
        }) else {
            return false;
        };
        let results: Vec<u16> = block.stmts[call]
            .call_outputs()
            .iter()
            .map(|output| output.dest.index)
            .collect();
        block.stmts[call + 1..].iter().any(|stmt| {
            let vlk_ir::ir::Stmt::Store { value, .. } = stmt else {
                return false;
            };
            let mut reads = std::collections::HashSet::new();
            vlk_ir::ir::visit::collect_reads(value, &mut reads);
            results.iter().any(|result| reads.contains(result))
        })
    });
    assert!(stored);
    // Go's register ABI returns findObject's third value in x2, which
    // wbBufFlush1 reads.
    let find = at("runtime.findObject");
    let flush = program
        .image
        .functions
        .get(&at("runtime.wbBufFlush1"))
        .unwrap();
    let lifted = crate::analysis::analyze(&program, flush, None).unwrap().ir;
    let outputs: Vec<u16> = lifted
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .find(|stmt| {
            matches!(stmt, vlk_ir::ir::Stmt::Call { target: Some(target), .. } if *target == find)
        })
        .unwrap()
        .call_outputs()
        .iter()
        .map(|output| output.register)
        .collect();
    assert!(outputs.contains(&2), "{outputs:?}");
    // walltime's assembly calls the vDSO through a register under the
    // procedure call standard, which keeps x20 and x21.
    let walltime = program
        .image
        .functions
        .get(&at("runtime.walltime"))
        .unwrap();
    let lifted = crate::analysis::analyze(&program, walltime, None)
        .unwrap()
        .ir;
    let conventions: Vec<Convention> = lifted
        .blocks
        .iter()
        .flat_map(|block| &block.stmts)
        .filter_map(|stmt| match stmt {
            vlk_ir::ir::Stmt::Call {
                through: Some(_),
                convention,
                ..
            } => Some(*convention),
            _ => None,
        })
        .collect();
    assert!(!conventions.is_empty());
    assert!(
        conventions
            .iter()
            .all(|convention| *convention == Convention::Aapcs64)
    );
}

#[test]
fn abi0_wrappers_initialize_fixed_registers_before_the_call() {
    let code = vec![
        0x45, 0x0f, 0x57, 0xff, 0x64, 0x4c, 0x8b, 0x34, 0x25, 0xf8, 0xff, 0xff, 0xff, 0xe8, 0, 0,
        0, 0, 0xc3,
    ];
    for (bytes, expected) in [
        (code.clone(), Convention::GoAbi0),
        (code[..14].to_vec(), Convention::GoAmd64),
        ([vec![0xb8], code.clone()].concat(), Convention::GoAmd64),
        ([vec![0xc3], code].concat(), Convention::GoAmd64),
    ] {
        let length = bytes.len();
        let mut image = Image::from_code(Isa::X86_64, 0x1000, bytes);
        image.go = true;
        vlk_loader::loader::upsert(
            &mut image.functions,
            0x1000,
            Some("wrapper".into()),
            Some(length as u64),
            vlk_loader::loader::NameSource::Pclntab,
        );
        assert_eq!(convention_of(&image, 0x1000), expected);
    }
}