use std::collections::HashSet;
use super::decode::{self, Alu, Branch, Instruction, Op};
use super::steps::always_taken;
use super::text;
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
}
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();
let mut doubtful = HashSet::new();
let mut entries = HashSet::new();
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 {
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)
})
};
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);
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, .. }
)
&& text::target(&before, pc.wrapping_sub(8)) != Some(pc)
});
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;
}
if instruction.op == Op::Break {
closed = true;
}
}
let possible: HashSet<u64> = candidates.iter().copied().collect();
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));
entries.contains(candidate)
|| !jumps.get(candidate).is_some_and(|sources| {
sources
.iter()
.any(|source| source < candidate && function(*source) == own)
})
})
.filter(|candidate| !doubtful.contains(candidate) || jumps.contains_key(candidate))
.filter(|candidate| {
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)
.any(|(_, target)| {
own < *target && target < candidate && !possible.contains(target)
})
&& {
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()
}