use std::collections::BTreeMap;
use std::fmt;
use hexicon_image::Image;
use crate::decode::{DecodeError, Instruction, Operand, Payload, decode};
use crate::opcode::Opcode;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodHeader {
pub param_count: u8,
pub varargs: bool,
pub optional_param_count: u8,
pub local_count: u16,
pub stack_depth: u16,
pub exception_table_offset: u16,
pub debug_records_offset: u16,
}
impl MethodHeader {
pub const MIN_SIZE: usize = 10;
pub fn parse(bytes: &[u8]) -> Option<Self> {
let b = bytes.get(..Self::MIN_SIZE)?;
let u16_at = |at: usize| u16::from_le_bytes([b[at], b[at + 1]]);
Some(Self {
param_count: b[0] & 0x7f,
varargs: b[0] & 0x80 != 0,
optional_param_count: b[1],
local_count: u16_at(2),
stack_depth: u16_at(4),
exception_table_offset: u16_at(6),
debug_records_offset: u16_at(8),
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExceptionHandler {
pub start: u16,
pub end: u16,
pub exception_class: u32,
pub handler: u16,
}
#[derive(Debug, Clone)]
pub struct Function {
pub address: u32,
pub header: MethodHeader,
pub instructions: Vec<Instruction>,
pub handlers: Vec<ExceptionHandler>,
pub code_end: u32,
pub extent: Extent,
pub size: u32,
pub stray_branches: Vec<StrayBranch>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StrayBranch {
pub offset: u32,
pub target: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Extent {
Table,
Limit,
Reachable,
Gap {
len: u32,
decodable_end: u32,
},
}
impl Function {
pub fn end_address(&self) -> u32 {
self.address + self.code_end
}
pub fn tail_address(&self) -> u32 {
self.address + self.size
}
pub fn function_references(&self) -> impl Iterator<Item = u32> + '_ {
self.instructions
.iter()
.flat_map(|i| &i.operands)
.filter_map(|operand| match operand {
Operand::Function(address) => Some(*address),
_ => None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DisassembleError {
BadAddress,
HeaderTooSmall,
BadTableOffset,
BadExceptionTable,
BadDebugRecords,
Decode(DecodeError),
Overrun {
offset: u32,
},
BadBranch {
offset: u32,
target: i64,
},
}
impl fmt::Display for DisassembleError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BadAddress => write!(f, "address is not a function in the code pool"),
Self::HeaderTooSmall => write!(f, "method header size is too small"),
Self::BadTableOffset => write!(f, "method header has an impossible table offset"),
Self::BadExceptionTable => write!(f, "exception table runs past the end of its page"),
Self::BadDebugRecords => write!(f, "debug records are malformed"),
Self::Decode(error) => write!(f, "{error}"),
Self::Overrun { offset } => {
write!(
f,
"instruction at offset {offset:#x} runs past the end of the code"
)
}
Self::BadBranch { offset, target } => {
write!(
f,
"branch at offset {offset:#x} targets {target:#x}, outside the function"
)
}
}
}
}
impl std::error::Error for DisassembleError {}
impl From<DecodeError> for DisassembleError {
fn from(error: DecodeError) -> Self {
Self::Decode(error)
}
}
fn falls_through(opcode: Opcode) -> bool {
!matches!(
opcode,
Opcode::RetVal
| Opcode::RetNil
| Opcode::RetTrue
| Opcode::Ret
| Opcode::Jmp
| Opcode::Throw
| Opcode::Switch
| Opcode::LRet
)
}
pub fn disassemble(
image: &Image,
address: u32,
limit: Option<u32>,
) -> Result<Function, DisassembleError> {
let header_size = image.entry_point.method_header_size as usize;
if header_size < MethodHeader::MIN_SIZE {
return Err(DisassembleError::HeaderTooSmall);
}
let page = image
.code_pool
.at(address)
.ok_or(DisassembleError::BadAddress)?;
let header = MethodHeader::parse(page).ok_or(DisassembleError::BadAddress)?;
if page.len() < header_size {
return Err(DisassembleError::BadAddress);
}
let first = header_size as u32;
let table_offset = match (header.exception_table_offset, header.debug_records_offset) {
(0, 0) => None,
(0, debug) => Some(debug),
(exceptions, _) => Some(exceptions),
};
if let Some(offset) = table_offset
&& ((offset as usize) < header_size || offset as usize > page.len())
{
return Err(DisassembleError::BadTableOffset);
}
let handlers = exception_table(image, page, &header)?;
let mut padding = 0u32;
let (instructions, code_end, extent) = match table_offset {
Some(end) => {
let code = &page[..end as usize];
let instructions =
linear(code, first)?.ok_or(DisassembleError::Overrun { offset: end.into() })?;
(instructions, u32::from(end), Extent::Table)
}
None => {
let mut found = reachable(page, &[first])?;
let mut end = found
.values()
.map(|i| i.offset + i.len)
.max()
.unwrap_or(first);
let bound = match limit {
Some(limit) if limit > address && ((limit - address) as usize) <= page.len() => {
limit - address
}
_ => page.len() as u32,
};
let mut extent = Extent::Reachable;
if bound >= end && (limit.is_some() || bound == end) {
match linear(&page[..bound as usize], end) {
Ok(Some(dead)) => {
for instruction in dead {
found.insert(instruction.offset, instruction);
}
end = bound;
extent = Extent::Limit;
}
_ => {
let (dead, stop) = linear_prefix(&page[..bound as usize], end);
if page[stop as usize..bound as usize].iter().all(|&b| b == 0) {
for instruction in dead {
found.insert(instruction.offset, instruction);
}
end = stop;
padding = bound - stop;
extent = Extent::Limit;
} else {
extent = Extent::Gap {
len: bound - end,
decodable_end: stop,
};
}
}
}
}
(found.into_values().collect(), end, extent)
}
};
let mut size = code_end + padding;
if header.exception_table_offset != 0 {
let table = 2 + handlers.len() as u32 * u32::from(image.entry_point.exception_entry_size);
size = u32::from(header.exception_table_offset) + table;
}
if header.debug_records_offset != 0 {
size = debug_records_end(image, page, &header).ok_or(DisassembleError::BadDebugRecords)?;
}
let mut function = Function {
address,
header,
instructions,
handlers,
code_end,
extent,
size,
stray_branches: Vec::new(),
};
function.stray_branches = stray_branches(&function);
Ok(function)
}
fn linear(code: &[u8], start: u32) -> Result<Option<Vec<Instruction>>, DecodeError> {
let mut instructions = Vec::new();
let mut offset = start;
while (offset as usize) < code.len() {
let instruction = decode(code, offset)?;
offset += instruction.len;
instructions.push(instruction);
}
Ok((offset as usize == code.len()).then_some(instructions))
}
fn linear_prefix(code: &[u8], start: u32) -> (Vec<Instruction>, u32) {
let mut instructions = Vec::new();
let mut offset = start;
while (offset as usize) < code.len() {
let Ok(instruction) = decode(code, offset) else {
break;
};
if (offset + instruction.len) as usize > code.len() {
break;
}
offset += instruction.len;
instructions.push(instruction);
}
(instructions, offset)
}
fn reachable(code: &[u8], entries: &[u32]) -> Result<BTreeMap<u32, Instruction>, DisassembleError> {
let mut found: BTreeMap<u32, Instruction> = BTreeMap::new();
let mut pending: Vec<u32> = entries.to_vec();
let mut defaults: Vec<u32> = Vec::new();
loop {
while let Some(offset) = pending.pop() {
if found.contains_key(&offset) {
continue;
}
let instruction = decode(code, offset)?;
let in_code = |target: i64| {
u32::try_from(target)
.ok()
.filter(|t| (*t as usize) < code.len())
.ok_or(DisassembleError::BadBranch { offset, target })
};
for operand in &instruction.operands {
match *operand {
Operand::Branch(target) => pending.push(in_code(target)?),
Operand::Table(table) => pending.push(table),
_ => {}
}
}
if let Payload::Switch { cases, default } = &instruction.payload {
for (_, target) in cases {
pending.push(in_code(*target)?);
}
if let Ok(default) = in_code(*default) {
defaults.push(default);
}
}
if falls_through(instruction.opcode) {
pending.push(offset + instruction.len);
}
found.insert(offset, instruction);
}
let Some(default) = defaults.pop() else {
break;
};
let inside_another = found
.range(..default)
.next_back()
.is_some_and(|(start, i)| start + i.len > default);
if !inside_another {
pending.push(default);
}
}
Ok(found)
}
fn exception_table(
image: &Image,
page: &[u8],
header: &MethodHeader,
) -> Result<Vec<ExceptionHandler>, DisassembleError> {
if header.exception_table_offset == 0 {
return Ok(Vec::new());
}
let entry_size = image.entry_point.exception_entry_size as usize;
let table = page
.get(header.exception_table_offset as usize..)
.ok_or(DisassembleError::BadExceptionTable)?;
let count = table
.get(..2)
.map(|b| u16::from_le_bytes([b[0], b[1]]) as usize)
.ok_or(DisassembleError::BadExceptionTable)?;
if entry_size < 10 {
return Err(DisassembleError::BadExceptionTable);
}
let entries = table
.get(2..2 + count * entry_size)
.ok_or(DisassembleError::BadExceptionTable)?;
Ok(entries
.chunks_exact(entry_size)
.map(|e| ExceptionHandler {
start: u16::from_le_bytes([e[0], e[1]]),
end: u16::from_le_bytes([e[2], e[3]]),
exception_class: u32::from_le_bytes([e[4], e[5], e[6], e[7]]),
handler: u16::from_le_bytes([e[8], e[9]]),
})
.collect())
}
fn debug_records_end(image: &Image, page: &[u8], header: &MethodHeader) -> Option<u32> {
let entry = &image.entry_point;
let u16_at =
|at: usize| Some(u16::from_le_bytes([*page.get(at)?, *page.get(at + 1)?]) as usize);
let mut pos = header.debug_records_offset as usize + entry.debug_table_header_size as usize;
let lines = u16_at(pos)?;
pos += 2 + lines * entry.debug_line_entry_size as usize;
pos += u16_at(pos)?;
pos += 4;
(pos <= page.len()).then_some(pos as u32)
}
fn stray_branches(function: &Function) -> Vec<StrayBranch> {
let starts: std::collections::BTreeSet<i64> = function
.instructions
.iter()
.map(|i| i64::from(i.offset))
.collect();
let mut stray = Vec::new();
for instruction in &function.instructions {
for target in instruction.branch_targets() {
if !starts.contains(&target) {
stray.push(StrayBranch {
offset: instruction.offset,
target,
});
}
}
}
for handler in &function.handlers {
if !starts.contains(&i64::from(handler.handler)) {
stray.push(StrayBranch {
offset: u32::from(function.header.exception_table_offset),
target: handler.handler.into(),
});
}
}
stray
}