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 FallThrough {
127 function: usize,
128 at: usize,
129 next_entry: usize,
130 },
131}
132
133impl fmt::Display for VerifyError {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 match self {
136 VerifyError::UnknownOpcode { at, byte } => {
137 write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
138 }
139 VerifyError::ConstOutOfRange { at, index, len } => write!(
140 f,
141 "instruction {at} references constant {index}, pool has {len} entries"
142 ),
143 VerifyError::FunctionOutOfRange { at, index, len } => write!(
144 f,
145 "instruction {at} references function {index}, table has {len} entries"
146 ),
147 VerifyError::JumpOutOfRange { at, target, len } => write!(
148 f,
149 "instruction {at} jumps to {target}, out of code bounds (len={len})"
150 ),
151 VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
152 VerifyError::EntryOutOfRange {
153 function,
154 entry,
155 len,
156 } => write!(
157 f,
158 "function {function} entry point {entry} is out of code bounds (len={len})"
159 ),
160 VerifyError::ArityExceedsRegisters {
161 function,
162 arity,
163 num_registers,
164 } => write!(
165 f,
166 "function {function} declares arity {arity} but only {num_registers} registers"
167 ),
168 VerifyError::ForbiddenConstant { index, kind } => {
169 write!(f, "untrusted constant[{index}] must not embed {kind}")
170 }
171 VerifyError::FallThrough {
172 function,
173 at,
174 next_entry,
175 } => write!(
176 f,
177 "function {function} falls through at instruction {at} into the function at {next_entry}"
178 ),
179 }
180 }
181}
182
183impl std::error::Error for VerifyError {}
184
185pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
206 verify_with(chunk, VerifyConfig::default())
207}
208
209pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
211 if chunk.functions.is_empty() {
212 return Err(VerifyError::EmptyFunctionTable);
213 }
214
215 for (index, value) in chunk.constants.iter().enumerate() {
216 validate_constant(value, config.trust, index)?;
217 }
218
219 let len = chunk.code.len();
220
221 for (function, def) in chunk.functions.iter().enumerate() {
225 if def.entry as usize >= len {
226 return Err(VerifyError::EntryOutOfRange {
227 function,
228 entry: def.entry,
229 len,
230 });
231 }
232 if def.arity > def.num_registers {
233 return Err(VerifyError::ArityExceedsRegisters {
234 function,
235 arity: def.arity,
236 num_registers: def.num_registers,
237 });
238 }
239 }
240
241 for (at, instr) in chunk.code.iter().enumerate() {
242 match instr.op {
243 Opcode::LoadConst => {
244 let idx = instr.imm as u32;
245 if idx as usize >= chunk.constants.len() {
246 return Err(VerifyError::ConstOutOfRange {
247 at,
248 index: idx,
249 len: chunk.constants.len(),
250 });
251 }
252 }
253 Opcode::Spawn | Opcode::Call | Opcode::StartChild => {
254 let idx = instr.imm as u32;
255 if idx as usize >= chunk.functions.len() {
256 return Err(VerifyError::FunctionOutOfRange {
257 at,
258 index: idx,
259 len: chunk.functions.len(),
260 });
261 }
262 }
263 Opcode::CallNative => {}
268 Opcode::Jump | Opcode::Branch => {
269 let target = at as i64 + 1 + instr.imm as i64;
270 if target < 0 || target as usize > len {
271 return Err(VerifyError::JumpOutOfRange { at, target, len });
274 }
275 if let Some((start, end)) = function_span(&chunk.functions, at, len) {
279 let t = target as usize;
280 if t != len && (t < start || t >= end) {
281 return Err(VerifyError::JumpOutOfRange { at, target, len });
282 }
283 }
284 }
285 _ => {}
286 }
287 }
288
289 reject_fallthrough(chunk)?;
290 Ok(())
291}
292
293fn is_terminator(op: Opcode) -> bool {
297 matches!(
298 op,
299 Opcode::Jump | Opcode::Return | Opcode::Halt | Opcode::Exit | Opcode::Trap
300 )
301}
302
303fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
306 let mut end = code_len;
307 for def in functions {
308 let entry = def.entry as usize;
309 if entry > start && entry < end {
310 end = entry;
311 }
312 }
313 end
314}
315
316fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
321 let len = chunk.code.len();
322 for (function, def) in chunk.functions.iter().enumerate() {
323 let start = def.entry as usize;
324 let end = exclusive_end(&chunk.functions, start, len);
325 if end >= len || end <= start {
326 continue;
327 }
328 let at = end - 1;
329 if !is_terminator(chunk.code[at].op) {
330 return Err(VerifyError::FallThrough {
331 function,
332 at,
333 next_entry: end,
334 });
335 }
336 }
337 Ok(())
338}
339
340fn function_span(
343 functions: &[super::chunk::FunctionDef],
344 at: usize,
345 code_len: usize,
346) -> Option<(usize, usize)> {
347 let mut start = None;
348 for def in functions {
349 let entry = def.entry as usize;
350 if entry <= at {
351 start = Some(match start {
352 Some(prev) if prev >= entry => prev,
353 _ => entry,
354 });
355 }
356 }
357 let start = start?;
358 let end = exclusive_end(functions, start, code_len);
359 if at >= end {
360 None
361 } else {
362 Some((start, end))
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::*;
369 use crate::bytecode::builder::ChunkBuilder;
370 use crate::bytecode::opcode::Opcode;
371
372 #[test]
373 fn rejects_empty_function_table() {
374 let chunk = Chunk::default();
375 assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
376 }
377
378 #[test]
379 fn accepts_well_formed_chunk() {
380 let mut b = ChunkBuilder::new("test");
381 b.begin_function("main", 0, 2);
382 let k = b.const_(crate::bytecode::value::Value::Int(41));
383 b.emit_load_const(0, k);
384 b.emit_load_imm(1, 1);
385 b.emit_binop(Opcode::Add, 0, 0, 1);
386 b.emit_return(0);
387 let chunk = b.finish();
388 assert!(verify(&chunk).is_ok());
389 }
390
391 #[test]
395 fn rejects_arity_larger_than_the_register_file() {
396 let mut b = ChunkBuilder::new("test");
397 b.begin_function("main", 3, 1);
398 b.emit_return(0);
399 let chunk = b.finish();
400 assert_eq!(
401 verify(&chunk),
402 Err(VerifyError::ArityExceedsRegisters {
403 function: 0,
404 arity: 3,
405 num_registers: 1,
406 })
407 );
408 }
409
410 #[test]
411 fn accepts_arity_equal_to_the_register_file() {
412 let mut b = ChunkBuilder::new("test");
413 b.begin_function("main", 2, 2);
414 b.emit_return(0);
415 let chunk = b.finish();
416 assert!(verify(&chunk).is_ok());
417 }
418
419 #[test]
420 fn rejects_start_child_function_out_of_range() {
421 use crate::bytecode::instruction::Instruction;
422 let mut chunk = Chunk::default();
423 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
424 name: "main".into(),
425 entry: 0,
426 arity: 0,
427 num_registers: 1,
428 });
429 chunk
430 .code
431 .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
432 assert!(matches!(
433 verify(&chunk),
434 Err(VerifyError::FunctionOutOfRange { index: 99, .. })
435 ));
436 }
437
438 #[test]
439 fn rejects_jump_into_another_function() {
440 use crate::bytecode::instruction::Instruction;
441 let mut chunk = Chunk::default();
442 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
443 name: "main".into(),
444 entry: 0,
445 arity: 0,
446 num_registers: 1,
447 });
448 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
449 name: "other".into(),
450 entry: 2,
451 arity: 0,
452 num_registers: 1,
453 });
454 chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
456 chunk.code.push(Instruction::nullary(Opcode::Nop));
457 chunk.code.push(Instruction::nullary(Opcode::Nop));
458 assert!(matches!(
459 verify(&chunk),
460 Err(VerifyError::JumpOutOfRange { target: 2, .. })
461 ));
462 }
463
464 #[test]
465 fn rejects_out_of_range_jump() {
466 use crate::bytecode::instruction::Instruction;
467 let mut chunk = Chunk::default();
468 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
469 name: "main".into(),
470 entry: 0,
471 arity: 0,
472 num_registers: 1,
473 });
474 chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
475 assert!(matches!(
476 verify(&chunk),
477 Err(VerifyError::JumpOutOfRange { .. })
478 ));
479 }
480
481 fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
482 use crate::bytecode::instruction::Instruction;
483 let mut chunk = Chunk::default();
484 for (name, entry) in [("main", 0u32), ("other", 1)] {
485 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
486 name: name.into(),
487 entry,
488 arity: 0,
489 num_registers: 1,
490 });
491 }
492 chunk.code.push(first);
493 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
494 chunk
495 }
496
497 #[test]
498 fn rejects_fallthrough_into_the_next_function() {
499 use crate::bytecode::instruction::Instruction;
500 let boundary = VerifyError::FallThrough {
501 function: 0,
502 at: 0,
503 next_entry: 1,
504 };
505 for first in [
506 Instruction::nullary(Opcode::Nop),
507 Instruction::a_imm(Opcode::Branch, 0, -1),
508 Instruction::new(Opcode::Call, 0, 0, 0, 1),
509 ] {
510 assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
511 }
512 }
513
514 #[test]
515 fn accepts_jump_closing_a_function_before_the_next() {
516 use crate::bytecode::instruction::Instruction;
517 let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
519 assert!(verify(&chunk).is_ok());
520 }
521
522 #[test]
523 fn accepts_implicit_return_on_the_last_function() {
524 use crate::bytecode::instruction::Instruction;
525 let mut chunk = Chunk::default();
526 chunk.functions.push(crate::bytecode::chunk::FunctionDef {
527 name: "main".into(),
528 entry: 0,
529 arity: 0,
530 num_registers: 1,
531 });
532 chunk.code.push(Instruction::nullary(Opcode::Nop));
533 assert!(verify(&chunk).is_ok());
534 }
535
536 #[test]
537 fn untrusted_rejects_cap_pid_message_constants() {
538 use crate::bytecode::cap::CapId;
539 use crate::bytecode::value::Message;
540 for (value, kind) in [
541 (
542 crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
543 ConstantKind::Capability,
544 ),
545 (
546 crate::bytecode::value::Value::Pid(7),
547 ConstantKind::ProcessId,
548 ),
549 (
550 crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
551 ConstantKind::Message,
552 ),
553 ] {
554 let mut b = ChunkBuilder::new("forge");
555 b.begin_function("main", 0, 1);
556 let k = b.const_(value);
557 b.emit_load_const(0, k);
558 b.emit_return(0);
559 let chunk = b.finish();
560 assert_eq!(
561 verify(&chunk),
562 Err(VerifyError::ForbiddenConstant { index: 0, kind })
563 );
564 assert!(verify_with(
565 &chunk,
566 VerifyConfig {
567 trust: TrustLevel::Trusted
568 }
569 )
570 .is_ok());
571 }
572 }
573}