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 if !value.within_nesting_limit() {
54 return Err(VerifyError::ForbiddenConstant {
55 index,
56 kind: ConstantKind::Capability,
57 });
58 }
59 reject_untrusted_constant(value, index)
60}
61
62fn reject_untrusted_constant(value: &Value, index: usize) -> Result<(), VerifyError> {
65 match value {
66 Value::Cap(_) => Err(VerifyError::ForbiddenConstant {
67 index,
68 kind: ConstantKind::Capability,
69 }),
70 Value::Pid(_) => Err(VerifyError::ForbiddenConstant {
71 index,
72 kind: ConstantKind::ProcessId,
73 }),
74 Value::Message(_) => Err(VerifyError::ForbiddenConstant {
75 index,
76 kind: ConstantKind::Message,
77 }),
78 Value::List(items) => {
79 for item in items.iter() {
80 reject_untrusted_constant(item, index)?;
81 }
82 Ok(())
83 }
84 Value::Map(entries) => {
85 for (_, value) in entries.iter() {
86 reject_untrusted_constant(value, index)?;
87 }
88 Ok(())
89 }
90 _ => Ok(()),
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum VerifyError {
105 UnknownOpcode {
106 at: usize,
107 byte: u8,
108 },
109 ConstOutOfRange {
110 at: usize,
111 index: u32,
112 len: usize,
113 },
114 FunctionOutOfRange {
115 at: usize,
116 index: u32,
117 len: usize,
118 },
119 JumpOutOfRange {
120 at: usize,
121 target: i64,
122 len: usize,
123 },
124 EmptyFunctionTable,
125 EntryOutOfRange {
126 function: usize,
127 entry: u32,
128 len: usize,
129 },
130 ArityExceedsRegisters {
137 function: usize,
138 arity: u8,
139 num_registers: u8,
140 },
141 CallArity {
145 at: usize,
146 function: u32,
147 argc: u8,
148 arity: u8,
149 },
150 ForbiddenConstant {
152 index: usize,
153 kind: ConstantKind,
154 },
155 FallThrough {
160 function: usize,
161 at: usize,
162 next_entry: usize,
163 },
164}
165
166impl fmt::Display for VerifyError {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match self {
169 VerifyError::UnknownOpcode { at, byte } => {
170 write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
171 }
172 VerifyError::ConstOutOfRange { at, index, len } => write!(
173 f,
174 "instruction {at} references constant {index}, pool has {len} entries"
175 ),
176 VerifyError::FunctionOutOfRange { at, index, len } => write!(
177 f,
178 "instruction {at} references function {index}, table has {len} entries"
179 ),
180 VerifyError::JumpOutOfRange { at, target, len } => write!(
181 f,
182 "instruction {at} jumps to {target}, out of code bounds (len={len})"
183 ),
184 VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
185 VerifyError::EntryOutOfRange {
186 function,
187 entry,
188 len,
189 } => write!(
190 f,
191 "function {function} entry point {entry} is out of code bounds (len={len})"
192 ),
193 VerifyError::ArityExceedsRegisters {
194 function,
195 arity,
196 num_registers,
197 } => write!(
198 f,
199 "function {function} declares arity {arity} but only {num_registers} registers"
200 ),
201 VerifyError::CallArity {
202 at,
203 function,
204 argc,
205 arity,
206 } => write!(
207 f,
208 "instruction {at} invokes function {function} with {argc} arguments, arity is {arity}"
209 ),
210 VerifyError::ForbiddenConstant { index, kind } => {
211 write!(f, "untrusted constant[{index}] must not embed {kind}")
212 }
213 VerifyError::FallThrough {
214 function,
215 at,
216 next_entry,
217 } => write!(
218 f,
219 "function {function} falls through at instruction {at} into the function at {next_entry}"
220 ),
221 }
222 }
223}
224
225impl std::error::Error for VerifyError {}
226
227pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
248 verify_with(chunk, VerifyConfig::default())
249}
250
251pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
253 if chunk.functions.is_empty() {
254 return Err(VerifyError::EmptyFunctionTable);
255 }
256
257 for (index, value) in chunk.constants.iter().enumerate() {
258 validate_constant(value, config.trust, index)?;
259 }
260
261 let len = chunk.code.len();
262
263 for (function, def) in chunk.functions.iter().enumerate() {
267 if def.entry as usize >= len {
268 return Err(VerifyError::EntryOutOfRange {
269 function,
270 entry: def.entry,
271 len,
272 });
273 }
274 if def.arity > def.num_registers {
275 return Err(VerifyError::ArityExceedsRegisters {
276 function,
277 arity: def.arity,
278 num_registers: def.num_registers,
279 });
280 }
281 }
282
283 for (at, instr) in chunk.code.iter().enumerate() {
284 match instr.op {
285 Opcode::LoadConst => {
286 let idx = instr.imm as u32;
287 if idx as usize >= chunk.constants.len() {
288 return Err(VerifyError::ConstOutOfRange {
289 at,
290 index: idx,
291 len: chunk.constants.len(),
292 });
293 }
294 }
295 Opcode::Call | Opcode::Spawn => {
296 let idx = instr.imm as u32;
297 if idx as usize >= chunk.functions.len() {
298 return Err(VerifyError::FunctionOutOfRange {
299 at,
300 index: idx,
301 len: chunk.functions.len(),
302 });
303 }
304 let arity = chunk.functions[idx as usize].arity;
305 if instr.b != arity {
306 return Err(VerifyError::CallArity {
307 at,
308 function: idx,
309 argc: instr.b,
310 arity,
311 });
312 }
313 }
314 Opcode::StartChild => {
315 let idx = instr.imm as u32;
316 if idx as usize >= chunk.functions.len() {
317 return Err(VerifyError::FunctionOutOfRange {
318 at,
319 index: idx,
320 len: chunk.functions.len(),
321 });
322 }
323 let arity = chunk.functions[idx as usize].arity;
326 if arity != 0 {
327 return Err(VerifyError::CallArity {
328 at,
329 function: idx,
330 argc: 0,
331 arity,
332 });
333 }
334 }
335 Opcode::CallNative | Opcode::CallNativeFrom => {}
340 Opcode::Jump | Opcode::Branch => {
341 let target = at as i64 + 1 + instr.imm as i64;
342 if target < 0 || target as usize > len {
343 return Err(VerifyError::JumpOutOfRange { at, target, len });
346 }
347 if let Some((start, end)) = function_span(&chunk.functions, at, len) {
351 let t = target as usize;
352 if t != len && (t < start || t >= end) {
353 return Err(VerifyError::JumpOutOfRange { at, target, len });
354 }
355 }
356 }
357 _ => {}
358 }
359 }
360
361 reject_fallthrough(chunk)?;
362 Ok(())
363}
364
365fn is_terminator(op: Opcode) -> bool {
369 matches!(
370 op,
371 Opcode::Jump | Opcode::Return | Opcode::Halt | Opcode::Exit | Opcode::Trap
372 )
373}
374
375fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
378 let mut end = code_len;
379 for def in functions {
380 let entry = def.entry as usize;
381 if entry > start && entry < end {
382 end = entry;
383 }
384 }
385 end
386}
387
388fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
393 let len = chunk.code.len();
394 for (function, def) in chunk.functions.iter().enumerate() {
395 let start = def.entry as usize;
396 let end = exclusive_end(&chunk.functions, start, len);
397 if end >= len || end <= start {
398 continue;
399 }
400 let at = end - 1;
401 if !is_terminator(chunk.code[at].op) {
402 return Err(VerifyError::FallThrough {
403 function,
404 at,
405 next_entry: end,
406 });
407 }
408 }
409 Ok(())
410}
411
412fn function_span(
415 functions: &[super::chunk::FunctionDef],
416 at: usize,
417 code_len: usize,
418) -> Option<(usize, usize)> {
419 let mut start = None;
420 for def in functions {
421 let entry = def.entry as usize;
422 if entry <= at {
423 start = Some(match start {
424 Some(prev) if prev >= entry => prev,
425 _ => entry,
426 });
427 }
428 }
429 let start = start?;
430 let end = exclusive_end(functions, start, code_len);
431 if at >= end {
432 None
433 } else {
434 Some((start, end))
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use crate::bytecode::builder::ChunkBuilder;
442 use crate::bytecode::opcode::Opcode;
443
444 #[test]
445 fn rejects_empty_function_table() {
446 let chunk = Chunk::default();
447 assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
448 }
449
450 #[test]
451 fn accepts_well_formed_chunk() {
452 let mut b = ChunkBuilder::new("test");
453 b.begin_function("main", 0, 2);
454 let k = b.const_(crate::bytecode::value::Value::Int(41));
455 b.emit_load_const(0, k);
456 b.emit_load_imm(1, 1);
457 b.emit_binop(Opcode::Add, 0, 0, 1);
458 b.emit_return(0);
459 let chunk = b.finish();
460 assert!(verify(&chunk).is_ok());
461 }
462
463 #[test]
467 fn rejects_arity_larger_than_the_register_file() {
468 let mut b = ChunkBuilder::new("test");
469 b.begin_function("main", 3, 1);
470 b.emit_return(0);
471 let chunk = b.finish();
472 assert_eq!(
473 verify(&chunk),
474 Err(VerifyError::ArityExceedsRegisters {
475 function: 0,
476 arity: 3,
477 num_registers: 1,
478 })
479 );
480 }
481
482 #[test]
483 fn accepts_arity_equal_to_the_register_file() {
484 let mut b = ChunkBuilder::new("test");
485 b.begin_function("main", 2, 2);
486 b.emit_return(0);
487 let chunk = b.finish();
488 assert!(verify(&chunk).is_ok());
489 }
490
491 #[test]
492 fn rejects_start_child_function_out_of_range() {
493 use crate::bytecode::instruction::Instruction;
494 let mut chunk = Chunk::default();
495 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
496 name: "main".into(),
497 entry: 0,
498 arity: 0,
499 num_registers: 1,
500 });
501 chunk
502 .code
503 .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
504 assert!(matches!(
505 verify(&chunk),
506 Err(VerifyError::FunctionOutOfRange { index: 99, .. })
507 ));
508 }
509
510 #[test]
511 fn rejects_jump_into_another_function() {
512 use crate::bytecode::instruction::Instruction;
513 let mut chunk = Chunk::default();
514 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
515 name: "main".into(),
516 entry: 0,
517 arity: 0,
518 num_registers: 1,
519 });
520 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
521 name: "other".into(),
522 entry: 2,
523 arity: 0,
524 num_registers: 1,
525 });
526 chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
528 chunk.code.push(Instruction::nullary(Opcode::Nop));
529 chunk.code.push(Instruction::nullary(Opcode::Nop));
530 assert!(matches!(
531 verify(&chunk),
532 Err(VerifyError::JumpOutOfRange { target: 2, .. })
533 ));
534 }
535
536 #[test]
537 fn rejects_out_of_range_jump() {
538 use crate::bytecode::instruction::Instruction;
539 let mut chunk = Chunk::default();
540 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
541 name: "main".into(),
542 entry: 0,
543 arity: 0,
544 num_registers: 1,
545 });
546 chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
547 assert!(matches!(
548 verify(&chunk),
549 Err(VerifyError::JumpOutOfRange { .. })
550 ));
551 }
552
553 fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
554 use crate::bytecode::instruction::Instruction;
555 let mut chunk = Chunk::default();
556 for (name, entry) in [("main", 0u32), ("other", 1)] {
557 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
558 name: name.into(),
559 entry,
560 arity: 0,
561 num_registers: 1,
562 });
563 }
564 chunk.code.push(first);
565 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
566 chunk
567 }
568
569 #[test]
570 fn rejects_fallthrough_into_the_next_function() {
571 use crate::bytecode::instruction::Instruction;
572 let boundary = VerifyError::FallThrough {
573 function: 0,
574 at: 0,
575 next_entry: 1,
576 };
577 for first in [
578 Instruction::nullary(Opcode::Nop),
579 Instruction::a_imm(Opcode::Branch, 0, -1),
580 Instruction::new(Opcode::Call, 0, 0, 0, 1),
581 ] {
582 assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
583 }
584 }
585
586 #[test]
587 fn accepts_jump_closing_a_function_before_the_next() {
588 use crate::bytecode::instruction::Instruction;
589 let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
591 assert!(verify(&chunk).is_ok());
592 }
593
594 #[test]
595 fn rejects_call_whose_argc_differs_from_the_callee() {
596 use crate::bytecode::instruction::Instruction;
597 let mut chunk = Chunk::default();
598 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
599 name: "main".into(),
600 entry: 0,
601 arity: 0,
602 num_registers: 1,
603 });
604 chunk.code.push(Instruction::new(Opcode::Call, 0, 1, 0, 0));
605 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
606 assert_eq!(
607 verify(&chunk),
608 Err(VerifyError::CallArity {
609 at: 0,
610 function: 0,
611 argc: 1,
612 arity: 0,
613 })
614 );
615 }
616
617 #[test]
618 fn rejects_spawn_whose_argc_differs_from_the_callee() {
619 use crate::bytecode::instruction::Instruction;
620 let mut chunk = Chunk::default();
621 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
622 name: "main".into(),
623 entry: 0,
624 arity: 2,
625 num_registers: 2,
626 });
627 chunk.code.push(Instruction::new(Opcode::Spawn, 0, 0, 0, 0));
628 chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
629 assert_eq!(
630 verify(&chunk),
631 Err(VerifyError::CallArity {
632 at: 0,
633 function: 0,
634 argc: 0,
635 arity: 2,
636 })
637 );
638 }
639
640 #[test]
641 fn rejects_start_child_of_a_function_that_expects_arguments() {
642 use crate::bytecode::instruction::Instruction;
643 let mut chunk = Chunk::default();
644 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
645 name: "main".into(),
646 entry: 0,
647 arity: 1,
648 num_registers: 1,
649 });
650 chunk
651 .code
652 .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 0));
653 chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
654 assert_eq!(
655 verify(&chunk),
656 Err(VerifyError::CallArity {
657 at: 0,
658 function: 0,
659 argc: 0,
660 arity: 1,
661 })
662 );
663 }
664
665 #[test]
666 fn accepts_implicit_return_on_the_last_function() {
667 use crate::bytecode::instruction::Instruction;
668 let mut chunk = Chunk::default();
669 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
670 name: "main".into(),
671 entry: 0,
672 arity: 0,
673 num_registers: 1,
674 });
675 chunk.code.push(Instruction::nullary(Opcode::Nop));
676 assert!(verify(&chunk).is_ok());
677 }
678
679 #[test]
680 fn untrusted_rejects_cap_pid_message_constants() {
681 use crate::bytecode::cap::CapId;
682 use crate::bytecode::value::Message;
683 for (value, kind) in [
684 (
685 crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
686 ConstantKind::Capability,
687 ),
688 (
689 crate::bytecode::value::Value::Pid(7),
690 ConstantKind::ProcessId,
691 ),
692 (
693 crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
694 ConstantKind::Message,
695 ),
696 ] {
697 let mut b = ChunkBuilder::new("forge");
698 b.begin_function("main", 0, 1);
699 let k = b.const_(value);
700 b.emit_load_const(0, k);
701 b.emit_return(0);
702 let chunk = b.finish();
703 assert_eq!(
704 verify(&chunk),
705 Err(VerifyError::ForbiddenConstant { index: 0, kind })
706 );
707 assert!(verify_with(
708 &chunk,
709 VerifyConfig {
710 trust: TrustLevel::Trusted
711 }
712 )
713 .is_ok());
714 }
715 }
716
717 #[test]
718 fn untrusted_rejects_authority_nested_in_a_list() {
719 use crate::bytecode::cap::CapId;
720 use crate::bytecode::value::{Message, Value};
721 let cases = [
722 (
723 Value::try_list(vec![Value::Int(1), Value::Cap(CapId::from_raw(1))]),
724 ConstantKind::Capability,
725 ),
726 (
727 Value::try_list(vec![Value::Pid(7)]),
728 ConstantKind::ProcessId,
729 ),
730 (
731 Value::try_list(vec![Value::Message(Message::new(1, 2, 3, 4u64))]),
732 ConstantKind::Message,
733 ),
734 ];
735 for (value, kind) in cases {
736 assert!(value.is_some());
737 let Some(value) = value else {
738 return;
739 };
740 let mut b = ChunkBuilder::new("nested-forge");
741 b.begin_function("main", 0, 1);
742 let k = b.const_(value);
743 b.emit_load_const(0, k);
744 b.emit_return(0);
745 let chunk = b.finish();
746 assert_eq!(
747 verify(&chunk),
748 Err(VerifyError::ForbiddenConstant { index: 0, kind })
749 );
750 assert!(verify_with(
751 &chunk,
752 VerifyConfig {
753 trust: TrustLevel::Trusted
754 }
755 )
756 .is_ok());
757 }
758 }
759}