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