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(
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    /// Enable runtime bounds checks on `Jump` / `Branch` targets.
93    ///
94    /// Production paths leave this off and rely on [`crate::verify`]. Turn it
95    /// on for hand-built or untrusted chunks that skip verification.
96    pub fn set_paranoid_jumps(&mut self, enabled: bool) {
97        self.paranoid_jumps = enabled;
98    }
99
100    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
101    ///
102    /// Overwrites use reserve(new) → release(old) → install (see
103    /// [`crate::memory`]). Same `Arc` rewritten into the same slot is not
104    /// charged twice.
105    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(&quota, self.memory.as_deref(), slot)?;
109            }
110        }
111        self.quota = Some(quota);
112        Ok(())
113    }
114
115    /// Attach the process-wide memory ceiling (call before or with [`Self::set_quota`]).
116    pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
117        self.memory = Some(memory);
118    }
119
120    /// Mint a per-flow correlation id. Never returns `0` (`next_request_id`
121    /// starts at 1 and saturates, so it cannot wrap to zero).
122    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    /// Index into `chunk.functions` for the active (top) call frame.
133    /// Useful for diagnostics / supervisor logs when a Flow traps.
134    pub fn current_function(&self) -> u32 {
135        // Category D: frames must be non-empty while the VM is runnable.
136        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
137        // broken invariant cannot panic a worker; the next `run` will trap.
138        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    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
146    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
147    /// needing to know anything about `Chunk`'s internals — every Flow
148    /// spawned (transitively) from the same top-level `spawn()` call shares
149    /// one immutable chunk in memory, never copies it.
150    pub fn chunk_arc(&self) -> Arc<Chunk> {
151        self.chunk.clone()
152    }
153
154    /// A cheap `Arc` clone of this VM's native function table, for the same
155    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
156    /// `CallNative` through the identical table its parent uses.
157    pub fn natives_arc(&self) -> Arc<NativeTable> {
158        self.natives.clone()
159    }
160
161    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
162    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
163    /// into the register the instruction that suspended us was targeting,
164    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
165    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
166    /// destination register holding its previous (stale) value.
167    #[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    /// Program counter of the active frame — used by the optional JIT hook.
173    pub fn current_pc(&self) -> Option<usize> {
174        self.frames.last().map(|f| f.pc())
175    }
176
177    /// Number of registers in the active frame.
178    pub fn current_num_registers(&self) -> Option<u8> {
179        self.frames.last().map(|f| f.registers().len() as u8)
180    }
181
182    /// Read-only view of the active register file.
183    pub fn top_registers(&self) -> Option<&[Value]> {
184        self.frames.last().map(|f| f.registers())
185    }
186
187    /// Mutable view of the active register file (JIT sync path).
188    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
189        self.frames.last_mut().map(|f| f.registers_mut())
190    }
191
192    /// Set the active frame's program counter.
193    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    /// Write one register in the active frame (JIT sync path).
200    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
201        self.set_reg(reg, value)
202    }
203
204    /// Deliver a return value through the call stack.
205    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
206        self.pop_frame(value)
207    }
208
209    /// Top call frame. Empty stack is a broken invariant (category D) —
210    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
211    #[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    /// Heap charge for `Str` / `Bytes` register stores.
258    ///
259    /// Order: reserve(new) → release(old). Failed reservation leaves the
260    /// slot and accounting untouched. Same `Arc` in the same slot is a no-op.
261    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        // Net accounting: reserve only the growth (or release the shrink).
275        // Semantically equal to reserve(new)→release(old) without needing
276        // temporary headroom of old+new against a tight mem_limit.
277        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    /// Fetch the next instruction and advance `pc`.
286    ///
287    /// `Ok(None)` if control fell off the end of the function body without an
288    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
289    /// (friendlier to hand-written bytecode that omits a trailing return).
290    /// `Err` if the frame stack is empty (invariant break).
291    ///
292    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
293    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
294    /// compile.
295    #[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    /// Same policy as `Sleep`: non-negative `Int` only; never silent clamp.
408    #[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    /// Apply a relative jump from the current (post-fetch) `pc`.
421    ///
422    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
423    /// Paranoid mode traps; otherwise preserves the historical fail-open cast.
424    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    /// Run at most `budget` instructions (cooperative-preemption quantum,
442    /// design notes §10-11), or until the Flow completes / needs an
443    /// effect the scheduler must perform / faults.
444    ///
445    /// Every exit path is captured by [`VmResult`] — this function itself
446    /// never panics on malformed *verified* bytecode; faults are returned,
447    /// not thrown, so a buggy Flow can't take a worker thread down.
448    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                    // Fell off the end of a function: implicit `return Unit`.
464                    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                    // Runs inline on this worker thread — see
570                    // `NativeFn`'s doc comment on why natives must not
571                    // block. This is the actual FFI boundary (design
572                    // notes §30-31): plain Rust on one side, bytecode
573                    // registers on the other, with `Fault::NativeError`
574                    // as the only channel for a native-side failure to
575                    // become a Flow fault instead of a host panic.
576                    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                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
600                    // child Cap. `a = 255` overflows on the first gather.
601                    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                    // Selective receive by payload wire-tag (`Value::wire_tag`,
669                    // 0..=8). Non-matching hops stay queued (FIFO skip).
670                    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                    // Flow-local OTP restart policy for the host Supervisor
771                    // (`0` Always / `1` OnFailure / `2` Never).
772                    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::RegisterName => {
784                    return VmResult::RegisterName {
785                        name: trap!(self.expect_str_reg(instr.a)),
786                    };
787                }
788                Opcode::Whereis => {
789                    return VmResult::Whereis {
790                        dest_reg: instr.a,
791                        name: trap!(self.expect_str_reg(instr.b)),
792                    };
793                }
794                Opcode::Delegate => {
795                    let src_cap = trap!(self.expect_cap_reg(instr.b));
796                    let want_native_cap = if instr.c == 255 {
797                        None
798                    } else {
799                        Some(trap!(self.expect_cap_reg(instr.c)))
800                    };
801                    return VmResult::Delegate {
802                        dest_reg: instr.a,
803                        src_cap,
804                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
805                        want_native_cap,
806                    };
807                }
808                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
809            }
810        }
811        VmResult::Yield
812    }
813
814    /// Pop the current frame, delivering `value` to the caller (or
815    /// finishing the Flow if this was the outermost frame). Returns
816    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
817    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
818        let finished = self
819            .frames
820            .pop()
821            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
822        match finished.dest_reg() {
823            Some(dest) => {
824                self.set_reg(dest, value)?;
825                Ok(None)
826            }
827            None => Ok(Some(VmResult::Complete(value))),
828        }
829    }
830}
831
832/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
833/// if that sum leaves the register index space.
834///
835/// Every multi-operand opcode gathers its arguments from consecutive
836/// registers. Written as a plain `base + offset` on `u8`, that addition
837/// panics in debug and **wraps** in release — so a release build silently
838/// reads the wrong register instead of failing, which is the worst of the
839/// two outcomes and the one a debug-mode test suite never sees. The sum is
840/// therefore computed in a wider type and narrowed explicitly.
841#[inline]
842fn load_frame_args(
843    frame: &mut Frame,
844    args: impl IntoIterator<Item = Value>,
845    arity: u8,
846) -> Result<(), Fault> {
847    let frame_size = frame.registers().len() as u8;
848    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
849        match frame.registers_mut().get_mut(i) {
850            Some(slot) => *slot = a,
851            None => {
852                return Err(Fault::RegisterOutOfRange {
853                    reg: i as u8,
854                    frame_size,
855                })
856            }
857        }
858    }
859    Ok(())
860}
861
862fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
863    match u8::try_from(u32::from(base) + u32::from(offset)) {
864        Ok(reg) => Ok(reg),
865        Err(_) => Err(Fault::RegisterIndexOverflow {
866            base,
867            offset: match u8::try_from(offset) {
868                Ok(o) => o,
869                Err(_) => u8::MAX,
870            },
871        }),
872    }
873}
874
875/// Bytes charged for a register-resident heap value (`Str` / `Bytes` len).
876#[inline]
877fn heap_charge_of(value: &Value) -> usize {
878    match value {
879        Value::Str(s) => s.len(),
880        Value::Bytes(b) => b.len(),
881        _ => 0,
882    }
883}
884
885/// Reserve `bytes` on the flow quota and optional runtime budget.
886/// Rolls back the flow charge if the global budget refuses.
887fn charge_pair(
888    quota: &FlowQuota,
889    memory: Option<&crate::MemoryBudget>,
890    bytes: usize,
891) -> Result<(), Fault> {
892    if bytes == 0 {
893        return Ok(());
894    }
895    quota
896        .alloc(bytes)
897        .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
898    if let Some(mem) = memory {
899        if let Err(e) = mem.try_charge(bytes) {
900            quota.free(bytes);
901            return Err(Fault::QuotaExceeded(e.to_string()));
902        }
903    }
904    Ok(())
905}
906
907fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
908    if bytes == 0 {
909        return;
910    }
911    quota.free(bytes);
912    if let Some(mem) = memory {
913        mem.release(bytes);
914    }
915}
916
917/// Charge `Str` / `Bytes` length (initial attach / frame scan).
918fn charge_heap_value(
919    quota: &FlowQuota,
920    memory: Option<&crate::MemoryBudget>,
921    value: &Value,
922) -> Result<(), Fault> {
923    charge_pair(quota, memory, heap_charge_of(value))
924}
925
926fn as_f64(v: &Value) -> Result<f64, Fault> {
927    match v {
928        Value::Int(i) => Ok(*i as f64),
929        Value::Float(f) => Ok(*f),
930        other => Err(Fault::TypeMismatch {
931            expected: "int or float",
932            got: other.type_name(),
933        }),
934    }
935}
936
937/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
938#[inline]
939fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
940    match u16::try_from(imm) {
941        Ok(t) if imm >= 0 => Ok(t),
942        _ => Err(Fault::TypeMismatch {
943            expected: "tag u16",
944            got: "imm-out-of-range",
945        }),
946    }
947}
948
949fn tag_from_value(v: &Value) -> Result<u16, Fault> {
950    match v.as_int() {
951        Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
952        Some(_) => Err(Fault::TypeMismatch {
953            expected: "tag u16",
954            got: "int-out-of-range",
955        }),
956        None => Err(Fault::TypeMismatch {
957            expected: "int",
958            got: v.type_name(),
959        }),
960    }
961}
962
963/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
964#[inline]
965fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
966    match v.as_int() {
967        Some(i) if i >= 0 => Ok(i as u64),
968        Some(_) => Err(Fault::TypeMismatch {
969            expected: "request_id u64",
970            got: "negative-int",
971        }),
972        None => Err(Fault::TypeMismatch {
973            expected: "int",
974            got: v.type_name(),
975        }),
976    }
977}
978
979#[cfg(test)]
980mod tests {
981    use super::*;
982    use crate::bytecode::builder::ChunkBuilder;
983
984    type TestResult = Result<(), Box<dyn std::error::Error>>;
985
986    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
987    /// already leaves the register space. This used to panic in debug and —
988    /// far worse — wrap around to `r0` in release, silently spawning with the
989    /// wrong argument.
990    #[test]
991    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
992        let mut b = ChunkBuilder::new("t");
993        b.begin_function("main", 0, 2);
994        b.emit_spawn(255, 0, 1);
995        b.emit_return(0);
996        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
997        match vm.run(10) {
998            VmResult::Trap(Fault::RegisterIndexOverflow {
999                base: 255,
1000                offset: 1,
1001            }) => Ok(()),
1002            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1003        }
1004    }
1005
1006    /// `Vm::new` is public and reachable without `verify`, and its panic
1007    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
1008    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
1009    #[test]
1010    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1011        let mut b = ChunkBuilder::new("t");
1012        b.begin_function("main", 3, 1);
1013        b.emit_return(0);
1014        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1015        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1016            Err(Fault::RegisterOutOfRange {
1017                reg: 1,
1018                frame_size: 1,
1019            }) => Ok(()),
1020            Err(e) => Err(format!("unexpected fault: {e}").into()),
1021            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1022        }
1023    }
1024
1025    #[test]
1026    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1027        let mut b = ChunkBuilder::new("t");
1028        let callee = b.begin_function("callee", 3, 1);
1029        b.emit_return(0);
1030        let main = b.begin_function("main", 0, 4);
1031        b.emit_load_imm(0, 7);
1032        b.emit_load_imm(1, 8);
1033        b.emit_load_imm(2, 9);
1034        b.emit_call(0, callee, 3);
1035        b.emit_return(0);
1036        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1037        match vm.run(50) {
1038            VmResult::Trap(Fault::RegisterOutOfRange {
1039                reg: 1,
1040                frame_size: 1,
1041            }) => Ok(()),
1042            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1043        }
1044    }
1045
1046    /// The boundary case that must keep working: gathering right up to the
1047    /// last register is legal, it is only going *past* it that faults.
1048    #[test]
1049    fn gathering_up_to_the_last_register_still_works() -> TestResult {
1050        let mut b = ChunkBuilder::new("t");
1051        let callee = b.begin_function("callee", 1, 1);
1052        b.emit_return(0);
1053        let main = b.begin_function("main", 0, 255);
1054        b.emit_load_imm(254, 5);
1055        // Argument at r254 — the highest index a 255-register frame has.
1056        b.emit_call(254, callee, 1);
1057        b.emit_return(254);
1058        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1059        match vm.run(100) {
1060            VmResult::Complete(_) => Ok(()),
1061            other => Err(format!("expected completion, got {other:?}").into()),
1062        }
1063    }
1064
1065    #[test]
1066    fn neg_i64_min_wrapping() -> TestResult {
1067        let mut b = ChunkBuilder::new("t");
1068        b.begin_function("main", 0, 1);
1069        let k = b.const_(Value::Int(i64::MIN));
1070        b.emit_load_const(0, k);
1071        b.emit_neg(0, 0);
1072        b.emit_return(0);
1073        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1074        match vm.run(10) {
1075            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1076            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1077        }
1078    }
1079
1080    #[test]
1081    fn mod_non_int_type_mismatch() -> TestResult {
1082        let mut b = ChunkBuilder::new("t");
1083        b.begin_function("main", 0, 3);
1084        b.emit_load_imm(0, 10);
1085        let kf = b.const_(Value::Float(3.0));
1086        b.emit_load_const(1, kf);
1087        b.emit_binop(Opcode::Mod, 2, 0, 1);
1088        b.emit_return(2);
1089        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1090        match vm.run(20) {
1091            VmResult::Trap(Fault::TypeMismatch {
1092                expected: "int",
1093                got: "float",
1094            }) => Ok(()),
1095            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1096        }
1097    }
1098
1099    #[test]
1100    fn receive_timeout_negative_traps() -> TestResult {
1101        let mut b = ChunkBuilder::new("t");
1102        b.begin_function("main", 0, 2);
1103        b.emit_load_imm(1, -1);
1104        b.emit_receive_timeout(0, 1);
1105        b.emit_return(0);
1106        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1107        match vm.run(10) {
1108            VmResult::Trap(Fault::TypeMismatch {
1109                expected: "non-negative int",
1110                ..
1111            }) => Ok(()),
1112            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1113        }
1114    }
1115
1116    #[test]
1117    fn ask_timeout_negative_traps() -> TestResult {
1118        let mut b = ChunkBuilder::new("t");
1119        b.begin_function("main", 0, 4);
1120        b.emit_load_imm(3, -5);
1121        // Cap/message regs are garbage; millis is checked first.
1122        b.emit_ask_timeout(0, 1, 2, 3);
1123        b.emit_return(0);
1124        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1125        match vm.run(10) {
1126            VmResult::Trap(Fault::TypeMismatch {
1127                expected: "non-negative int",
1128                ..
1129            }) => Ok(()),
1130            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1131        }
1132    }
1133
1134    #[test]
1135    fn paranoid_jump_out_of_range_traps() -> TestResult {
1136        let mut b = ChunkBuilder::new("t");
1137        b.begin_function("main", 0, 1);
1138        b.emit_load_imm(0, 0);
1139        b.emit_return(0);
1140        let mut chunk = b.finish();
1141        let code_len = chunk.code.len();
1142        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1143        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1144        vm.set_paranoid_jumps(true);
1145        match vm.run(10) {
1146            VmResult::Trap(Fault::BadJump {
1147                target: 101,
1148                code_len: len,
1149            }) if len == code_len => Ok(()),
1150            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1151        }
1152    }
1153
1154    #[test]
1155    fn overwrite_releases_previous_heap_charge() -> TestResult {
1156        let mut b = ChunkBuilder::new("t");
1157        let k1 = b.const_(Value::Str("a".repeat(100).into()));
1158        let k2 = b.const_(Value::Str("b".repeat(100).into()));
1159        b.begin_function("main", 0, 1);
1160        b.emit_load_const(0, k1);
1161        b.emit_load_const(0, k2);
1162        b.emit_return(0);
1163        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1164        // Limit 150: first 100 fits; without release the second 100 would fail.
1165        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1166            crate::QuotaConfig {
1167                mem_limit: 150,
1168                ..crate::QuotaConfig::permissive()
1169            },
1170        ));
1171        let memory = Arc::new(crate::MemoryBudget::new(10_000));
1172        vm.set_memory_budget(Arc::clone(&memory));
1173        vm.set_quota(Arc::clone(&quota))?;
1174        match vm.run(20) {
1175            VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1176                assert_eq!(quota.mem_used(), 100);
1177                assert_eq!(memory.used(), 100);
1178                Ok(())
1179            }
1180            other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1181        }
1182    }
1183
1184    #[test]
1185    fn returning_over_quota_keeps_quota_fault() -> TestResult {
1186        let mut b = ChunkBuilder::new("t");
1187        let k = b.const_(Value::Str("x".repeat(200).into()));
1188        let callee = b.begin_function("callee", 0, 1);
1189        b.emit_load_const(0, k);
1190        b.emit_return(0);
1191        let main = b.begin_function("main", 0, 1);
1192        b.emit_call(0, callee, 0);
1193        b.emit_return(0);
1194        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1195        // 200 fits the callee store; writeback into the caller charges again.
1196        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1197        vm.set_quota(quota)?;
1198        match vm.run(50) {
1199            VmResult::Trap(Fault::QuotaExceeded(_)) => Ok(()),
1200            other => {
1201                Err(format!("expected QuotaExceeded from return writeback, got {other:?}").into())
1202            }
1203        }
1204    }
1205
1206    #[test]
1207    fn call_native_without_gate_is_typed_denied() -> TestResult {
1208        let mut b = ChunkBuilder::new("t");
1209        b.begin_function("main", 0, 1);
1210        b.emit_call_native(0, 0, 0);
1211        b.emit_return(0);
1212        let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1213        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1214        match vm.run(10) {
1215            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1216            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1217        }
1218    }
1219
1220    #[test]
1221    fn non_paranoid_bad_jump_still_fail_opens() -> TestResult {
1222        let mut b = ChunkBuilder::new("t");
1223        b.begin_function("main", 0, 1);
1224        b.emit_load_imm(0, 7);
1225        b.emit_return(0);
1226        let mut chunk = b.finish();
1227        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1228        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1229        match vm.run(10) {
1230            // Fall off the end → implicit return Unit from outermost frame.
1231            VmResult::Complete(Value::Unit) => Ok(()),
1232            other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1233        }
1234    }
1235}