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