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    /// Interim heap charge for `Str`/`Bytes` written into registers.
38    quota: Option<Arc<FlowQuota>>,
39    /// When true, `Jump`/`Branch` bounds-check targets at runtime (see
40    /// [`Self::set_paranoid_jumps`]). Default off: verified chunks trust
41    /// `verify`; unverified corrupt jumps fail-open as implicit `return Unit`.
42    paranoid_jumps: bool,
43}
44
45impl Vm {
46    /// Construct a `Vm` ready to run `function` (an index into
47    /// `chunk.functions`) with the given arguments loaded into `r0..argc`.
48    /// `natives` is the FFI table `Opcode::CallNative` dispatches through —
49    /// pass [`NativeTable::empty`] if the chunk never calls out to Rust.
50    ///
51    /// Native calls are **denied** until [`Self::with_native_gate`] installs
52    /// an allowlist (the runtime does this from the flow's attenuated Cap).
53    pub fn new(chunk: Arc<Chunk>, natives: Arc<NativeTable>, function: u32, args: &[Value]) -> Result<Self, Fault> {
54        let gate = NativeGate::deny(natives.len());
55        Self::with_native_gate(chunk, natives, gate, function, args)
56    }
57
58    pub fn with_native_gate(
59        chunk: Arc<Chunk>,
60        natives: Arc<NativeTable>,
61        native_gate: NativeGate,
62        function: u32,
63        args: &[Value],
64    ) -> Result<Self, Fault> {
65        let def = chunk
66            .function(function)
67            .ok_or(Fault::BadFunction { index: function, table_size: chunk.functions.len() as u32 })?;
68        let mut frame = Frame::new(function, def.num_registers, None);
69        frame.set_pc(def.entry as usize);
70        load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
71        Ok(Vm {
72            chunk,
73            natives,
74            native_gate,
75            frames: vec![frame],
76            instructions_executed: 0,
77            next_request_id: 1,
78            quota: None,
79            paranoid_jumps: false,
80        })
81    }
82
83    /// Enable runtime bounds checks on `Jump` / `Branch` targets.
84    ///
85    /// Production paths leave this off and rely on [`crate::verify`]. Turn it
86    /// on for hand-built or untrusted chunks that skip verification.
87    pub fn set_paranoid_jumps(&mut self, enabled: bool) {
88        self.paranoid_jumps = enabled;
89    }
90
91    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
92    ///
93    /// Interim: charge on write, never release until the flow exits. Same
94    /// `Arc` rewritten into the same slot is not charged twice.
95    pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
96        for frame in &self.frames {
97            for slot in frame.registers() {
98                charge_heap_value(&quota, slot)?;
99            }
100        }
101        self.quota = Some(quota);
102        Ok(())
103    }
104
105    /// Mint a per-flow correlation id. Never returns `0` (`next_request_id`
106    /// starts at 1 and saturates, so it cannot wrap to zero).
107    pub fn fresh_request_id(&mut self) -> u64 {
108        let id = self.next_request_id;
109        self.next_request_id = self.next_request_id.saturating_add(1);
110        id
111    }
112
113    pub fn instructions_executed(&self) -> u64 {
114        self.instructions_executed
115    }
116
117    /// Index into `chunk.functions` for the active (top) call frame.
118    /// Useful for diagnostics / supervisor logs when a Flow traps.
119    pub fn current_function(&self) -> u32 {
120        // Category D: frames must be non-empty while the VM is runnable.
121        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
122        // broken invariant cannot panic a worker; the next `run` will trap.
123        debug_assert!(!self.frames.is_empty(), "frames empty while running");
124        match self.frames.last() {
125            Some(frame) => frame.function(),
126            None => 0,
127        }
128    }
129
130    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
131    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
132    /// needing to know anything about `Chunk`'s internals — every Flow
133    /// spawned (transitively) from the same top-level `spawn()` call shares
134    /// one immutable chunk in memory, never copies it.
135    pub fn chunk_arc(&self) -> Arc<Chunk> {
136        self.chunk.clone()
137    }
138
139    /// A cheap `Arc` clone of this VM's native function table, for the same
140    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
141    /// `CallNative` through the identical table its parent uses.
142    pub fn natives_arc(&self) -> Arc<NativeTable> {
143        self.natives.clone()
144    }
145
146    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
147    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
148    /// into the register the instruction that suspended us was targeting,
149    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
150    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
151    /// destination register holding its previous (stale) value.
152    #[inline]
153    pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
154        self.set_reg(dest_reg, value)
155    }
156
157    /// Program counter of the active frame — used by the optional JIT hook.
158    pub fn current_pc(&self) -> Option<usize> {
159        self.frames.last().map(|f| f.pc())
160    }
161
162    /// Number of registers in the active frame.
163    pub fn current_num_registers(&self) -> Option<u8> {
164        self.frames.last().map(|f| f.registers().len() as u8)
165    }
166
167    /// Read-only view of the active register file.
168    pub fn top_registers(&self) -> Option<&[Value]> {
169        self.frames.last().map(|f| f.registers())
170    }
171
172    /// Mutable view of the active register file (JIT sync path).
173    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
174        self.frames.last_mut().map(|f| f.registers_mut())
175    }
176
177    /// Set the active frame's program counter.
178    pub fn set_pc(&mut self, pc: usize) {
179        if let Some(frame) = self.frames.last_mut() {
180            frame.set_pc(pc);
181        }
182    }
183
184    /// Write one register in the active frame (JIT sync path).
185    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
186        self.set_reg(reg, value)
187    }
188
189    /// Deliver a return value through the call stack.
190    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
191        self.pop_frame(value)
192    }
193
194    /// Top call frame. Empty stack is a broken invariant (category D) —
195    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
196    #[inline]
197    fn current(&mut self) -> Result<&mut Frame, Fault> {
198        debug_assert!(!self.frames.is_empty(), "frames empty while running");
199        self.frames
200            .last_mut()
201            .ok_or(Fault::Invariant("empty frame stack while running"))
202    }
203
204    #[inline]
205    fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
206        let frame = self
207            .frames
208            .last()
209            .ok_or(Fault::Invariant("empty frame stack while running"))?;
210        frame
211            .registers()
212            .get(reg as usize)
213            .cloned()
214            .ok_or(Fault::RegisterOutOfRange {
215                reg,
216                frame_size: frame.registers().len() as u8,
217            })
218    }
219
220    #[inline]
221    fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
222        self.charge_register_store(reg, &value)?;
223        let frame = self.current()?;
224        let len = frame.registers().len() as u8;
225        match frame.registers_mut().get_mut(reg as usize) {
226            Some(slot) => {
227                *slot = value;
228                Ok(())
229            }
230            None => Err(Fault::RegisterOutOfRange { reg, frame_size: len }),
231        }
232    }
233
234    #[inline]
235    fn peek_reg(&self, reg: u8) -> Option<&Value> {
236        self.frames.last()?.registers().get(reg as usize)
237    }
238
239    /// Interim heap charge: `Str` / `Bytes` only. Hop payloads are charged
240    /// at `Send` / `Ask`. Overwrites of the same `Arc` in the same slot
241    /// are skipped; other copies super-count until the flow exits.
242    fn charge_register_store(&self, reg: u8, value: &Value) -> Result<(), Fault> {
243        let Some(quota) = self.quota.as_ref() else {
244            return Ok(());
245        };
246        match (value, self.peek_reg(reg)) {
247            (Value::Str(s), Some(Value::Str(old))) if Arc::ptr_eq(s, old) => Ok(()),
248            (Value::Bytes(b), Some(Value::Bytes(old))) if Arc::ptr_eq(b, old) => Ok(()),
249            (Value::Str(_) | Value::Bytes(_), _) => charge_heap_value(quota, value),
250            _ => Ok(()),
251        }
252    }
253
254    /// Fetch the next instruction and advance `pc`.
255    ///
256    /// `Ok(None)` if control fell off the end of the function body without an
257    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
258    /// (friendlier to hand-written bytecode that omits a trailing return).
259    /// `Err` if the frame stack is empty (invariant break).
260    ///
261    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
262    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
263    /// compile.
264    #[inline]
265    fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
266        let pc = self.current()?.pc();
267        let instr = self.chunk.code.get(pc).copied();
268        if instr.is_some() {
269            self.current()?.set_pc(pc + 1);
270        }
271        Ok(instr)
272    }
273
274    fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
275        let a = self.get_reg(lhs)?;
276        let b = self.get_reg(rhs)?;
277        let result = match (op, &a, &b) {
278            (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
279            (Opcode::Add, _, _) => Value::Float(as_f64(&a)? + as_f64(&b)?),
280            (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
281            (Opcode::Sub, _, _) => Value::Float(as_f64(&a)? - as_f64(&b)?),
282            (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
283            (Opcode::Mul, _, _) => Value::Float(as_f64(&a)? * as_f64(&b)?),
284            (Opcode::Div, Value::Int(x), Value::Int(y)) => {
285                if *y == 0 {
286                    return Err(Fault::DivideByZero);
287                }
288                Value::Int(x.wrapping_div(*y))
289            }
290            (Opcode::Div, _, _) => {
291                let denom = as_f64(&b)?;
292                Value::Float(as_f64(&a)? / denom)
293            }
294            (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
295                if *y == 0 {
296                    return Err(Fault::DivideByZero);
297                }
298                Value::Int(x.wrapping_rem(*y))
299            }
300            (Opcode::Mod, _, _) => {
301                let got = if !matches!(a, Value::Int(_)) {
302                    a.type_name()
303                } else {
304                    b.type_name()
305                };
306                return Err(Fault::TypeMismatch {
307                    expected: "int",
308                    got,
309                });
310            }
311            (Opcode::Eq, _, _) => Value::Bool(a == b),
312            (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
313            (Opcode::Lt, _, _) => Value::Bool(as_f64(&a)? < as_f64(&b)?),
314            (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
315            (Opcode::Le, _, _) => Value::Bool(as_f64(&a)? <= as_f64(&b)?),
316            _ => {
317                return Err(Fault::Invariant(
318                    "numeric_binop called with a non-arithmetic opcode",
319                ))
320            }
321        };
322        self.set_reg(dst, result)
323    }
324
325    #[inline]
326    fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
327        let v = self.get_reg(reg)?;
328        v.as_cap().ok_or(Fault::TypeMismatch {
329            expected: "cap",
330            got: v.type_name(),
331        })
332    }
333
334    #[inline]
335    fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
336        let v = self.get_reg(reg)?;
337        if v.as_message().is_none() {
338            return Err(Fault::TypeMismatch {
339                expected: "message",
340                got: v.type_name(),
341            });
342        }
343        Ok(v)
344    }
345
346    #[inline]
347    fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
348        match self.get_reg(reg)? {
349            Value::Str(s) => Ok(s),
350            other => Err(Fault::TypeMismatch {
351                expected: "str",
352                got: other.type_name(),
353            }),
354        }
355    }
356
357    #[inline]
358    fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
359        tag_from_value(&self.get_reg(reg)?)
360    }
361
362    #[inline]
363    fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
364        request_id_from_value(&self.get_reg(reg)?)
365    }
366
367    fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
368        let mut args = Vec::with_capacity(argc as usize);
369        for i in 0..argc {
370            let reg = reg_at(base, first_offset + u16::from(i))?;
371            args.push(self.get_reg(reg)?);
372        }
373        Ok(args)
374    }
375
376    /// Same policy as `Sleep`: non-negative `Int` only; never silent clamp.
377    #[inline]
378    fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
379        let millis = self.get_reg(reg)?;
380        match millis.as_int() {
381            Some(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
382            _ => Err(Fault::TypeMismatch {
383                expected: "non-negative int",
384                got: millis.type_name(),
385            }),
386        }
387    }
388
389    /// Apply a relative jump from the current (post-fetch) `pc`.
390    ///
391    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
392    /// Paranoid mode traps; otherwise preserves the historical fail-open cast.
393    fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
394        let code_len = self.chunk.code.len();
395        let paranoid = self.paranoid_jumps;
396        let frame = self.current()?;
397        let target_i = frame.pc() as i64 + i64::from(imm);
398        if paranoid && (target_i < 0 || target_i as usize > code_len) {
399            let target = if target_i < 0 {
400                usize::MAX
401            } else {
402                target_i as usize
403            };
404            return Err(Fault::BadJump { target, code_len });
405        }
406        frame.set_pc(target_i as usize);
407        Ok(())
408    }
409
410    /// Run at most `budget` instructions (cooperative-preemption quantum,
411    /// design notes §10-11), or until the Flow completes / needs an
412    /// effect the scheduler must perform / faults.
413    ///
414    /// Every exit path is captured by [`VmResult`] — this function itself
415    /// never panics on malformed *verified* bytecode; faults are returned,
416    /// not thrown, so a buggy Flow can't take a worker thread down.
417    pub fn run(&mut self, budget: u32) -> VmResult {
418        macro_rules! trap {
419            ($e:expr) => {
420                match $e {
421                    Ok(v) => v,
422                    Err(fault) => return VmResult::Trap(fault),
423                }
424            };
425        }
426
427        for _ in 0..budget {
428            self.instructions_executed += 1;
429            let instr = match self.fetch() {
430                Ok(Some(i)) => i,
431                Ok(None) => {
432                    // Fell off the end of a function: implicit `return Unit`.
433                    match self.pop_frame(Value::Unit) {
434                        Ok(Some(result)) => return result,
435                        Ok(None) => continue,
436                        Err(fault) => return VmResult::Trap(fault),
437                    }
438                }
439                Err(fault) => return VmResult::Trap(fault),
440            };
441
442            match instr.op {
443                Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
444                Opcode::Nop => {}
445                Opcode::LoadConst => {
446                    let idx = instr.imm as u32;
447                    let konst = match self.chunk.constant(idx) {
448                        Some(v) => v.clone(),
449                        None => {
450                            return VmResult::Trap(Fault::BadConstant {
451                                index: idx,
452                                pool_size: self.chunk.constants.len() as u32,
453                            })
454                        }
455                    };
456                    trap!(self.set_reg(instr.a, konst));
457                }
458                Opcode::LoadImm => {
459                    trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
460                }
461                Opcode::Move => {
462                    let v = trap!(self.get_reg(instr.b));
463                    trap!(self.set_reg(instr.a, v));
464                }
465                Opcode::Add | Opcode::Sub | Opcode::Mul | Opcode::Div | Opcode::Mod
466                | Opcode::Eq | Opcode::Lt | Opcode::Le => {
467                    trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
468                }
469                Opcode::Neg => {
470                    let v = trap!(self.get_reg(instr.b));
471                    let negated = match v {
472                        Value::Int(x) => Value::Int(x.wrapping_neg()),
473                        Value::Float(x) => Value::Float(-x),
474                        other => {
475                            return VmResult::Trap(Fault::TypeMismatch {
476                                expected: "int or float",
477                                got: other.type_name(),
478                            })
479                        }
480                    };
481                    trap!(self.set_reg(instr.a, negated));
482                }
483                Opcode::Jump => {
484                    trap!(self.apply_relative_jump(instr.imm));
485                }
486                Opcode::Branch => {
487                    let cond = trap!(self.get_reg(instr.a));
488                    if !cond.is_truthy() {
489                        trap!(self.apply_relative_jump(instr.imm));
490                    }
491                }
492                Opcode::Call => {
493                    let function = instr.imm as u32;
494                    let argc = instr.b;
495                    let dst = instr.a;
496                    if self.frames.len() >= MAX_CALL_DEPTH {
497                        return VmResult::Trap(Fault::CallStackOverflow { depth: self.frames.len() });
498                    }
499                    let (num_registers, arity, entry) = match self.chunk.function(function) {
500                        Some(d) => (d.num_registers, d.arity, d.entry as usize),
501                        None => {
502                            return VmResult::Trap(Fault::BadFunction {
503                                index: function,
504                                table_size: self.chunk.functions.len() as u32,
505                            })
506                        }
507                    };
508                    let args = trap!(self.gather_regs(dst, argc, 0));
509                    let mut new_frame = Frame::new(function, num_registers, Some(dst));
510                    new_frame.set_pc(entry);
511                    trap!(load_frame_args(&mut new_frame, args, arity));
512                    self.frames.push(new_frame);
513                }
514                Opcode::CallNative => {
515                    let native_index = instr.imm as u32;
516                    let argc = instr.b;
517                    let dst = instr.a;
518                    if let Err(err) = check_native_gate(&self.native_gate, &self.natives, native_index)
519                    {
520                        return VmResult::Trap(match err {
521                            NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
522                                index,
523                                table_size: self.natives.len() as u32,
524                            },
525                            other => Fault::NativeDenied(other),
526                        });
527                    }
528                    let args = trap!(self.gather_regs(dst, argc, 0));
529                    // Runs inline on this worker thread — see
530                    // `NativeFn`'s doc comment on why natives must not
531                    // block. This is the actual FFI boundary (design
532                    // notes §30-31): plain Rust on one side, bytecode
533                    // registers on the other, with `Fault::NativeError`
534                    // as the only channel for a native-side failure to
535                    // become a Flow fault instead of a host panic.
536                    let result = match self.natives.get(native_index) {
537                        Some(native_fn) => native_fn(&args),
538                        None => {
539                            return VmResult::Trap(Fault::BadNative {
540                                index: native_index,
541                                table_size: self.natives.len() as u32,
542                            })
543                        }
544                    };
545                    match result {
546                        Ok(value) => trap!(self.set_reg(dst, value)),
547                        Err(fault) => return VmResult::Trap(fault),
548                    }
549                }
550                Opcode::Return => {
551                    let v = trap!(self.get_reg(instr.a));
552                    match self.pop_frame(v) {
553                        Ok(Some(result)) => return result,
554                        Ok(None) => {}
555                        Err(fault) => return VmResult::Trap(fault),
556                    }
557                }
558                Opcode::Spawn => {
559                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
560                    // child Cap. `a = 255` overflows on the first gather.
561                    let args = trap!(self.gather_regs(instr.a, instr.b, 1));
562                    return VmResult::Spawn {
563                        function: instr.imm as u32,
564                        args,
565                        dest_reg: instr.a,
566                        requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
567                    };
568                }
569                Opcode::Yield => return VmResult::Yield,
570                Opcode::Sleep => {
571                    return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
572                }
573                Opcode::Exit => {
574                    let v = trap!(self.get_reg(instr.a));
575                    return VmResult::Complete(v);
576                }
577                Opcode::SelfPid => {
578                    return VmResult::SelfPid { dest_reg: instr.a };
579                }
580                Opcode::Send => {
581                    let target_cap = trap!(self.expect_cap_reg(instr.a));
582                    let message = trap!(self.expect_message_value(instr.b));
583                    return VmResult::Send {
584                        target_cap,
585                        message,
586                    };
587                }
588                Opcode::Receive => {
589                    return VmResult::Receive {
590                        dest_reg: instr.a,
591                        timeout: None,
592                        match_tag: None,
593                        match_request_id: None,
594                    };
595                }
596                Opcode::ReceiveTimeout => {
597                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
598                    return VmResult::Receive {
599                        dest_reg: instr.a,
600                        timeout: Some(timeout),
601                        match_tag: None,
602                        match_request_id: None,
603                    };
604                }
605                Opcode::ReceiveMatch => {
606                    let tag = trap!(self.tag_from_reg(instr.b));
607                    return VmResult::Receive {
608                        dest_reg: instr.a,
609                        timeout: None,
610                        match_tag: Some(tag),
611                        match_request_id: None,
612                    };
613                }
614                Opcode::ReceiveMatchImm => {
615                    let tag = trap!(tag_from_imm(instr.imm));
616                    return VmResult::Receive {
617                        dest_reg: instr.a,
618                        timeout: None,
619                        match_tag: Some(tag),
620                        match_request_id: None,
621                    };
622                }
623                Opcode::FreshRequestId => {
624                    let id = self.fresh_request_id();
625                    trap!(self.set_reg(instr.a, Value::Int(id as i64)));
626                }
627                Opcode::ReceiveMatchCorr => {
628                    let tag = trap!(self.tag_from_reg(instr.b));
629                    let rid = trap!(self.request_id_from_reg(instr.c));
630                    return VmResult::Receive {
631                        dest_reg: instr.a,
632                        timeout: None,
633                        match_tag: Some(tag),
634                        match_request_id: Some(rid),
635                    };
636                }
637                Opcode::ReceiveMatchCorrImm => {
638                    let tag = trap!(tag_from_imm(instr.imm));
639                    let rid = trap!(self.request_id_from_reg(instr.b));
640                    return VmResult::Receive {
641                        dest_reg: instr.a,
642                        timeout: None,
643                        match_tag: Some(tag),
644                        match_request_id: Some(rid),
645                    };
646                }
647                Opcode::Ask => {
648                    let target_cap = trap!(self.expect_cap_reg(instr.b));
649                    let request = trap!(self.expect_message_value(instr.c));
650                    return VmResult::Ask {
651                        dest_reg: instr.a,
652                        target_cap,
653                        request,
654                        timeout: None,
655                    };
656                }
657                Opcode::AskTimeout => {
658                    let millis_reg = match u8::try_from(instr.imm) {
659                        Ok(r) => r,
660                        Err(_) => {
661                            return VmResult::Trap(Fault::TypeMismatch {
662                                expected: "millis register",
663                                got: "imm-out-of-range",
664                            })
665                        }
666                    };
667                    let timeout = trap!(self.duration_millis_from_reg(millis_reg));
668                    let target_cap = trap!(self.expect_cap_reg(instr.b));
669                    let request = trap!(self.expect_message_value(instr.c));
670                    return VmResult::Ask {
671                        dest_reg: instr.a,
672                        target_cap,
673                        request,
674                        timeout: Some(timeout),
675                    };
676                }
677                Opcode::Monitor => {
678                    let target_cap = trap!(self.expect_cap_reg(instr.b));
679                    return VmResult::Monitor {
680                        dest_reg: instr.a,
681                        target_cap,
682                    };
683                }
684                Opcode::Demonitor => {
685                    return VmResult::Demonitor {
686                        monitor_reg: instr.a,
687                    };
688                }
689                Opcode::Link => {
690                    let target_cap = trap!(self.expect_cap_reg(instr.b));
691                    return VmResult::Link {
692                        dest_reg: instr.a,
693                        target_cap,
694                    };
695                }
696                Opcode::Unlink => {
697                    return VmResult::Unlink {
698                        link_reg: instr.a,
699                    };
700                }
701                Opcode::RegisterName => {
702                    return VmResult::RegisterName {
703                        name: trap!(self.expect_str_reg(instr.a)),
704                    };
705                }
706                Opcode::Whereis => {
707                    return VmResult::Whereis {
708                        dest_reg: instr.a,
709                        name: trap!(self.expect_str_reg(instr.b)),
710                    };
711                }
712                Opcode::Delegate => {
713                    let src_cap = trap!(self.expect_cap_reg(instr.b));
714                    let want_native_cap = if instr.c == 255 {
715                        None
716                    } else {
717                        Some(trap!(self.expect_cap_reg(instr.c)))
718                    };
719                    return VmResult::Delegate {
720                        dest_reg: instr.a,
721                        src_cap,
722                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
723                        want_native_cap,
724                    };
725                }
726                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
727            }
728        }
729        VmResult::Yield
730    }
731
732    /// Pop the current frame, delivering `value` to the caller (or
733    /// finishing the Flow if this was the outermost frame). Returns
734    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
735    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
736        let finished = self
737            .frames
738            .pop()
739            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
740        match finished.dest_reg() {
741            Some(dest) => {
742                self.set_reg(dest, value)?;
743                Ok(None)
744            }
745            None => Ok(Some(VmResult::Complete(value))),
746        }
747    }
748}
749
750/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
751/// if that sum leaves the register index space.
752///
753/// Every multi-operand opcode gathers its arguments from consecutive
754/// registers. Written as a plain `base + offset` on `u8`, that addition
755/// panics in debug and **wraps** in release — so a release build silently
756/// reads the wrong register instead of failing, which is the worst of the
757/// two outcomes and the one a debug-mode test suite never sees. The sum is
758/// therefore computed in a wider type and narrowed explicitly.
759#[inline]
760fn load_frame_args(
761    frame: &mut Frame,
762    args: impl IntoIterator<Item = Value>,
763    arity: u8,
764) -> Result<(), Fault> {
765    let frame_size = frame.registers().len() as u8;
766    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
767        match frame.registers_mut().get_mut(i) {
768            Some(slot) => *slot = a,
769            None => return Err(Fault::RegisterOutOfRange { reg: i as u8, frame_size }),
770        }
771    }
772    Ok(())
773}
774
775fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
776    match u8::try_from(u32::from(base) + u32::from(offset)) {
777        Ok(reg) => Ok(reg),
778        Err(_) => Err(Fault::RegisterIndexOverflow {
779            base,
780            offset: match u8::try_from(offset) {
781                Ok(o) => o,
782                Err(_) => u8::MAX,
783            },
784        }),
785    }
786}
787
788/// Charge `Str` / `Bytes` length against the flow heap quota.
789/// Empty buffers are free. Fail-closed: the store does not happen on error.
790fn charge_heap_value(quota: &FlowQuota, value: &Value) -> Result<(), Fault> {
791    let bytes = match value {
792        Value::Str(s) => s.len(),
793        Value::Bytes(b) => b.len(),
794        _ => return Ok(()),
795    };
796    if bytes == 0 {
797        return Ok(());
798    }
799    quota
800        .alloc(bytes)
801        .map_err(|e| Fault::QuotaExceeded(e.to_string()))
802}
803
804fn as_f64(v: &Value) -> Result<f64, Fault> {
805    match v {
806        Value::Int(i) => Ok(*i as f64),
807        Value::Float(f) => Ok(*f),
808        other => Err(Fault::TypeMismatch { expected: "int or float", got: other.type_name() }),
809    }
810}
811
812/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
813#[inline]
814fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
815    match u16::try_from(imm) {
816        Ok(t) if imm >= 0 => Ok(t),
817        _ => Err(Fault::TypeMismatch {
818            expected: "tag u16",
819            got: "imm-out-of-range",
820        }),
821    }
822}
823
824fn tag_from_value(v: &Value) -> Result<u16, Fault> {
825    match v.as_int() {
826        Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
827        Some(_) => Err(Fault::TypeMismatch {
828            expected: "tag u16",
829            got: "int-out-of-range",
830        }),
831        None => Err(Fault::TypeMismatch {
832            expected: "int",
833            got: v.type_name(),
834        }),
835    }
836}
837
838/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
839#[inline]
840fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
841    match v.as_int() {
842        Some(i) if i >= 0 => Ok(i as u64),
843        Some(_) => Err(Fault::TypeMismatch {
844            expected: "request_id u64",
845            got: "negative-int",
846        }),
847        None => Err(Fault::TypeMismatch {
848            expected: "int",
849            got: v.type_name(),
850        }),
851    }
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857    use crate::bytecode::builder::ChunkBuilder;
858
859    type TestResult = Result<(), Box<dyn std::error::Error>>;
860
861    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
862    /// already leaves the register space. This used to panic in debug and —
863    /// far worse — wrap around to `r0` in release, silently spawning with the
864    /// wrong argument.
865    #[test]
866    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
867        let mut b = ChunkBuilder::new("t");
868        b.begin_function("main", 0, 2);
869        b.emit_spawn(255, 0, 1);
870        b.emit_return(0);
871        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
872        match vm.run(10) {
873            VmResult::Trap(Fault::RegisterIndexOverflow {
874                base: 255,
875                offset: 1,
876            }) => Ok(()),
877            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
878        }
879    }
880
881    /// `Vm::new` is public and reachable without `verify`, and its panic
882    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
883    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
884    #[test]
885    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
886        let mut b = ChunkBuilder::new("t");
887        b.begin_function("main", 3, 1);
888        b.emit_return(0);
889        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
890        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
891            Err(Fault::RegisterOutOfRange {
892                reg: 1,
893                frame_size: 1,
894            }) => Ok(()),
895            Err(e) => Err(format!("unexpected fault: {e}").into()),
896            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
897        }
898    }
899
900    #[test]
901    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
902        let mut b = ChunkBuilder::new("t");
903        let callee = b.begin_function("callee", 3, 1);
904        b.emit_return(0);
905        let main = b.begin_function("main", 0, 4);
906        b.emit_load_imm(0, 7);
907        b.emit_load_imm(1, 8);
908        b.emit_load_imm(2, 9);
909        b.emit_call(0, callee, 3);
910        b.emit_return(0);
911        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
912        match vm.run(50) {
913            VmResult::Trap(Fault::RegisterOutOfRange {
914                reg: 1,
915                frame_size: 1,
916            }) => Ok(()),
917            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
918        }
919    }
920
921    /// The boundary case that must keep working: gathering right up to the
922    /// last register is legal, it is only going *past* it that faults.
923    #[test]
924    fn gathering_up_to_the_last_register_still_works() -> TestResult {
925        let mut b = ChunkBuilder::new("t");
926        let callee = b.begin_function("callee", 1, 1);
927        b.emit_return(0);
928        let main = b.begin_function("main", 0, 255);
929        b.emit_load_imm(254, 5);
930        // Argument at r254 — the highest index a 255-register frame has.
931        b.emit_call(254, callee, 1);
932        b.emit_return(254);
933        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
934        match vm.run(100) {
935            VmResult::Complete(_) => Ok(()),
936            other => Err(format!("expected completion, got {other:?}").into()),
937        }
938    }
939
940    #[test]
941    fn neg_i64_min_wrapping() -> TestResult {
942        let mut b = ChunkBuilder::new("t");
943        b.begin_function("main", 0, 1);
944        let k = b.const_(Value::Int(i64::MIN));
945        b.emit_load_const(0, k);
946        b.emit_neg(0, 0);
947        b.emit_return(0);
948        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
949        match vm.run(10) {
950            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
951            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
952        }
953    }
954
955    #[test]
956    fn mod_non_int_type_mismatch() -> TestResult {
957        let mut b = ChunkBuilder::new("t");
958        b.begin_function("main", 0, 3);
959        b.emit_load_imm(0, 10);
960        let kf = b.const_(Value::Float(3.0));
961        b.emit_load_const(1, kf);
962        b.emit_binop(Opcode::Mod, 2, 0, 1);
963        b.emit_return(2);
964        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
965        match vm.run(20) {
966            VmResult::Trap(Fault::TypeMismatch {
967                expected: "int",
968                got: "float",
969            }) => Ok(()),
970            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
971        }
972    }
973
974    #[test]
975    fn receive_timeout_negative_traps() -> TestResult {
976        let mut b = ChunkBuilder::new("t");
977        b.begin_function("main", 0, 2);
978        b.emit_load_imm(1, -1);
979        b.emit_receive_timeout(0, 1);
980        b.emit_return(0);
981        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
982        match vm.run(10) {
983            VmResult::Trap(Fault::TypeMismatch {
984                expected: "non-negative int",
985                ..
986            }) => Ok(()),
987            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
988        }
989    }
990
991    #[test]
992    fn ask_timeout_negative_traps() -> TestResult {
993        let mut b = ChunkBuilder::new("t");
994        b.begin_function("main", 0, 4);
995        b.emit_load_imm(3, -5);
996        // Cap/message regs are garbage; millis is checked first.
997        b.emit_ask_timeout(0, 1, 2, 3);
998        b.emit_return(0);
999        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1000        match vm.run(10) {
1001            VmResult::Trap(Fault::TypeMismatch {
1002                expected: "non-negative int",
1003                ..
1004            }) => Ok(()),
1005            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1006        }
1007    }
1008
1009    #[test]
1010    fn paranoid_jump_out_of_range_traps() -> TestResult {
1011        let mut b = ChunkBuilder::new("t");
1012        b.begin_function("main", 0, 1);
1013        b.emit_load_imm(0, 0);
1014        b.emit_return(0);
1015        let mut chunk = b.finish();
1016        let code_len = chunk.code.len();
1017        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1018        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1019        vm.set_paranoid_jumps(true);
1020        match vm.run(10) {
1021            VmResult::Trap(Fault::BadJump {
1022                target: 101,
1023                code_len: len,
1024            }) if len == code_len => Ok(()),
1025            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1026        }
1027    }
1028
1029    #[test]
1030    fn returning_over_quota_keeps_quota_fault() -> TestResult {
1031        let mut b = ChunkBuilder::new("t");
1032        let k = b.const_(Value::Str("x".repeat(200).into()));
1033        let callee = b.begin_function("callee", 0, 1);
1034        b.emit_load_const(0, k);
1035        b.emit_return(0);
1036        let main = b.begin_function("main", 0, 1);
1037        b.emit_call(0, callee, 0);
1038        b.emit_return(0);
1039        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1040        // 200 fits the callee store; writeback into the caller charges again.
1041        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1042        vm.set_quota(quota)?;
1043        match vm.run(50) {
1044            VmResult::Trap(Fault::QuotaExceeded(_)) => Ok(()),
1045            other => Err(format!("expected QuotaExceeded from return writeback, got {other:?}").into()),
1046        }
1047    }
1048
1049    #[test]
1050    fn call_native_without_gate_is_typed_denied() -> TestResult {
1051        let mut b = ChunkBuilder::new("t");
1052        b.begin_function("main", 0, 1);
1053        b.emit_call_native(0, 0, 0);
1054        b.emit_return(0);
1055        let table = NativeTable::builder()
1056            .register("noop", |_| Ok(Value::Unit))?;
1057        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1058        match vm.run(10) {
1059            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1060            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1061        }
1062    }
1063
1064    #[test]
1065    fn non_paranoid_bad_jump_still_fail_opens() -> TestResult {
1066        let mut b = ChunkBuilder::new("t");
1067        b.begin_function("main", 0, 1);
1068        b.emit_load_imm(0, 7);
1069        b.emit_return(0);
1070        let mut chunk = b.finish();
1071        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1072        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1073        match vm.run(10) {
1074            // Fall off the end → implicit return Unit from outermost frame.
1075            VmResult::Complete(Value::Unit) => Ok(()),
1076            other => Err(format!("expected Complete(Unit), got {other:?}").into()),
1077        }
1078    }
1079}