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 | Opcode::StartChild => {
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 if let Some((start, end)) = function_span(&chunk.functions, at, len) {
260 let t = target as usize;
261 if t != len && (t < start || t >= end) {
262 return Err(VerifyError::JumpOutOfRange { at, target, len });
263 }
264 }
265 }
266 _ => {}
267 }
268 }
269
270 Ok(())
271}
272
273fn function_span(
276 functions: &[super::chunk::FunctionDef],
277 at: usize,
278 code_len: usize,
279) -> Option<(usize, usize)> {
280 let mut start = None;
281 for def in functions {
282 let entry = def.entry as usize;
283 if entry <= at {
284 start = Some(match start {
285 Some(prev) if prev >= entry => prev,
286 _ => entry,
287 });
288 }
289 }
290 let start = start?;
291 let mut end = code_len;
292 for def in functions {
293 let entry = def.entry as usize;
294 if entry > start && entry < end {
295 end = entry;
296 }
297 }
298 if at >= end {
299 None
300 } else {
301 Some((start, end))
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308 use crate::bytecode::builder::ChunkBuilder;
309 use crate::bytecode::opcode::Opcode;
310
311 #[test]
312 fn rejects_empty_function_table() {
313 let chunk = Chunk::default();
314 assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
315 }
316
317 #[test]
318 fn accepts_well_formed_chunk() {
319 let mut b = ChunkBuilder::new("test");
320 b.begin_function("main", 0, 2);
321 let k = b.const_(crate::bytecode::value::Value::Int(41));
322 b.emit_load_const(0, k);
323 b.emit_load_imm(1, 1);
324 b.emit_binop(Opcode::Add, 0, 0, 1);
325 b.emit_return(0);
326 let chunk = b.finish();
327 assert!(verify(&chunk).is_ok());
328 }
329
330 #[test]
334 fn rejects_arity_larger_than_the_register_file() {
335 let mut b = ChunkBuilder::new("test");
336 b.begin_function("main", 3, 1);
337 b.emit_return(0);
338 let chunk = b.finish();
339 assert_eq!(
340 verify(&chunk),
341 Err(VerifyError::ArityExceedsRegisters {
342 function: 0,
343 arity: 3,
344 num_registers: 1,
345 })
346 );
347 }
348
349 #[test]
350 fn accepts_arity_equal_to_the_register_file() {
351 let mut b = ChunkBuilder::new("test");
352 b.begin_function("main", 2, 2);
353 b.emit_return(0);
354 let chunk = b.finish();
355 assert!(verify(&chunk).is_ok());
356 }
357
358 #[test]
359 fn rejects_start_child_function_out_of_range() {
360 use crate::bytecode::instruction::Instruction;
361 let mut chunk = Chunk::default();
362 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
363 name: "main".into(),
364 entry: 0,
365 arity: 0,
366 num_registers: 1,
367 });
368 chunk
369 .code
370 .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
371 assert!(matches!(
372 verify(&chunk),
373 Err(VerifyError::FunctionOutOfRange { index: 99, .. })
374 ));
375 }
376
377 #[test]
378 fn rejects_jump_into_another_function() {
379 use crate::bytecode::instruction::Instruction;
380 let mut chunk = Chunk::default();
381 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
382 name: "main".into(),
383 entry: 0,
384 arity: 0,
385 num_registers: 1,
386 });
387 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
388 name: "other".into(),
389 entry: 2,
390 arity: 0,
391 num_registers: 1,
392 });
393 chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
395 chunk.code.push(Instruction::nullary(Opcode::Nop));
396 chunk.code.push(Instruction::nullary(Opcode::Nop));
397 assert!(matches!(
398 verify(&chunk),
399 Err(VerifyError::JumpOutOfRange { target: 2, .. })
400 ));
401 }
402
403 #[test]
404 fn rejects_out_of_range_jump() {
405 use crate::bytecode::instruction::Instruction;
406 let mut chunk = Chunk::default();
407 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
408 name: "main".into(),
409 entry: 0,
410 arity: 0,
411 num_registers: 1,
412 });
413 chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
414 assert!(matches!(
415 verify(&chunk),
416 Err(VerifyError::JumpOutOfRange { .. })
417 ));
418 }
419
420 #[test]
421 fn untrusted_rejects_cap_pid_message_constants() {
422 use crate::bytecode::cap::CapId;
423 use crate::bytecode::value::Message;
424 for (value, kind) in [
425 (
426 crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
427 ConstantKind::Capability,
428 ),
429 (
430 crate::bytecode::value::Value::Pid(7),
431 ConstantKind::ProcessId,
432 ),
433 (
434 crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
435 ConstantKind::Message,
436 ),
437 ] {
438 let mut b = ChunkBuilder::new("forge");
439 b.begin_function("main", 0, 1);
440 let k = b.const_(value);
441 b.emit_load_const(0, k);
442 b.emit_return(0);
443 let chunk = b.finish();
444 assert_eq!(
445 verify(&chunk),
446 Err(VerifyError::ForbiddenConstant { index: 0, kind })
447 );
448 assert!(verify_with(
449 &chunk,
450 VerifyConfig {
451 trust: TrustLevel::Trusted
452 }
453 )
454 .is_ok());
455 }
456 }
457}