1use std::fmt;
4
5use hexicon_image::Value;
6
7use crate::opcode::{Layout, Opcode, OperandKind};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Operand {
15 Unsigned(u32),
17 Signed(i32),
19 Argc(u16),
21 Local(u16),
23 Arg(u16),
25 String(u32),
27 List(u32),
29 Object(u32),
31 Property(u16),
33 Function(u32),
35 Enum(u32),
37 Branch(i64),
40 Table(u32),
42 Metaclass(u16),
44 FunctionSet(u16),
46 FunctionIndex(u16),
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum Payload {
53 None,
55 InlineString(Vec<u8>),
57 Switch {
59 cases: Vec<(Value, i64)>,
61 default: i64,
63 },
64 NamedArgs(Vec<String>),
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct Instruction {
71 pub offset: u32,
73 pub opcode: Opcode,
75 pub len: u32,
77 pub operands: Vec<Operand>,
79 pub payload: Payload,
81}
82
83impl Instruction {
84 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum DecodeError {
105 InvalidOpcode {
107 offset: u32,
109 byte: u8,
111 },
112 Truncated {
114 offset: u32,
116 opcode: Opcode,
118 },
119 BadNamedArgTable {
121 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
148pub fn decode(code: &[u8], offset: u32) -> Result<Instruction, DecodeError> {
153 let start = offset as usize;
154 let Some(&byte) = code.get(start) else {
155 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
208fn 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 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}