use super::decode::{Alu, Instruction, Op};
use super::{Step, decode};
use crate::lift::Decoded;
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
}
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
}
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();
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
};
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;
}
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,
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);
}
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()
}
pub(crate) fn opens(bytes: &[u8]) -> bool {
!matches!(
bytes,
[] | [_] | [0, 0, ..] | [1, 0, ..] | [0x13, 0, 0, 0, ..]
)
}
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);
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
}