vlk-analysis 0.3.0

Lifting, SSA and simplification passes of the vlk decompiler
//! The arguments of a variadic call, counted from its format string.

use vlk_ir::ir::{Expr, Stmt};
use vlk_types::types::Convention;

use crate::lift::{Summaries, arguments};

/// Gives a call to a function that names `named` arguments and takes
/// further ones as many as the format at `address` asks for.
pub(super) fn count_from_format(
    image: &vlk_loader::loader::Image,
    made: &mut Stmt,
    named: usize,
    address: Option<u32>,
) {
    if let Some(address) = address
        && let Some(format) = crate::ssa::c_string(image, u64::from(address))
        && let Stmt::Call { kind, args, .. } = made
    {
        let (words, skipped) = crate::analysis::variadic::o32_argument_words(&format, named);
        *args = arguments(
            *kind,
            Convention::O32,
            image.isa,
            Some(words.min(4)),
            words.saturating_sub(4),
        );
        if let Some(args) = args {
            for word in skipped.into_iter().rev() {
                args.remove(word);
            }
        }
    }
}

/// Gives a direct call, made after the block was lifted, the arguments its
/// format asks for, where the statements before it in the block set the
/// format's address whole.
pub(crate) fn count_from_block_format(
    image: &vlk_loader::loader::Image,
    summaries: Summaries<'_>,
    before: &[Stmt],
    made: &mut Stmt,
) {
    let Stmt::Call {
        target: Some(target),
        convention: Convention::O32,
        ..
    } = made
    else {
        return;
    };
    let named = usize::from(summaries(*target).further_from);
    if !(1..=4).contains(&named) {
        return;
    }
    let format = left_in(before, Convention::O32.arguments()[named - 1]);
    count_from_format(image, made, named, format);
}

/// Gives a direct call the arguments its format asks for, where `held`
/// gives the address the format's register holds at the call.
pub(in crate::lift) fn count_format(
    image: &vlk_loader::loader::Image,
    summaries: Summaries<'_>,
    made: &mut Stmt,
    held: impl Fn(u16) -> Option<u64>,
) {
    let Stmt::Call {
        target: Some(target),
        convention: Convention::O32,
        ..
    } = made
    else {
        return;
    };
    let named = usize::from(summaries(*target).further_from);
    if !(1..=4).contains(&named) {
        return;
    }
    let format = held(Convention::O32.arguments()[named - 1])
        .and_then(|address| u32::try_from(address).ok());
    count_from_format(image, made, named, format);
}

/// The address the statements leave whole in `register`, where the last
/// write of it is a constant.
fn left_in(stmts: &[Stmt], register: u16) -> Option<u32> {
    stmts.iter().fold(None, |held, stmt| match stmt {
        Stmt::Assign {
            dest,
            value: Expr::Const(value),
            ..
        } if dest.index == register => u32::try_from(*value).ok(),
        other
            if vlk_ir::ir::visit::statement_registers(other)
                .0
                .contains(&register) =>
        {
            None
        }
        _ => held,
    })
}

/// The most statements of a block that is copied into the blocks before
/// it.
const COPIED: usize = 24;

/// Gives each way of reaching a shared call its own copy of the call.
/// Compilers merge calls of a function that reads a format, as on the
/// error paths of several tests: the blocks before set each their own
/// format and jump to one block that makes the call. That block is
/// copied to the end of each block that sets a format and jumps to it,
/// and the copy takes the arguments its format asks for. A block left
/// with no way in is removed. `kept` names the blocks reached in ways the
/// statements do not show.
pub(in crate::lift) fn split_shared_calls(
    image: &vlk_loader::loader::Image,
    summaries: Summaries<'_>,
    kept: &std::collections::HashSet<u64>,
    blocks: &mut Vec<vlk_ir::ir::Block>,
) {
    let mut index = 1;
    while index < blocks.len() {
        let shared = &blocks[index];
        let ends = matches!(
            shared.stmts.last(),
            Some(
                Stmt::Br {
                    target: Some(_),
                    ..
                } | Stmt::Ret { .. }
                    | Stmt::Trap { .. }
            )
        );
        // The first call of the block whose format the block does not set.
        let call = shared.stmts.iter().enumerate().find_map(|(at, stmt)| {
            let Stmt::Call {
                target: Some(target),
                convention: Convention::O32,
                ..
            } = stmt
            else {
                return None;
            };
            let named = usize::from(summaries(*target).further_from);
            (1..=4)
                .contains(&named)
                .then(|| (at, Convention::O32.arguments()[named - 1]))
        });
        let Some((at, register)) = call.filter(|(at, register)| {
            ends && shared.stmts.len() <= COPIED
                && !shared.stmts[..*at].iter().any(|stmt| {
                    vlk_ir::ir::visit::statement_registers(stmt)
                        .0
                        .contains(register)
                })
        }) else {
            index += 1;
            continue;
        };
        let start = shared.start;
        let jumps_here = |block: &vlk_ir::ir::Block| matches!(block.stmts.last(), Some(Stmt::Br { target: Some(target), .. }) if *target == start);
        // The blocks that set a format and jump here, with the format.
        let setting: Vec<(usize, u32)> = blocks
            .iter()
            .enumerate()
            .filter(|(other, block)| *other != index && jumps_here(block))
            .filter_map(|(other, block)| Some((other, left_in(&block.stmts, register)?)))
            .collect();
        if setting.len() < 2 || setting.iter().all(|(_, format)| *format == setting[0].1) {
            index += 1;
            continue;
        }
        let copied = blocks[index].stmts.clone();
        for (other, _) in &setting {
            let stmts = &mut blocks[*other].stmts;
            stmts.pop();
            let call_at = stmts.len() + at;
            stmts.extend(copied.iter().cloned());
            let (before, rest) = stmts.split_at_mut(call_at);
            count_from_block_format(image, summaries, before, &mut rest[0]);
        }
        // Whether anything still leads to the block.
        let falls_in = !matches!(
            blocks[index - 1].stmts.last(),
            Some(
                Stmt::Br { .. }
                    | Stmt::Ret { .. }
                    | Stmt::Trap { .. }
                    | Stmt::BrIndirect { .. }
                    | Stmt::Switch { .. }
            )
        );
        let reached = falls_in
            || kept.contains(&start)
            || blocks.iter().any(|block| {
                block.stmts.iter().any(|stmt| match stmt {
                    Stmt::Br {
                        target: Some(target),
                        ..
                    }
                    | Stmt::Brif { target, .. }
                    | Stmt::BrifFlags { target, .. } => *target == start,
                    Stmt::Switch { cases, default, .. } => {
                        cases.iter().any(|(_, target)| *target == start) || *default == Some(start)
                    }
                    _ => false,
                })
            });
        if reached {
            index += 1;
        } else {
            blocks.remove(index);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::split_shared_calls;
    use vlk_base::target::Isa;
    use vlk_ir::ir::{Block, Cond, Expr, RegRef, Stmt};
    use vlk_loader::loader::{Image, Summary};
    use vlk_types::types::{CallKind, Convention};

    const START: u64 = 0x1000;
    const CALLEE: u64 = 0x2000;

    /// An image whose bytes hold "done" at `START` and "%d of %d" after it.
    fn image() -> Image {
        Image::from_code(Isa::Mips32, START, b"done\0%d of %d\0\0\0".to_vec())
    }

    fn summaries(target: u64) -> Summary {
        Summary {
            further_from: u8::from(target == CALLEE),
            ..Summary::default()
        }
    }

    fn set(value: u64) -> Stmt {
        Stmt::Assign {
            dest: RegRef {
                index: Convention::O32.arguments()[0],
                width: 64,
            },
            value: Expr::Const(value),
            at: None,
        }
    }

    fn jump(target: u64) -> Stmt {
        Stmt::Br {
            target: Some(target),
            at: None,
        }
    }

    fn returns() -> Stmt {
        Stmt::Ret {
            value: Expr::reg(vlk_arch::arch::RETURN, 32),
            at: None,
        }
    }

    fn blocks(image: &Image, first: u64, second: u64) -> Vec<Block> {
        let call = crate::lift::call(CallKind::Invoke, image, &summaries, Some(CALLEE));
        vec![
            Block {
                start: 0x100,
                stmts: vec![Stmt::Brif {
                    cond: Cond::Eq,
                    lhs: Expr::reg(9, 64),
                    rhs: Expr::Const(0),
                    target: 0x120,
                    at: None,
                }],
            },
            Block {
                start: 0x110,
                stmts: vec![set(first), jump(0x130)],
            },
            Block {
                start: 0x120,
                stmts: vec![set(second), jump(0x130)],
            },
            Block {
                start: 0x130,
                stmts: vec![call, returns()],
            },
        ]
    }

    fn arguments(block: &Block) -> usize {
        block
            .stmts
            .iter()
            .find_map(|stmt| match stmt {
                Stmt::Call {
                    args: Some(args), ..
                } => Some(args.len()),
                _ => None,
            })
            .unwrap_or_else(|| panic!("{block:?}"))
    }

    #[test]
    fn a_call_two_formats_reach_is_made_once_for_each() {
        let image = image();
        let mut split = blocks(&image, START, START + 5);
        split_shared_calls(&image, &summaries, &HashSet::new(), &mut split);
        // Each block that set a format ends as the shared one did, and the
        // shared one is gone.
        assert_eq!(
            split.iter().map(|block| block.start).collect::<Vec<_>>(),
            [0x100, 0x110, 0x120]
        );
        assert!(matches!(split[1].stmts.last(), Some(Stmt::Ret { .. })));
        assert_eq!(arguments(&split[1]), 1);
        assert_eq!(arguments(&split[2]), 3);
    }

    #[test]
    fn a_shared_call_stays_where_copying_would_not_help() {
        let image = image();
        // One format for both ways in.
        let same = blocks(&image, START, START);
        let mut split = same.clone();
        split_shared_calls(&image, &summaries, &HashSet::new(), &mut split);
        assert_eq!(split.len(), same.len());
        // A block reached in a way the statements do not show is kept
        // beside its copies.
        let mut split = blocks(&image, START, START + 5);
        split_shared_calls(&image, &summaries, &HashSet::from([0x130]), &mut split);
        assert_eq!(split.len(), 4);
        assert_eq!(arguments(&split[1]), 1);
        // A block that sets the format itself is not shared in that sense.
        let mut own = blocks(&image, START, START + 5);
        own[3].stmts.insert(0, set(START));
        let before = own.len();
        split_shared_calls(&image, &summaries, &HashSet::new(), &mut own);
        assert_eq!(own.len(), before);
    }
}