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::HostAwait => {
784                    let args = trap!(self.get_reg(instr.b));
785                    let op = if instr.imm < 0 {
786                        return VmResult::Trap(Fault::TypeMismatch {
787                            expected: "HostAwait op >= 0",
788                            got: "imm-negative",
789                        });
790                    } else {
791                        instr.imm as u32
792                    };
793                    return VmResult::HostAwait {
794                        dest_reg: instr.a,
795                        op,
796                        args,
797                    };
798                }
799                Opcode::RegisterName => {
800                    return VmResult::RegisterName {
801                        name: trap!(self.expect_str_reg(instr.a)),
802                    };
803                }
804                Opcode::Whereis => {
805                    return VmResult::Whereis {
806                        dest_reg: instr.a,
807                        name: trap!(self.expect_str_reg(instr.b)),
808                    };
809                }
810                Opcode::Delegate => {
811                    let src_cap = trap!(self.expect_cap_reg(instr.b));
812                    let want_native_cap = if instr.c == 255 {
813                        None
814                    } else {
815                        Some(trap!(self.expect_cap_reg(instr.c)))
816                    };
817                    return VmResult::Delegate {
818                        dest_reg: instr.a,
819                        src_cap,
820                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
821                        want_native_cap,
822                    };
823                }
824                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
825            }
826        }
827        VmResult::Yield
828    }
829
830    /// Pop the current frame, delivering `value` to the caller (or
831    /// finishing the Flow if this was the outermost frame). Returns
832    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
833    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
834        let finished = self
835            .frames
836            .pop()
837            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
838        match finished.dest_reg() {
839            Some(dest) => {
840                self.set_reg(dest, value)?;
841                Ok(None)
842            }
843            None => Ok(Some(VmResult::Complete(value))),
844        }
845    }
846}
847
848/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
849/// if that sum leaves the register index space.
850///
851/// Every multi-operand opcode gathers its arguments from consecutive
852/// registers. Written as a plain `base + offset` on `u8`, that addition
853/// panics in debug and **wraps** in release — so a release build silently
854/// reads the wrong register instead of failing, which is the worst of the
855/// two outcomes and the one a debug-mode test suite never sees. The sum is
856/// therefore computed in a wider type and narrowed explicitly.
857#[inline]
858fn load_frame_args(
859    frame: &mut Frame,
860    args: impl IntoIterator<Item = Value>,
861    arity: u8,
862) -> Result<(), Fault> {
863    let frame_size = frame.registers().len() as u8;
864    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
865        match frame.registers_mut().get_mut(i) {
866            Some(slot) => *slot = a,
867            None => {
868                return Err(Fault::RegisterOutOfRange {
869                    reg: i as u8,
870                    frame_size,
871                })
872            }
873        }
874    }
875    Ok(())
876}
877
878fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
879    match u8::try_from(u32::from(base) + u32::from(offset)) {
880        Ok(reg) => Ok(reg),
881        Err(_) => Err(Fault::RegisterIndexOverflow {
882            base,
883            offset: match u8::try_from(offset) {
884                Ok(o) => o,
885                Err(_) => u8::MAX,
886            },
887        }),
888    }
889}
890
891/// Bytes charged for a register-resident heap value (`Str` / `Bytes` len).
892#[inline]
893fn heap_charge_of(value: &Value) -> usize {
894    match value {
895        Value::Str(s) => s.len(),
896        Value::Bytes(b) => b.len(),
897        _ => 0,
898    }
899}
900
901/// Reserve `bytes` on the flow quota and optional runtime budget.
902/// Rolls back the flow charge if the global budget refuses.
903fn charge_pair(
904    quota: &FlowQuota,
905    memory: Option<&crate::MemoryBudget>,
906    bytes: usize,
907) -> Result<(), Fault> {
908    if bytes == 0 {
909        return Ok(());
910    }
911    quota
912        .alloc(bytes)
913        .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
914    if let Some(mem) = memory {
915        if let Err(e) = mem.try_charge(bytes) {
916            quota.free(bytes);
917            return Err(Fault::QuotaExceeded(e.to_string()));
918        }
919    }
920    Ok(())
921}
922
923fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
924    if bytes == 0 {
925        return;
926    }
927    quota.free(bytes);
928    if let Some(mem) = memory {
929        mem.release(bytes);
930    }
931}
932
933/// Charge `Str` / `Bytes` length (initial attach / frame scan).
934fn charge_heap_value(
935    quota: &FlowQuota,
936    memory: Option<&crate::MemoryBudget>,
937    value: &Value,
938) -> Result<(), Fault> {
939    charge_pair(quota, memory, heap_charge_of(value))
940}
941
942fn as_f64(v: &Value) -> Result<f64, Fault> {
943    match v {
944        Value::Int(i) => Ok(*i as f64),
945        Value::Float(f) => Ok(*f),
946        other => Err(Fault::TypeMismatch {
947            expected: "int or float",
948            got: other.type_name(),
949        }),
950    }
951}
952
953/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
954#[inline]
955fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
956    match u16::try_from(imm) {
957        Ok(t) if imm >= 0 => Ok(t),
958        _ => Err(Fault::TypeMismatch {
959            expected: "tag u16",
960            got: "imm-out-of-range",
961        }),
962    }
963}
964
965fn tag_from_value(v: &Value) -> Result<u16, Fault> {
966    match v.as_int() {
967        Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
968        Some(_) => Err(Fault::TypeMismatch {
969            expected: "tag u16",
970            got: "int-out-of-range",
971        }),
972        None => Err(Fault::TypeMismatch {
973            expected: "int",
974            got: v.type_name(),
975        }),
976    }
977}
978
979/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
980#[inline]
981fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
982    match v.as_int() {
983        Some(i) if i >= 0 => Ok(i as u64),
984        Some(_) => Err(Fault::TypeMismatch {
985            expected: "request_id u64",
986            got: "negative-int",
987        }),
988        None => Err(Fault::TypeMismatch {
989            expected: "int",
990            got: v.type_name(),
991        }),
992    }
993}
994
995#[cfg(test)]
996mod tests {
997    use super::*;
998    use crate::bytecode::builder::ChunkBuilder;
999
1000    type TestResult = Result<(), Box<dyn std::error::Error>>;
1001
1002    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
1003    /// already leaves the register space. This used to panic in debug and —
1004    /// far worse — wrap around to `r0` in release, silently spawning with the
1005    /// wrong argument.
1006    #[test]
1007    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1008        let mut b = ChunkBuilder::new("t");
1009        b.begin_function("main", 0, 2);
1010        b.emit_spawn(255, 0, 1);
1011        b.emit_return(0);
1012        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1013        match vm.run(10) {
1014            VmResult::Trap(Fault::RegisterIndexOverflow {
1015                base: 255,
1016                offset: 1,
1017            }) => Ok(()),
1018            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1019        }
1020    }
1021
1022    /// `Vm::new` is public and reachable without `verify`, and its panic
1023    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
1024    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
1025    #[test]
1026    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1027        let mut b = ChunkBuilder::new("t");
1028        b.begin_function("main", 3, 1);
1029        b.emit_return(0);
1030        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1031        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1032            Err(Fault::RegisterOutOfRange {
1033                reg: 1,
1034                frame_size: 1,
1035            }) => Ok(()),
1036            Err(e) => Err(format!("unexpected fault: {e}").into()),
1037            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1038        }
1039    }
1040
1041    #[test]
1042    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1043        let mut b = ChunkBuilder::new("t");
1044        let callee = b.begin_function("callee", 3, 1);
1045        b.emit_return(0);
1046        let main = b.begin_function("main", 0, 4);
1047        b.emit_load_imm(0, 7);
1048        b.emit_load_imm(1, 8);
1049        b.emit_load_imm(2, 9);
1050        b.emit_call(0, callee, 3);
1051        b.emit_return(0);
1052        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1053        match vm.run(50) {
1054            VmResult::Trap(Fault::RegisterOutOfRange {
1055                reg: 1,
1056                frame_size: 1,
1057            }) => Ok(()),
1058            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1059        }
1060    }
1061
1062    /// The boundary case that must keep working: gathering right up to the
1063    /// last register is legal, it is only going *past* it that faults.
1064    #[test]
1065    fn gathering_up_to_the_last_register_still_works() -> TestResult {
1066        let mut b = ChunkBuilder::new("t");
1067        let callee = b.begin_function("callee", 1, 1);
1068        b.emit_return(0);
1069        let main = b.begin_function("main", 0, 255);
1070        b.emit_load_imm(254, 5);
1071        // Argument at r254 — the highest index a 255-register frame has.
1072        b.emit_call(254, callee, 1);
1073        b.emit_return(254);
1074        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1075        match vm.run(100) {
1076            VmResult::Complete(_) => Ok(()),
1077            other => Err(format!("expected completion, got {other:?}").into()),
1078        }
1079    }
1080
1081    #[test]
1082    fn neg_i64_min_wrapping() -> TestResult {
1083        let mut b = ChunkBuilder::new("t");
1084        b.begin_function("main", 0, 1);
1085        let k = b.const_(Value::Int(i64::MIN));
1086        b.emit_load_const(0, k);
1087        b.emit_neg(0, 0);
1088        b.emit_return(0);
1089        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1090        match vm.run(10) {
1091            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1092            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1093        }
1094    }
1095
1096    #[test]
1097    fn mod_non_int_type_mismatch() -> TestResult {
1098        let mut b = ChunkBuilder::new("t");
1099        b.begin_function("main", 0, 3);
1100        b.emit_load_imm(0, 10);
1101        let kf = b.const_(Value::Float(3.0));
1102        b.emit_load_const(1, kf);
1103        b.emit_binop(Opcode::Mod, 2, 0, 1);
1104        b.emit_return(2);
1105        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1106        match vm.run(20) {
1107            VmResult::Trap(Fault::TypeMismatch {
1108                expected: "int",
1109                got: "float",
1110            }) => Ok(()),
1111            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1112        }
1113    }
1114
1115    #[test]
1116    fn receive_timeout_negative_traps() -> TestResult {
1117        let mut b = ChunkBuilder::new("t");
1118        b.begin_function("main", 0, 2);
1119        b.emit_load_imm(1, -1);
1120        b.emit_receive_timeout(0, 1);
1121        b.emit_return(0);
1122        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1123        match vm.run(10) {
1124            VmResult::Trap(Fault::TypeMismatch {
1125                expected: "non-negative int",
1126                ..
1127            }) => Ok(()),
1128            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1129        }
1130    }
1131
1132    #[test]
1133    fn ask_timeout_negative_traps() -> TestResult {
1134        let mut b = ChunkBuilder::new("t");
1135        b.begin_function("main", 0, 4);
1136        b.emit_load_imm(3, -5);
1137        // Cap/message regs are garbage; millis is checked first.
1138        b.emit_ask_timeout(0, 1, 2, 3);
1139        b.emit_return(0);
1140        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1141        match vm.run(10) {
1142            VmResult::Trap(Fault::TypeMismatch {
1143                expected: "non-negative int",
1144                ..
1145            }) => Ok(()),
1146            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1147        }
1148    }
1149
1150    #[test]
1151    fn paranoid_jump_out_of_range_traps() -> TestResult {
1152        let mut b = ChunkBuilder::new("t");
1153        b.begin_function("main", 0, 1);
1154        b.emit_load_imm(0, 0);
1155        b.emit_return(0);
1156        let mut chunk = b.finish();
1157        let code_len = chunk.code.len();
1158        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1159        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1160        vm.set_paranoid_jumps(true);
1161        match vm.run(10) {
1162            VmResult::Trap(Fault::BadJump {
1163                target: 101,
1164                code_len: len,
1165            }) if len == code_len => Ok(()),
1166            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1167        }
1168    }
1169
1170    #[test]
1171    fn overwrite_releases_previous_heap_charge() -> TestResult {
1172        let mut b = ChunkBuilder::new("t");
1173        let k1 = b.const_(Value::Str("a".repeat(100).into()));
1174        let k2 = b.const_(Value::Str("b".repeat(100).into()));
1175        b.begin_function("main", 0, 1);
1176        b.emit_load_const(0, k1);
1177        b.emit_load_const(0, k2);
1178        b.emit_return(0);
1179        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1180        // Limit 150: first 100 fits; without release the second 100 would fail.
1181        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1182            crate::QuotaConfig {
1183                mem_limit: 150,
1184                ..crate::QuotaConfig::permissive()
1185            },
1186        ));
1187        let memory = Arc::new(crate::MemoryBudget::new(10_000));
1188        vm.set_memory_budget(Arc::clone(&memory));
1189        vm.set_quota(Arc::clone(&quota))?;
1190        match vm.run(20) {
1191            VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1192                assert_eq!(quota.mem_used(), 100);
1193                assert_eq!(memory.used(), 100);
1194                Ok(())
1195            }
1196            other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1197        }
1198    }
1199
1200    #[test]
1201    fn returning_over_quota_keeps_quota_fault() -> TestResult {
1202        let mut b = ChunkBuilder::new("t");
1203        let k = b.const_(Value::Str("x".repeat(200).into()));
1204        let callee = b.begin_function("callee", 0, 1);
1205        b.emit_load_const(0, k);
1206        b.emit_return(0);
1207        let main = b.begin_function("main", 0, 1);
1208        b.emit_call(0, callee, 0);
1209        b.emit_return(0);
1210        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1211        // 200 fits the callee store; writeback into the caller charges again.
1212        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1213        vm.set_quota(quota)?;
1214        match vm.run(50) {
1215            VmResult::Trap(Fault::QuotaExceeded(_)) => Ok(()),
1216            other => {
1217                Err(format!("expected QuotaExceeded from return writeback, got {other:?}").into())
1218            }
1219        }
1220    }
1221
1222    #[test]
1223    fn call_native_without_gate_is_typed_denied() -> TestResult {
1224        let mut b = ChunkBuilder::new("t");
1225        b.begin_function("main", 0, 1);
1226        b.emit_call_native(0, 0, 0);
1227        b.emit_return(0);
1228        let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1229        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1230        match vm.run(10) {
1231            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1232            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1233        }
1234    }
1235
1236    #[test]
1237    fn non_paranoid_bad_jump_still_fail_opens() -> TestResult {
1238        let mut b = ChunkBuilder::new("t");
1239        b.begin_function("main", 0, 1);
1240        b.emit_load_imm(0, 7);
1241        b.emit_return(0);
1242        let mut chunk = b.finish();
1243        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1244        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1245        match vm.run(10) {
1246            // Fall off the end → implicit return Unit from outermost frame.
1247            VmResult::Complete(Value::Unit) => Ok(()),
1248            other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1249        }
1250    }
1251}