Skip to main content

hexicon_bytecode/
decode.rs

1//! Decoding single instructions.
2
3use std::fmt;
4
5use hexicon_image::Value;
6
7use crate::opcode::{Layout, Opcode, OperandKind};
8
9/// A decoded operand.
10///
11/// Offsets within a function are measured from the start of the function's
12/// method header, which is how the VM's own tables express them.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Operand {
15    /// An unsigned number.
16    Unsigned(u32),
17    /// A signed number.
18    Signed(i32),
19    /// An argument count.
20    Argc(u16),
21    /// A local variable number.
22    Local(u16),
23    /// A parameter number.
24    Arg(u16),
25    /// A constant pool offset of a string.
26    String(u32),
27    /// A constant pool offset of a list.
28    List(u32),
29    /// An object ID.
30    Object(u32),
31    /// A property ID.
32    Property(u16),
33    /// A code pool offset of a function.
34    Function(u32),
35    /// An enumerator ID.
36    Enum(u32),
37    /// A branch target, as an offset within the function. A target before
38    /// the start of the function, which no valid code has, is negative.
39    Branch(i64),
40    /// The offset within the function of a named argument table.
41    Table(u32),
42    /// An index into the image's metaclass dependency list.
43    Metaclass(u16),
44    /// An index into the image's function set dependency list.
45    FunctionSet(u16),
46    /// The index of a function within its function set.
47    FunctionIndex(u16),
48}
49
50/// The variable-length part of the instructions that have one.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Payload {
53    /// The instruction has only fixed operands.
54    None,
55    /// The text of a `pushstri`.
56    InlineString(Vec<u8>),
57    /// The case table of a `switch`.
58    Switch {
59        /// Each case value and its branch target, as an offset within the function.
60        cases: Vec<(Value, i64)>,
61        /// The branch target when no case matches.
62        default: i64,
63    },
64    /// The argument names of a `namedargtab`.
65    NamedArgs(Vec<String>),
66}
67
68/// A decoded instruction.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Instruction {
71    /// Offset of the instruction within its function.
72    pub offset: u32,
73    /// The instruction.
74    pub opcode: Opcode,
75    /// Total encoded length in bytes, including the opcode byte.
76    pub len: u32,
77    /// The fixed operands, in encoding order.
78    pub operands: Vec<Operand>,
79    /// The variable-length part, if any.
80    pub payload: Payload,
81}
82
83impl Instruction {
84    /// Offsets within the function that this instruction can branch to.
85    pub fn branch_targets(&self) -> Vec<i64> {
86        let mut targets: Vec<i64> = self
87            .operands
88            .iter()
89            .filter_map(|operand| match operand {
90                Operand::Branch(target) => Some(*target),
91                _ => None,
92            })
93            .collect();
94        if let Payload::Switch { cases, default } = &self.payload {
95            targets.extend(cases.iter().map(|(_, target)| *target));
96            targets.push(*default);
97        }
98        targets
99    }
100}
101
102/// Why an instruction could not be decoded.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum DecodeError {
105    /// The byte at this offset is not a defined opcode.
106    InvalidOpcode {
107        /// Offset within the function.
108        offset: u32,
109        /// The byte found.
110        byte: u8,
111    },
112    /// The instruction at this offset runs past the end of the code.
113    Truncated {
114        /// Offset within the function.
115        offset: u32,
116        /// The instruction being decoded.
117        opcode: Opcode,
118    },
119    /// A named argument table's index is inconsistent.
120    BadNamedArgTable {
121        /// Offset within the function.
122        offset: u32,
123    },
124}
125
126impl fmt::Display for DecodeError {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        match self {
129            Self::InvalidOpcode { offset, byte } => {
130                write!(f, "invalid opcode {byte:#04x} at offset {offset:#x}")
131            }
132            Self::Truncated { offset, opcode } => {
133                write!(
134                    f,
135                    "{} at offset {offset:#x} runs past the end of the code",
136                    opcode.name()
137                )
138            }
139            Self::BadNamedArgTable { offset } => {
140                write!(f, "malformed named argument table at offset {offset:#x}")
141            }
142        }
143    }
144}
145
146impl std::error::Error for DecodeError {}
147
148/// Decode the instruction at `offset` in `code`.
149///
150/// `code` starts at the function's method header, so `offset` and all
151/// branch targets are relative to the header.
152pub fn decode(code: &[u8], offset: u32) -> Result<Instruction, DecodeError> {
153    let start = offset as usize;
154    let Some(&byte) = code.get(start) else {
155        // There is no opcode to name; report the end of the code.
156        return Err(DecodeError::InvalidOpcode { offset, byte: 0 });
157    };
158    let opcode = Opcode::from_byte(byte).ok_or(DecodeError::InvalidOpcode { offset, byte })?;
159    let truncated = DecodeError::Truncated { offset, opcode };
160
161    let mut cursor = Cursor {
162        code,
163        pos: start + 1,
164    };
165    let mut operands = Vec::new();
166    let mut payload = Payload::None;
167
168    match opcode.layout() {
169        Layout::Fixed(kinds) => {
170            operands.reserve(kinds.len());
171            for &kind in kinds {
172                operands.push(cursor.operand(kind).ok_or(truncated)?);
173            }
174        }
175        Layout::InlineString => {
176            let len = cursor.u16().ok_or(truncated)? as usize;
177            payload = Payload::InlineString(cursor.bytes(len).ok_or(truncated)?.to_vec());
178        }
179        Layout::Switch => {
180            let count = cursor.u16().ok_or(truncated)? as usize;
181            let mut cases = Vec::with_capacity(count.min(1024));
182            for _ in 0..count {
183                let holder = cursor.bytes(Value::ENCODED_SIZE).ok_or(truncated)?;
184                let value = Value::decode([holder[0], holder[1], holder[2], holder[3], holder[4]]);
185                cases.push((value, cursor.branch().ok_or(truncated)?));
186            }
187            let default = cursor.branch().ok_or(truncated)?;
188            payload = Payload::Switch { cases, default };
189        }
190        Layout::NamedArgTable => {
191            let table_len = cursor.u16().ok_or(truncated)? as usize;
192            let table = cursor.bytes(table_len).ok_or(truncated)?;
193            payload = Payload::NamedArgs(
194                named_args(table).ok_or(DecodeError::BadNamedArgTable { offset })?,
195            );
196        }
197    }
198
199    Ok(Instruction {
200        offset,
201        opcode,
202        len: (cursor.pos - start) as u32,
203        operands,
204        payload,
205    })
206}
207
208/// Read the names from a named argument table: a count, an index of
209/// `count + 1` offsets measured from the start of the index, and the names
210/// themselves, each running from its offset to the next.
211fn named_args(table: &[u8]) -> Option<Vec<String>> {
212    let u16_at = |at: usize| Some(u16::from_le_bytes([*table.get(at)?, *table.get(at + 1)?]));
213    let count = u16_at(0)? as usize;
214    let index = table.get(2..)?;
215    let mut names = Vec::with_capacity(count.min(256));
216    for i in 0..count {
217        let start = u16_at(2 + i * 2)? as usize;
218        let end = u16_at(2 + (i + 1) * 2)? as usize;
219        names.push(String::from_utf8_lossy(index.get(start..end)?).into_owned());
220    }
221    Some(names)
222}
223
224struct Cursor<'a> {
225    code: &'a [u8],
226    pos: usize,
227}
228
229impl<'a> Cursor<'a> {
230    fn bytes(&mut self, len: usize) -> Option<&'a [u8]> {
231        let slice = self.code.get(self.pos..self.pos.checked_add(len)?)?;
232        self.pos += len;
233        Some(slice)
234    }
235
236    fn u8(&mut self) -> Option<u8> {
237        Some(self.bytes(1)?[0])
238    }
239
240    fn u16(&mut self) -> Option<u16> {
241        let b = self.bytes(2)?;
242        Some(u16::from_le_bytes([b[0], b[1]]))
243    }
244
245    fn u32(&mut self) -> Option<u32> {
246        let b = self.bytes(4)?;
247        Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
248    }
249
250    /// A branch offset, resolved against its own position.
251    fn branch(&mut self) -> Option<i64> {
252        let at = self.pos as i64;
253        Some(at + i64::from(self.u16()? as i16))
254    }
255
256    fn operand(&mut self, kind: OperandKind) -> Option<Operand> {
257        Some(match kind {
258            OperandKind::U8 => Operand::Unsigned(self.u8()?.into()),
259            OperandKind::S8 => Operand::Signed((self.u8()? as i8).into()),
260            OperandKind::U16 => Operand::Unsigned(self.u16()?.into()),
261            OperandKind::S32 => Operand::Signed(self.u32()? as i32),
262            OperandKind::Argc8 => Operand::Argc(self.u8()?.into()),
263            OperandKind::Argc16 => Operand::Argc(self.u16()?),
264            OperandKind::Local8 => Operand::Local(self.u8()?.into()),
265            OperandKind::Local16 => Operand::Local(self.u16()?),
266            OperandKind::Arg8 => Operand::Arg(self.u8()?.into()),
267            OperandKind::Arg16 => Operand::Arg(self.u16()?),
268            OperandKind::String => Operand::String(self.u32()?),
269            OperandKind::List => Operand::List(self.u32()?),
270            OperandKind::Object => Operand::Object(self.u32()?),
271            OperandKind::Property => Operand::Property(self.u16()?),
272            OperandKind::Function => Operand::Function(self.u32()?),
273            OperandKind::Enum => Operand::Enum(self.u32()?),
274            OperandKind::Branch => Operand::Branch(self.branch()?),
275            OperandKind::TableOffset => {
276                let at = self.pos as u32;
277                Operand::Table(at + u32::from(self.u16()?))
278            }
279            OperandKind::Metaclass8 => Operand::Metaclass(self.u8()?.into()),
280            OperandKind::Metaclass16 => Operand::Metaclass(self.u16()?),
281            OperandKind::FunctionSet8 => Operand::FunctionSet(self.u8()?.into()),
282            OperandKind::FunctionSet16 => Operand::FunctionSet(self.u16()?),
283            OperandKind::FunctionIndex8 => Operand::FunctionIndex(self.u8()?.into()),
284            OperandKind::FunctionIndex16 => Operand::FunctionIndex(self.u16()?),
285        })
286    }
287}