1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::bytecode::{CapId, Chunk, Instruction, Opcode, Value};
6use crate::scheduler::FlowQuota;
7
8use super::fault::{Fault, NativeCallError};
9use super::frame::Frame;
10use super::native::{check_native_gate, NativeGate, NativeTable};
11use super::result::VmResult;
12
13fn dict_scalar(value: &Value) -> bool {
14 matches!(
15 value,
16 Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Float(_)
17 )
18}
19
20pub const MAX_CALL_DEPTH: usize = 4096;
26
27pub struct Vm {
35 chunk: Arc<Chunk>,
36 natives: Arc<NativeTable>,
37 native_gate: NativeGate,
38 frames: Vec<Frame>,
39 instructions_executed: u64,
42 next_request_id: u64,
45 quota: Option<Arc<FlowQuota>>,
47 memory: Option<Arc<crate::MemoryBudget>>,
49 paranoid_jumps: bool,
53 dict: HashMap<i64, Value>,
56}
57
58impl Vm {
59 pub fn new(
67 chunk: Arc<Chunk>,
68 natives: Arc<NativeTable>,
69 function: u32,
70 args: &[Value],
71 ) -> Result<Self, Fault> {
72 let gate = NativeGate::deny(natives.len());
73 Self::with_native_gate(chunk, natives, gate, function, args)
74 }
75
76 pub fn with_native_gate(
77 chunk: Arc<Chunk>,
78 natives: Arc<NativeTable>,
79 native_gate: NativeGate,
80 function: u32,
81 args: &[Value],
82 ) -> Result<Self, Fault> {
83 let def = chunk.function(function).ok_or(Fault::BadFunction {
84 index: function,
85 table_size: chunk.functions.len() as u32,
86 })?;
87 let mut frame = Frame::new(function, def.num_registers, None);
88 frame.set_pc(def.entry as usize);
89 load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
90 Ok(Vm {
91 chunk,
92 natives,
93 native_gate,
94 frames: vec![frame],
95 instructions_executed: 0,
96 next_request_id: 1,
97 quota: None,
98 memory: None,
99 paranoid_jumps: false,
100 dict: HashMap::new(),
101 })
102 }
103
104 pub fn set_paranoid_jumps(&mut self, enabled: bool) {
109 self.paranoid_jumps = enabled;
110 }
111
112 pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
118 for frame in &self.frames {
119 for slot in frame.registers() {
120 charge_heap_value("a, self.memory.as_deref(), slot)?;
121 }
122 }
123 self.quota = Some(quota);
124 Ok(())
125 }
126
127 pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
129 self.memory = Some(memory);
130 }
131
132 pub fn fresh_request_id(&mut self) -> u64 {
135 let id = self.next_request_id;
136 self.next_request_id = self.next_request_id.saturating_add(1);
137 id
138 }
139
140 pub fn instructions_executed(&self) -> u64 {
141 self.instructions_executed
142 }
143
144 pub fn current_function(&self) -> u32 {
147 debug_assert!(!self.frames.is_empty(), "frames empty while running");
151 match self.frames.last() {
152 Some(frame) => frame.function(),
153 None => 0,
154 }
155 }
156
157 pub fn chunk_arc(&self) -> Arc<Chunk> {
163 self.chunk.clone()
164 }
165
166 pub fn natives_arc(&self) -> Arc<NativeTable> {
170 self.natives.clone()
171 }
172
173 #[inline]
180 pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
181 self.set_reg(dest_reg, value)
182 }
183
184 pub fn current_pc(&self) -> Option<usize> {
186 self.frames.last().map(|f| f.pc())
187 }
188
189 pub fn current_num_registers(&self) -> Option<u8> {
191 self.frames.last().map(|f| f.registers().len() as u8)
192 }
193
194 pub fn top_registers(&self) -> Option<&[Value]> {
196 self.frames.last().map(|f| f.registers())
197 }
198
199 pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
201 self.frames.last_mut().map(|f| f.registers_mut())
202 }
203
204 pub fn set_pc(&mut self, pc: usize) {
206 if let Some(frame) = self.frames.last_mut() {
207 frame.set_pc(pc);
208 }
209 }
210
211 pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
213 self.set_reg(reg, value)
214 }
215
216 pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
218 self.pop_frame(value)
219 }
220
221 #[inline]
224 fn current(&mut self) -> Result<&mut Frame, Fault> {
225 debug_assert!(!self.frames.is_empty(), "frames empty while running");
226 self.frames
227 .last_mut()
228 .ok_or(Fault::Invariant("empty frame stack while running"))
229 }
230
231 #[inline]
232 fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
233 let frame = self
234 .frames
235 .last()
236 .ok_or(Fault::Invariant("empty frame stack while running"))?;
237 frame
238 .registers()
239 .get(reg as usize)
240 .cloned()
241 .ok_or(Fault::RegisterOutOfRange {
242 reg,
243 frame_size: frame.registers().len() as u8,
244 })
245 }
246
247 #[inline]
248 fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
249 self.charge_register_store(reg, &value)?;
250 let frame = self.current()?;
251 let len = frame.registers().len() as u8;
252 match frame.registers_mut().get_mut(reg as usize) {
253 Some(slot) => {
254 *slot = value;
255 Ok(())
256 }
257 None => Err(Fault::RegisterOutOfRange {
258 reg,
259 frame_size: len,
260 }),
261 }
262 }
263
264 #[inline]
265 fn peek_reg(&self, reg: u8) -> Option<&Value> {
266 self.frames.last()?.registers().get(reg as usize)
267 }
268
269 fn charge_register_store(&self, reg: u8, value: &Value) -> Result<(), Fault> {
274 let Some(quota) = self.quota.as_ref() else {
275 return Ok(());
276 };
277 match (value, self.peek_reg(reg)) {
278 (Value::Str(s), Some(Value::Str(old))) if Arc::ptr_eq(s, old) => return Ok(()),
279 (Value::Bytes(b), Some(Value::Bytes(old))) if Arc::ptr_eq(b, old) => return Ok(()),
280 _ => {}
281 }
282
283 let new_bytes = heap_charge_of(value);
284 let old_bytes = self.peek_reg(reg).map(heap_charge_of).unwrap_or(0);
285
286 if new_bytes > old_bytes {
290 charge_pair(quota, self.memory.as_deref(), new_bytes - old_bytes)?;
291 } else if old_bytes > new_bytes {
292 release_pair(quota, self.memory.as_deref(), old_bytes - new_bytes);
293 }
294 Ok(())
295 }
296
297 #[inline]
308 fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
309 let pc = self.current()?.pc();
310 let instr = self.chunk.code.get(pc).copied();
311 if instr.is_some() {
312 self.current()?.set_pc(pc + 1);
313 }
314 Ok(instr)
315 }
316
317 fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
318 let a = self.get_reg(lhs)?;
319 let b = self.get_reg(rhs)?;
320 let result = match (op, &a, &b) {
321 (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
322 (Opcode::Add, _, _) => Value::Float(as_f64(&a)? + as_f64(&b)?),
323 (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
324 (Opcode::Sub, _, _) => Value::Float(as_f64(&a)? - as_f64(&b)?),
325 (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
326 (Opcode::Mul, _, _) => Value::Float(as_f64(&a)? * as_f64(&b)?),
327 (Opcode::Div, Value::Int(x), Value::Int(y)) => {
328 if *y == 0 {
329 return Err(Fault::DivideByZero);
330 }
331 Value::Int(x.wrapping_div(*y))
332 }
333 (Opcode::Div, _, _) => {
334 let denom = as_f64(&b)?;
335 Value::Float(as_f64(&a)? / denom)
336 }
337 (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
338 if *y == 0 {
339 return Err(Fault::DivideByZero);
340 }
341 Value::Int(x.wrapping_rem(*y))
342 }
343 (Opcode::Mod, _, _) => {
344 let got = if !matches!(a, Value::Int(_)) {
345 a.type_name()
346 } else {
347 b.type_name()
348 };
349 return Err(Fault::TypeMismatch {
350 expected: "int",
351 got,
352 });
353 }
354 (Opcode::Eq, _, _) => Value::Bool(a == b),
355 (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
356 (Opcode::Lt, _, _) => Value::Bool(as_f64(&a)? < as_f64(&b)?),
357 (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
358 (Opcode::Le, _, _) => Value::Bool(as_f64(&a)? <= as_f64(&b)?),
359 _ => {
360 return Err(Fault::Invariant(
361 "numeric_binop called with a non-arithmetic opcode",
362 ))
363 }
364 };
365 self.set_reg(dst, result)
366 }
367
368 #[inline]
369 fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
370 let v = self.get_reg(reg)?;
371 v.as_cap().ok_or(Fault::TypeMismatch {
372 expected: "cap",
373 got: v.type_name(),
374 })
375 }
376
377 #[inline]
378 fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
379 let v = self.get_reg(reg)?;
380 if v.as_message().is_none() {
381 return Err(Fault::TypeMismatch {
382 expected: "message",
383 got: v.type_name(),
384 });
385 }
386 Ok(v)
387 }
388
389 #[inline]
390 fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
391 match self.get_reg(reg)? {
392 Value::Str(s) => Ok(s),
393 other => Err(Fault::TypeMismatch {
394 expected: "str",
395 got: other.type_name(),
396 }),
397 }
398 }
399
400 #[inline]
401 fn int_from_reg(&self, reg: u8) -> Result<i64, Fault> {
402 match self.get_reg(reg)? {
403 Value::Int(n) => Ok(n),
404 other => Err(Fault::TypeMismatch {
405 expected: "int",
406 got: other.type_name(),
407 }),
408 }
409 }
410
411 #[inline]
412 fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
413 tag_from_value(&self.get_reg(reg)?)
414 }
415
416 #[inline]
417 fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
418 request_id_from_value(&self.get_reg(reg)?)
419 }
420
421 fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
422 let mut args = Vec::with_capacity(argc as usize);
423 for i in 0..argc {
424 let reg = reg_at(base, first_offset + u16::from(i))?;
425 args.push(self.get_reg(reg)?);
426 }
427 Ok(args)
428 }
429
430 #[inline]
432 fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
433 let millis = self.get_reg(reg)?;
434 match millis.as_int() {
435 Some(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
436 _ => Err(Fault::TypeMismatch {
437 expected: "non-negative int",
438 got: millis.type_name(),
439 }),
440 }
441 }
442
443 fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
448 let code_len = self.chunk.code.len();
449 let paranoid = self.paranoid_jumps;
450 let frame = self.current()?;
451 let target_i = frame.pc() as i64 + i64::from(imm);
452 if paranoid && (target_i < 0 || target_i as usize > code_len) {
453 let target = if target_i < 0 {
454 usize::MAX
455 } else {
456 target_i as usize
457 };
458 return Err(Fault::BadJump { target, code_len });
459 }
460 frame.set_pc(target_i as usize);
461 Ok(())
462 }
463
464 pub fn run(&mut self, budget: u32) -> VmResult {
472 macro_rules! trap {
473 ($e:expr) => {
474 match $e {
475 Ok(v) => v,
476 Err(fault) => return VmResult::Trap(fault),
477 }
478 };
479 }
480
481 for _ in 0..budget {
482 self.instructions_executed += 1;
483 let instr = match self.fetch() {
484 Ok(Some(i)) => i,
485 Ok(None) => {
486 match self.pop_frame(Value::Unit) {
488 Ok(Some(result)) => return result,
489 Ok(None) => continue,
490 Err(fault) => return VmResult::Trap(fault),
491 }
492 }
493 Err(fault) => return VmResult::Trap(fault),
494 };
495
496 match instr.op {
497 Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
498 Opcode::Nop => {}
499 Opcode::LoadConst => {
500 let idx = instr.imm as u32;
501 let konst = match self.chunk.constant(idx) {
502 Some(v) => v.clone(),
503 None => {
504 return VmResult::Trap(Fault::BadConstant {
505 index: idx,
506 pool_size: self.chunk.constants.len() as u32,
507 })
508 }
509 };
510 trap!(self.set_reg(instr.a, konst));
511 }
512 Opcode::LoadImm => {
513 trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
514 }
515 Opcode::Move => {
516 let v = trap!(self.get_reg(instr.b));
517 trap!(self.set_reg(instr.a, v));
518 }
519 Opcode::Add
520 | Opcode::Sub
521 | Opcode::Mul
522 | Opcode::Div
523 | Opcode::Mod
524 | Opcode::Eq
525 | Opcode::Lt
526 | Opcode::Le => {
527 trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
528 }
529 Opcode::Neg => {
530 let v = trap!(self.get_reg(instr.b));
531 let negated = match v {
532 Value::Int(x) => Value::Int(x.wrapping_neg()),
533 Value::Float(x) => Value::Float(-x),
534 other => {
535 return VmResult::Trap(Fault::TypeMismatch {
536 expected: "int or float",
537 got: other.type_name(),
538 })
539 }
540 };
541 trap!(self.set_reg(instr.a, negated));
542 }
543 Opcode::Jump => {
544 trap!(self.apply_relative_jump(instr.imm));
545 }
546 Opcode::Branch => {
547 let cond = trap!(self.get_reg(instr.a));
548 if !cond.is_truthy() {
549 trap!(self.apply_relative_jump(instr.imm));
550 }
551 }
552 Opcode::Call => {
553 let function = instr.imm as u32;
554 let argc = instr.b;
555 let dst = instr.a;
556 if self.frames.len() >= MAX_CALL_DEPTH {
557 return VmResult::Trap(Fault::CallStackOverflow {
558 depth: self.frames.len(),
559 });
560 }
561 let (num_registers, arity, entry) = match self.chunk.function(function) {
562 Some(d) => (d.num_registers, d.arity, d.entry as usize),
563 None => {
564 return VmResult::Trap(Fault::BadFunction {
565 index: function,
566 table_size: self.chunk.functions.len() as u32,
567 })
568 }
569 };
570 let args = trap!(self.gather_regs(dst, argc, 0));
571 let mut new_frame = Frame::new(function, num_registers, Some(dst));
572 new_frame.set_pc(entry);
573 trap!(load_frame_args(&mut new_frame, args, arity));
574 self.frames.push(new_frame);
575 }
576 Opcode::CallNative => {
577 let native_index = instr.imm as u32;
578 let argc = instr.b;
579 let dst = instr.a;
580 if let Err(err) =
581 check_native_gate(&self.native_gate, &self.natives, native_index)
582 {
583 return VmResult::Trap(match err {
584 NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
585 index,
586 table_size: self.natives.len() as u32,
587 },
588 other => Fault::NativeDenied(other),
589 });
590 }
591 let args = trap!(self.gather_regs(dst, argc, 0));
592 let result = match self.natives.get(native_index) {
600 Some(native_fn) => native_fn(&args),
601 None => {
602 return VmResult::Trap(Fault::BadNative {
603 index: native_index,
604 table_size: self.natives.len() as u32,
605 })
606 }
607 };
608 match result {
609 Ok(value) => trap!(self.set_reg(dst, value)),
610 Err(fault) => return VmResult::Trap(fault),
611 }
612 }
613 Opcode::Return => {
614 let v = trap!(self.get_reg(instr.a));
615 match self.pop_frame(v) {
616 Ok(Some(result)) => return result,
617 Ok(None) => {}
618 Err(fault) => return VmResult::Trap(fault),
619 }
620 }
621 Opcode::Spawn => {
622 let args = trap!(self.gather_regs(instr.a, instr.b, 1));
625 return VmResult::Spawn {
626 function: instr.imm as u32,
627 args,
628 dest_reg: instr.a,
629 requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
630 };
631 }
632 Opcode::Yield => return VmResult::Yield,
633 Opcode::Sleep => {
634 return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
635 }
636 Opcode::Exit => {
637 let v = trap!(self.get_reg(instr.a));
638 return VmResult::Complete(v);
639 }
640 Opcode::SelfPid => {
641 return VmResult::SelfPid { dest_reg: instr.a };
642 }
643 Opcode::Send => {
644 let target_cap = trap!(self.expect_cap_reg(instr.a));
645 let message = trap!(self.expect_message_value(instr.b));
646 return VmResult::Send {
647 target_cap,
648 message,
649 };
650 }
651 Opcode::Receive => {
652 return VmResult::Receive {
653 dest_reg: instr.a,
654 timeout: None,
655 match_tag: None,
656 match_request_id: None,
657 match_payload_kind: None,
658 match_payload_eq: None,
659 };
660 }
661 Opcode::ReceiveTimeout => {
662 let timeout = trap!(self.duration_millis_from_reg(instr.b));
663 return VmResult::Receive {
664 dest_reg: instr.a,
665 timeout: Some(timeout),
666 match_tag: None,
667 match_request_id: None,
668 match_payload_kind: None,
669 match_payload_eq: None,
670 };
671 }
672 Opcode::ReceiveMatch => {
673 let tag = trap!(self.tag_from_reg(instr.b));
674 return VmResult::Receive {
675 dest_reg: instr.a,
676 timeout: None,
677 match_tag: Some(tag),
678 match_request_id: None,
679 match_payload_kind: None,
680 match_payload_eq: None,
681 };
682 }
683 Opcode::ReceiveMatchImm => {
684 let tag = trap!(tag_from_imm(instr.imm));
685 return VmResult::Receive {
686 dest_reg: instr.a,
687 timeout: None,
688 match_tag: Some(tag),
689 match_request_id: None,
690 match_payload_kind: None,
691 match_payload_eq: None,
692 };
693 }
694 Opcode::ReceiveMatchTimeout => {
695 let tag = trap!(self.tag_from_reg(instr.b));
696 let timeout = trap!(self.duration_millis_from_reg(instr.c));
697 return VmResult::Receive {
698 dest_reg: instr.a,
699 timeout: Some(timeout),
700 match_tag: Some(tag),
701 match_request_id: None,
702 match_payload_kind: None,
703 match_payload_eq: None,
704 };
705 }
706 Opcode::ReceiveMatchImmTimeout => {
707 let tag = trap!(tag_from_imm(instr.imm));
708 let timeout = trap!(self.duration_millis_from_reg(instr.b));
709 return VmResult::Receive {
710 dest_reg: instr.a,
711 timeout: Some(timeout),
712 match_tag: Some(tag),
713 match_request_id: None,
714 match_payload_kind: None,
715 match_payload_eq: None,
716 };
717 }
718 Opcode::IsAlive => {
719 let target_cap = trap!(self.expect_cap_reg(instr.b));
720 return VmResult::IsAlive {
721 dest_reg: instr.a,
722 target_cap,
723 };
724 }
725 Opcode::ExitSignal => {
726 let target_cap = trap!(self.expect_cap_reg(instr.a));
727 let reason = trap!(self.int_from_reg(instr.b));
728 let Ok(reason_u) = u64::try_from(reason) else {
729 return VmResult::Trap(Fault::TypeMismatch {
730 expected: "FlowExitReason 0..=6",
731 got: "imm-out-of-range",
732 });
733 };
734 if crate::FlowExitReason::from_u64(reason_u).is_none() {
735 return VmResult::Trap(Fault::TypeMismatch {
736 expected: "FlowExitReason 0..=6",
737 got: "imm-out-of-range",
738 });
739 }
740 return VmResult::ExitSignal {
741 target_cap,
742 reason: reason_u,
743 };
744 }
745 Opcode::DictPut => {
746 let key = trap!(self.int_from_reg(instr.b));
747 let value = trap!(self.get_reg(instr.c));
748 if !dict_scalar(&value) {
749 return VmResult::Trap(Fault::TypeMismatch {
750 expected: "dict scalar (unit/bool/int/float)",
751 got: "heap-or-cap",
752 });
753 }
754 let old = self.dict.insert(key, value).unwrap_or(Value::Unit);
755 trap!(self.set_reg(instr.a, old));
756 }
757 Opcode::DictGet => {
758 let key = trap!(self.int_from_reg(instr.b));
759 let value = self.dict.get(&key).cloned().unwrap_or(Value::Unit);
760 trap!(self.set_reg(instr.a, value));
761 }
762 Opcode::DictErase => {
763 let key = trap!(self.int_from_reg(instr.b));
764 let old = self.dict.remove(&key).unwrap_or(Value::Unit);
765 trap!(self.set_reg(instr.a, old));
766 }
767 Opcode::ReceiveMatchEq => {
768 let tag = trap!(self.tag_from_reg(instr.b));
769 let payload = trap!(self.int_from_reg(instr.c));
770 return VmResult::Receive {
771 dest_reg: instr.a,
772 timeout: None,
773 match_tag: Some(tag),
774 match_request_id: None,
775 match_payload_kind: None,
776 match_payload_eq: Some(payload),
777 };
778 }
779 Opcode::StartChild => {
780 let function = u32::try_from(instr.imm).unwrap_or(u32::MAX);
781 if self.chunk.function(function).is_none() {
782 return VmResult::Trap(Fault::BadFunction {
783 index: function,
784 table_size: self.chunk.functions.len() as u32,
785 });
786 }
787 if crate::RestartPolicy::from_u8(instr.b).is_none() {
788 return VmResult::Trap(Fault::TypeMismatch {
789 expected: "restart policy 0..=2",
790 got: "imm-out-of-range",
791 });
792 }
793 return VmResult::StartChild {
794 dest_reg: instr.a,
795 function,
796 policy: instr.b,
797 };
798 }
799 Opcode::ReceiveMatchKind => {
800 let kind = match u8::try_from(instr.imm) {
803 Ok(k) if k <= 8 => k,
804 _ => {
805 return VmResult::Trap(Fault::TypeMismatch {
806 expected: "payload kind 0..=8",
807 got: "imm-out-of-range",
808 })
809 }
810 };
811 return VmResult::Receive {
812 dest_reg: instr.a,
813 timeout: None,
814 match_tag: None,
815 match_request_id: None,
816 match_payload_kind: Some(kind),
817 match_payload_eq: None,
818 };
819 }
820 Opcode::FreshRequestId => {
821 let id = self.fresh_request_id();
822 trap!(self.set_reg(instr.a, Value::Int(id as i64)));
823 }
824 Opcode::ReceiveMatchCorr => {
825 let tag = trap!(self.tag_from_reg(instr.b));
826 let rid = trap!(self.request_id_from_reg(instr.c));
827 return VmResult::Receive {
828 dest_reg: instr.a,
829 timeout: None,
830 match_tag: Some(tag),
831 match_request_id: Some(rid),
832 match_payload_kind: None,
833 match_payload_eq: None,
834 };
835 }
836 Opcode::ReceiveMatchCorrImm => {
837 let tag = trap!(tag_from_imm(instr.imm));
838 let rid = trap!(self.request_id_from_reg(instr.b));
839 return VmResult::Receive {
840 dest_reg: instr.a,
841 timeout: None,
842 match_tag: Some(tag),
843 match_request_id: Some(rid),
844 match_payload_kind: None,
845 match_payload_eq: None,
846 };
847 }
848 Opcode::Ask => {
849 let target_cap = trap!(self.expect_cap_reg(instr.b));
850 let request = trap!(self.expect_message_value(instr.c));
851 return VmResult::Ask {
852 dest_reg: instr.a,
853 target_cap,
854 request,
855 timeout: None,
856 };
857 }
858 Opcode::AskTimeout => {
859 let millis_reg = match u8::try_from(instr.imm) {
860 Ok(r) => r,
861 Err(_) => {
862 return VmResult::Trap(Fault::TypeMismatch {
863 expected: "millis register",
864 got: "imm-out-of-range",
865 })
866 }
867 };
868 let timeout = trap!(self.duration_millis_from_reg(millis_reg));
869 let target_cap = trap!(self.expect_cap_reg(instr.b));
870 let request = trap!(self.expect_message_value(instr.c));
871 return VmResult::Ask {
872 dest_reg: instr.a,
873 target_cap,
874 request,
875 timeout: Some(timeout),
876 };
877 }
878 Opcode::Monitor => {
879 let target_cap = trap!(self.expect_cap_reg(instr.b));
880 return VmResult::Monitor {
881 dest_reg: instr.a,
882 target_cap,
883 };
884 }
885 Opcode::Demonitor => {
886 return VmResult::Demonitor {
887 monitor_reg: instr.a,
888 };
889 }
890 Opcode::Link => {
891 let target_cap = trap!(self.expect_cap_reg(instr.b));
892 return VmResult::Link {
893 dest_reg: instr.a,
894 target_cap,
895 };
896 }
897 Opcode::Unlink => {
898 return VmResult::Unlink { link_reg: instr.a };
899 }
900 Opcode::SetTrapExit => {
901 let enabled = trap!(self.get_reg(instr.a)).is_truthy();
902 return VmResult::SetTrapExit { enabled };
903 }
904 Opcode::SetRestartPolicy => {
905 let policy = match instr.imm {
908 0..=2 => instr.imm as u8,
909 _ => {
910 return VmResult::Trap(Fault::TypeMismatch {
911 expected: "restart policy 0..=2",
912 got: "imm-out-of-range",
913 })
914 }
915 };
916 return VmResult::SetRestartPolicy { policy };
917 }
918 Opcode::HostAwait => {
919 let args = trap!(self.get_reg(instr.b));
920 let op = if instr.imm < 0 {
921 return VmResult::Trap(Fault::TypeMismatch {
922 expected: "HostAwait op >= 0",
923 got: "imm-negative",
924 });
925 } else {
926 instr.imm as u32
927 };
928 return VmResult::HostAwait {
929 dest_reg: instr.a,
930 op,
931 args,
932 };
933 }
934 Opcode::RegisterName => {
935 return VmResult::RegisterName {
936 name: trap!(self.expect_str_reg(instr.a)),
937 };
938 }
939 Opcode::Whereis => {
940 return VmResult::Whereis {
941 dest_reg: instr.a,
942 name: trap!(self.expect_str_reg(instr.b)),
943 };
944 }
945 Opcode::Delegate => {
946 let src_cap = trap!(self.expect_cap_reg(instr.b));
947 let want_native_cap = if instr.c == 255 {
948 None
949 } else {
950 Some(trap!(self.expect_cap_reg(instr.c)))
951 };
952 return VmResult::Delegate {
953 dest_reg: instr.a,
954 src_cap,
955 want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
956 want_native_cap,
957 };
958 }
959 Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
960 }
961 }
962 VmResult::Yield
963 }
964
965 fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
969 let finished = self
970 .frames
971 .pop()
972 .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
973 match finished.dest_reg() {
974 Some(dest) => {
975 self.set_reg(dest, value)?;
976 Ok(None)
977 }
978 None => Ok(Some(VmResult::Complete(value))),
979 }
980 }
981}
982
983#[inline]
993fn load_frame_args(
994 frame: &mut Frame,
995 args: impl IntoIterator<Item = Value>,
996 arity: u8,
997) -> Result<(), Fault> {
998 let frame_size = frame.registers().len() as u8;
999 for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1000 match frame.registers_mut().get_mut(i) {
1001 Some(slot) => *slot = a,
1002 None => {
1003 return Err(Fault::RegisterOutOfRange {
1004 reg: i as u8,
1005 frame_size,
1006 })
1007 }
1008 }
1009 }
1010 Ok(())
1011}
1012
1013fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
1014 match u8::try_from(u32::from(base) + u32::from(offset)) {
1015 Ok(reg) => Ok(reg),
1016 Err(_) => Err(Fault::RegisterIndexOverflow {
1017 base,
1018 offset: match u8::try_from(offset) {
1019 Ok(o) => o,
1020 Err(_) => u8::MAX,
1021 },
1022 }),
1023 }
1024}
1025
1026#[inline]
1028fn heap_charge_of(value: &Value) -> usize {
1029 match value {
1030 Value::Str(s) => s.len(),
1031 Value::Bytes(b) => b.len(),
1032 _ => 0,
1033 }
1034}
1035
1036fn charge_pair(
1039 quota: &FlowQuota,
1040 memory: Option<&crate::MemoryBudget>,
1041 bytes: usize,
1042) -> Result<(), Fault> {
1043 if bytes == 0 {
1044 return Ok(());
1045 }
1046 quota
1047 .alloc(bytes)
1048 .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
1049 if let Some(mem) = memory {
1050 if let Err(e) = mem.try_charge(bytes) {
1051 quota.free(bytes);
1052 return Err(Fault::QuotaExceeded(e.to_string()));
1053 }
1054 }
1055 Ok(())
1056}
1057
1058fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
1059 if bytes == 0 {
1060 return;
1061 }
1062 quota.free(bytes);
1063 if let Some(mem) = memory {
1064 mem.release(bytes);
1065 }
1066}
1067
1068fn charge_heap_value(
1070 quota: &FlowQuota,
1071 memory: Option<&crate::MemoryBudget>,
1072 value: &Value,
1073) -> Result<(), Fault> {
1074 charge_pair(quota, memory, heap_charge_of(value))
1075}
1076
1077fn as_f64(v: &Value) -> Result<f64, Fault> {
1078 match v {
1079 Value::Int(i) => Ok(*i as f64),
1080 Value::Float(f) => Ok(*f),
1081 other => Err(Fault::TypeMismatch {
1082 expected: "int or float",
1083 got: other.type_name(),
1084 }),
1085 }
1086}
1087
1088#[inline]
1090fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
1091 match u16::try_from(imm) {
1092 Ok(t) if imm >= 0 => Ok(t),
1093 _ => Err(Fault::TypeMismatch {
1094 expected: "tag u16",
1095 got: "imm-out-of-range",
1096 }),
1097 }
1098}
1099
1100fn tag_from_value(v: &Value) -> Result<u16, Fault> {
1101 match v.as_int() {
1102 Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
1103 Some(_) => Err(Fault::TypeMismatch {
1104 expected: "tag u16",
1105 got: "int-out-of-range",
1106 }),
1107 None => Err(Fault::TypeMismatch {
1108 expected: "int",
1109 got: v.type_name(),
1110 }),
1111 }
1112}
1113
1114#[inline]
1116fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
1117 match v.as_int() {
1118 Some(i) if i >= 0 => Ok(i as u64),
1119 Some(_) => Err(Fault::TypeMismatch {
1120 expected: "request_id u64",
1121 got: "negative-int",
1122 }),
1123 None => Err(Fault::TypeMismatch {
1124 expected: "int",
1125 got: v.type_name(),
1126 }),
1127 }
1128}
1129
1130#[cfg(test)]
1131mod tests {
1132 use super::*;
1133 use crate::bytecode::builder::ChunkBuilder;
1134
1135 type TestResult = Result<(), Box<dyn std::error::Error>>;
1136
1137 #[test]
1142 fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1143 let mut b = ChunkBuilder::new("t");
1144 b.begin_function("main", 0, 2);
1145 b.emit_spawn(255, 0, 1);
1146 b.emit_return(0);
1147 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1148 match vm.run(10) {
1149 VmResult::Trap(Fault::RegisterIndexOverflow {
1150 base: 255,
1151 offset: 1,
1152 }) => Ok(()),
1153 other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1154 }
1155 }
1156
1157 #[test]
1161 fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1162 let mut b = ChunkBuilder::new("t");
1163 b.begin_function("main", 3, 1);
1164 b.emit_return(0);
1165 let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1166 match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1167 Err(Fault::RegisterOutOfRange {
1168 reg: 1,
1169 frame_size: 1,
1170 }) => Ok(()),
1171 Err(e) => Err(format!("unexpected fault: {e}").into()),
1172 Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1173 }
1174 }
1175
1176 #[test]
1177 fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1178 let mut b = ChunkBuilder::new("t");
1179 let callee = b.begin_function("callee", 3, 1);
1180 b.emit_return(0);
1181 let main = b.begin_function("main", 0, 4);
1182 b.emit_load_imm(0, 7);
1183 b.emit_load_imm(1, 8);
1184 b.emit_load_imm(2, 9);
1185 b.emit_call(0, callee, 3);
1186 b.emit_return(0);
1187 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1188 match vm.run(50) {
1189 VmResult::Trap(Fault::RegisterOutOfRange {
1190 reg: 1,
1191 frame_size: 1,
1192 }) => Ok(()),
1193 other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1194 }
1195 }
1196
1197 #[test]
1200 fn gathering_up_to_the_last_register_still_works() -> TestResult {
1201 let mut b = ChunkBuilder::new("t");
1202 let callee = b.begin_function("callee", 1, 1);
1203 b.emit_return(0);
1204 let main = b.begin_function("main", 0, 255);
1205 b.emit_load_imm(254, 5);
1206 b.emit_call(254, callee, 1);
1208 b.emit_return(254);
1209 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1210 match vm.run(100) {
1211 VmResult::Complete(_) => Ok(()),
1212 other => Err(format!("expected completion, got {other:?}").into()),
1213 }
1214 }
1215
1216 #[test]
1217 fn neg_i64_min_wrapping() -> TestResult {
1218 let mut b = ChunkBuilder::new("t");
1219 b.begin_function("main", 0, 1);
1220 let k = b.const_(Value::Int(i64::MIN));
1221 b.emit_load_const(0, k);
1222 b.emit_neg(0, 0);
1223 b.emit_return(0);
1224 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1225 match vm.run(10) {
1226 VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1227 other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1228 }
1229 }
1230
1231 #[test]
1232 fn mod_non_int_type_mismatch() -> TestResult {
1233 let mut b = ChunkBuilder::new("t");
1234 b.begin_function("main", 0, 3);
1235 b.emit_load_imm(0, 10);
1236 let kf = b.const_(Value::Float(3.0));
1237 b.emit_load_const(1, kf);
1238 b.emit_binop(Opcode::Mod, 2, 0, 1);
1239 b.emit_return(2);
1240 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1241 match vm.run(20) {
1242 VmResult::Trap(Fault::TypeMismatch {
1243 expected: "int",
1244 got: "float",
1245 }) => Ok(()),
1246 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1247 }
1248 }
1249
1250 #[test]
1251 fn receive_timeout_negative_traps() -> TestResult {
1252 let mut b = ChunkBuilder::new("t");
1253 b.begin_function("main", 0, 2);
1254 b.emit_load_imm(1, -1);
1255 b.emit_receive_timeout(0, 1);
1256 b.emit_return(0);
1257 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1258 match vm.run(10) {
1259 VmResult::Trap(Fault::TypeMismatch {
1260 expected: "non-negative int",
1261 ..
1262 }) => Ok(()),
1263 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1264 }
1265 }
1266
1267 #[test]
1268 fn ask_timeout_negative_traps() -> TestResult {
1269 let mut b = ChunkBuilder::new("t");
1270 b.begin_function("main", 0, 4);
1271 b.emit_load_imm(3, -5);
1272 b.emit_ask_timeout(0, 1, 2, 3);
1274 b.emit_return(0);
1275 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1276 match vm.run(10) {
1277 VmResult::Trap(Fault::TypeMismatch {
1278 expected: "non-negative int",
1279 ..
1280 }) => Ok(()),
1281 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1282 }
1283 }
1284
1285 #[test]
1286 fn paranoid_jump_out_of_range_traps() -> TestResult {
1287 let mut b = ChunkBuilder::new("t");
1288 b.begin_function("main", 0, 1);
1289 b.emit_load_imm(0, 0);
1290 b.emit_return(0);
1291 let mut chunk = b.finish();
1292 let code_len = chunk.code.len();
1293 chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1294 let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1295 vm.set_paranoid_jumps(true);
1296 match vm.run(10) {
1297 VmResult::Trap(Fault::BadJump {
1298 target: 101,
1299 code_len: len,
1300 }) if len == code_len => Ok(()),
1301 other => Err(format!("expected BadJump(101), got {other:?}").into()),
1302 }
1303 }
1304
1305 #[test]
1306 fn overwrite_releases_previous_heap_charge() -> TestResult {
1307 let mut b = ChunkBuilder::new("t");
1308 let k1 = b.const_(Value::Str("a".repeat(100).into()));
1309 let k2 = b.const_(Value::Str("b".repeat(100).into()));
1310 b.begin_function("main", 0, 1);
1311 b.emit_load_const(0, k1);
1312 b.emit_load_const(0, k2);
1313 b.emit_return(0);
1314 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1315 let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1317 crate::QuotaConfig {
1318 mem_limit: 150,
1319 ..crate::QuotaConfig::permissive()
1320 },
1321 ));
1322 let memory = Arc::new(crate::MemoryBudget::new(10_000));
1323 vm.set_memory_budget(Arc::clone(&memory));
1324 vm.set_quota(Arc::clone("a))?;
1325 match vm.run(20) {
1326 VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1327 assert_eq!(quota.mem_used(), 100);
1328 assert_eq!(memory.used(), 100);
1329 Ok(())
1330 }
1331 other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1332 }
1333 }
1334
1335 #[test]
1336 fn returning_over_quota_keeps_quota_fault() -> TestResult {
1337 let mut b = ChunkBuilder::new("t");
1338 let k = b.const_(Value::Str("x".repeat(200).into()));
1339 let callee = b.begin_function("callee", 0, 1);
1340 b.emit_load_const(0, k);
1341 b.emit_return(0);
1342 let main = b.begin_function("main", 0, 1);
1343 b.emit_call(0, callee, 0);
1344 b.emit_return(0);
1345 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1346 let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1348 vm.set_quota(quota)?;
1349 match vm.run(50) {
1350 VmResult::Trap(Fault::QuotaExceeded(_)) => Ok(()),
1351 other => {
1352 Err(format!("expected QuotaExceeded from return writeback, got {other:?}").into())
1353 }
1354 }
1355 }
1356
1357 #[test]
1358 fn call_native_without_gate_is_typed_denied() -> TestResult {
1359 let mut b = ChunkBuilder::new("t");
1360 b.begin_function("main", 0, 1);
1361 b.emit_call_native(0, 0, 0);
1362 b.emit_return(0);
1363 let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1364 let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1365 match vm.run(10) {
1366 VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1367 other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1368 }
1369 }
1370
1371 #[test]
1372 fn non_paranoid_bad_jump_still_fail_opens() -> TestResult {
1373 let mut b = ChunkBuilder::new("t");
1374 b.begin_function("main", 0, 1);
1375 b.emit_load_imm(0, 7);
1376 b.emit_return(0);
1377 let mut chunk = b.finish();
1378 chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1379 let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1380 match vm.run(10) {
1381 VmResult::Complete(Value::Unit) => Ok(()),
1383 other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1384 }
1385 }
1386}