Skip to main content

byteflow/vm/
machine.rs

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
12/// Hard limit on call nesting. Frames are heap-allocated, so
13/// unbounded recursion would grow the Flow's memory instead of crashing
14/// the worker thread's native stack — which is worse, not better, without a
15/// limit. `4096` comfortably covers real recursive algorithms while keeping
16/// a runaway `fn f() { f() }` a `Fault`, not an OOM.
17pub const MAX_CALL_DEPTH: usize = 4096;
18
19/// One virtual Flow's execution state: call stack + registers. Cheap
20/// enough to construct that spawning a Flow is a handful of small heap
21/// allocations, not a native thread/stack (contrast: a `std::thread` reserves
22/// megabytes of stack whether it uses them or not).
23///
24/// `Vm` owns no scheduler, mailbox, or thread handle — see [`VmResult`] for
25/// why that separation is the whole point.
26pub struct Vm {
27    chunk: Arc<Chunk>,
28    natives: Arc<NativeTable>,
29    native_gate: NativeGate,
30    frames: Vec<Frame>,
31    /// Lifetime instruction counter, exposed for `FlowMetrics` (design
32    /// notes §26).
33    instructions_executed: u64,
34    /// Next `Message.request_id` for [`Opcode::FreshRequestId`] and for
35    /// hops that still carry `0` (“unset”) at the Send/Ask boundary.
36    next_request_id: u64,
37    /// Per-flow heap charge for `Str`/`Bytes` written into registers.
38    quota: Option<Arc<FlowQuota>>,
39    /// Process-wide memory ceiling (optional; set by the runtime).
40    memory: Option<Arc<crate::MemoryBudget>>,
41    /// When true, `Jump`/`Branch` bounds-check targets at runtime (see
42    /// [`Self::set_paranoid_jumps`]). Default off: verified chunks trust
43    /// `verify`; unverified corrupt jumps fail-open as implicit `return Unit`.
44    paranoid_jumps: bool,
45}
46
47impl Vm {
48    /// Construct a `Vm` ready to run `function` (an index into
49    /// `chunk.functions`) with the given arguments loaded into `r0..argc`.
50    /// `natives` is the FFI table `Opcode::CallNative` dispatches through —
51    /// pass [`NativeTable::empty`] if the chunk never calls out to Rust.
52    ///
53    /// Native calls are **denied** until [`Self::with_native_gate`] installs
54    /// an allowlist (the runtime does this from the flow's attenuated Cap).
55    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    /// Enable runtime bounds checks on `Jump` / `Branch` targets.
87    ///
88    /// Production paths leave this off and rely on [`crate::verify`]. Turn it
89    /// on for hand-built or untrusted chunks that skip verification.
90    pub fn set_paranoid_jumps(&mut self, enabled: bool) {
91        self.paranoid_jumps = enabled;
92    }
93
94    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
95    ///
96    /// Overwrites use reserve(new) → release(old) → install (see
97    /// [`crate::memory`]). Same `Arc` rewritten into the same slot is not
98    /// charged twice.
99    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(&quota, self.memory.as_deref(), slot)?;
103            }
104        }
105        self.quota = Some(quota);
106        Ok(())
107    }
108
109    /// Attach the process-wide memory ceiling (call before or with [`Self::set_quota`]).
110    pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
111        self.memory = Some(memory);
112    }
113
114    /// Mint a per-flow correlation id. Never returns `0` (`next_request_id`
115    /// starts at 1 and saturates, so it cannot wrap to zero).
116    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    /// Index into `chunk.functions` for the active (top) call frame.
127    /// Useful for diagnostics / supervisor logs when a Flow traps.
128    pub fn current_function(&self) -> u32 {
129        // Category D: frames must be non-empty while the VM is runnable.
130        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
131        // broken invariant cannot panic a worker; the next `run` will trap.
132        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    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
140    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
141    /// needing to know anything about `Chunk`'s internals — every Flow
142    /// spawned (transitively) from the same top-level `spawn()` call shares
143    /// one immutable chunk in memory, never copies it.
144    pub fn chunk_arc(&self) -> Arc<Chunk> {
145        self.chunk.clone()
146    }
147
148    /// A cheap `Arc` clone of this VM's native function table, for the same
149    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
150    /// `CallNative` through the identical table its parent uses.
151    pub fn natives_arc(&self) -> Arc<NativeTable> {
152        self.natives.clone()
153    }
154
155    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
156    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
157    /// into the register the instruction that suspended us was targeting,
158    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
159    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
160    /// destination register holding its previous (stale) value.
161    #[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    /// Program counter of the active frame — used by the optional JIT hook.
167    pub fn current_pc(&self) -> Option<usize> {
168        self.frames.last().map(|f| f.pc())
169    }
170
171    /// Number of registers in the active frame.
172    pub fn current_num_registers(&self) -> Option<u8> {
173        self.frames.last().map(|f| f.registers().len() as u8)
174    }
175
176    /// Read-only view of the active register file.
177    pub fn top_registers(&self) -> Option<&[Value]> {
178        self.frames.last().map(|f| f.registers())
179    }
180
181    /// Mutable view of the active register file (JIT sync path).
182    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
183        self.frames.last_mut().map(|f| f.registers_mut())
184    }
185
186    /// Set the active frame's program counter.
187    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    /// Write one register in the active frame (JIT sync path).
194    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
195        self.set_reg(reg, value)
196    }
197
198    /// Deliver a return value through the call stack.
199    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
200        self.pop_frame(value)
201    }
202
203    /// Top call frame. Empty stack is a broken invariant (category D) —
204    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
205    #[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    /// Heap charge for `Str` / `Bytes` register stores.
249    ///
250    /// Order: reserve(new) → release(old). Failed reservation leaves the
251    /// slot and accounting untouched. Same `Arc` in the same slot is a no-op.
252    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        // Net accounting: reserve only the growth (or release the shrink).
266        // Semantically equal to reserve(new)→release(old) without needing
267        // temporary headroom of old+new against a tight mem_limit.
268        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    /// Fetch the next instruction and advance `pc`.
277    ///
278    /// `Ok(None)` if control fell off the end of the function body without an
279    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
280    /// (friendlier to hand-written bytecode that omits a trailing return).
281    /// `Err` if the frame stack is empty (invariant break).
282    ///
283    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
284    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
285    /// compile.
286    #[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    /// Same policy as `Sleep`: non-negative `Int` only; never silent clamp.
399    #[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    /// Apply a relative jump from the current (post-fetch) `pc`.
412    ///
413    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
414    /// Paranoid mode traps; otherwise preserves the historical fail-open cast.
415    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    /// Run at most `budget` instructions (cooperative-preemption quantum,
433    /// design notes §10-11), or until the Flow completes / needs an
434    /// effect the scheduler must perform / faults.
435    ///
436    /// Every exit path is captured by [`VmResult`] — this function itself
437    /// never panics on malformed *verified* bytecode; faults are returned,
438    /// not thrown, so a buggy Flow can't take a worker thread down.
439    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                    // Fell off the end of a function: implicit `return Unit`.
455                    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                    // Runs inline on this worker thread — see
552                    // `NativeFn`'s doc comment on why natives must not
553                    // block. This is the actual FFI boundary (design
554                    // notes §30-31): plain Rust on one side, bytecode
555                    // registers on the other, with `Fault::NativeError`
556                    // as the only channel for a native-side failure to
557                    // become a Flow fault instead of a host panic.
558                    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                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
582                    // child Cap. `a = 255` overflows on the first gather.
583                    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    /// Pop the current frame, delivering `value` to the caller (or
755    /// finishing the Flow if this was the outermost frame). Returns
756    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
757    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/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
773/// if that sum leaves the register index space.
774///
775/// Every multi-operand opcode gathers its arguments from consecutive
776/// registers. Written as a plain `base + offset` on `u8`, that addition
777/// panics in debug and **wraps** in release — so a release build silently
778/// reads the wrong register instead of failing, which is the worst of the
779/// two outcomes and the one a debug-mode test suite never sees. The sum is
780/// therefore computed in a wider type and narrowed explicitly.
781#[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/// Bytes charged for a register-resident heap value (`Str` / `Bytes` len).
811#[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
820/// Reserve `bytes` on the flow quota and optional runtime budget.
821/// Rolls back the flow charge if the global budget refuses.
822fn 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
852/// Charge `Str` / `Bytes` length (initial attach / frame scan).
853fn 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/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
870#[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/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
896#[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    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
919    /// already leaves the register space. This used to panic in debug and —
920    /// far worse — wrap around to `r0` in release, silently spawning with the
921    /// wrong argument.
922    #[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    /// `Vm::new` is public and reachable without `verify`, and its panic
939    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
940    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
941    #[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    /// The boundary case that must keep working: gathering right up to the
979    /// last register is legal, it is only going *past* it that faults.
980    #[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        // Argument at r254 — the highest index a 255-register frame has.
988        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        // Cap/message regs are garbage; millis is checked first.
1054        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        // Limit 150: first 100 fits; without release the second 100 would fail.
1097        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(&quota))?;
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        // 200 fits the callee store; writeback into the caller charges again.
1128        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            // Fall off the end → implicit return Unit from outermost frame.
1162            VmResult::Complete(Value::Unit) => Ok(()),
1163            other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1164        }
1165    }
1166}