Skip to main content

byteflow/bytecode/
verify.rs

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