vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Argument registers of calls whose callee does not say what it reads.

use std::collections::{HashMap, HashSet};

use vlk_ir::ir::{BinOp, Block, Expr, FunctionIr, Stmt};
use vlk_types::types::abi::LayoutKind;
use vlk_types::types::{CallKind, Convention};

use super::abi;

/// The argument registers the system call `number` reads, when its
/// argument count is known; they pass no more arguments than there are of
/// them. `operation` is what the block set its second argument to, when
/// that is a constant: some calls take fewer arguments for some operations.
pub(crate) fn system_call_arguments(
    convention: Convention,
    number: u64,
    operation: Option<u64>,
) -> Option<&'static [u16]> {
    let registers = convention.arguments();
    let name = vlk_prototypes::prototypes::syscalls::name(convention, number);
    let arity = match name.and_then(vlk_prototypes::prototypes::syscalls::arity) {
        // futex(address, operation, value): waking takes no more, and
        // waiting takes a timeout. The operation's low bits say which.
        Some(_) if name == Some("futex") && operation.map(|op| op & 0x7f) == Some(1) => 3,
        Some(_) if name == Some("futex") && operation.map(|op| op & 0x7f) == Some(0) => 4,
        // The MIPS kernel takes no address for pipe: it returns the two
        // descriptors in v0 and v1.
        _ if convention == Convention::SyscallMips && name == Some("pipe") => 0,
        Some(arity) => arity,
        // A MIPS system call takes four arguments in registers at most:
        // one whose count is not known is given them all, so that a
        // function that only makes the call keeps its parameters.
        None if convention == Convention::SyscallMips => registers.len() - 1,
        None => return None,
    };
    registers.get(1..(arity + 1).min(registers.len()))
}

/// The registers an expression reads other than as the base of a load.
fn collect_used(expr: &Expr, out: &mut HashSet<u16>) {
    match expr {
        Expr::Load { addr, .. } => match addr.as_ref() {
            Expr::Reg { .. } => {}
            Expr::Bin {
                op: BinOp::Add,
                lhs,
                rhs,
            } if matches!(lhs.as_ref(), Expr::Reg { .. })
                && matches!(rhs.as_ref(), Expr::Const(_)) => {}
            other => collect_used(other, out),
        },
        Expr::Reg { index, .. } => {
            out.insert(*index);
        }
        other => {
            for child in vlk_ir::ir::visit::children(other) {
                collect_used(child, out);
            }
        }
    }
}

/// The registers that hold arguments as the function starts: its
/// parameters, and under the Windows x64 convention those its declared
/// parameters of a register's size take.
fn incoming_arguments(
    ir: &FunctionIr,
    types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
) -> HashSet<u16> {
    let mut incoming: HashSet<u16> = ir.params.iter().map(|param| param.index).collect();
    if ir.convention == Convention::Win64
        && let Some(types) = types.filter(|types| !abi::has_aggregate(types))
    {
        for (register, layout) in ir.convention.arguments().iter().zip(&types.param_layouts) {
            if layout.as_ref().is_ok_and(|layout| {
                matches!(layout.size, 1 | 2 | 4 | 8)
                    && matches!(
                        layout.kind,
                        LayoutKind::Integer | LayoutKind::Boolean | LayoutKind::Pointer
                    )
            }) {
                incoming.insert(*register);
            }
        }
    }
    incoming
}

/// The constants registers hold.
type Constants = HashMap<u16, u64>;

/// The constants each block leaves in registers after its last statement.
fn constants_left(blocks: &[Block]) -> Vec<Constants> {
    blocks
        .iter()
        .map(|block| {
            let mut constants = Constants::new();
            for stmt in &block.stmts {
                for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
                    constants.remove(&register);
                }
                if let Stmt::Assign {
                    dest,
                    value: Expr::Const(value),
                    ..
                } = stmt
                {
                    constants.insert(dest.index, *value);
                }
            }
            constants
        })
        .collect()
}

/// The constant every block before `block` leaves in `register`, when they
/// all leave the same one. The entry block starts with none.
fn carried_constant(
    entering: &[Vec<usize>],
    left: &[Constants],
    block: usize,
    register: u16,
) -> Option<u64> {
    let Some((first, rest)) = entering[block].split_first() else {
        return None;
    };
    if block == 0 {
        return None;
    }
    let Some(value) = left[*first].get(&register).copied() else {
        return None;
    };
    rest.iter()
        .all(|other| left[*other].get(&register) == Some(&value))
        .then_some(value)
}

/// Gives a call whose callee's arguments are unknown, such as one through a
/// pointer, the argument registers the code sets up for it: up to the last
/// one written since the block's previous call and not used again before
/// the call, as a register holding scratch is. Loading through a register,
/// as a virtual call loads its table through the object, is no such use.
pub(super) fn set_up_arguments(
    ir: &mut FunctionIr,
    types: Option<&vlk_loader::loader::dwarf::FunctionTypes>,
) {
    let incoming = incoming_arguments(ir, types);
    // Only the operation of a system call is looked up in the blocks
    // before its own.
    let left = constants_left(&ir.blocks);
    let mut entering: Vec<Vec<usize>> = vec![Vec::new(); ir.blocks.len()];
    for index in 0..ir.blocks.len() {
        for next in vlk_ir::ir::cfg::block_successors(&ir.blocks, index) {
            entering[next].push(index);
        }
    }
    for (position, block) in ir.blocks.iter_mut().enumerate() {
        let mut written = if position == 0 && ir.convention == Convention::Win64 {
            incoming.clone()
        } else {
            HashSet::new()
        };
        // The registers the block has set to constants.
        let mut constants = Constants::new();
        // Those it has written at all.
        let mut touched: HashSet<u16> = HashSet::new();
        for stmt in &mut block.stmts {
            touched.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
            let assigned = match stmt {
                Stmt::Assign {
                    dest,
                    value: Expr::Const(value),
                    ..
                } => Some((dest.index, *value)),
                _ => None,
            };
            if !matches!(stmt, Stmt::Call { .. }) {
                for register in vlk_ir::ir::visit::statement_registers(stmt).0 {
                    constants.remove(&register);
                }
                constants.extend(assigned);
            }
            // A declared call names what it reads; it keeps no argument
            // guessed from the writes before it.
            if stmt.has_declared_call() {
                written.clear();
                continue;
            }
            let Stmt::Call {
                kind,
                convention,
                args,
                through,
                ..
            } = stmt
            else {
                let mut reads = HashSet::new();
                for operand in stmt.operands() {
                    collect_used(operand, &mut reads);
                }
                for read in reads {
                    written.remove(&read);
                }
                written.extend(vlk_ir::ir::visit::statement_registers(stmt).0);
                continue;
            };
            // The register holding the callee's address is no argument.
            if let Some(through) = through {
                let mut read = HashSet::new();
                vlk_ir::ir::visit::collect_reads(through, &mut read);
                written.retain(|register| !read.contains(register));
            }
            let registers = convention.arguments();
            // A system call of a known number reads the arguments it
            // takes, whether or not the block set them.
            if *kind == CallKind::Syscall
                && args.is_none()
                && let Some(number) = registers.first().and_then(|first| constants.get(first))
                && let Some(read) = system_call_arguments(
                    *convention,
                    *number,
                    registers.get(2).and_then(|second| {
                        constants.get(second).copied().or_else(|| {
                            (!touched.contains(second))
                                .then(|| carried_constant(&entering, &left, position, *second))
                                .flatten()
                        })
                    }),
                )
            {
                let width = if matches!(
                    convention,
                    Convention::Aapcs32 | Convention::O32 | Convention::SyscallMips
                ) {
                    32
                } else {
                    64
                };
                *args = Some(
                    registers[..1]
                        .iter()
                        .chain(read)
                        .map(|register| Expr::reg(*register, width))
                        .collect(),
                );
            }
            constants.clear();
            if args.is_none()
                && let Some(last) = registers
                    .iter()
                    .rposition(|register| written.contains(register))
            {
                let width = if matches!(convention, Convention::Aapcs32 | Convention::O32) {
                    32
                } else {
                    64
                };
                *args = Some(
                    registers[..=last]
                        .iter()
                        .map(|register| Expr::reg(*register, width))
                        .collect(),
                );
            }
            written.clear();
        }
    }
}