1use std::collections::BTreeMap;
4use std::fmt;
5
6use hexicon_image::Image;
7
8use crate::decode::{DecodeError, Instruction, Operand, Payload, decode};
9use crate::opcode::Opcode;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct MethodHeader {
14 pub param_count: u8,
16 pub varargs: bool,
18 pub optional_param_count: u8,
20 pub local_count: u16,
22 pub stack_depth: u16,
24 pub exception_table_offset: u16,
26 pub debug_records_offset: u16,
28}
29
30impl MethodHeader {
31 pub const MIN_SIZE: usize = 10;
34
35 pub fn parse(bytes: &[u8]) -> Option<Self> {
37 let b = bytes.get(..Self::MIN_SIZE)?;
38 let u16_at = |at: usize| u16::from_le_bytes([b[at], b[at + 1]]);
39 Some(Self {
40 param_count: b[0] & 0x7f,
41 varargs: b[0] & 0x80 != 0,
42 optional_param_count: b[1],
43 local_count: u16_at(2),
44 stack_depth: u16_at(4),
45 exception_table_offset: u16_at(6),
46 debug_records_offset: u16_at(8),
47 })
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct ExceptionHandler {
54 pub start: u16,
56 pub end: u16,
58 pub exception_class: u32,
60 pub handler: u16,
62}
63
64#[derive(Debug, Clone)]
66pub struct Function {
67 pub address: u32,
69 pub header: MethodHeader,
71 pub instructions: Vec<Instruction>,
73 pub handlers: Vec<ExceptionHandler>,
75 pub code_end: u32,
77 pub extent: Extent,
79 pub size: u32,
82 pub stray_branches: Vec<StrayBranch>,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct StrayBranch {
94 pub offset: u32,
97 pub target: i64,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum Extent {
108 Table,
110 Limit,
113 Reachable,
116 Gap {
120 len: u32,
122 decodable_end: u32,
126 },
127}
128
129impl Function {
130 pub fn end_address(&self) -> u32 {
132 self.address + self.code_end
133 }
134
135 pub fn tail_address(&self) -> u32 {
138 self.address + self.size
139 }
140
141 pub fn function_references(&self) -> impl Iterator<Item = u32> + '_ {
143 self.instructions
144 .iter()
145 .flat_map(|i| &i.operands)
146 .filter_map(|operand| match operand {
147 Operand::Function(address) => Some(*address),
148 _ => None,
149 })
150 }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum DisassembleError {
156 BadAddress,
159 HeaderTooSmall,
161 BadTableOffset,
164 BadExceptionTable,
166 BadDebugRecords,
168 Decode(DecodeError),
170 Overrun {
172 offset: u32,
174 },
175 BadBranch {
177 offset: u32,
179 target: i64,
181 },
182}
183
184impl fmt::Display for DisassembleError {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 match self {
187 Self::BadAddress => write!(f, "address is not a function in the code pool"),
188 Self::HeaderTooSmall => write!(f, "method header size is too small"),
189 Self::BadTableOffset => write!(f, "method header has an impossible table offset"),
190 Self::BadExceptionTable => write!(f, "exception table runs past the end of its page"),
191 Self::BadDebugRecords => write!(f, "debug records are malformed"),
192 Self::Decode(error) => write!(f, "{error}"),
193 Self::Overrun { offset } => {
194 write!(
195 f,
196 "instruction at offset {offset:#x} runs past the end of the code"
197 )
198 }
199 Self::BadBranch { offset, target } => {
200 write!(
201 f,
202 "branch at offset {offset:#x} targets {target:#x}, outside the function"
203 )
204 }
205 }
206 }
207}
208
209impl std::error::Error for DisassembleError {}
210
211impl From<DecodeError> for DisassembleError {
212 fn from(error: DecodeError) -> Self {
213 Self::Decode(error)
214 }
215}
216
217fn falls_through(opcode: Opcode) -> bool {
219 !matches!(
220 opcode,
221 Opcode::RetVal
222 | Opcode::RetNil
223 | Opcode::RetTrue
224 | Opcode::Ret
225 | Opcode::Jmp
226 | Opcode::Throw
227 | Opcode::Switch
228 | Opcode::LRet
229 )
230}
231
232pub fn disassemble(
237 image: &Image,
238 address: u32,
239 limit: Option<u32>,
240) -> Result<Function, DisassembleError> {
241 let header_size = image.entry_point.method_header_size as usize;
242 if header_size < MethodHeader::MIN_SIZE {
243 return Err(DisassembleError::HeaderTooSmall);
244 }
245 let page = image
247 .code_pool
248 .at(address)
249 .ok_or(DisassembleError::BadAddress)?;
250 let header = MethodHeader::parse(page).ok_or(DisassembleError::BadAddress)?;
251 if page.len() < header_size {
252 return Err(DisassembleError::BadAddress);
253 }
254 let first = header_size as u32;
255
256 let table_offset = match (header.exception_table_offset, header.debug_records_offset) {
257 (0, 0) => None,
258 (0, debug) => Some(debug),
259 (exceptions, _) => Some(exceptions),
260 };
261 if let Some(offset) = table_offset
262 && ((offset as usize) < header_size || offset as usize > page.len())
263 {
264 return Err(DisassembleError::BadTableOffset);
265 }
266
267 let handlers = exception_table(image, page, &header)?;
268
269 let mut padding = 0u32;
270 let (instructions, code_end, extent) = match table_offset {
271 Some(end) => {
272 let code = &page[..end as usize];
273 let instructions =
274 linear(code, first)?.ok_or(DisassembleError::Overrun { offset: end.into() })?;
275 (instructions, u32::from(end), Extent::Table)
276 }
277 None => {
278 let mut found = reachable(page, &[first])?;
281 let mut end = found
282 .values()
283 .map(|i| i.offset + i.len)
284 .max()
285 .unwrap_or(first);
286 let bound = match limit {
287 Some(limit) if limit > address && ((limit - address) as usize) <= page.len() => {
288 limit - address
289 }
290 _ => page.len() as u32,
291 };
292 let mut extent = Extent::Reachable;
293 if bound >= end && (limit.is_some() || bound == end) {
294 match linear(&page[..bound as usize], end) {
298 Ok(Some(dead)) => {
299 for instruction in dead {
300 found.insert(instruction.offset, instruction);
301 }
302 end = bound;
303 extent = Extent::Limit;
304 }
305 _ => {
306 let (dead, stop) = linear_prefix(&page[..bound as usize], end);
309 if page[stop as usize..bound as usize].iter().all(|&b| b == 0) {
310 for instruction in dead {
311 found.insert(instruction.offset, instruction);
312 }
313 end = stop;
314 padding = bound - stop;
315 extent = Extent::Limit;
316 } else {
317 extent = Extent::Gap {
318 len: bound - end,
319 decodable_end: stop,
320 };
321 }
322 }
323 }
324 }
325 (found.into_values().collect(), end, extent)
326 }
327 };
328
329 let mut size = code_end + padding;
330 if header.exception_table_offset != 0 {
331 let table = 2 + handlers.len() as u32 * u32::from(image.entry_point.exception_entry_size);
332 size = u32::from(header.exception_table_offset) + table;
333 }
334 if header.debug_records_offset != 0 {
335 size = debug_records_end(image, page, &header).ok_or(DisassembleError::BadDebugRecords)?;
336 }
337
338 let mut function = Function {
339 address,
340 header,
341 instructions,
342 handlers,
343 code_end,
344 extent,
345 size,
346 stray_branches: Vec::new(),
347 };
348 function.stray_branches = stray_branches(&function);
349 Ok(function)
350}
351
352fn linear(code: &[u8], start: u32) -> Result<Option<Vec<Instruction>>, DecodeError> {
355 let mut instructions = Vec::new();
356 let mut offset = start;
357 while (offset as usize) < code.len() {
358 let instruction = decode(code, offset)?;
359 offset += instruction.len;
360 instructions.push(instruction);
361 }
362 Ok((offset as usize == code.len()).then_some(instructions))
363}
364
365fn linear_prefix(code: &[u8], start: u32) -> (Vec<Instruction>, u32) {
368 let mut instructions = Vec::new();
369 let mut offset = start;
370 while (offset as usize) < code.len() {
371 let Ok(instruction) = decode(code, offset) else {
372 break;
373 };
374 if (offset + instruction.len) as usize > code.len() {
375 break;
376 }
377 offset += instruction.len;
378 instructions.push(instruction);
379 }
380 (instructions, offset)
381}
382
383fn reachable(code: &[u8], entries: &[u32]) -> Result<BTreeMap<u32, Instruction>, DisassembleError> {
385 let mut found: BTreeMap<u32, Instruction> = BTreeMap::new();
386 let mut pending: Vec<u32> = entries.to_vec();
387 let mut defaults: Vec<u32> = Vec::new();
390 loop {
391 while let Some(offset) = pending.pop() {
392 if found.contains_key(&offset) {
393 continue;
394 }
395 let instruction = decode(code, offset)?;
396 let in_code = |target: i64| {
397 u32::try_from(target)
398 .ok()
399 .filter(|t| (*t as usize) < code.len())
400 .ok_or(DisassembleError::BadBranch { offset, target })
401 };
402 for operand in &instruction.operands {
403 match *operand {
404 Operand::Branch(target) => pending.push(in_code(target)?),
405 Operand::Table(table) => pending.push(table),
408 _ => {}
409 }
410 }
411 if let Payload::Switch { cases, default } = &instruction.payload {
412 for (_, target) in cases {
413 pending.push(in_code(*target)?);
414 }
415 if let Ok(default) = in_code(*default) {
416 defaults.push(default);
417 }
418 }
419 if falls_through(instruction.opcode) {
420 pending.push(offset + instruction.len);
421 }
422 found.insert(offset, instruction);
423 }
424 let Some(default) = defaults.pop() else {
425 break;
426 };
427 let inside_another = found
428 .range(..default)
429 .next_back()
430 .is_some_and(|(start, i)| start + i.len > default);
431 if !inside_another {
432 pending.push(default);
433 }
434 }
435 Ok(found)
436}
437
438fn exception_table(
439 image: &Image,
440 page: &[u8],
441 header: &MethodHeader,
442) -> Result<Vec<ExceptionHandler>, DisassembleError> {
443 if header.exception_table_offset == 0 {
444 return Ok(Vec::new());
445 }
446 let entry_size = image.entry_point.exception_entry_size as usize;
447 let table = page
448 .get(header.exception_table_offset as usize..)
449 .ok_or(DisassembleError::BadExceptionTable)?;
450 let count = table
451 .get(..2)
452 .map(|b| u16::from_le_bytes([b[0], b[1]]) as usize)
453 .ok_or(DisassembleError::BadExceptionTable)?;
454 if entry_size < 10 {
455 return Err(DisassembleError::BadExceptionTable);
456 }
457 let entries = table
458 .get(2..2 + count * entry_size)
459 .ok_or(DisassembleError::BadExceptionTable)?;
460 Ok(entries
461 .chunks_exact(entry_size)
462 .map(|e| ExceptionHandler {
463 start: u16::from_le_bytes([e[0], e[1]]),
464 end: u16::from_le_bytes([e[2], e[3]]),
465 exception_class: u32::from_le_bytes([e[4], e[5], e[6], e[7]]),
466 handler: u16::from_le_bytes([e[8], e[9]]),
467 })
468 .collect())
469}
470
471fn debug_records_end(image: &Image, page: &[u8], header: &MethodHeader) -> Option<u32> {
478 let entry = &image.entry_point;
479 let u16_at =
480 |at: usize| Some(u16::from_le_bytes([*page.get(at)?, *page.get(at + 1)?]) as usize);
481 let mut pos = header.debug_records_offset as usize + entry.debug_table_header_size as usize;
482 let lines = u16_at(pos)?;
483 pos += 2 + lines * entry.debug_line_entry_size as usize;
484 pos += u16_at(pos)?;
487 pos += 4;
488 (pos <= page.len()).then_some(pos as u32)
489}
490
491fn stray_branches(function: &Function) -> Vec<StrayBranch> {
494 let starts: std::collections::BTreeSet<i64> = function
495 .instructions
496 .iter()
497 .map(|i| i64::from(i.offset))
498 .collect();
499 let mut stray = Vec::new();
500 for instruction in &function.instructions {
501 for target in instruction.branch_targets() {
502 if !starts.contains(&target) {
503 stray.push(StrayBranch {
504 offset: instruction.offset,
505 target,
506 });
507 }
508 }
509 }
510 for handler in &function.handlers {
511 if !starts.contains(&i64::from(handler.handler)) {
512 stray.push(StrayBranch {
513 offset: u32::from(function.header.exception_table_offset),
514 target: handler.handler.into(),
515 });
516 }
517 }
518 stray
519}