vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Where the functions of a run of code start.

use std::collections::HashSet;

use super::decode::{self, Alu, Branch, Instruction, Op};
use super::steps::always_taken;
use super::text;

/// Every direct call and jump in `bytes`, as its address and its target.
pub(crate) fn direct_transfers(bytes: &[u8], base: u64, big: bool) -> Vec<(u64, u64)> {
    let mut out = Vec::new();
    for (index, word) in bytes.as_chunks::<4>().0.iter().enumerate() {
        let pc = base.wrapping_add(index as u64 * 4);
        let Some(instruction) = decode::decode(word, big) else {
            continue;
        };
        if (matches!(instruction.op, Op::Jump { .. }) || always_taken(&instruction))
            && let Some(target) = text::target(&instruction, pc)
        {
            out.push((pc, target));
        }
    }
    out
}

/// Function starts in code without symbols: the target of every call,
/// and the instruction past the delay slot of a return or of a jump that
/// no branch of the same function goes to. One of the latter whose address
/// is in `tabled`, the code addresses read-only data holds, is taken for
/// a case of a switch unless it opens a frame or sets gp, as a function
/// does, or padding comes before it.
pub(crate) fn function_starts(
    bytes: &[u8],
    base: u64,
    big: bool,
    tabled: &HashSet<u64>,
) -> Vec<u64> {
    let words = bytes.as_chunks::<4>().0;
    let inside = |address: u64| address >= base && address - base < bytes.len() as u64;
    let instructions: Vec<Option<Instruction>> =
        words.iter().map(|word| decode::decode(word, big)).collect();
    let mut starts = std::collections::BTreeSet::new();
    let mut spans: Vec<(u64, u64)> = Vec::new();
    let mut jumps: std::collections::HashMap<u64, Vec<u64>> = std::collections::HashMap::new();
    for (index, instruction) in instructions.iter().enumerate() {
        let Some(instruction) = instruction else {
            continue;
        };
        let pc = base.wrapping_add(index as u64 * 4);
        let Some(target) = text::target(instruction, pc) else {
            continue;
        };
        let always = always_taken(instruction);
        match instruction.op {
            Op::Jump { link: true } | Op::Branch { link: true, .. } => {
                if inside(target) && target != pc.wrapping_add(8) {
                    starts.insert(target);
                }
            }
            Op::Branch { .. } if !always => spans.push((pc.min(target), pc.max(target))),
            Op::FloatBranch { .. } => spans.push((pc.min(target), pc.max(target))),
            _ => jumps.entry(target).or_default().push(pc),
        }
    }
    spans.sort_unstable();
    let mut merged: Vec<(u64, u64)> = Vec::new();
    for (low, high) in spans {
        match merged.last_mut() {
            Some(last) if low <= last.1 => last.1 = last.1.max(high),
            _ => merged.push((low, high)),
        }
    }
    let spanned = |address: u64| {
        let after = merged.partition_point(|(low, _)| *low < address);
        after > 0 && address <= merged[after - 1].1
    };
    let mut candidates = Vec::new();
    // The candidates read-only data points at that do not begin as a
    // function does.
    let mut doubtful = HashSet::new();
    // The candidates that begin by setting gp from a constant.
    let mut entries = HashSet::new();
    // Counts down the delay slot of what closed the code.
    let mut closing = 0;
    let mut closed = false;
    let mut padded = false;
    for (index, instruction) in instructions.iter().enumerate() {
        let pc = base.wrapping_add(index as u64 * 4);
        let Some(instruction) = instruction else {
            closed = true;
            closing = 0;
            continue;
        };
        if closing == 1 {
            closing = 0;
            closed = true;
            continue;
        }
        if instruction.word == 0 {
            // Past the delay slot this is padding, which aligns a function.
            padded |= closed;
            continue;
        }
        let opens = |index: usize| {
            instructions[index..]
                .iter()
                .take(3)
                .flatten()
                .any(|opening| {
                    (opening.op == Op::Immediate(Alu::Add)
                        && opening.rs == 29
                        && opening.rt == 29
                        && opening.imm < 0)
                        || (opening.op == Op::Lui && opening.rt == 28)
                })
        };
        // gp set from a constant, as a function does first: lui $gp and,
        // next or after one more, addiu $gp, $gp.
        let sets_gp = instruction.op == Op::Lui
            && instruction.rt == 28
            && instructions[index + 1..]
                .iter()
                .take(2)
                .flatten()
                .any(|next| next.op == Op::Immediate(Alu::Add) && next.rs == 28 && next.rt == 28);
        // A call that does not return has the next function right after
        // its delay slot.
        let after_call = index >= 2
            && instructions[index - 2].is_some_and(|before| {
                matches!(
                    before.op,
                    Op::Jump { link: true }
                        | Op::JumpRegister { link: true }
                        | Op::Branch { link: true, .. }
                )
                // A call to the instruction past its slot only reads
                // the address it runs at.
                && text::target(&before, pc.wrapping_sub(8)) != Some(pc)
            });
        // Or second, after it opens its frame.
        let frame_then_gp = instruction.op == Op::Immediate(Alu::Add)
            && instruction.rs == 29
            && instruction.rt == 29
            && instruction.imm < 0
            && instructions
                .get(index + 1)
                .copied()
                .flatten()
                .is_some_and(|next| next.op == Op::Lui && next.rt == 28);
        if closed && !spanned(pc) {
            candidates.push(pc);
            if tabled.contains(&pc) && !opens(index) && !padded {
                doubtful.insert(pc);
            }
            if sets_gp || frame_then_gp {
                entries.insert(pc);
            }
        } else if sets_gp && after_call && !closed && !spanned(pc) {
            candidates.push(pc);
            entries.insert(pc);
        }
        closed = false;
        padded = false;
        let always = matches!(
            instruction.op,
            Op::Branch {
                test: Branch::Equal,
                link: false,
                ..
            }
        ) && instruction.rs == 0
            && instruction.rt == 0;
        let previous_add = index
            .checked_sub(1)
            .and_then(|previous| instructions[previous])
            .is_some_and(|previous| {
                previous.op == Op::Register(Alu::Add) && previous.rd == instruction.rs
            });
        if matches!(instruction.op, Op::Jump { link: false })
            || always
            || (matches!(instruction.op, Op::JumpRegister { link: false }) && !previous_add)
        {
            closing = 1;
        }
        // A break has no delay slot: the code ends with it.
        if instruction.op == Op::Break {
            closed = true;
        }
    }
    let possible: HashSet<u64> = candidates.iter().copied().collect();
    // Every jump, by where it is.
    let mut leaving: Vec<(u64, u64)> = jumps
        .iter()
        .flat_map(|(target, sources)| sources.iter().map(|source| (*source, *target)))
        .collect();
    leaving.sort_unstable();
    loop {
        let function = |address: u64| starts.range(..=address).next_back().copied();
        let found: Vec<u64> = candidates
            .iter()
            .copied()
            .filter(|candidate| !starts.contains(candidate))
            .filter(|candidate| {
                let own = function(candidate.saturating_sub(1));
                // One that sets gp is a function though the code before
                // it jumps there, as a function that ends by going on to
                // the next does.
                entries.contains(candidate)
                    // A jump back to it from further on is the candidate's
                    // own, when it is a function.
                    || !jumps.get(candidate).is_some_and(|sources| {
                        sources
                            .iter()
                            .any(|source| source < candidate && function(*source) == own)
                    })
            })
            // A doubtful one is a function only when a jump from another
            // function goes to it.
            .filter(|candidate| !doubtful.contains(candidate) || jumps.contains_key(candidate))
            // Code that jumps back into the middle of the function before
            // it is a part of that function.
            .filter(|candidate| {
                // The code before the first start found is a function too.
                let own = function(candidate.saturating_sub(1)).unwrap_or(base);
                let end = candidates
                    .iter()
                    .copied()
                    .chain(starts.range(candidate + 1..).next().copied())
                    .filter(|next| next > candidate)
                    .min()
                    .unwrap_or(u64::MAX);
                let first = leaving.partition_point(|(source, _)| source < candidate);
                !leaving[first..]
                    .iter()
                    .take_while(|(source, _)| *source < end)
                    // A jump to what may be a function's start is a call
                    // that does not return here.
                    .any(|(_, target)| {
                        own < *target && target < candidate && !possible.contains(target)
                    })
                    // So is code the function before it jumps into the
                    // middle of.
                    && {
                        let before = leaving.partition_point(|(source, _)| *source < own);
                        !leaving[before..first].iter().any(|(_, target)| {
                            candidate < target && *target < end && !possible.contains(target)
                        })
                    }
            })
            .collect();
        if found.is_empty() {
            break;
        }
        starts.extend(found);
    }
    starts.into_iter().collect()
}