Skip to main content

hexicon_bytecode/
function.rs

1//! Functions: method headers, exception tables, and whole-function disassembly.
2
3use 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/// The fixed-size record at the start of every function.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct MethodHeader {
14    /// Number of required parameters.
15    pub param_count: u8,
16    /// Whether the function accepts any number of further arguments.
17    pub varargs: bool,
18    /// Number of optional parameters after the required ones.
19    pub optional_param_count: u8,
20    /// Number of local variables.
21    pub local_count: u16,
22    /// Stack slots the function needs for locals and intermediate values.
23    pub stack_depth: u16,
24    /// Offset of the exception table from the start of the header, or 0.
25    pub exception_table_offset: u16,
26    /// Offset of the debug records from the start of the header, or 0.
27    pub debug_records_offset: u16,
28}
29
30impl MethodHeader {
31    /// The smallest header this crate reads. Images state their own header
32    /// size, which may be larger; later fields are ignored.
33    pub const MIN_SIZE: usize = 10;
34
35    /// Read a header from the start of `bytes`.
36    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/// One entry of a function's exception table.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct ExceptionHandler {
54    /// Offset of the first byte of protected code.
55    pub start: u16,
56    /// Offset of the last byte of protected code.
57    pub end: u16,
58    /// The exception class caught, or 0 to catch everything.
59    pub exception_class: u32,
60    /// Offset of the handler's code.
61    pub handler: u16,
62}
63
64/// A disassembled function.
65#[derive(Debug, Clone)]
66pub struct Function {
67    /// Code pool address of the function's method header.
68    pub address: u32,
69    /// The method header.
70    pub header: MethodHeader,
71    /// The instructions, in ascending order of offset.
72    pub instructions: Vec<Instruction>,
73    /// The exception table.
74    pub handlers: Vec<ExceptionHandler>,
75    /// Offset just past the last decoded instruction.
76    pub code_end: u32,
77    /// How the extent of the code was established.
78    pub extent: Extent,
79    /// Total size in bytes: header, code, exception table, and debug
80    /// records, plus any zero padding that follows the code.
81    pub size: u32,
82    /// Branches that do not land on the start of an instruction.
83    pub stray_branches: Vec<StrayBranch>,
84}
85
86/// A branch that does not land on the start of an instruction.
87///
88/// The reference compiler produces a few of these: the `switch` it
89/// generates for some expressions has a default branch that points into
90/// the middle of an instruction. The default is never taken, so the
91/// program runs correctly, and a disassembler has to tolerate it.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct StrayBranch {
94    /// Offset of the branching instruction within the function, or of the
95    /// exception table for a stray handler.
96    pub offset: u32,
97    /// The target offset.
98    pub target: i64,
99}
100
101/// How the end of a function's code was established.
102///
103/// A method header gives no code length. The code ends where the exception
104/// table or debug records begin, if the function has either. Otherwise the
105/// only evidence is the code itself and where the next function starts.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum Extent {
108    /// The header locates a table that follows the code.
109    Table,
110    /// The code runs exactly to the start of the next known function, or to
111    /// the end of its page.
112    Limit,
113    /// The code was followed along its branches; nothing more is known
114    /// about what lies beyond the last reachable instruction.
115    Reachable,
116    /// Reachable code ends before the next known function, and the bytes
117    /// between are not a whole number of instructions. They may be an
118    /// undiscovered function.
119    Gap {
120        /// Number of bytes between the reachable code and the limit.
121        len: u32,
122        /// Offset within the function where the bytes after the reachable
123        /// code stop decoding as instructions. If unreachable code follows
124        /// the function, the next function starts here.
125        decodable_end: u32,
126    },
127}
128
129impl Function {
130    /// Code pool address just past the function's code.
131    pub fn end_address(&self) -> u32 {
132        self.address + self.code_end
133    }
134
135    /// Code pool address just past everything that belongs to the function:
136    /// its code, exception table, and debug records.
137    pub fn tail_address(&self) -> u32 {
138        self.address + self.size
139    }
140
141    /// Code pool addresses of the functions this function refers to.
142    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/// Why a function could not be disassembled.
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
155pub enum DisassembleError {
156    /// The address is not in the image's code pool, or too close to the end
157    /// of its page to hold a method header.
158    BadAddress,
159    /// The image's method header size is smaller than this crate can read.
160    HeaderTooSmall,
161    /// The header places the exception table or debug records before the
162    /// first instruction or beyond the page.
163    BadTableOffset,
164    /// The exception table runs past the end of the page.
165    BadExceptionTable,
166    /// The debug records are malformed or run past the end of the page.
167    BadDebugRecords,
168    /// An instruction could not be decoded.
169    Decode(DecodeError),
170    /// An instruction runs past the end of the code.
171    Overrun {
172        /// Offset of the instruction within the function.
173        offset: u32,
174    },
175    /// A branch leaves the function's code, so the code cannot be followed.
176    BadBranch {
177        /// Offset of the branching instruction within the function.
178        offset: u32,
179        /// The target offset.
180        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
217/// Whether control can continue to the instruction after this one.
218fn 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
232/// Disassemble the function at a code pool address.
233///
234/// `limit` is the code pool address of the next function, if known. It is
235/// used only for functions whose headers do not locate the end of the code.
236pub 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    // A function lies within one page, so the page bounds the code.
246    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            // No handlers exist without an exception table, so the first
279            // instruction is the only entry.
280            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                // Code after the last reachable instruction is unreachable
295                // but still part of the function, if it decodes cleanly up
296                // to the bound.
297                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                        // Decode what there is; if only zero bytes remain,
307                        // they are padding, not code.
308                        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
352/// Decode instructions one after another from `start` to the end of `code`.
353/// Returns `None` if the last instruction does not end exactly there.
354fn 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
365/// Decode instructions one after another from `start` for as long as they
366/// decode and fit, returning them and the offset where decoding stopped.
367fn 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
383/// Decode every instruction that can be reached from the entry offsets.
384fn 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    // Switch defaults are followed last, and only if they do not point into
388    // an instruction already decoded; see `StrayBranch`.
389    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                    // A named argument table is data in the code stream,
406                    // laid out as an instruction so it can be skipped.
407                    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
471/// Find the offset just past a function's debug records.
472///
473/// The records are a header, a counted array of line records, a frame table
474/// that states its own length, and a reserved 32-bit zero. Release builds
475/// have them too, for functions with local variables: the frame table is
476/// what lets a running program look up its locals by name.
477fn 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    // The frame table starts with the offset, from that field, to the
485    // first byte after the table.
486    pos += u16_at(pos)?;
487    pos += 4;
488    (pos <= page.len()).then_some(pos as u32)
489}
490
491/// Find the branches and handlers that do not land on the start of an
492/// instruction.
493fn 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}