Skip to main content

byteflow/bytecode/
verify.rs

1// Docs ratchet: public items here predate `missing_docs`. Delete this
2// allow once they are documented; new files get the lint by default.
3#![allow(missing_docs)]
4
5use super::chunk::Chunk;
6use super::opcode::Opcode;
7use super::value::Value;
8use std::fmt;
9
10/// Whether the chunk may contain authority-bearing constants, and how
11/// aggressively the host should treat the module.
12///
13/// Default is [`TrustLevel::Untrusted`] (fail closed). Host assemblers that
14/// intentionally embed `Cap` / `Pid` / `Message` in the pool must pass
15/// [`TrustLevel::Trusted`].
16///
17/// [`TrustLevel::Restricted`] is the middle tier: same constant-pool denial
18/// as Untrusted (no Cap/Pid/Message injection), but the host may still grant
19/// explicit Caps / natives after load. Elevation is host-only — bytecode
20/// never changes its own trust level.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum TrustLevel {
23    /// Host-controlled module. May embed Cap / Pid / Message in the pool.
24    Trusted,
25    /// Untrusted load path with explicit host grants after admission.
26    /// Constant pool still rejects Cap / Pid / Message (fail closed).
27    Restricted,
28    /// Deny-by-default guest. Constant pool rejects Cap / Pid / Message.
29    Untrusted,
30}
31
32impl TrustLevel {
33    /// Only [`TrustLevel::Trusted`] may embed authority-bearing constant-pool tags.
34    #[inline]
35    pub const fn allows_authority_constants(self) -> bool {
36        matches!(self, TrustLevel::Trusted)
37    }
38
39    /// Fail-closed tiers that reject Cap / Pid / Message in the pool.
40    #[inline]
41    pub const fn forbids_authority_constants(self) -> bool {
42        !self.allows_authority_constants()
43    }
44}
45
46/// Knob for [`verify_with`]. Default trust is untrusted.
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct VerifyConfig {
49    pub trust: TrustLevel,
50}
51
52impl Default for VerifyConfig {
53    fn default() -> Self {
54        Self {
55            trust: TrustLevel::Untrusted,
56        }
57    }
58}
59
60/// Constant-pool tags that untrusted modules must not embed.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub enum ConstantKind {
63    Capability,
64    ProcessId,
65    Message,
66}
67
68impl fmt::Display for ConstantKind {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match self {
71            ConstantKind::Capability => f.write_str("capability"),
72            ConstantKind::ProcessId => f.write_str("pid"),
73            ConstantKind::Message => f.write_str("message"),
74        }
75    }
76}
77
78#[inline]
79fn validate_constant(value: &Value, trust: TrustLevel, index: usize) -> Result<(), VerifyError> {
80    if trust.allows_authority_constants() {
81        return Ok(());
82    }
83    if !value.within_nesting_limit() {
84        return Err(VerifyError::ForbiddenConstant {
85            index,
86            kind: ConstantKind::Capability,
87        });
88    }
89    reject_untrusted_constant(value, index)
90}
91
92/// `Cap`, `Pid`, and `Message` are rejected at every depth. A list is not
93/// authority by itself, but it must not smuggle those tags past the pool check.
94#[inline]
95fn reject_untrusted_constant(value: &Value, index: usize) -> Result<(), VerifyError> {
96    match value {
97        Value::Cap(_) => Err(VerifyError::ForbiddenConstant {
98            index,
99            kind: ConstantKind::Capability,
100        }),
101        Value::Pid(_) => Err(VerifyError::ForbiddenConstant {
102            index,
103            kind: ConstantKind::ProcessId,
104        }),
105        Value::Message(_) => Err(VerifyError::ForbiddenConstant {
106            index,
107            kind: ConstantKind::Message,
108        }),
109        Value::List(items) | Value::Record(items) => {
110            for item in items.iter() {
111                reject_untrusted_constant(item, index)?;
112            }
113            Ok(())
114        }
115        Value::Map(entries) => {
116            for (_, value) in entries.iter() {
117                reject_untrusted_constant(value, index)?;
118            }
119            Ok(())
120        }
121        _ => Ok(()),
122    }
123}
124
125/// Why a [`Chunk`] failed verification.
126///
127/// The verifier's job is to make every fact the interpreter's hot loop
128/// relies on (jump targets in range, constant/function indices in range)
129/// true *before* a single instruction runs, so `byteflow-vm` never has to
130/// re-check them per-step. Skipping this on trusted, compiler-generated
131/// bytecode is fine; it is mandatory before loading anything that crossed a
132/// trust boundary (a plugin, a network-fetched module, see design notes
133/// §24 capability/sandboxing).
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum VerifyError {
136    UnknownOpcode {
137        at: usize,
138        byte: u8,
139    },
140    ConstOutOfRange {
141        at: usize,
142        index: u32,
143        len: usize,
144    },
145    FunctionOutOfRange {
146        at: usize,
147        index: u32,
148        len: usize,
149    },
150    JumpOutOfRange {
151        at: usize,
152        target: i64,
153        len: usize,
154    },
155    EmptyFunctionTable,
156    EntryOutOfRange {
157        function: usize,
158        entry: u32,
159        len: usize,
160    },
161    /// A function declares more parameters than it has registers to hold
162    /// them. The VM loads `r0..arity` on entry, so this makes the very first
163    /// thing a call does — copying arguments in — reach past the register
164    /// file. Cheap to settle here: it is a static property of the function
165    /// table, one comparison per function, and no amount of runtime checking
166    /// makes such a function callable.
167    ArityExceedsRegisters {
168        function: usize,
169        arity: u8,
170        num_registers: u8,
171    },
172    /// `Call` or `Spawn` passes a different argument count than the callee
173    /// declares. `StartChild` is the same fact with `argc == 0`: the opcode
174    /// has no argument window, so a non-zero arity would enter as `Unit`.
175    CallArity {
176        at: usize,
177        function: u32,
178        argc: u8,
179        arity: u8,
180    },
181    /// Untrusted chunk embedded a Cap, Pid, or Message in the constant pool.
182    ForbiddenConstant {
183        index: usize,
184        kind: ConstantKind,
185    },
186    /// The instruction before the next function's `entry` can continue, so
187    /// the VM would run that body on this function's register window.
188    /// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` close the span.
189    /// `Branch` and `Call` do not: both can execute the following instruction.
190    FallThrough {
191        function: usize,
192        at: usize,
193        next_entry: usize,
194    },
195    /// An immediate or a register window is not a value the ISA can execute.
196    ///
197    /// Pack lengths above the value cap, a window that would address register
198    /// 255, a `ReceiveMatchKind` outside `0..=10`, a `ReceiveMatchCmp`
199    /// selector outside `Eq` / `Lt` / `Le`, a `ReceiveMatch*Imm` tag outside
200    /// `u16`, a `SetRestartPolicy` / `StartChild` policy outside `0..=2`,
201    /// and a register window of `Call` / `Spawn` / `CallNative` /
202    /// `CallNativeFrom` / `StartChild` that reaches past the enclosing
203    /// function's register file are properties of the instruction word. The
204    /// VM still traps if `verify` was skipped.
205    BadImmediate {
206        at: usize,
207        what: &'static str,
208    },
209}
210
211impl fmt::Display for VerifyError {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        match self {
214            VerifyError::UnknownOpcode { at, byte } => {
215                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
216            }
217            VerifyError::ConstOutOfRange { at, index, len } => write!(
218                f,
219                "instruction {at} references constant {index}, pool has {len} entries"
220            ),
221            VerifyError::FunctionOutOfRange { at, index, len } => write!(
222                f,
223                "instruction {at} references function {index}, table has {len} entries"
224            ),
225            VerifyError::JumpOutOfRange { at, target, len } => write!(
226                f,
227                "instruction {at} jumps to {target}, out of code bounds (len={len})"
228            ),
229            VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
230            VerifyError::EntryOutOfRange {
231                function,
232                entry,
233                len,
234            } => write!(
235                f,
236                "function {function} entry point {entry} is out of code bounds (len={len})"
237            ),
238            VerifyError::ArityExceedsRegisters {
239                function,
240                arity,
241                num_registers,
242            } => write!(
243                f,
244                "function {function} declares arity {arity} but only {num_registers} registers"
245            ),
246            VerifyError::CallArity {
247                at,
248                function,
249                argc,
250                arity,
251            } => write!(
252                f,
253                "instruction {at} invokes function {function} with {argc} arguments, arity is {arity}"
254            ),
255            VerifyError::ForbiddenConstant { index, kind } => {
256                write!(f, "untrusted constant[{index}] must not embed {kind}")
257            }
258            VerifyError::FallThrough {
259                function,
260                at,
261                next_entry,
262            } => write!(
263                f,
264                "function {function} falls through at instruction {at} into the function at {next_entry}"
265            ),
266            VerifyError::BadImmediate { at, what } => {
267                write!(f, "instruction {at} has an invalid {what}")
268            }
269        }
270    }
271}
272
273impl std::error::Error for VerifyError {}
274
275/// Verify structural invariants of `chunk`. See [`VerifyError`] for what is
276/// checked. This does **not** perform full dataflow/register-liveness
277/// verification (unlike, say, the JVM verifier) — v0 trades that off
278/// against implementation complexity.
279///
280/// Register facts that *are* settled statically:
281///
282/// - [`VerifyError::ArityExceedsRegisters`] — a table property: such a
283///   function cannot be entered at all.
284/// - The destination / gather windows of `Call`, `Spawn`, `CallNative`,
285///   `CallNativeFrom`, and `StartChild` — checked against the enclosing
286///   function's `num_registers`. These are the multi-register gathers the
287///   hot loop (and the return path) address as a span; a single out-of-range
288///   register is still cheap to trap at runtime, but a window that reaches
289///   past the frame is the same class of fact as the pack windows below, so
290///   it settles here too.
291///
292/// Single-register operands stay per-step checks in the VM (cheap: an array
293/// index against a fixed small register file, not worth statically proving
294/// away in full). Sorting is not needed for validity: skipping `verify` on
295/// compiler-generated bytecode is fine, but it is mandatory before loading
296/// anything that crossed a trust boundary (a plugin, a network-fetched
297/// module, see design notes §24 capability/sandboxing).
298///
299/// `Opcode::CallNative` targets are deliberately **not** range-checked
300/// here: native functions live in a `byteflow_vm::NativeTable` supplied by
301/// the embedder at `Vm` construction time, entirely outside this crate's
302/// (and this `Chunk`'s) knowledge. An out-of-range `CallNative` is instead
303/// caught at runtime as `Fault::BadNative`.
304pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
305    verify_with(chunk, VerifyConfig::default())
306}
307
308/// Like [`verify`], with an explicit [`VerifyConfig`].
309pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
310    if chunk.functions.is_empty() {
311        return Err(VerifyError::EmptyFunctionTable);
312    }
313
314    for (index, value) in chunk.constants.iter().enumerate() {
315        validate_constant(value, config.trust, index)?;
316    }
317
318    let len = chunk.code.len();
319    let limits = register_limits(chunk);
320
321    // `enumerate` rather than looking the index back up by name: two
322    // functions may share a name, and a search would then report the wrong
323    // one (and cost O(n²) doing it).
324    for (function, def) in chunk.functions.iter().enumerate() {
325        if def.entry as usize >= len {
326            return Err(VerifyError::EntryOutOfRange {
327                function,
328                entry: def.entry,
329                len,
330            });
331        }
332        if def.arity > def.num_registers {
333            return Err(VerifyError::ArityExceedsRegisters {
334                function,
335                arity: def.arity,
336                num_registers: def.num_registers,
337            });
338        }
339    }
340
341    for (at, instr) in chunk.code.iter().enumerate() {
342        match instr.op {
343            Opcode::LoadConst => {
344                let idx = instr.imm as u32;
345                if idx as usize >= chunk.constants.len() {
346                    return Err(VerifyError::ConstOutOfRange {
347                        at,
348                        index: idx,
349                        len: chunk.constants.len(),
350                    });
351                }
352            }
353            Opcode::Call | Opcode::TailCall | Opcode::Spawn => {
354                let idx = instr.imm as u32;
355                if idx as usize >= chunk.functions.len() {
356                    return Err(VerifyError::FunctionOutOfRange {
357                        at,
358                        index: idx,
359                        len: chunk.functions.len(),
360                    });
361                }
362                let arity = chunk.functions[idx as usize].arity;
363                if instr.b != arity {
364                    return Err(VerifyError::CallArity {
365                        at,
366                        function: idx,
367                        argc: instr.b,
368                        arity,
369                    });
370                }
371                // `Call` gathers args `r[a..a+argc]` and returns into
372                // `r[a]`. `Spawn` reserves `r[a]` for the child Cap and
373                // gathers `r[a+1..a+1+argc]`.
374                if let Some(limit) = limits[at] {
375                    check_slot(at, instr.a, limit, "destination register")?;
376                    check_window(
377                        at,
378                        instr.a,
379                        if instr.op == Opcode::Spawn { 1 } else { 0 },
380                        u32::from(instr.b),
381                        limit,
382                    )?;
383                }
384            }
385            Opcode::StartChild => {
386                let idx = instr.imm as u32;
387                if idx as usize >= chunk.functions.len() {
388                    return Err(VerifyError::FunctionOutOfRange {
389                        at,
390                        index: idx,
391                        len: chunk.functions.len(),
392                    });
393                }
394                // The opcode carries a restart policy, not an argument list.
395                // The supervisor starts the child with an empty window.
396                let arity = chunk.functions[idx as usize].arity;
397                if arity != 0 {
398                    return Err(VerifyError::CallArity {
399                        at,
400                        function: idx,
401                        argc: 0,
402                        arity,
403                    });
404                }
405                if instr.b > 2 {
406                    return Err(VerifyError::BadImmediate {
407                        at,
408                        what: "restart policy",
409                    });
410                }
411                // The child Cap arrives in `r[a]` — a register, not a hole.
412                if let Some(limit) = limits[at] {
413                    check_slot(at, instr.a, limit, "destination register")?;
414                }
415            }
416            // `CallNative` targets a `byteflow_vm::NativeTable` supplied at
417            // runtime, outside this chunk — see this function's doc
418            // comment. Not checked here; checked as `Fault::BadNative` at
419            // call time instead.
420            Opcode::CallNative | Opcode::CallNativeFrom => {
421                // `CallNative` gathers `r[a..a+argc]` and writes the result
422                // to `r[a]`. `CallNativeFrom` gathers only `r[b]` and writes
423                // `r[a]`.
424                if let Some(limit) = limits[at] {
425                    if instr.op == Opcode::CallNativeFrom {
426                        check_slot(at, instr.a, limit, "destination register")?;
427                        check_slot(at, instr.b, limit, "source register")?;
428                    } else {
429                        check_window(at, instr.a, 0, u32::from(instr.b), limit)?;
430                    }
431                }
432            }
433            Opcode::ListPack | Opcode::RecordPack => {
434                let max = if instr.op == Opcode::ListPack {
435                    super::value::MAX_LIST_LEN
436                } else {
437                    super::value::MAX_RECORD_LEN
438                };
439                check_pack(at, instr.b, instr.imm, 1, max)?;
440            }
441            Opcode::MapPack => {
442                check_pack(at, instr.b, instr.imm, 2, super::value::MAX_MAP_LEN)?;
443            }
444            Opcode::ReceiveMatchKind => {
445                if !(0..=10).contains(&instr.imm) {
446                    return Err(VerifyError::BadImmediate {
447                        at,
448                        what: "payload kind",
449                    });
450                }
451            }
452            Opcode::ReceiveMatchCmp => {
453                if super::opcode::IntCmp::from_imm(instr.imm).is_none() {
454                    return Err(VerifyError::BadImmediate {
455                        at,
456                        what: "compare immediate",
457                    });
458                }
459            }
460            Opcode::ReceiveMatchImm | Opcode::ReceiveMatchCorrImm => {
461                // The ISA passes message tags as `u16` (see the `Opcode`
462                // encoding notes); anything wider truncates at runtime, so
463                // it is not a value the ISA can execute.
464                if !(0..=u32::from(u16::MAX))
465                    .contains(&u32::try_from(instr.imm).unwrap_or(u32::MAX))
466                {
467                    return Err(VerifyError::BadImmediate {
468                        at,
469                        what: "tag immediate",
470                    });
471                }
472            }
473            Opcode::SetRestartPolicy => {
474                if !(0..=2).contains(&instr.imm) {
475                    return Err(VerifyError::BadImmediate {
476                        at,
477                        what: "restart policy",
478                    });
479                }
480            }
481            Opcode::AskTimeout => {
482                // The timeout lives in a register of the calling frame,
483                // packed into `imm` (see the `Opcode` encoding notes).
484                if let Some(limit) = limits[at] {
485                    match u32::try_from(instr.imm) {
486                        Ok(reg) if reg < u32::from(limit) => {}
487                        Ok(_) | Err(_) => {
488                            return Err(VerifyError::BadImmediate {
489                                at,
490                                what: "millis register",
491                            })
492                        }
493                    }
494                }
495            }
496            Opcode::Jump | Opcode::Branch | Opcode::BranchTrue => {
497                let target = at as i64 + 1 + instr.imm as i64;
498                if target < 0 || target as usize > len {
499                    // == len is allowed: jumping to "one past the end" is a
500                    // valid way to fall off the end of the chunk.
501                    return Err(VerifyError::JumpOutOfRange { at, target, len });
502                }
503                // A jump may stay inside the function that contains `at`, or
504                // land exactly at `code.len()` (implicit return). Landing on
505                // another function's body would run that code with this frame.
506                if let Some((start, end)) = function_span(&chunk.functions, at, len) {
507                    let t = target as usize;
508                    if t != len && (t < start || t >= end) {
509                        return Err(VerifyError::JumpOutOfRange { at, target, len });
510                    }
511                }
512            }
513            _ => {}
514        }
515    }
516
517    reject_fallthrough(chunk)?;
518    Ok(())
519}
520
521/// `width` is 1 for a list or record and 2 for a map pair.
522///
523/// Register 255 is not a slot: `num_registers` is a `u8`, so the highest
524/// index a frame can name is 254. A pack whose exclusive end is above 255
525/// would gather that index.
526fn check_pack(
527    at: usize,
528    base: u8,
529    count: i32,
530    width: u32,
531    max_len: usize,
532) -> Result<(), VerifyError> {
533    let max = match i32::try_from(max_len) {
534        Ok(n) => n,
535        Err(_) => i32::MAX,
536    };
537    if !(0..=max).contains(&count) {
538        return Err(VerifyError::BadImmediate {
539            at,
540            what: "pack length",
541        });
542    }
543    if count == 0 {
544        return Ok(());
545    }
546    let span = match u32::try_from(count).ok().and_then(|n| n.checked_mul(width)) {
547        Some(n) => n,
548        None => {
549            return Err(VerifyError::BadImmediate {
550                at,
551                what: "pack window",
552            })
553        }
554    };
555    let end = match u32::from(base).checked_add(span) {
556        Some(n) => n,
557        None => {
558            return Err(VerifyError::BadImmediate {
559                at,
560                what: "pack window",
561            })
562        }
563    };
564    if end > 255 {
565        return Err(VerifyError::BadImmediate {
566            at,
567            what: "pack window",
568        });
569    }
570    Ok(())
571}
572
573/// The register file that runs each instruction: the `num_registers` of the
574/// enclosing function's span, or `None` for instructions outside any span
575/// (unreachable from any entry — entries are `< code.len()` by the time this
576/// runs, and jumps are confined to their own span).
577///
578/// Functions sharing an `entry` pool the **smallest** `num_registers` of the
579/// group: the span belongs to both bodies, so a window that fits only the
580/// larger one is not a fact the interpreter can rely on.
581fn register_limits(chunk: &Chunk) -> Vec<Option<u8>> {
582    let mut entries: Vec<u32> = chunk.functions.iter().map(|def| def.entry).collect();
583    entries.sort_unstable();
584    entries.dedup();
585    let mut limits = vec![None; chunk.code.len()];
586    for (i, &entry) in entries.iter().enumerate() {
587        let start = entry as usize;
588        let end = match entries.get(i + 1) {
589            Some(&next) => next as usize,
590            None => chunk.code.len(),
591        };
592        let limit = chunk
593            .functions
594            .iter()
595            .filter(|def| def.entry == entry)
596            .map(|def| def.num_registers)
597            .min()
598            .unwrap_or_default();
599        for slot in limits.iter_mut().take(end).skip(start) {
600            *slot = Some(limit);
601        }
602    }
603    limits
604}
605
606/// One named register must hold a value: index strictly below the frame's
607/// register file (register 255 is never a slot, so the `u8` limit covers it).
608fn check_slot(at: usize, reg: u8, limit: u8, what: &'static str) -> Result<(), VerifyError> {
609    if u32::from(reg) < u32::from(limit) {
610        Ok(())
611    } else {
612        Err(VerifyError::BadImmediate { at, what })
613    }
614}
615
616/// A gathered register window `[base + extra, base + extra + count)` must
617/// stay inside the caller's register file. An empty window is skipped here:
618/// the destination slot (if any) is checked by [`check_slot`] instead.
619fn check_window(at: usize, base: u8, extra: u32, count: u32, limit: u8) -> Result<(), VerifyError> {
620    if count == 0 {
621        return Ok(());
622    }
623    let end = match u32::from(base)
624        .checked_add(extra)
625        .and_then(|n| n.checked_add(count))
626    {
627        Some(n) => n,
628        None => {
629            return Err(VerifyError::BadImmediate {
630                at,
631                what: "register window",
632            })
633        }
634    };
635    if end > u32::from(limit) {
636        return Err(VerifyError::BadImmediate {
637            at,
638            what: "register window",
639        });
640    }
641    Ok(())
642}
643
644/// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` never execute the next
645/// instruction. Every other opcode can: `Branch` falls through when the
646/// condition is false, and `Call` / `Yield` / `Send` resume at `pc + 1`.
647fn is_terminator(op: Opcode) -> bool {
648    matches!(
649        op,
650        Opcode::Jump
651            | Opcode::Return
652            | Opcode::Halt
653            | Opcode::Exit
654            | Opcode::Trap
655            | Opcode::TailCall
656    )
657}
658
659/// Smallest function `entry` strictly after `start`, or `code_len` when
660/// this span runs to the end of the chunk.
661fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
662    let mut end = code_len;
663    for def in functions {
664        let entry = def.entry as usize;
665        if entry > start && entry < end {
666            end = entry;
667        }
668    }
669    end
670}
671
672/// Each function whose span ends at another `entry` must close with a
673/// terminator. Falling off `code.len()` is the implicit return and stays
674/// legal. A span that does not extend past `start` has no instruction to
675/// check (two functions sharing an `entry`).
676fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
677    let len = chunk.code.len();
678    for (function, def) in chunk.functions.iter().enumerate() {
679        let start = def.entry as usize;
680        let end = exclusive_end(&chunk.functions, start, len);
681        if end >= len || end <= start {
682            continue;
683        }
684        let at = end - 1;
685        if !is_terminator(chunk.code[at].op) {
686            return Err(VerifyError::FallThrough {
687                function,
688                at,
689                next_entry: end,
690            });
691        }
692    }
693    Ok(())
694}
695
696/// Instruction range owned by the function whose `entry` is the greatest
697/// entry `<= at`. The end is the next function entry, or `code_len`.
698fn function_span(
699    functions: &[super::chunk::FunctionDef],
700    at: usize,
701    code_len: usize,
702) -> Option<(usize, usize)> {
703    let mut start = None;
704    for def in functions {
705        let entry = def.entry as usize;
706        if entry <= at {
707            start = Some(match start {
708                Some(prev) if prev >= entry => prev,
709                _ => entry,
710            });
711        }
712    }
713    let start = start?;
714    let end = exclusive_end(functions, start, code_len);
715    if at >= end {
716        None
717    } else {
718        Some((start, end))
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725    use crate::bytecode::builder::ChunkBuilder;
726    use crate::bytecode::opcode::Opcode;
727
728    #[test]
729    fn rejects_empty_function_table() {
730        let chunk = Chunk::default();
731        assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
732    }
733
734    #[test]
735    fn accepts_well_formed_chunk() {
736        let mut b = ChunkBuilder::new("test");
737        b.begin_function("main", 0, 2);
738        let k = b.const_(crate::bytecode::value::Value::Int(41));
739        b.emit_load_const(0, k);
740        b.emit_load_imm(1, 1);
741        b.emit_binop(Opcode::Add, 0, 0, 1);
742        b.emit_return(0);
743        let chunk = b.finish();
744        assert!(verify(&chunk).is_ok());
745    }
746
747    /// A function the VM cannot even enter: entry copies `r0..arity`, but
748    /// the frame only has `num_registers` slots. Used to be accepted here and
749    /// then panic with an out-of-bounds index inside `Vm::new` / `Call`.
750    #[test]
751    fn rejects_arity_larger_than_the_register_file() {
752        let mut b = ChunkBuilder::new("test");
753        b.begin_function("main", 3, 1);
754        b.emit_return(0);
755        let chunk = b.finish();
756        assert_eq!(
757            verify(&chunk),
758            Err(VerifyError::ArityExceedsRegisters {
759                function: 0,
760                arity: 3,
761                num_registers: 1,
762            })
763        );
764    }
765
766    #[test]
767    fn accepts_arity_equal_to_the_register_file() {
768        let mut b = ChunkBuilder::new("test");
769        b.begin_function("main", 2, 2);
770        b.emit_return(0);
771        let chunk = b.finish();
772        assert!(verify(&chunk).is_ok());
773    }
774
775    #[test]
776    fn rejects_start_child_function_out_of_range() {
777        use crate::bytecode::instruction::Instruction;
778        let mut chunk = Chunk::default();
779        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
780            name: "main".into(),
781            entry: 0,
782            arity: 0,
783            num_registers: 1,
784        });
785        chunk
786            .code
787            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
788        assert!(matches!(
789            verify(&chunk),
790            Err(VerifyError::FunctionOutOfRange { index: 99, .. })
791        ));
792    }
793
794    #[test]
795    fn rejects_jump_into_another_function() {
796        use crate::bytecode::instruction::Instruction;
797        let mut chunk = Chunk::default();
798        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
799            name: "main".into(),
800            entry: 0,
801            arity: 0,
802            num_registers: 1,
803        });
804        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
805            name: "other".into(),
806            entry: 2,
807            arity: 0,
808            num_registers: 1,
809        });
810        // at 0, imm 1 → target 2, the other function's entry.
811        chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
812        chunk.code.push(Instruction::nullary(Opcode::Nop));
813        chunk.code.push(Instruction::nullary(Opcode::Nop));
814        assert!(matches!(
815            verify(&chunk),
816            Err(VerifyError::JumpOutOfRange { target: 2, .. })
817        ));
818    }
819
820    #[test]
821    fn rejects_out_of_range_jump() {
822        use crate::bytecode::instruction::Instruction;
823        let mut chunk = Chunk::default();
824        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
825            name: "main".into(),
826            entry: 0,
827            arity: 0,
828            num_registers: 1,
829        });
830        chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
831        assert!(matches!(
832            verify(&chunk),
833            Err(VerifyError::JumpOutOfRange { .. })
834        ));
835    }
836
837    fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
838        use crate::bytecode::instruction::Instruction;
839        let mut chunk = Chunk::default();
840        for (name, entry) in [("main", 0u32), ("other", 1)] {
841            chunk.functions.push(crate::bytecode::chunk::FunctionDef {
842                name: name.into(),
843                entry,
844                arity: 0,
845                num_registers: 1,
846            });
847        }
848        chunk.code.push(first);
849        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
850        chunk
851    }
852
853    #[test]
854    fn rejects_fallthrough_into_the_next_function() {
855        use crate::bytecode::instruction::Instruction;
856        let boundary = VerifyError::FallThrough {
857            function: 0,
858            at: 0,
859            next_entry: 1,
860        };
861        for first in [
862            Instruction::nullary(Opcode::Nop),
863            Instruction::a_imm(Opcode::Branch, 0, -1),
864            Instruction::new(Opcode::Call, 0, 0, 0, 1),
865        ] {
866            assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
867        }
868    }
869
870    #[test]
871    fn accepts_jump_closing_a_function_before_the_next() {
872        use crate::bytecode::instruction::Instruction;
873        // target = 0 + 1 + (-1) = 0, still inside `main`.
874        let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
875        assert!(verify(&chunk).is_ok());
876    }
877
878    #[test]
879    fn rejects_call_whose_argc_differs_from_the_callee() {
880        use crate::bytecode::instruction::Instruction;
881        let mut chunk = Chunk::default();
882        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
883            name: "main".into(),
884            entry: 0,
885            arity: 0,
886            num_registers: 1,
887        });
888        chunk.code.push(Instruction::new(Opcode::Call, 0, 1, 0, 0));
889        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
890        assert_eq!(
891            verify(&chunk),
892            Err(VerifyError::CallArity {
893                at: 0,
894                function: 0,
895                argc: 1,
896                arity: 0,
897            })
898        );
899    }
900
901    #[test]
902    fn rejects_spawn_whose_argc_differs_from_the_callee() {
903        use crate::bytecode::instruction::Instruction;
904        let mut chunk = Chunk::default();
905        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
906            name: "main".into(),
907            entry: 0,
908            arity: 2,
909            num_registers: 2,
910        });
911        chunk.code.push(Instruction::new(Opcode::Spawn, 0, 0, 0, 0));
912        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
913        assert_eq!(
914            verify(&chunk),
915            Err(VerifyError::CallArity {
916                at: 0,
917                function: 0,
918                argc: 0,
919                arity: 2,
920            })
921        );
922    }
923
924    #[test]
925    fn rejects_start_child_of_a_function_that_expects_arguments() {
926        use crate::bytecode::instruction::Instruction;
927        let mut chunk = Chunk::default();
928        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
929            name: "main".into(),
930            entry: 0,
931            arity: 1,
932            num_registers: 1,
933        });
934        chunk
935            .code
936            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 0));
937        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
938        assert_eq!(
939            verify(&chunk),
940            Err(VerifyError::CallArity {
941                at: 0,
942                function: 0,
943                argc: 0,
944                arity: 1,
945            })
946        );
947    }
948
949    #[test]
950    fn accepts_implicit_return_on_the_last_function() {
951        use crate::bytecode::instruction::Instruction;
952        let mut chunk = Chunk::default();
953        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
954            name: "main".into(),
955            entry: 0,
956            arity: 0,
957            num_registers: 1,
958        });
959        chunk.code.push(Instruction::nullary(Opcode::Nop));
960        assert!(verify(&chunk).is_ok());
961    }
962
963    #[test]
964    fn untrusted_rejects_cap_pid_message_constants() {
965        use crate::bytecode::cap::CapId;
966        use crate::bytecode::value::Message;
967        for (value, kind) in [
968            (
969                crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
970                ConstantKind::Capability,
971            ),
972            (
973                crate::bytecode::value::Value::Pid(7),
974                ConstantKind::ProcessId,
975            ),
976            (
977                crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
978                ConstantKind::Message,
979            ),
980        ] {
981            let mut b = ChunkBuilder::new("forge");
982            b.begin_function("main", 0, 1);
983            let k = b.const_(value);
984            b.emit_load_const(0, k);
985            b.emit_return(0);
986            let chunk = b.finish();
987            assert_eq!(
988                verify(&chunk),
989                Err(VerifyError::ForbiddenConstant { index: 0, kind })
990            );
991            assert!(verify_with(
992                &chunk,
993                VerifyConfig {
994                    trust: TrustLevel::Trusted
995                }
996            )
997            .is_ok());
998        }
999    }
1000
1001    #[test]
1002    fn untrusted_rejects_authority_nested_in_a_list() {
1003        use crate::bytecode::cap::CapId;
1004        use crate::bytecode::value::{Message, Value};
1005        let cases = [
1006            (
1007                Value::try_list(vec![Value::Int(1), Value::Cap(CapId::from_raw(1))]),
1008                ConstantKind::Capability,
1009            ),
1010            (
1011                Value::try_list(vec![Value::Pid(7)]),
1012                ConstantKind::ProcessId,
1013            ),
1014            (
1015                Value::try_list(vec![Value::Message(Message::new(1, 2, 3, 4u64))]),
1016                ConstantKind::Message,
1017            ),
1018        ];
1019        for (value, kind) in cases {
1020            assert!(value.is_some());
1021            let Some(value) = value else {
1022                return;
1023            };
1024            let mut b = ChunkBuilder::new("nested-forge");
1025            b.begin_function("main", 0, 1);
1026            let k = b.const_(value);
1027            b.emit_load_const(0, k);
1028            b.emit_return(0);
1029            let chunk = b.finish();
1030            assert_eq!(
1031                verify(&chunk),
1032                Err(VerifyError::ForbiddenConstant { index: 0, kind })
1033            );
1034            assert!(verify_with(
1035                &chunk,
1036                VerifyConfig {
1037                    trust: TrustLevel::Trusted
1038                }
1039            )
1040            .is_ok());
1041        }
1042    }
1043
1044    #[test]
1045    fn pack_window_past_the_register_file_is_rejected() {
1046        let mut b = ChunkBuilder::new("wide");
1047        b.begin_function("main", 0, 255);
1048        b.emit_list_pack(0, 250, 10);
1049        b.emit_return(0);
1050        let chunk = b.finish();
1051        assert_eq!(
1052            verify(&chunk),
1053            Err(VerifyError::BadImmediate {
1054                at: 0,
1055                what: "pack window",
1056            })
1057        );
1058    }
1059
1060    #[test]
1061    fn pack_length_above_the_value_cap_is_rejected() {
1062        let mut b = ChunkBuilder::new("long");
1063        b.begin_function("main", 0, 1);
1064        b.emit_record_pack(0, 0, 257);
1065        b.emit_return(0);
1066        let chunk = b.finish();
1067        assert_eq!(
1068            verify(&chunk),
1069            Err(VerifyError::BadImmediate {
1070                at: 0,
1071                what: "pack length",
1072            })
1073        );
1074    }
1075
1076    #[test]
1077    fn receive_kind_outside_the_scalar_range_is_rejected() {
1078        let mut b = ChunkBuilder::new("kind");
1079        b.begin_function("main", 0, 1);
1080        b.emit_receive_match_kind(0, 11);
1081        b.emit_return(0);
1082        let chunk = b.finish();
1083        assert_eq!(
1084            verify(&chunk),
1085            Err(VerifyError::BadImmediate {
1086                at: 0,
1087                what: "payload kind",
1088            })
1089        );
1090    }
1091
1092    #[test]
1093    fn receive_compare_outside_int_cmp_is_rejected() {
1094        let mut b = ChunkBuilder::new("cmp");
1095        b.begin_function("main", 0, 2);
1096        b.emit_receive_match_cmp(0, 0, 1, crate::bytecode::opcode::IntCmp::Eq);
1097        b.emit_return(0);
1098        let mut chunk = b.finish();
1099        chunk.code[0].imm = 9;
1100        assert_eq!(
1101            verify(&chunk),
1102            Err(VerifyError::BadImmediate {
1103                at: 0,
1104                what: "compare immediate",
1105            })
1106        );
1107    }
1108
1109    #[test]
1110    fn a_short_list_pack_still_verifies() {
1111        let mut b = ChunkBuilder::new("ok-pack");
1112        b.begin_function("main", 0, 3);
1113        b.emit_list_pack(2, 0, 2);
1114        b.emit_return(2);
1115        let chunk = b.finish();
1116        assert!(verify(&chunk).is_ok());
1117    }
1118
1119    // --- register windows (Call / Spawn / CallNative / StartChild) ---
1120
1121    #[test]
1122    fn call_window_past_the_caller_register_file_is_rejected() {
1123        let mut b = ChunkBuilder::new("wide-call");
1124        let callee = b.begin_function("callee", 2, 2);
1125        b.emit_return(0);
1126        b.begin_function("main", 0, 2);
1127        // Args at r1..r3 — the frame ends at r2.
1128        b.emit_call(1, callee, 2);
1129        b.emit_return(1);
1130        let chunk = b.finish();
1131        assert_eq!(
1132            verify(&chunk),
1133            Err(VerifyError::BadImmediate {
1134                at: 1,
1135                what: "register window",
1136            })
1137        );
1138    }
1139
1140    #[test]
1141    fn call_window_filling_the_register_file_still_verifies() {
1142        let mut b = ChunkBuilder::new("ok-call");
1143        let callee = b.begin_function("callee", 2, 2);
1144        b.emit_return(0);
1145        b.begin_function("main", 0, 2);
1146        // Args at r0..r2 with `num_registers == 2`: exactly full, no hole.
1147        b.emit_call(0, callee, 2);
1148        b.emit_return(0);
1149        let chunk = b.finish();
1150        assert!(verify(&chunk).is_ok());
1151    }
1152
1153    #[test]
1154    fn call_with_no_arguments_still_needs_a_real_destination() {
1155        let mut b = ChunkBuilder::new("hole-call");
1156        let callee = b.begin_function("callee", 0, 1);
1157        b.emit_return(0);
1158        b.begin_function("main", 0, 1);
1159        // argc == 0 has no window, but `r[1]` is still not a slot.
1160        b.emit_call(1, callee, 0);
1161        b.emit_return(1);
1162        let chunk = b.finish();
1163        assert_eq!(
1164            verify(&chunk),
1165            Err(VerifyError::BadImmediate {
1166                at: 1,
1167                what: "destination register",
1168            })
1169        );
1170    }
1171
1172    #[test]
1173    fn spawn_window_with_the_cap_slot_past_the_register_file_is_rejected() {
1174        let mut b = ChunkBuilder::new("wide-spawn");
1175        let child = b.begin_function("child", 1, 1);
1176        b.emit_halt();
1177        b.begin_function("main", 0, 2);
1178        // Cap reserved at r1, args gathered from r2 — past the file.
1179        b.emit_spawn(1, child, 1);
1180        b.emit_trap(0);
1181        let chunk = b.finish();
1182        assert_eq!(
1183            verify(&chunk),
1184            Err(VerifyError::BadImmediate {
1185                at: 1,
1186                what: "register window",
1187            })
1188        );
1189    }
1190
1191    #[test]
1192    fn spawn_with_no_arguments_still_needs_a_real_cap_slot() {
1193        let mut b = ChunkBuilder::new("hole-spawn");
1194        let child = b.begin_function("child", 0, 1);
1195        b.emit_halt();
1196        b.begin_function("main", 0, 1);
1197        b.emit_spawn(1, child, 0);
1198        b.emit_trap(0);
1199        let chunk = b.finish();
1200        assert_eq!(
1201            verify(&chunk),
1202            Err(VerifyError::BadImmediate {
1203                at: 1,
1204                what: "destination register",
1205            })
1206        );
1207    }
1208
1209    #[test]
1210    fn native_one_arg_source_must_be_inside_the_frame() {
1211        let mut b = ChunkBuilder::new("gen-nat1");
1212        b.begin_function("main", 0, 1);
1213        // `r[a] = native(r[b])` — r1 is past the 1-register frame.
1214        b.emit_native1_from(0, 1, 0);
1215        b.emit_return(0);
1216        let chunk = b.finish();
1217        assert_eq!(
1218            verify(&chunk),
1219            Err(VerifyError::BadImmediate {
1220                at: 0,
1221                what: "source register",
1222            })
1223        );
1224    }
1225
1226    #[test]
1227    fn start_child_past_the_register_file_is_rejected() {
1228        let mut b = ChunkBuilder::new("wide-child");
1229        let child = b.begin_function("child", 0, 1);
1230        b.emit_halt();
1231        b.begin_function("main", 0, 1);
1232        b.emit_start_child(1, child, 0);
1233        b.emit_halt();
1234        let chunk = b.finish();
1235        assert_eq!(
1236            verify(&chunk),
1237            Err(VerifyError::BadImmediate {
1238                at: 1,
1239                what: "destination register",
1240            })
1241        );
1242    }
1243
1244    #[test]
1245    fn start_child_policy_must_be_zero_to_two() {
1246        let mut b = ChunkBuilder::new("child-policy");
1247        let child = b.begin_function("child", 0, 1);
1248        b.emit_halt();
1249        b.begin_function("main", 0, 1);
1250        // The policy rides in `b` (see `emit_start_child`); 3 traps at runtime.
1251        b.emit_start_child(0, child, 3);
1252        b.emit_halt();
1253        let chunk = b.finish();
1254        assert_eq!(
1255            verify(&chunk),
1256            Err(VerifyError::BadImmediate {
1257                at: 1,
1258                what: "restart policy",
1259            })
1260        );
1261    }
1262
1263    // --- immediates: tag u16, restart policy, millis register ---
1264
1265    #[test]
1266    fn receive_tag_immediate_must_fit_a_u16() {
1267        let mut b = ChunkBuilder::new("wide-tag");
1268        b.begin_function("main", 0, 1);
1269        b.emit_receive_match_imm(0, 7);
1270        b.emit_return(0);
1271        let mut chunk = b.finish();
1272        chunk.code[0].imm = 70_000;
1273        assert_eq!(
1274            verify(&chunk),
1275            Err(VerifyError::BadImmediate {
1276                at: 0,
1277                what: "tag immediate",
1278            })
1279        );
1280    }
1281
1282    #[test]
1283    fn receive_tag_immediate_until_u16_max_still_verifies() {
1284        let mut b = ChunkBuilder::new("edge-tag");
1285        b.begin_function("main", 0, 1);
1286        b.emit_receive_match_imm(0, u16::MAX);
1287        b.emit_return(0);
1288        let chunk = b.finish();
1289        assert!(verify(&chunk).is_ok());
1290    }
1291
1292    #[test]
1293    fn restart_policy_immediate_must_be_zero_to_two() {
1294        let mut b = ChunkBuilder::new("policy-imm");
1295        b.begin_function("main", 0, 1);
1296        b.emit_set_restart_policy(3);
1297        b.emit_return(0);
1298        let mut chunk = b.finish();
1299        chunk.code[0].imm = 3;
1300        assert_eq!(
1301            verify(&chunk),
1302            Err(VerifyError::BadImmediate {
1303                at: 0,
1304                what: "restart policy",
1305            })
1306        );
1307    }
1308
1309    #[test]
1310    fn ask_timeout_millis_register_must_be_inside_the_frame() {
1311        let mut b = ChunkBuilder::new("ask-far");
1312        b.begin_function("main", 0, 4);
1313        b.emit_ask_timeout(0, 1, 2, 3);
1314        b.emit_return(0);
1315        let mut chunk = b.finish();
1316        chunk.code[0].imm = 9; // the timeout register rides in `imm`
1317        assert_eq!(
1318            verify(&chunk),
1319            Err(VerifyError::BadImmediate {
1320                at: 0,
1321                what: "millis register",
1322            })
1323        );
1324    }
1325
1326    #[test]
1327    fn ask_timeout_with_a_local_millis_register_still_verifies() {
1328        let mut b = ChunkBuilder::new("ask-ok");
1329        b.begin_function("main", 0, 4);
1330        b.emit_load_imm(3, 50);
1331        b.emit_ask_timeout(0, 1, 2, 3);
1332        b.emit_return(0);
1333        let chunk = b.finish();
1334        assert!(verify(&chunk).is_ok());
1335    }
1336
1337    /// Instructions outside any function span are unreachable from any
1338    /// entry (jumps stay inside their own span), so their windows are not
1339    /// a fact the hot loop relies on and `verify` leaves them alone.
1340    #[test]
1341    fn code_outside_any_function_span_is_not_window_checked() {
1342        use crate::bytecode::instruction::Instruction;
1343        let mut chunk = Chunk::default();
1344        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
1345            name: "main".into(),
1346            entry: 1,
1347            arity: 0,
1348            num_registers: 1,
1349        });
1350        // Unreachable: CallNativeFrom(src r1) past the 1-register frame.
1351        chunk
1352            .code
1353            .push(Instruction::new(Opcode::CallNativeFrom, 0, 1, 0, 0));
1354        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
1355        assert!(verify(&chunk).is_ok());
1356    }
1357}