1use std::sync::Arc;
2use std::time::Duration;
3
4use crate::bytecode::{CapId, Chunk, Instruction, Opcode, Value};
5use crate::scheduler::FlowQuota;
6
7use super::fault::{Fault, NativeCallError};
8use super::frame::Frame;
9use super::native::{check_native_gate, NativeGate, NativeTable};
10use super::result::VmResult;
11
12pub const MAX_CALL_DEPTH: usize = 4096;
18
19pub struct Vm {
27 chunk: Arc<Chunk>,
28 natives: Arc<NativeTable>,
29 native_gate: NativeGate,
30 frames: Vec<Frame>,
31 instructions_executed: u64,
34 next_request_id: u64,
37 quota: Option<Arc<FlowQuota>>,
39 memory: Option<Arc<crate::MemoryBudget>>,
41 paranoid_jumps: bool,
45}
46
47impl Vm {
48 pub fn new(
56 chunk: Arc<Chunk>,
57 natives: Arc<NativeTable>,
58 function: u32,
59 args: &[Value],
60 ) -> Result<Self, Fault> {
61 let gate = NativeGate::deny(natives.len());
62 Self::with_native_gate(chunk, natives, gate, function, args)
63 }
64
65 pub fn with_native_gate(
66 chunk: Arc<Chunk>,
67 natives: Arc<NativeTable>,
68 native_gate: NativeGate,
69 function: u32,
70 args: &[Value],
71 ) -> Result<Self, Fault> {
72 let def = chunk.function(function).ok_or(Fault::BadFunction {
73 index: function,
74 table_size: chunk.functions.len() as u32,
75 })?;
76 let mut frame = Frame::new(function, def.num_registers, None);
77 frame.set_pc(def.entry as usize);
78 load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
79 Ok(Vm {
80 chunk,
81 natives,
82 native_gate,
83 frames: vec![frame],
84 instructions_executed: 0,
85 next_request_id: 1,
86 quota: None,
87 memory: None,
88 paranoid_jumps: false,
89 })
90 }
91
92 pub fn set_paranoid_jumps(&mut self, enabled: bool) {
97 self.paranoid_jumps = enabled;
98 }
99
100 pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
106 for frame in &self.frames {
107 for slot in frame.registers() {
108 charge_heap_value("a, self.memory.as_deref(), slot)?;
109 }
110 }
111 self.quota = Some(quota);
112 Ok(())
113 }
114
115 pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
117 self.memory = Some(memory);
118 }
119
120 pub fn fresh_request_id(&mut self) -> u64 {
123 let id = self.next_request_id;
124 self.next_request_id = self.next_request_id.saturating_add(1);
125 id
126 }
127
128 pub fn instructions_executed(&self) -> u64 {
129 self.instructions_executed
130 }
131
132 pub fn current_function(&self) -> u32 {
135 debug_assert!(!self.frames.is_empty(), "frames empty while running");
139 match self.frames.last() {
140 Some(frame) => frame.function(),
141 None => 0,
142 }
143 }
144
145 pub fn chunk_arc(&self) -> Arc<Chunk> {
151 self.chunk.clone()
152 }
153
154 pub fn natives_arc(&self) -> Arc<NativeTable> {
158 self.natives.clone()
159 }
160
161 #[inline]
168 pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
169 self.set_reg(dest_reg, value)
170 }
171
172 pub fn current_pc(&self) -> Option<usize> {
174 self.frames.last().map(|f| f.pc())
175 }
176
177 pub fn current_num_registers(&self) -> Option<u8> {
179 self.frames.last().map(|f| f.registers().len() as u8)
180 }
181
182 pub fn top_registers(&self) -> Option<&[Value]> {
184 self.frames.last().map(|f| f.registers())
185 }
186
187 pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
189 self.frames.last_mut().map(|f| f.registers_mut())
190 }
191
192 pub fn set_pc(&mut self, pc: usize) {
194 if let Some(frame) = self.frames.last_mut() {
195 frame.set_pc(pc);
196 }
197 }
198
199 pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
201 self.set_reg(reg, value)
202 }
203
204 pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
206 self.pop_frame(value)
207 }
208
209 #[inline]
212 fn current(&mut self) -> Result<&mut Frame, Fault> {
213 debug_assert!(!self.frames.is_empty(), "frames empty while running");
214 self.frames
215 .last_mut()
216 .ok_or(Fault::Invariant("empty frame stack while running"))
217 }
218
219 #[inline]
220 fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
221 let frame = self
222 .frames
223 .last()
224 .ok_or(Fault::Invariant("empty frame stack while running"))?;
225 frame
226 .registers()
227 .get(reg as usize)
228 .cloned()
229 .ok_or(Fault::RegisterOutOfRange {
230 reg,
231 frame_size: frame.registers().len() as u8,
232 })
233 }
234
235 #[inline]
236 fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
237 self.charge_register_store(reg, &value)?;
238 let frame = self.current()?;
239 let len = frame.registers().len() as u8;
240 match frame.registers_mut().get_mut(reg as usize) {
241 Some(slot) => {
242 *slot = value;
243 Ok(())
244 }
245 None => Err(Fault::RegisterOutOfRange {
246 reg,
247 frame_size: len,
248 }),
249 }
250 }
251
252 #[inline]
253 fn peek_reg(&self, reg: u8) -> Option<&Value> {
254 self.frames.last()?.registers().get(reg as usize)
255 }
256
257 fn charge_register_store(&self, reg: u8, value: &Value) -> Result<(), Fault> {
262 let Some(quota) = self.quota.as_ref() else {
263 return Ok(());
264 };
265 match (value, self.peek_reg(reg)) {
266 (Value::Str(s), Some(Value::Str(old))) if Arc::ptr_eq(s, old) => return Ok(()),
267 (Value::Bytes(b), Some(Value::Bytes(old))) if Arc::ptr_eq(b, old) => return Ok(()),
268 _ => {}
269 }
270
271 let new_bytes = heap_charge_of(value);
272 let old_bytes = self.peek_reg(reg).map(heap_charge_of).unwrap_or(0);
273
274 if new_bytes > old_bytes {
278 charge_pair(quota, self.memory.as_deref(), new_bytes - old_bytes)?;
279 } else if old_bytes > new_bytes {
280 release_pair(quota, self.memory.as_deref(), old_bytes - new_bytes);
281 }
282 Ok(())
283 }
284
285 #[inline]
296 fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
297 let pc = self.current()?.pc();
298 let instr = self.chunk.code.get(pc).copied();
299 if instr.is_some() {
300 self.current()?.set_pc(pc + 1);
301 }
302 Ok(instr)
303 }
304
305 fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
306 let a = self.get_reg(lhs)?;
307 let b = self.get_reg(rhs)?;
308 let result = match (op, &a, &b) {
309 (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
310 (Opcode::Add, _, _) => Value::Float(as_f64(&a)? + as_f64(&b)?),
311 (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
312 (Opcode::Sub, _, _) => Value::Float(as_f64(&a)? - as_f64(&b)?),
313 (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
314 (Opcode::Mul, _, _) => Value::Float(as_f64(&a)? * as_f64(&b)?),
315 (Opcode::Div, Value::Int(x), Value::Int(y)) => {
316 if *y == 0 {
317 return Err(Fault::DivideByZero);
318 }
319 Value::Int(x.wrapping_div(*y))
320 }
321 (Opcode::Div, _, _) => {
322 let denom = as_f64(&b)?;
323 Value::Float(as_f64(&a)? / denom)
324 }
325 (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
326 if *y == 0 {
327 return Err(Fault::DivideByZero);
328 }
329 Value::Int(x.wrapping_rem(*y))
330 }
331 (Opcode::Mod, _, _) => {
332 let got = if !matches!(a, Value::Int(_)) {
333 a.type_name()
334 } else {
335 b.type_name()
336 };
337 return Err(Fault::TypeMismatch {
338 expected: "int",
339 got,
340 });
341 }
342 (Opcode::Eq, _, _) => Value::Bool(a == b),
343 (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
344 (Opcode::Lt, _, _) => Value::Bool(as_f64(&a)? < as_f64(&b)?),
345 (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
346 (Opcode::Le, _, _) => Value::Bool(as_f64(&a)? <= as_f64(&b)?),
347 _ => {
348 return Err(Fault::Invariant(
349 "numeric_binop called with a non-arithmetic opcode",
350 ))
351 }
352 };
353 self.set_reg(dst, result)
354 }
355
356 #[inline]
357 fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
358 let v = self.get_reg(reg)?;
359 v.as_cap().ok_or(Fault::TypeMismatch {
360 expected: "cap",
361 got: v.type_name(),
362 })
363 }
364
365 #[inline]
366 fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
367 let v = self.get_reg(reg)?;
368 if v.as_message().is_none() {
369 return Err(Fault::TypeMismatch {
370 expected: "message",
371 got: v.type_name(),
372 });
373 }
374 Ok(v)
375 }
376
377 #[inline]
378 fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
379 match self.get_reg(reg)? {
380 Value::Str(s) => Ok(s),
381 other => Err(Fault::TypeMismatch {
382 expected: "str",
383 got: other.type_name(),
384 }),
385 }
386 }
387
388 #[inline]
389 fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
390 tag_from_value(&self.get_reg(reg)?)
391 }
392
393 #[inline]
394 fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
395 request_id_from_value(&self.get_reg(reg)?)
396 }
397
398 fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
399 let mut args = Vec::with_capacity(argc as usize);
400 for i in 0..argc {
401 let reg = reg_at(base, first_offset + u16::from(i))?;
402 args.push(self.get_reg(reg)?);
403 }
404 Ok(args)
405 }
406
407 #[inline]
409 fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
410 let millis = self.get_reg(reg)?;
411 match millis.as_int() {
412 Some(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
413 _ => Err(Fault::TypeMismatch {
414 expected: "non-negative int",
415 got: millis.type_name(),
416 }),
417 }
418 }
419
420 fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
425 let code_len = self.chunk.code.len();
426 let paranoid = self.paranoid_jumps;
427 let frame = self.current()?;
428 let target_i = frame.pc() as i64 + i64::from(imm);
429 if paranoid && (target_i < 0 || target_i as usize > code_len) {
430 let target = if target_i < 0 {
431 usize::MAX
432 } else {
433 target_i as usize
434 };
435 return Err(Fault::BadJump { target, code_len });
436 }
437 frame.set_pc(target_i as usize);
438 Ok(())
439 }
440
441 pub fn run(&mut self, budget: u32) -> VmResult {
449 macro_rules! trap {
450 ($e:expr) => {
451 match $e {
452 Ok(v) => v,
453 Err(fault) => return VmResult::Trap(fault),
454 }
455 };
456 }
457
458 for _ in 0..budget {
459 self.instructions_executed += 1;
460 let instr = match self.fetch() {
461 Ok(Some(i)) => i,
462 Ok(None) => {
463 match self.pop_frame(Value::Unit) {
465 Ok(Some(result)) => return result,
466 Ok(None) => continue,
467 Err(fault) => return VmResult::Trap(fault),
468 }
469 }
470 Err(fault) => return VmResult::Trap(fault),
471 };
472
473 match instr.op {
474 Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
475 Opcode::Nop => {}
476 Opcode::LoadConst => {
477 let idx = instr.imm as u32;
478 let konst = match self.chunk.constant(idx) {
479 Some(v) => v.clone(),
480 None => {
481 return VmResult::Trap(Fault::BadConstant {
482 index: idx,
483 pool_size: self.chunk.constants.len() as u32,
484 })
485 }
486 };
487 trap!(self.set_reg(instr.a, konst));
488 }
489 Opcode::LoadImm => {
490 trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
491 }
492 Opcode::Move => {
493 let v = trap!(self.get_reg(instr.b));
494 trap!(self.set_reg(instr.a, v));
495 }
496 Opcode::Add
497 | Opcode::Sub
498 | Opcode::Mul
499 | Opcode::Div
500 | Opcode::Mod
501 | Opcode::Eq
502 | Opcode::Lt
503 | Opcode::Le => {
504 trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
505 }
506 Opcode::Neg => {
507 let v = trap!(self.get_reg(instr.b));
508 let negated = match v {
509 Value::Int(x) => Value::Int(x.wrapping_neg()),
510 Value::Float(x) => Value::Float(-x),
511 other => {
512 return VmResult::Trap(Fault::TypeMismatch {
513 expected: "int or float",
514 got: other.type_name(),
515 })
516 }
517 };
518 trap!(self.set_reg(instr.a, negated));
519 }
520 Opcode::Jump => {
521 trap!(self.apply_relative_jump(instr.imm));
522 }
523 Opcode::Branch => {
524 let cond = trap!(self.get_reg(instr.a));
525 if !cond.is_truthy() {
526 trap!(self.apply_relative_jump(instr.imm));
527 }
528 }
529 Opcode::Call => {
530 let function = instr.imm as u32;
531 let argc = instr.b;
532 let dst = instr.a;
533 if self.frames.len() >= MAX_CALL_DEPTH {
534 return VmResult::Trap(Fault::CallStackOverflow {
535 depth: self.frames.len(),
536 });
537 }
538 let (num_registers, arity, entry) = match self.chunk.function(function) {
539 Some(d) => (d.num_registers, d.arity, d.entry as usize),
540 None => {
541 return VmResult::Trap(Fault::BadFunction {
542 index: function,
543 table_size: self.chunk.functions.len() as u32,
544 })
545 }
546 };
547 let args = trap!(self.gather_regs(dst, argc, 0));
548 let mut new_frame = Frame::new(function, num_registers, Some(dst));
549 new_frame.set_pc(entry);
550 trap!(load_frame_args(&mut new_frame, args, arity));
551 self.frames.push(new_frame);
552 }
553 Opcode::CallNative => {
554 let native_index = instr.imm as u32;
555 let argc = instr.b;
556 let dst = instr.a;
557 if let Err(err) =
558 check_native_gate(&self.native_gate, &self.natives, native_index)
559 {
560 return VmResult::Trap(match err {
561 NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
562 index,
563 table_size: self.natives.len() as u32,
564 },
565 other => Fault::NativeDenied(other),
566 });
567 }
568 let args = trap!(self.gather_regs(dst, argc, 0));
569 let result = match self.natives.get(native_index) {
577 Some(native_fn) => native_fn(&args),
578 None => {
579 return VmResult::Trap(Fault::BadNative {
580 index: native_index,
581 table_size: self.natives.len() as u32,
582 })
583 }
584 };
585 match result {
586 Ok(value) => trap!(self.set_reg(dst, value)),
587 Err(fault) => return VmResult::Trap(fault),
588 }
589 }
590 Opcode::Return => {
591 let v = trap!(self.get_reg(instr.a));
592 match self.pop_frame(v) {
593 Ok(Some(result)) => return result,
594 Ok(None) => {}
595 Err(fault) => return VmResult::Trap(fault),
596 }
597 }
598 Opcode::Spawn => {
599 let args = trap!(self.gather_regs(instr.a, instr.b, 1));
602 return VmResult::Spawn {
603 function: instr.imm as u32,
604 args,
605 dest_reg: instr.a,
606 requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
607 };
608 }
609 Opcode::Yield => return VmResult::Yield,
610 Opcode::Sleep => {
611 return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
612 }
613 Opcode::Exit => {
614 let v = trap!(self.get_reg(instr.a));
615 return VmResult::Complete(v);
616 }
617 Opcode::SelfPid => {
618 return VmResult::SelfPid { dest_reg: instr.a };
619 }
620 Opcode::Send => {
621 let target_cap = trap!(self.expect_cap_reg(instr.a));
622 let message = trap!(self.expect_message_value(instr.b));
623 return VmResult::Send {
624 target_cap,
625 message,
626 };
627 }
628 Opcode::Receive => {
629 return VmResult::Receive {
630 dest_reg: instr.a,
631 timeout: None,
632 match_tag: None,
633 match_request_id: None,
634 match_payload_kind: None,
635 };
636 }
637 Opcode::ReceiveTimeout => {
638 let timeout = trap!(self.duration_millis_from_reg(instr.b));
639 return VmResult::Receive {
640 dest_reg: instr.a,
641 timeout: Some(timeout),
642 match_tag: None,
643 match_request_id: None,
644 match_payload_kind: None,
645 };
646 }
647 Opcode::ReceiveMatch => {
648 let tag = trap!(self.tag_from_reg(instr.b));
649 return VmResult::Receive {
650 dest_reg: instr.a,
651 timeout: None,
652 match_tag: Some(tag),
653 match_request_id: None,
654 match_payload_kind: None,
655 };
656 }
657 Opcode::ReceiveMatchImm => {
658 let tag = trap!(tag_from_imm(instr.imm));
659 return VmResult::Receive {
660 dest_reg: instr.a,
661 timeout: None,
662 match_tag: Some(tag),
663 match_request_id: None,
664 match_payload_kind: None,
665 };
666 }
667 Opcode::ReceiveMatchKind => {
668 let kind = match u8::try_from(instr.imm) {
671 Ok(k) if k <= 8 => k,
672 _ => {
673 return VmResult::Trap(Fault::TypeMismatch {
674 expected: "payload kind 0..=8",
675 got: "imm-out-of-range",
676 })
677 }
678 };
679 return VmResult::Receive {
680 dest_reg: instr.a,
681 timeout: None,
682 match_tag: None,
683 match_request_id: None,
684 match_payload_kind: Some(kind),
685 };
686 }
687 Opcode::FreshRequestId => {
688 let id = self.fresh_request_id();
689 trap!(self.set_reg(instr.a, Value::Int(id as i64)));
690 }
691 Opcode::ReceiveMatchCorr => {
692 let tag = trap!(self.tag_from_reg(instr.b));
693 let rid = trap!(self.request_id_from_reg(instr.c));
694 return VmResult::Receive {
695 dest_reg: instr.a,
696 timeout: None,
697 match_tag: Some(tag),
698 match_request_id: Some(rid),
699 match_payload_kind: None,
700 };
701 }
702 Opcode::ReceiveMatchCorrImm => {
703 let tag = trap!(tag_from_imm(instr.imm));
704 let rid = trap!(self.request_id_from_reg(instr.b));
705 return VmResult::Receive {
706 dest_reg: instr.a,
707 timeout: None,
708 match_tag: Some(tag),
709 match_request_id: Some(rid),
710 match_payload_kind: None,
711 };
712 }
713 Opcode::Ask => {
714 let target_cap = trap!(self.expect_cap_reg(instr.b));
715 let request = trap!(self.expect_message_value(instr.c));
716 return VmResult::Ask {
717 dest_reg: instr.a,
718 target_cap,
719 request,
720 timeout: None,
721 };
722 }
723 Opcode::AskTimeout => {
724 let millis_reg = match u8::try_from(instr.imm) {
725 Ok(r) => r,
726 Err(_) => {
727 return VmResult::Trap(Fault::TypeMismatch {
728 expected: "millis register",
729 got: "imm-out-of-range",
730 })
731 }
732 };
733 let timeout = trap!(self.duration_millis_from_reg(millis_reg));
734 let target_cap = trap!(self.expect_cap_reg(instr.b));
735 let request = trap!(self.expect_message_value(instr.c));
736 return VmResult::Ask {
737 dest_reg: instr.a,
738 target_cap,
739 request,
740 timeout: Some(timeout),
741 };
742 }
743 Opcode::Monitor => {
744 let target_cap = trap!(self.expect_cap_reg(instr.b));
745 return VmResult::Monitor {
746 dest_reg: instr.a,
747 target_cap,
748 };
749 }
750 Opcode::Demonitor => {
751 return VmResult::Demonitor {
752 monitor_reg: instr.a,
753 };
754 }
755 Opcode::Link => {
756 let target_cap = trap!(self.expect_cap_reg(instr.b));
757 return VmResult::Link {
758 dest_reg: instr.a,
759 target_cap,
760 };
761 }
762 Opcode::Unlink => {
763 return VmResult::Unlink { link_reg: instr.a };
764 }
765 Opcode::SetTrapExit => {
766 let enabled = trap!(self.get_reg(instr.a)).is_truthy();
767 return VmResult::SetTrapExit { enabled };
768 }
769 Opcode::SetRestartPolicy => {
770 let policy = match instr.imm {
773 0..=2 => instr.imm as u8,
774 _ => {
775 return VmResult::Trap(Fault::TypeMismatch {
776 expected: "restart policy 0..=2",
777 got: "imm-out-of-range",
778 })
779 }
780 };
781 return VmResult::SetRestartPolicy { policy };
782 }
783 Opcode::HostAwait => {
784 let args = trap!(self.get_reg(instr.b));
785 let op = if instr.imm < 0 {
786 return VmResult::Trap(Fault::TypeMismatch {
787 expected: "HostAwait op >= 0",
788 got: "imm-negative",
789 });
790 } else {
791 instr.imm as u32
792 };
793 return VmResult::HostAwait {
794 dest_reg: instr.a,
795 op,
796 args,
797 };
798 }
799 Opcode::RegisterName => {
800 return VmResult::RegisterName {
801 name: trap!(self.expect_str_reg(instr.a)),
802 };
803 }
804 Opcode::Whereis => {
805 return VmResult::Whereis {
806 dest_reg: instr.a,
807 name: trap!(self.expect_str_reg(instr.b)),
808 };
809 }
810 Opcode::Delegate => {
811 let src_cap = trap!(self.expect_cap_reg(instr.b));
812 let want_native_cap = if instr.c == 255 {
813 None
814 } else {
815 Some(trap!(self.expect_cap_reg(instr.c)))
816 };
817 return VmResult::Delegate {
818 dest_reg: instr.a,
819 src_cap,
820 want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
821 want_native_cap,
822 };
823 }
824 Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
825 }
826 }
827 VmResult::Yield
828 }
829
830 fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
834 let finished = self
835 .frames
836 .pop()
837 .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
838 match finished.dest_reg() {
839 Some(dest) => {
840 self.set_reg(dest, value)?;
841 Ok(None)
842 }
843 None => Ok(Some(VmResult::Complete(value))),
844 }
845 }
846}
847
848#[inline]
858fn load_frame_args(
859 frame: &mut Frame,
860 args: impl IntoIterator<Item = Value>,
861 arity: u8,
862) -> Result<(), Fault> {
863 let frame_size = frame.registers().len() as u8;
864 for (i, a) in args.into_iter().enumerate().take(arity as usize) {
865 match frame.registers_mut().get_mut(i) {
866 Some(slot) => *slot = a,
867 None => {
868 return Err(Fault::RegisterOutOfRange {
869 reg: i as u8,
870 frame_size,
871 })
872 }
873 }
874 }
875 Ok(())
876}
877
878fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
879 match u8::try_from(u32::from(base) + u32::from(offset)) {
880 Ok(reg) => Ok(reg),
881 Err(_) => Err(Fault::RegisterIndexOverflow {
882 base,
883 offset: match u8::try_from(offset) {
884 Ok(o) => o,
885 Err(_) => u8::MAX,
886 },
887 }),
888 }
889}
890
891#[inline]
893fn heap_charge_of(value: &Value) -> usize {
894 match value {
895 Value::Str(s) => s.len(),
896 Value::Bytes(b) => b.len(),
897 _ => 0,
898 }
899}
900
901fn charge_pair(
904 quota: &FlowQuota,
905 memory: Option<&crate::MemoryBudget>,
906 bytes: usize,
907) -> Result<(), Fault> {
908 if bytes == 0 {
909 return Ok(());
910 }
911 quota
912 .alloc(bytes)
913 .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
914 if let Some(mem) = memory {
915 if let Err(e) = mem.try_charge(bytes) {
916 quota.free(bytes);
917 return Err(Fault::QuotaExceeded(e.to_string()));
918 }
919 }
920 Ok(())
921}
922
923fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
924 if bytes == 0 {
925 return;
926 }
927 quota.free(bytes);
928 if let Some(mem) = memory {
929 mem.release(bytes);
930 }
931}
932
933fn charge_heap_value(
935 quota: &FlowQuota,
936 memory: Option<&crate::MemoryBudget>,
937 value: &Value,
938) -> Result<(), Fault> {
939 charge_pair(quota, memory, heap_charge_of(value))
940}
941
942fn as_f64(v: &Value) -> Result<f64, Fault> {
943 match v {
944 Value::Int(i) => Ok(*i as f64),
945 Value::Float(f) => Ok(*f),
946 other => Err(Fault::TypeMismatch {
947 expected: "int or float",
948 got: other.type_name(),
949 }),
950 }
951}
952
953#[inline]
955fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
956 match u16::try_from(imm) {
957 Ok(t) if imm >= 0 => Ok(t),
958 _ => Err(Fault::TypeMismatch {
959 expected: "tag u16",
960 got: "imm-out-of-range",
961 }),
962 }
963}
964
965fn tag_from_value(v: &Value) -> Result<u16, Fault> {
966 match v.as_int() {
967 Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
968 Some(_) => Err(Fault::TypeMismatch {
969 expected: "tag u16",
970 got: "int-out-of-range",
971 }),
972 None => Err(Fault::TypeMismatch {
973 expected: "int",
974 got: v.type_name(),
975 }),
976 }
977}
978
979#[inline]
981fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
982 match v.as_int() {
983 Some(i) if i >= 0 => Ok(i as u64),
984 Some(_) => Err(Fault::TypeMismatch {
985 expected: "request_id u64",
986 got: "negative-int",
987 }),
988 None => Err(Fault::TypeMismatch {
989 expected: "int",
990 got: v.type_name(),
991 }),
992 }
993}
994
995#[cfg(test)]
996mod tests {
997 use super::*;
998 use crate::bytecode::builder::ChunkBuilder;
999
1000 type TestResult = Result<(), Box<dyn std::error::Error>>;
1001
1002 #[test]
1007 fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1008 let mut b = ChunkBuilder::new("t");
1009 b.begin_function("main", 0, 2);
1010 b.emit_spawn(255, 0, 1);
1011 b.emit_return(0);
1012 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1013 match vm.run(10) {
1014 VmResult::Trap(Fault::RegisterIndexOverflow {
1015 base: 255,
1016 offset: 1,
1017 }) => Ok(()),
1018 other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1019 }
1020 }
1021
1022 #[test]
1026 fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1027 let mut b = ChunkBuilder::new("t");
1028 b.begin_function("main", 3, 1);
1029 b.emit_return(0);
1030 let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1031 match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1032 Err(Fault::RegisterOutOfRange {
1033 reg: 1,
1034 frame_size: 1,
1035 }) => Ok(()),
1036 Err(e) => Err(format!("unexpected fault: {e}").into()),
1037 Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1038 }
1039 }
1040
1041 #[test]
1042 fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1043 let mut b = ChunkBuilder::new("t");
1044 let callee = b.begin_function("callee", 3, 1);
1045 b.emit_return(0);
1046 let main = b.begin_function("main", 0, 4);
1047 b.emit_load_imm(0, 7);
1048 b.emit_load_imm(1, 8);
1049 b.emit_load_imm(2, 9);
1050 b.emit_call(0, callee, 3);
1051 b.emit_return(0);
1052 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1053 match vm.run(50) {
1054 VmResult::Trap(Fault::RegisterOutOfRange {
1055 reg: 1,
1056 frame_size: 1,
1057 }) => Ok(()),
1058 other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1059 }
1060 }
1061
1062 #[test]
1065 fn gathering_up_to_the_last_register_still_works() -> TestResult {
1066 let mut b = ChunkBuilder::new("t");
1067 let callee = b.begin_function("callee", 1, 1);
1068 b.emit_return(0);
1069 let main = b.begin_function("main", 0, 255);
1070 b.emit_load_imm(254, 5);
1071 b.emit_call(254, callee, 1);
1073 b.emit_return(254);
1074 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1075 match vm.run(100) {
1076 VmResult::Complete(_) => Ok(()),
1077 other => Err(format!("expected completion, got {other:?}").into()),
1078 }
1079 }
1080
1081 #[test]
1082 fn neg_i64_min_wrapping() -> TestResult {
1083 let mut b = ChunkBuilder::new("t");
1084 b.begin_function("main", 0, 1);
1085 let k = b.const_(Value::Int(i64::MIN));
1086 b.emit_load_const(0, k);
1087 b.emit_neg(0, 0);
1088 b.emit_return(0);
1089 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1090 match vm.run(10) {
1091 VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1092 other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1093 }
1094 }
1095
1096 #[test]
1097 fn mod_non_int_type_mismatch() -> TestResult {
1098 let mut b = ChunkBuilder::new("t");
1099 b.begin_function("main", 0, 3);
1100 b.emit_load_imm(0, 10);
1101 let kf = b.const_(Value::Float(3.0));
1102 b.emit_load_const(1, kf);
1103 b.emit_binop(Opcode::Mod, 2, 0, 1);
1104 b.emit_return(2);
1105 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1106 match vm.run(20) {
1107 VmResult::Trap(Fault::TypeMismatch {
1108 expected: "int",
1109 got: "float",
1110 }) => Ok(()),
1111 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1112 }
1113 }
1114
1115 #[test]
1116 fn receive_timeout_negative_traps() -> TestResult {
1117 let mut b = ChunkBuilder::new("t");
1118 b.begin_function("main", 0, 2);
1119 b.emit_load_imm(1, -1);
1120 b.emit_receive_timeout(0, 1);
1121 b.emit_return(0);
1122 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1123 match vm.run(10) {
1124 VmResult::Trap(Fault::TypeMismatch {
1125 expected: "non-negative int",
1126 ..
1127 }) => Ok(()),
1128 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1129 }
1130 }
1131
1132 #[test]
1133 fn ask_timeout_negative_traps() -> TestResult {
1134 let mut b = ChunkBuilder::new("t");
1135 b.begin_function("main", 0, 4);
1136 b.emit_load_imm(3, -5);
1137 b.emit_ask_timeout(0, 1, 2, 3);
1139 b.emit_return(0);
1140 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1141 match vm.run(10) {
1142 VmResult::Trap(Fault::TypeMismatch {
1143 expected: "non-negative int",
1144 ..
1145 }) => Ok(()),
1146 other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1147 }
1148 }
1149
1150 #[test]
1151 fn paranoid_jump_out_of_range_traps() -> TestResult {
1152 let mut b = ChunkBuilder::new("t");
1153 b.begin_function("main", 0, 1);
1154 b.emit_load_imm(0, 0);
1155 b.emit_return(0);
1156 let mut chunk = b.finish();
1157 let code_len = chunk.code.len();
1158 chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1159 let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1160 vm.set_paranoid_jumps(true);
1161 match vm.run(10) {
1162 VmResult::Trap(Fault::BadJump {
1163 target: 101,
1164 code_len: len,
1165 }) if len == code_len => Ok(()),
1166 other => Err(format!("expected BadJump(101), got {other:?}").into()),
1167 }
1168 }
1169
1170 #[test]
1171 fn overwrite_releases_previous_heap_charge() -> TestResult {
1172 let mut b = ChunkBuilder::new("t");
1173 let k1 = b.const_(Value::Str("a".repeat(100).into()));
1174 let k2 = b.const_(Value::Str("b".repeat(100).into()));
1175 b.begin_function("main", 0, 1);
1176 b.emit_load_const(0, k1);
1177 b.emit_load_const(0, k2);
1178 b.emit_return(0);
1179 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1180 let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1182 crate::QuotaConfig {
1183 mem_limit: 150,
1184 ..crate::QuotaConfig::permissive()
1185 },
1186 ));
1187 let memory = Arc::new(crate::MemoryBudget::new(10_000));
1188 vm.set_memory_budget(Arc::clone(&memory));
1189 vm.set_quota(Arc::clone("a))?;
1190 match vm.run(20) {
1191 VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1192 assert_eq!(quota.mem_used(), 100);
1193 assert_eq!(memory.used(), 100);
1194 Ok(())
1195 }
1196 other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1197 }
1198 }
1199
1200 #[test]
1201 fn returning_over_quota_keeps_quota_fault() -> TestResult {
1202 let mut b = ChunkBuilder::new("t");
1203 let k = b.const_(Value::Str("x".repeat(200).into()));
1204 let callee = b.begin_function("callee", 0, 1);
1205 b.emit_load_const(0, k);
1206 b.emit_return(0);
1207 let main = b.begin_function("main", 0, 1);
1208 b.emit_call(0, callee, 0);
1209 b.emit_return(0);
1210 let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1211 let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1213 vm.set_quota(quota)?;
1214 match vm.run(50) {
1215 VmResult::Trap(Fault::QuotaExceeded(_)) => Ok(()),
1216 other => {
1217 Err(format!("expected QuotaExceeded from return writeback, got {other:?}").into())
1218 }
1219 }
1220 }
1221
1222 #[test]
1223 fn call_native_without_gate_is_typed_denied() -> TestResult {
1224 let mut b = ChunkBuilder::new("t");
1225 b.begin_function("main", 0, 1);
1226 b.emit_call_native(0, 0, 0);
1227 b.emit_return(0);
1228 let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1229 let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1230 match vm.run(10) {
1231 VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1232 other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1233 }
1234 }
1235
1236 #[test]
1237 fn non_paranoid_bad_jump_still_fail_opens() -> TestResult {
1238 let mut b = ChunkBuilder::new("t");
1239 b.begin_function("main", 0, 1);
1240 b.emit_load_imm(0, 7);
1241 b.emit_return(0);
1242 let mut chunk = b.finish();
1243 chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1244 let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1245 match vm.run(10) {
1246 VmResult::Complete(Value::Unit) => Ok(()),
1248 other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1249 }
1250 }
1251}