vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! Where the functions of a run of code start, and what its entry code
//! gives the global pointer.

use super::decode::{Alu, Instruction, Op};
use super::{Step, decode};
use crate::lift::Decoded;

/// The address the startup code at the image's entry leaves in gp: the
/// sum of the `auipc gp` and `addi gp, gp` it begins with.
pub(crate) fn global_pointer_at_entry(image: &vlk_loader::loader::Image) -> Option<u64> {
    let Some(entry) = image.entry else {
        return None;
    };
    let Some(section) = image.section_at(entry) else {
        return None;
    };
    let available = section.vaddr.saturating_add(section.size) - entry;
    let Some(bytes) = image.read_vaddr(entry, available.min(64)) else {
        return None;
    };
    let mut upper = None;
    for step in decode(bytes, entry).0 {
        let Instruction {
            op, rd, rs1, imm, ..
        } = step.instruction.instruction;
        match op {
            Op::Auipc if rd == 3 => upper = Some(step.pc.wrapping_add(imm as u64)),
            Op::Immediate {
                op: Alu::Add,
                word: false,
            } if rd == 3 && rs1 == 3 => {
                return upper.map(|upper| upper.wrapping_add(imm as u64));
            }
            _ => {}
        }
    }
    None
}

/// The instructions of `bytes` taken one after another; where one does not
/// decode, two bytes are skipped and None stands for the gap.
pub(super) fn sweep(bytes: &[u8], base: u64) -> Vec<Option<Decoded<Step>>> {
    let mut out = Vec::new();
    let mut offset = 0;
    while offset + 1 < bytes.len() {
        let (decoded, stop) = decode(&bytes[offset..], base.wrapping_add(offset as u64));
        for step in decoded {
            offset += usize::from(step.instruction.instruction.length);
            out.push(Some(step));
        }
        if stop.is_none() {
            break;
        }
        out.push(None);
        offset += 2;
    }
    out
}

/// Function starts in code without symbols: the target of every call,
/// and the first instruction after a return, a jump, a trap or data,
/// unless a branch of the same function goes to it. A jump from another
/// function is a tail call, and what it goes to starts a function too.
pub(crate) fn function_starts(bytes: &[u8], base: u64) -> Vec<u64> {
    let steps = sweep(bytes, base);
    let inside = |address: u64| address >= base && address - base < bytes.len() as u64;
    let mut jumps: std::collections::HashMap<u64, Vec<u64>> = std::collections::HashMap::new();
    let mut starts = std::collections::BTreeSet::new();
    // A conditional branch stays in its function, so nothing between it
    // and where it goes starts another.
    let mut spans: Vec<(u64, u64)> = Vec::new();
    for step in steps.iter().flatten() {
        let Instruction { op, rd, imm, .. } = step.instruction.instruction;
        if matches!(op, Op::Branch(_)) {
            let target = step.pc.wrapping_add(imm as u64);
            spans.push((step.pc.min(target), step.pc.max(target)));
        }
        let target = match op {
            Op::Jal | Op::Branch(_) => Some(step.pc.wrapping_add(imm as u64)),
            Op::Jalr => step.instruction.far,
            _ => None,
        };
        let Some(target) = target else {
            continue;
        };
        if matches!(op, Op::Jal | Op::Jalr) && rd != 0 {
            if inside(target) && target != step.next {
                starts.insert(target);
            }
        } else {
            jumps.entry(target).or_default().push(step.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
    };
    // The places straight-line code cannot reach.
    let mut candidates = Vec::new();
    let mut closed = false;
    let mut previous: Option<&Instruction> = None;
    for step in &steps {
        let Some(step) = step else {
            closed = true;
            previous = None;
            continue;
        };
        let instruction = &step.instruction.instruction;
        let padding = matches!(
            instruction.op,
            Op::Immediate {
                op: Alu::Add,
                word: false
            }
        ) && instruction.rd == 0;
        if padding {
            continue;
        }
        // A frame is not opened right after a call that returns: the
        // caller's frame is still open there. So that call does not
        // return, and a function starts.
        let opens_frame = matches!(
            instruction.op,
            Op::Immediate {
                op: Alu::Add,
                word: false
            }
        ) && instruction.rd == 2
            && instruction.rs1 == 2
            && instruction.imm < 0;
        let after_call = previous
            .is_some_and(|previous| matches!(previous.op, Op::Jal | Op::Jalr) && previous.rd != 0);
        if (closed || (opens_frame && after_call)) && !spanned(step.pc) {
            candidates.push(step.pc);
        }
        closed = match instruction.op {
            Op::Jal => instruction.rd == 0,
            Op::Ebreak => true,
            // A jump through a register ends a function, as a return or a
            // tail call, unless the sum before it chose a jump table's case.
            Op::Jalr if instruction.rd == 0 => {
                step.instruction.far.is_some()
                    || !previous.is_some_and(|previous| {
                        matches!(
                            previous.op,
                            Op::Register {
                                op: Alu::Add,
                                word: false
                            }
                        ) && previous.rd == instruction.rs1
                    })
            }
            _ => false,
        };
        previous = Some(instruction);
    }
    // A candidate stays inside its function while a jump from that same
    // function goes to it; each start found may put a jump's two ends in
    // different functions, so the rest are looked at again.
    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));
                !jumps
                    .get(candidate)
                    .is_some_and(|sources| sources.iter().any(|source| function(*source) == own))
            })
            .collect();
        if found.is_empty() {
            break;
        }
        starts.extend(found);
    }
    starts.into_iter().collect()
}

/// Whether code begins at the start of `bytes`: neither zeros nor a no-op.
pub(crate) fn opens(bytes: &[u8]) -> bool {
    !matches!(
        bytes,
        [] | [_] | [0, 0, ..] | [1, 0, ..] | [0x13, 0, 0, 0, ..]
    )
}

/// Every direct call and jump in `bytes`, as its address and its target:
/// a `jal`, and an `auipc` with the `jalr` through its register after it.
pub(crate) fn direct_transfers(bytes: &[u8], base: u64) -> Vec<(u64, u64)> {
    let mut out = Vec::new();
    let mut offset = 0;
    let mut upper: Option<(u8, u64)> = None;
    while offset + 1 < bytes.len() {
        let pc = base.wrapping_add(offset as u64);
        // Data among the code is stepped over two bytes at a time, the
        // alignment of every instruction.
        let Some(instruction) = decode::decode(&bytes[offset..]) else {
            upper = None;
            offset += 2;
            continue;
        };
        let held = upper.take();
        match instruction.op {
            Op::Jal => out.push((pc, pc.wrapping_add(instruction.imm as u64))),
            Op::Auipc => upper = Some((instruction.rd, pc.wrapping_add(instruction.imm as u64))),
            Op::Jalr => {
                if let Some((register, value)) = held
                    && register == instruction.rs1
                {
                    out.push((pc, value.wrapping_add(instruction.imm as u64)));
                }
            }
            _ => {}
        }
        offset += usize::from(instruction.length);
    }
    out
}