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`, and a `ReceiveMatchCmp`
168    /// selector outside `Eq` / `Lt` / `Le` are properties of the instruction
169    /// word. The VM still traps if `verify` was skipped.
170    BadImmediate {
171        at: usize,
172        what: &'static str,
173    },
174}
175
176impl fmt::Display for VerifyError {
177    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178        match self {
179            VerifyError::UnknownOpcode { at, byte } => {
180                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
181            }
182            VerifyError::ConstOutOfRange { at, index, len } => write!(
183                f,
184                "instruction {at} references constant {index}, pool has {len} entries"
185            ),
186            VerifyError::FunctionOutOfRange { at, index, len } => write!(
187                f,
188                "instruction {at} references function {index}, table has {len} entries"
189            ),
190            VerifyError::JumpOutOfRange { at, target, len } => write!(
191                f,
192                "instruction {at} jumps to {target}, out of code bounds (len={len})"
193            ),
194            VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
195            VerifyError::EntryOutOfRange {
196                function,
197                entry,
198                len,
199            } => write!(
200                f,
201                "function {function} entry point {entry} is out of code bounds (len={len})"
202            ),
203            VerifyError::ArityExceedsRegisters {
204                function,
205                arity,
206                num_registers,
207            } => write!(
208                f,
209                "function {function} declares arity {arity} but only {num_registers} registers"
210            ),
211            VerifyError::CallArity {
212                at,
213                function,
214                argc,
215                arity,
216            } => write!(
217                f,
218                "instruction {at} invokes function {function} with {argc} arguments, arity is {arity}"
219            ),
220            VerifyError::ForbiddenConstant { index, kind } => {
221                write!(f, "untrusted constant[{index}] must not embed {kind}")
222            }
223            VerifyError::FallThrough {
224                function,
225                at,
226                next_entry,
227            } => write!(
228                f,
229                "function {function} falls through at instruction {at} into the function at {next_entry}"
230            ),
231            VerifyError::BadImmediate { at, what } => {
232                write!(f, "instruction {at} has an invalid {what}")
233            }
234        }
235    }
236}
237
238impl std::error::Error for VerifyError {}
239
240/// Verify structural invariants of `chunk`. See [`VerifyError`] for what is
241/// checked. This does **not** perform full dataflow/register-liveness
242/// verification (unlike, say, the JVM verifier) — v0 trades that off
243/// against implementation complexity, and instead the VM bounds-checks
244/// register indices at runtime (cheap: it's an array index against a fixed
245/// small register file, not worth statically proving away yet).
246///
247/// The one register fact that *is* settled statically is
248/// [`VerifyError::ArityExceedsRegisters`]. It belongs here rather than in
249/// the VM because it is a property of the function table, not of an
250/// execution: such a function cannot be entered at all, so letting it reach
251/// the interpreter only moves the same rejection later and per call.
252/// [`VerifyError::FallThrough`] is the same kind of fact for control flow:
253/// a span that reaches the next `entry` runs that body on the wrong frame.
254///
255/// `Opcode::CallNative` targets are deliberately **not** range-checked
256/// here: native functions live in a `byteflow_vm::NativeTable` supplied by
257/// the embedder at `Vm` construction time, entirely outside this crate's
258/// (and this `Chunk`'s) knowledge. An out-of-range `CallNative` is instead
259/// caught at runtime as `Fault::BadNative`.
260pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
261    verify_with(chunk, VerifyConfig::default())
262}
263
264/// Like [`verify`], with an explicit [`VerifyConfig`].
265pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
266    if chunk.functions.is_empty() {
267        return Err(VerifyError::EmptyFunctionTable);
268    }
269
270    for (index, value) in chunk.constants.iter().enumerate() {
271        validate_constant(value, config.trust, index)?;
272    }
273
274    let len = chunk.code.len();
275
276    // `enumerate` rather than looking the index back up by name: two
277    // functions may share a name, and a search would then report the wrong
278    // one (and cost O(n²) doing it).
279    for (function, def) in chunk.functions.iter().enumerate() {
280        if def.entry as usize >= len {
281            return Err(VerifyError::EntryOutOfRange {
282                function,
283                entry: def.entry,
284                len,
285            });
286        }
287        if def.arity > def.num_registers {
288            return Err(VerifyError::ArityExceedsRegisters {
289                function,
290                arity: def.arity,
291                num_registers: def.num_registers,
292            });
293        }
294    }
295
296    for (at, instr) in chunk.code.iter().enumerate() {
297        match instr.op {
298            Opcode::LoadConst => {
299                let idx = instr.imm as u32;
300                if idx as usize >= chunk.constants.len() {
301                    return Err(VerifyError::ConstOutOfRange {
302                        at,
303                        index: idx,
304                        len: chunk.constants.len(),
305                    });
306                }
307            }
308            Opcode::Call | Opcode::Spawn => {
309                let idx = instr.imm as u32;
310                if idx as usize >= chunk.functions.len() {
311                    return Err(VerifyError::FunctionOutOfRange {
312                        at,
313                        index: idx,
314                        len: chunk.functions.len(),
315                    });
316                }
317                let arity = chunk.functions[idx as usize].arity;
318                if instr.b != arity {
319                    return Err(VerifyError::CallArity {
320                        at,
321                        function: idx,
322                        argc: instr.b,
323                        arity,
324                    });
325                }
326            }
327            Opcode::StartChild => {
328                let idx = instr.imm as u32;
329                if idx as usize >= chunk.functions.len() {
330                    return Err(VerifyError::FunctionOutOfRange {
331                        at,
332                        index: idx,
333                        len: chunk.functions.len(),
334                    });
335                }
336                // The opcode carries a restart policy, not an argument list.
337                // The supervisor starts the child with an empty window.
338                let arity = chunk.functions[idx as usize].arity;
339                if arity != 0 {
340                    return Err(VerifyError::CallArity {
341                        at,
342                        function: idx,
343                        argc: 0,
344                        arity,
345                    });
346                }
347            }
348            // `CallNative` targets a `byteflow_vm::NativeTable` supplied at
349            // runtime, outside this chunk — see this function's doc
350            // comment. Not checked here; checked as `Fault::BadNative` at
351            // call time instead.
352            Opcode::CallNative | Opcode::CallNativeFrom => {}
353            Opcode::ListPack | Opcode::RecordPack => {
354                let max = if instr.op == Opcode::ListPack {
355                    super::value::MAX_LIST_LEN
356                } else {
357                    super::value::MAX_RECORD_LEN
358                };
359                check_pack(at, instr.b, instr.imm, 1, max)?;
360            }
361            Opcode::MapPack => {
362                check_pack(at, instr.b, instr.imm, 2, super::value::MAX_MAP_LEN)?;
363            }
364            Opcode::ReceiveMatchKind => {
365                if !(0..=10).contains(&instr.imm) {
366                    return Err(VerifyError::BadImmediate {
367                        at,
368                        what: "payload kind",
369                    });
370                }
371            }
372            Opcode::ReceiveMatchCmp => {
373                if super::opcode::IntCmp::from_imm(instr.imm).is_none() {
374                    return Err(VerifyError::BadImmediate {
375                        at,
376                        what: "compare immediate",
377                    });
378                }
379            }
380            Opcode::Jump | Opcode::Branch => {
381                let target = at as i64 + 1 + instr.imm as i64;
382                if target < 0 || target as usize > len {
383                    // == len is allowed: jumping to "one past the end" is a
384                    // valid way to fall off the end of the chunk.
385                    return Err(VerifyError::JumpOutOfRange { at, target, len });
386                }
387                // A jump may stay inside the function that contains `at`, or
388                // land exactly at `code.len()` (implicit return). Landing on
389                // another function's body would run that code with this frame.
390                if let Some((start, end)) = function_span(&chunk.functions, at, len) {
391                    let t = target as usize;
392                    if t != len && (t < start || t >= end) {
393                        return Err(VerifyError::JumpOutOfRange { at, target, len });
394                    }
395                }
396            }
397            _ => {}
398        }
399    }
400
401    reject_fallthrough(chunk)?;
402    Ok(())
403}
404
405/// `width` is 1 for a list or record and 2 for a map pair.
406///
407/// Register 255 is not a slot: `num_registers` is a `u8`, so the highest
408/// index a frame can name is 254. A pack whose exclusive end is above 255
409/// would gather that index.
410fn check_pack(
411    at: usize,
412    base: u8,
413    count: i32,
414    width: u32,
415    max_len: usize,
416) -> Result<(), VerifyError> {
417    let max = match i32::try_from(max_len) {
418        Ok(n) => n,
419        Err(_) => i32::MAX,
420    };
421    if !(0..=max).contains(&count) {
422        return Err(VerifyError::BadImmediate {
423            at,
424            what: "pack length",
425        });
426    }
427    if count == 0 {
428        return Ok(());
429    }
430    let span = match u32::try_from(count).ok().and_then(|n| n.checked_mul(width)) {
431        Some(n) => n,
432        None => {
433            return Err(VerifyError::BadImmediate {
434                at,
435                what: "pack window",
436            })
437        }
438    };
439    let end = match u32::from(base).checked_add(span) {
440        Some(n) => n,
441        None => {
442            return Err(VerifyError::BadImmediate {
443                at,
444                what: "pack window",
445            })
446        }
447    };
448    if end > 255 {
449        return Err(VerifyError::BadImmediate {
450            at,
451            what: "pack window",
452        });
453    }
454    Ok(())
455}
456
457/// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` never execute the next
458/// instruction. Every other opcode can: `Branch` falls through when the
459/// condition is false, and `Call` / `Yield` / `Send` resume at `pc + 1`.
460fn is_terminator(op: Opcode) -> bool {
461    matches!(
462        op,
463        Opcode::Jump | Opcode::Return | Opcode::Halt | Opcode::Exit | Opcode::Trap
464    )
465}
466
467/// Smallest function `entry` strictly after `start`, or `code_len` when
468/// this span runs to the end of the chunk.
469fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
470    let mut end = code_len;
471    for def in functions {
472        let entry = def.entry as usize;
473        if entry > start && entry < end {
474            end = entry;
475        }
476    }
477    end
478}
479
480/// Each function whose span ends at another `entry` must close with a
481/// terminator. Falling off `code.len()` is the implicit return and stays
482/// legal. A span that does not extend past `start` has no instruction to
483/// check (two functions sharing an `entry`).
484fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
485    let len = chunk.code.len();
486    for (function, def) in chunk.functions.iter().enumerate() {
487        let start = def.entry as usize;
488        let end = exclusive_end(&chunk.functions, start, len);
489        if end >= len || end <= start {
490            continue;
491        }
492        let at = end - 1;
493        if !is_terminator(chunk.code[at].op) {
494            return Err(VerifyError::FallThrough {
495                function,
496                at,
497                next_entry: end,
498            });
499        }
500    }
501    Ok(())
502}
503
504/// Instruction range owned by the function whose `entry` is the greatest
505/// entry `<= at`. The end is the next function entry, or `code_len`.
506fn function_span(
507    functions: &[super::chunk::FunctionDef],
508    at: usize,
509    code_len: usize,
510) -> Option<(usize, usize)> {
511    let mut start = None;
512    for def in functions {
513        let entry = def.entry as usize;
514        if entry <= at {
515            start = Some(match start {
516                Some(prev) if prev >= entry => prev,
517                _ => entry,
518            });
519        }
520    }
521    let start = start?;
522    let end = exclusive_end(functions, start, code_len);
523    if at >= end {
524        None
525    } else {
526        Some((start, end))
527    }
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533    use crate::bytecode::builder::ChunkBuilder;
534    use crate::bytecode::opcode::Opcode;
535
536    #[test]
537    fn rejects_empty_function_table() {
538        let chunk = Chunk::default();
539        assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
540    }
541
542    #[test]
543    fn accepts_well_formed_chunk() {
544        let mut b = ChunkBuilder::new("test");
545        b.begin_function("main", 0, 2);
546        let k = b.const_(crate::bytecode::value::Value::Int(41));
547        b.emit_load_const(0, k);
548        b.emit_load_imm(1, 1);
549        b.emit_binop(Opcode::Add, 0, 0, 1);
550        b.emit_return(0);
551        let chunk = b.finish();
552        assert!(verify(&chunk).is_ok());
553    }
554
555    /// A function the VM cannot even enter: entry copies `r0..arity`, but
556    /// the frame only has `num_registers` slots. Used to be accepted here and
557    /// then panic with an out-of-bounds index inside `Vm::new` / `Call`.
558    #[test]
559    fn rejects_arity_larger_than_the_register_file() {
560        let mut b = ChunkBuilder::new("test");
561        b.begin_function("main", 3, 1);
562        b.emit_return(0);
563        let chunk = b.finish();
564        assert_eq!(
565            verify(&chunk),
566            Err(VerifyError::ArityExceedsRegisters {
567                function: 0,
568                arity: 3,
569                num_registers: 1,
570            })
571        );
572    }
573
574    #[test]
575    fn accepts_arity_equal_to_the_register_file() {
576        let mut b = ChunkBuilder::new("test");
577        b.begin_function("main", 2, 2);
578        b.emit_return(0);
579        let chunk = b.finish();
580        assert!(verify(&chunk).is_ok());
581    }
582
583    #[test]
584    fn rejects_start_child_function_out_of_range() {
585        use crate::bytecode::instruction::Instruction;
586        let mut chunk = Chunk::default();
587        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
588            name: "main".into(),
589            entry: 0,
590            arity: 0,
591            num_registers: 1,
592        });
593        chunk
594            .code
595            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
596        assert!(matches!(
597            verify(&chunk),
598            Err(VerifyError::FunctionOutOfRange { index: 99, .. })
599        ));
600    }
601
602    #[test]
603    fn rejects_jump_into_another_function() {
604        use crate::bytecode::instruction::Instruction;
605        let mut chunk = Chunk::default();
606        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
607            name: "main".into(),
608            entry: 0,
609            arity: 0,
610            num_registers: 1,
611        });
612        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
613            name: "other".into(),
614            entry: 2,
615            arity: 0,
616            num_registers: 1,
617        });
618        // at 0, imm 1 → target 2, the other function's entry.
619        chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
620        chunk.code.push(Instruction::nullary(Opcode::Nop));
621        chunk.code.push(Instruction::nullary(Opcode::Nop));
622        assert!(matches!(
623            verify(&chunk),
624            Err(VerifyError::JumpOutOfRange { target: 2, .. })
625        ));
626    }
627
628    #[test]
629    fn rejects_out_of_range_jump() {
630        use crate::bytecode::instruction::Instruction;
631        let mut chunk = Chunk::default();
632        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
633            name: "main".into(),
634            entry: 0,
635            arity: 0,
636            num_registers: 1,
637        });
638        chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
639        assert!(matches!(
640            verify(&chunk),
641            Err(VerifyError::JumpOutOfRange { .. })
642        ));
643    }
644
645    fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
646        use crate::bytecode::instruction::Instruction;
647        let mut chunk = Chunk::default();
648        for (name, entry) in [("main", 0u32), ("other", 1)] {
649            chunk.functions.push(crate::bytecode::chunk::FunctionDef {
650                name: name.into(),
651                entry,
652                arity: 0,
653                num_registers: 1,
654            });
655        }
656        chunk.code.push(first);
657        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
658        chunk
659    }
660
661    #[test]
662    fn rejects_fallthrough_into_the_next_function() {
663        use crate::bytecode::instruction::Instruction;
664        let boundary = VerifyError::FallThrough {
665            function: 0,
666            at: 0,
667            next_entry: 1,
668        };
669        for first in [
670            Instruction::nullary(Opcode::Nop),
671            Instruction::a_imm(Opcode::Branch, 0, -1),
672            Instruction::new(Opcode::Call, 0, 0, 0, 1),
673        ] {
674            assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
675        }
676    }
677
678    #[test]
679    fn accepts_jump_closing_a_function_before_the_next() {
680        use crate::bytecode::instruction::Instruction;
681        // target = 0 + 1 + (-1) = 0, still inside `main`.
682        let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
683        assert!(verify(&chunk).is_ok());
684    }
685
686    #[test]
687    fn rejects_call_whose_argc_differs_from_the_callee() {
688        use crate::bytecode::instruction::Instruction;
689        let mut chunk = Chunk::default();
690        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
691            name: "main".into(),
692            entry: 0,
693            arity: 0,
694            num_registers: 1,
695        });
696        chunk.code.push(Instruction::new(Opcode::Call, 0, 1, 0, 0));
697        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
698        assert_eq!(
699            verify(&chunk),
700            Err(VerifyError::CallArity {
701                at: 0,
702                function: 0,
703                argc: 1,
704                arity: 0,
705            })
706        );
707    }
708
709    #[test]
710    fn rejects_spawn_whose_argc_differs_from_the_callee() {
711        use crate::bytecode::instruction::Instruction;
712        let mut chunk = Chunk::default();
713        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
714            name: "main".into(),
715            entry: 0,
716            arity: 2,
717            num_registers: 2,
718        });
719        chunk.code.push(Instruction::new(Opcode::Spawn, 0, 0, 0, 0));
720        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
721        assert_eq!(
722            verify(&chunk),
723            Err(VerifyError::CallArity {
724                at: 0,
725                function: 0,
726                argc: 0,
727                arity: 2,
728            })
729        );
730    }
731
732    #[test]
733    fn rejects_start_child_of_a_function_that_expects_arguments() {
734        use crate::bytecode::instruction::Instruction;
735        let mut chunk = Chunk::default();
736        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
737            name: "main".into(),
738            entry: 0,
739            arity: 1,
740            num_registers: 1,
741        });
742        chunk
743            .code
744            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 0));
745        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
746        assert_eq!(
747            verify(&chunk),
748            Err(VerifyError::CallArity {
749                at: 0,
750                function: 0,
751                argc: 0,
752                arity: 1,
753            })
754        );
755    }
756
757    #[test]
758    fn accepts_implicit_return_on_the_last_function() {
759        use crate::bytecode::instruction::Instruction;
760        let mut chunk = Chunk::default();
761        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
762            name: "main".into(),
763            entry: 0,
764            arity: 0,
765            num_registers: 1,
766        });
767        chunk.code.push(Instruction::nullary(Opcode::Nop));
768        assert!(verify(&chunk).is_ok());
769    }
770
771    #[test]
772    fn untrusted_rejects_cap_pid_message_constants() {
773        use crate::bytecode::cap::CapId;
774        use crate::bytecode::value::Message;
775        for (value, kind) in [
776            (
777                crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
778                ConstantKind::Capability,
779            ),
780            (
781                crate::bytecode::value::Value::Pid(7),
782                ConstantKind::ProcessId,
783            ),
784            (
785                crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
786                ConstantKind::Message,
787            ),
788        ] {
789            let mut b = ChunkBuilder::new("forge");
790            b.begin_function("main", 0, 1);
791            let k = b.const_(value);
792            b.emit_load_const(0, k);
793            b.emit_return(0);
794            let chunk = b.finish();
795            assert_eq!(
796                verify(&chunk),
797                Err(VerifyError::ForbiddenConstant { index: 0, kind })
798            );
799            assert!(verify_with(
800                &chunk,
801                VerifyConfig {
802                    trust: TrustLevel::Trusted
803                }
804            )
805            .is_ok());
806        }
807    }
808
809    #[test]
810    fn untrusted_rejects_authority_nested_in_a_list() {
811        use crate::bytecode::cap::CapId;
812        use crate::bytecode::value::{Message, Value};
813        let cases = [
814            (
815                Value::try_list(vec![Value::Int(1), Value::Cap(CapId::from_raw(1))]),
816                ConstantKind::Capability,
817            ),
818            (
819                Value::try_list(vec![Value::Pid(7)]),
820                ConstantKind::ProcessId,
821            ),
822            (
823                Value::try_list(vec![Value::Message(Message::new(1, 2, 3, 4u64))]),
824                ConstantKind::Message,
825            ),
826        ];
827        for (value, kind) in cases {
828            assert!(value.is_some());
829            let Some(value) = value else {
830                return;
831            };
832            let mut b = ChunkBuilder::new("nested-forge");
833            b.begin_function("main", 0, 1);
834            let k = b.const_(value);
835            b.emit_load_const(0, k);
836            b.emit_return(0);
837            let chunk = b.finish();
838            assert_eq!(
839                verify(&chunk),
840                Err(VerifyError::ForbiddenConstant { index: 0, kind })
841            );
842            assert!(verify_with(
843                &chunk,
844                VerifyConfig {
845                    trust: TrustLevel::Trusted
846                }
847            )
848            .is_ok());
849        }
850    }
851
852    #[test]
853    fn pack_window_past_the_register_file_is_rejected() {
854        let mut b = ChunkBuilder::new("wide");
855        b.begin_function("main", 0, 255);
856        b.emit_list_pack(0, 250, 10);
857        b.emit_return(0);
858        let chunk = b.finish();
859        assert_eq!(
860            verify(&chunk),
861            Err(VerifyError::BadImmediate {
862                at: 0,
863                what: "pack window",
864            })
865        );
866    }
867
868    #[test]
869    fn pack_length_above_the_value_cap_is_rejected() {
870        let mut b = ChunkBuilder::new("long");
871        b.begin_function("main", 0, 1);
872        b.emit_record_pack(0, 0, 257);
873        b.emit_return(0);
874        let chunk = b.finish();
875        assert_eq!(
876            verify(&chunk),
877            Err(VerifyError::BadImmediate {
878                at: 0,
879                what: "pack length",
880            })
881        );
882    }
883
884    #[test]
885    fn receive_kind_outside_the_scalar_range_is_rejected() {
886        let mut b = ChunkBuilder::new("kind");
887        b.begin_function("main", 0, 1);
888        b.emit_receive_match_kind(0, 11);
889        b.emit_return(0);
890        let chunk = b.finish();
891        assert_eq!(
892            verify(&chunk),
893            Err(VerifyError::BadImmediate {
894                at: 0,
895                what: "payload kind",
896            })
897        );
898    }
899
900    #[test]
901    fn receive_compare_outside_int_cmp_is_rejected() {
902        let mut b = ChunkBuilder::new("cmp");
903        b.begin_function("main", 0, 2);
904        b.emit_receive_match_cmp(0, 0, 1, crate::bytecode::opcode::IntCmp::Eq);
905        b.emit_return(0);
906        let mut chunk = b.finish();
907        chunk.code[0].imm = 9;
908        assert_eq!(
909            verify(&chunk),
910            Err(VerifyError::BadImmediate {
911                at: 0,
912                what: "compare immediate",
913            })
914        );
915    }
916
917    #[test]
918    fn a_short_list_pack_still_verifies() {
919        let mut b = ChunkBuilder::new("ok-pack");
920        b.begin_function("main", 0, 3);
921        b.emit_list_pack(2, 0, 2);
922        b.emit_return(2);
923        let chunk = b.finish();
924        assert!(verify(&chunk).is_ok());
925    }
926}