1use super::chunk::Chunk;
2use super::opcode::Opcode;
3use super::value::Value;
4use std::fmt;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum TrustLevel {
13 Trusted,
14 Untrusted,
15}
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub struct VerifyConfig {
20 pub trust: TrustLevel,
21}
22
23impl Default for VerifyConfig {
24 fn default() -> Self {
25 Self {
26 trust: TrustLevel::Untrusted,
27 }
28 }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ConstantKind {
34 Capability,
35 ProcessId,
36 Message,
37}
38
39impl fmt::Display for ConstantKind {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 match self {
42 ConstantKind::Capability => f.write_str("capability"),
43 ConstantKind::ProcessId => f.write_str("pid"),
44 ConstantKind::Message => f.write_str("message"),
45 }
46 }
47}
48
49fn validate_constant(value: &Value, trust: TrustLevel, index: usize) -> Result<(), VerifyError> {
50 if trust == TrustLevel::Trusted {
51 return Ok(());
52 }
53 match value {
54 Value::Cap(_) => Err(VerifyError::ForbiddenConstant {
55 index,
56 kind: ConstantKind::Capability,
57 }),
58 Value::Pid(_) => Err(VerifyError::ForbiddenConstant {
59 index,
60 kind: ConstantKind::ProcessId,
61 }),
62 Value::Message(_) => Err(VerifyError::ForbiddenConstant {
63 index,
64 kind: ConstantKind::Message,
65 }),
66 _ => Ok(()),
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum VerifyError {
81 UnknownOpcode {
82 at: usize,
83 byte: u8,
84 },
85 ConstOutOfRange {
86 at: usize,
87 index: u32,
88 len: usize,
89 },
90 FunctionOutOfRange {
91 at: usize,
92 index: u32,
93 len: usize,
94 },
95 JumpOutOfRange {
96 at: usize,
97 target: i64,
98 len: usize,
99 },
100 EmptyFunctionTable,
101 EntryOutOfRange {
102 function: usize,
103 entry: u32,
104 len: usize,
105 },
106 ArityExceedsRegisters {
113 function: usize,
114 arity: u8,
115 num_registers: u8,
116 },
117 ForbiddenConstant {
119 index: usize,
120 kind: ConstantKind,
121 },
122}
123
124impl fmt::Display for VerifyError {
125 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126 match self {
127 VerifyError::UnknownOpcode { at, byte } => {
128 write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
129 }
130 VerifyError::ConstOutOfRange { at, index, len } => write!(
131 f,
132 "instruction {at} references constant {index}, pool has {len} entries"
133 ),
134 VerifyError::FunctionOutOfRange { at, index, len } => write!(
135 f,
136 "instruction {at} references function {index}, table has {len} entries"
137 ),
138 VerifyError::JumpOutOfRange { at, target, len } => write!(
139 f,
140 "instruction {at} jumps to {target}, out of code bounds (len={len})"
141 ),
142 VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
143 VerifyError::EntryOutOfRange {
144 function,
145 entry,
146 len,
147 } => write!(
148 f,
149 "function {function} entry point {entry} is out of code bounds (len={len})"
150 ),
151 VerifyError::ArityExceedsRegisters {
152 function,
153 arity,
154 num_registers,
155 } => write!(
156 f,
157 "function {function} declares arity {arity} but only {num_registers} registers"
158 ),
159 VerifyError::ForbiddenConstant { index, kind } => {
160 write!(f, "untrusted constant[{index}] must not embed {kind}")
161 }
162 }
163 }
164}
165
166impl std::error::Error for VerifyError {}
167
168pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
187 verify_with(chunk, VerifyConfig::default())
188}
189
190pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
192 if chunk.functions.is_empty() {
193 return Err(VerifyError::EmptyFunctionTable);
194 }
195
196 for (index, value) in chunk.constants.iter().enumerate() {
197 validate_constant(value, config.trust, index)?;
198 }
199
200 let len = chunk.code.len();
201
202 for (function, def) in chunk.functions.iter().enumerate() {
206 if def.entry as usize >= len {
207 return Err(VerifyError::EntryOutOfRange {
208 function,
209 entry: def.entry,
210 len,
211 });
212 }
213 if def.arity > def.num_registers {
214 return Err(VerifyError::ArityExceedsRegisters {
215 function,
216 arity: def.arity,
217 num_registers: def.num_registers,
218 });
219 }
220 }
221
222 for (at, instr) in chunk.code.iter().enumerate() {
223 match instr.op {
224 Opcode::LoadConst => {
225 let idx = instr.imm as u32;
226 if idx as usize >= chunk.constants.len() {
227 return Err(VerifyError::ConstOutOfRange {
228 at,
229 index: idx,
230 len: chunk.constants.len(),
231 });
232 }
233 }
234 Opcode::Spawn | Opcode::Call => {
235 let idx = instr.imm as u32;
236 if idx as usize >= chunk.functions.len() {
237 return Err(VerifyError::FunctionOutOfRange {
238 at,
239 index: idx,
240 len: chunk.functions.len(),
241 });
242 }
243 }
244 Opcode::CallNative => {}
249 Opcode::Jump | Opcode::Branch => {
250 let target = at as i64 + 1 + instr.imm as i64;
251 if target < 0 || target as usize > len {
252 return Err(VerifyError::JumpOutOfRange { at, target, len });
255 }
256 }
257 _ => {}
258 }
259 }
260
261 Ok(())
262}
263
264#[cfg(test)]
265mod tests {
266 use super::*;
267 use crate::bytecode::builder::ChunkBuilder;
268 use crate::bytecode::opcode::Opcode;
269
270 #[test]
271 fn rejects_empty_function_table() {
272 let chunk = Chunk::default();
273 assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
274 }
275
276 #[test]
277 fn accepts_well_formed_chunk() {
278 let mut b = ChunkBuilder::new("test");
279 b.begin_function("main", 0, 2);
280 let k = b.const_(crate::bytecode::value::Value::Int(41));
281 b.emit_load_const(0, k);
282 b.emit_load_imm(1, 1);
283 b.emit_binop(Opcode::Add, 0, 0, 1);
284 b.emit_return(0);
285 let chunk = b.finish();
286 assert!(verify(&chunk).is_ok());
287 }
288
289 #[test]
293 fn rejects_arity_larger_than_the_register_file() {
294 let mut b = ChunkBuilder::new("test");
295 b.begin_function("main", 3, 1);
296 b.emit_return(0);
297 let chunk = b.finish();
298 assert_eq!(
299 verify(&chunk),
300 Err(VerifyError::ArityExceedsRegisters {
301 function: 0,
302 arity: 3,
303 num_registers: 1,
304 })
305 );
306 }
307
308 #[test]
309 fn accepts_arity_equal_to_the_register_file() {
310 let mut b = ChunkBuilder::new("test");
311 b.begin_function("main", 2, 2);
312 b.emit_return(0);
313 let chunk = b.finish();
314 assert!(verify(&chunk).is_ok());
315 }
316
317 #[test]
318 fn rejects_out_of_range_jump() {
319 use crate::bytecode::instruction::Instruction;
320 let mut chunk = Chunk::default();
321 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
322 name: "main".into(),
323 entry: 0,
324 arity: 0,
325 num_registers: 1,
326 });
327 chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
328 assert!(matches!(
329 verify(&chunk),
330 Err(VerifyError::JumpOutOfRange { .. })
331 ));
332 }
333
334 #[test]
335 fn untrusted_rejects_cap_pid_message_constants() {
336 use crate::bytecode::cap::CapId;
337 use crate::bytecode::value::Message;
338 for (value, kind) in [
339 (
340 crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
341 ConstantKind::Capability,
342 ),
343 (
344 crate::bytecode::value::Value::Pid(7),
345 ConstantKind::ProcessId,
346 ),
347 (
348 crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
349 ConstantKind::Message,
350 ),
351 ] {
352 let mut b = ChunkBuilder::new("forge");
353 b.begin_function("main", 0, 1);
354 let k = b.const_(value);
355 b.emit_load_const(0, k);
356 b.emit_return(0);
357 let chunk = b.finish();
358 assert_eq!(
359 verify(&chunk),
360 Err(VerifyError::ForbiddenConstant { index: 0, kind })
361 );
362 assert!(verify_with(
363 &chunk,
364 VerifyConfig {
365 trust: TrustLevel::Trusted
366 }
367 )
368 .is_ok());
369 }
370 }
371}