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    match value {
54        Value::Cap(_) => Err(VerifyError::ForbiddenConstant {
55            index,
56            kind: ConstantKind::Capability,
57        }),
58        Value::Pid(_) => Err(VerifyError::ForbiddenConstant {
59            index,
60            kind: ConstantKind::ProcessId,
61        }),
62        Value::Message(_) => Err(VerifyError::ForbiddenConstant {
63            index,
64            kind: ConstantKind::Message,
65        }),
66        _ => Ok(()),
67    }
68}
69
70/// Why a [`Chunk`] failed verification.
71///
72/// The verifier's job is to make every fact the interpreter's hot loop
73/// relies on (jump targets in range, constant/function indices in range)
74/// true *before* a single instruction runs, so `byteflow-vm` never has to
75/// re-check them per-step. Skipping this on trusted, compiler-generated
76/// bytecode is fine; it is mandatory before loading anything that crossed a
77/// trust boundary (a plugin, a network-fetched module, see design notes
78/// §24 capability/sandboxing).
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum VerifyError {
81    UnknownOpcode {
82        at: usize,
83        byte: u8,
84    },
85    ConstOutOfRange {
86        at: usize,
87        index: u32,
88        len: usize,
89    },
90    FunctionOutOfRange {
91        at: usize,
92        index: u32,
93        len: usize,
94    },
95    JumpOutOfRange {
96        at: usize,
97        target: i64,
98        len: usize,
99    },
100    EmptyFunctionTable,
101    EntryOutOfRange {
102        function: usize,
103        entry: u32,
104        len: usize,
105    },
106    /// A function declares more parameters than it has registers to hold
107    /// them. The VM loads `r0..arity` on entry, so this makes the very first
108    /// thing a call does — copying arguments in — reach past the register
109    /// file. Cheap to settle here: it is a static property of the function
110    /// table, one comparison per function, and no amount of runtime checking
111    /// makes such a function callable.
112    ArityExceedsRegisters {
113        function: usize,
114        arity: u8,
115        num_registers: u8,
116    },
117    /// `Call` or `Spawn` passes a different argument count than the callee
118    /// declares. `StartChild` is the same fact with `argc == 0`: the opcode
119    /// has no argument window, so a non-zero arity would enter as `Unit`.
120    CallArity {
121        at: usize,
122        function: u32,
123        argc: u8,
124        arity: u8,
125    },
126    /// Untrusted chunk embedded a Cap, Pid, or Message in the constant pool.
127    ForbiddenConstant {
128        index: usize,
129        kind: ConstantKind,
130    },
131    /// The instruction before the next function's `entry` can continue, so
132    /// the VM would run that body on this function's register window.
133    /// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` close the span.
134    /// `Branch` and `Call` do not: both can execute the following instruction.
135    FallThrough {
136        function: usize,
137        at: usize,
138        next_entry: usize,
139    },
140}
141
142impl fmt::Display for VerifyError {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        match self {
145            VerifyError::UnknownOpcode { at, byte } => {
146                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
147            }
148            VerifyError::ConstOutOfRange { at, index, len } => write!(
149                f,
150                "instruction {at} references constant {index}, pool has {len} entries"
151            ),
152            VerifyError::FunctionOutOfRange { at, index, len } => write!(
153                f,
154                "instruction {at} references function {index}, table has {len} entries"
155            ),
156            VerifyError::JumpOutOfRange { at, target, len } => write!(
157                f,
158                "instruction {at} jumps to {target}, out of code bounds (len={len})"
159            ),
160            VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
161            VerifyError::EntryOutOfRange {
162                function,
163                entry,
164                len,
165            } => write!(
166                f,
167                "function {function} entry point {entry} is out of code bounds (len={len})"
168            ),
169            VerifyError::ArityExceedsRegisters {
170                function,
171                arity,
172                num_registers,
173            } => write!(
174                f,
175                "function {function} declares arity {arity} but only {num_registers} registers"
176            ),
177            VerifyError::CallArity {
178                at,
179                function,
180                argc,
181                arity,
182            } => write!(
183                f,
184                "instruction {at} invokes function {function} with {argc} arguments, arity is {arity}"
185            ),
186            VerifyError::ForbiddenConstant { index, kind } => {
187                write!(f, "untrusted constant[{index}] must not embed {kind}")
188            }
189            VerifyError::FallThrough {
190                function,
191                at,
192                next_entry,
193            } => write!(
194                f,
195                "function {function} falls through at instruction {at} into the function at {next_entry}"
196            ),
197        }
198    }
199}
200
201impl std::error::Error for VerifyError {}
202
203/// Verify structural invariants of `chunk`. See [`VerifyError`] for what is
204/// checked. This does **not** perform full dataflow/register-liveness
205/// verification (unlike, say, the JVM verifier) — v0 trades that off
206/// against implementation complexity, and instead the VM bounds-checks
207/// register indices at runtime (cheap: it's an array index against a fixed
208/// small register file, not worth statically proving away yet).
209///
210/// The one register fact that *is* settled statically is
211/// [`VerifyError::ArityExceedsRegisters`]. It belongs here rather than in
212/// the VM because it is a property of the function table, not of an
213/// execution: such a function cannot be entered at all, so letting it reach
214/// the interpreter only moves the same rejection later and per call.
215/// [`VerifyError::FallThrough`] is the same kind of fact for control flow:
216/// a span that reaches the next `entry` runs that body on the wrong frame.
217///
218/// `Opcode::CallNative` targets are deliberately **not** range-checked
219/// here: native functions live in a `byteflow_vm::NativeTable` supplied by
220/// the embedder at `Vm` construction time, entirely outside this crate's
221/// (and this `Chunk`'s) knowledge. An out-of-range `CallNative` is instead
222/// caught at runtime as `Fault::BadNative`.
223pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
224    verify_with(chunk, VerifyConfig::default())
225}
226
227/// Like [`verify`], with an explicit [`VerifyConfig`].
228pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
229    if chunk.functions.is_empty() {
230        return Err(VerifyError::EmptyFunctionTable);
231    }
232
233    for (index, value) in chunk.constants.iter().enumerate() {
234        validate_constant(value, config.trust, index)?;
235    }
236
237    let len = chunk.code.len();
238
239    // `enumerate` rather than looking the index back up by name: two
240    // functions may share a name, and a search would then report the wrong
241    // one (and cost O(n²) doing it).
242    for (function, def) in chunk.functions.iter().enumerate() {
243        if def.entry as usize >= len {
244            return Err(VerifyError::EntryOutOfRange {
245                function,
246                entry: def.entry,
247                len,
248            });
249        }
250        if def.arity > def.num_registers {
251            return Err(VerifyError::ArityExceedsRegisters {
252                function,
253                arity: def.arity,
254                num_registers: def.num_registers,
255            });
256        }
257    }
258
259    for (at, instr) in chunk.code.iter().enumerate() {
260        match instr.op {
261            Opcode::LoadConst => {
262                let idx = instr.imm as u32;
263                if idx as usize >= chunk.constants.len() {
264                    return Err(VerifyError::ConstOutOfRange {
265                        at,
266                        index: idx,
267                        len: chunk.constants.len(),
268                    });
269                }
270            }
271            Opcode::Call | Opcode::Spawn => {
272                let idx = instr.imm as u32;
273                if idx as usize >= chunk.functions.len() {
274                    return Err(VerifyError::FunctionOutOfRange {
275                        at,
276                        index: idx,
277                        len: chunk.functions.len(),
278                    });
279                }
280                let arity = chunk.functions[idx as usize].arity;
281                if instr.b != arity {
282                    return Err(VerifyError::CallArity {
283                        at,
284                        function: idx,
285                        argc: instr.b,
286                        arity,
287                    });
288                }
289            }
290            Opcode::StartChild => {
291                let idx = instr.imm as u32;
292                if idx as usize >= chunk.functions.len() {
293                    return Err(VerifyError::FunctionOutOfRange {
294                        at,
295                        index: idx,
296                        len: chunk.functions.len(),
297                    });
298                }
299                // The opcode carries a restart policy, not an argument list.
300                // The supervisor starts the child with an empty window.
301                let arity = chunk.functions[idx as usize].arity;
302                if arity != 0 {
303                    return Err(VerifyError::CallArity {
304                        at,
305                        function: idx,
306                        argc: 0,
307                        arity,
308                    });
309                }
310            }
311            // `CallNative` targets a `byteflow_vm::NativeTable` supplied at
312            // runtime, outside this chunk — see this function's doc
313            // comment. Not checked here; checked as `Fault::BadNative` at
314            // call time instead.
315            Opcode::CallNative => {}
316            Opcode::Jump | Opcode::Branch => {
317                let target = at as i64 + 1 + instr.imm as i64;
318                if target < 0 || target as usize > len {
319                    // == len is allowed: jumping to "one past the end" is a
320                    // valid way to fall off the end of the chunk.
321                    return Err(VerifyError::JumpOutOfRange { at, target, len });
322                }
323                // A jump may stay inside the function that contains `at`, or
324                // land exactly at `code.len()` (implicit return). Landing on
325                // another function's body would run that code with this frame.
326                if let Some((start, end)) = function_span(&chunk.functions, at, len) {
327                    let t = target as usize;
328                    if t != len && (t < start || t >= end) {
329                        return Err(VerifyError::JumpOutOfRange { at, target, len });
330                    }
331                }
332            }
333            _ => {}
334        }
335    }
336
337    reject_fallthrough(chunk)?;
338    Ok(())
339}
340
341/// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` never execute the next
342/// instruction. Every other opcode can: `Branch` falls through when the
343/// condition is false, and `Call` / `Yield` / `Send` resume at `pc + 1`.
344fn is_terminator(op: Opcode) -> bool {
345    matches!(
346        op,
347        Opcode::Jump | Opcode::Return | Opcode::Halt | Opcode::Exit | Opcode::Trap
348    )
349}
350
351/// Smallest function `entry` strictly after `start`, or `code_len` when
352/// this span runs to the end of the chunk.
353fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
354    let mut end = code_len;
355    for def in functions {
356        let entry = def.entry as usize;
357        if entry > start && entry < end {
358            end = entry;
359        }
360    }
361    end
362}
363
364/// Each function whose span ends at another `entry` must close with a
365/// terminator. Falling off `code.len()` is the implicit return and stays
366/// legal. A span that does not extend past `start` has no instruction to
367/// check (two functions sharing an `entry`).
368fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
369    let len = chunk.code.len();
370    for (function, def) in chunk.functions.iter().enumerate() {
371        let start = def.entry as usize;
372        let end = exclusive_end(&chunk.functions, start, len);
373        if end >= len || end <= start {
374            continue;
375        }
376        let at = end - 1;
377        if !is_terminator(chunk.code[at].op) {
378            return Err(VerifyError::FallThrough {
379                function,
380                at,
381                next_entry: end,
382            });
383        }
384    }
385    Ok(())
386}
387
388/// Instruction range owned by the function whose `entry` is the greatest
389/// entry `<= at`. The end is the next function entry, or `code_len`.
390fn function_span(
391    functions: &[super::chunk::FunctionDef],
392    at: usize,
393    code_len: usize,
394) -> Option<(usize, usize)> {
395    let mut start = None;
396    for def in functions {
397        let entry = def.entry as usize;
398        if entry <= at {
399            start = Some(match start {
400                Some(prev) if prev >= entry => prev,
401                _ => entry,
402            });
403        }
404    }
405    let start = start?;
406    let end = exclusive_end(functions, start, code_len);
407    if at >= end {
408        None
409    } else {
410        Some((start, end))
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use crate::bytecode::builder::ChunkBuilder;
418    use crate::bytecode::opcode::Opcode;
419
420    #[test]
421    fn rejects_empty_function_table() {
422        let chunk = Chunk::default();
423        assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
424    }
425
426    #[test]
427    fn accepts_well_formed_chunk() {
428        let mut b = ChunkBuilder::new("test");
429        b.begin_function("main", 0, 2);
430        let k = b.const_(crate::bytecode::value::Value::Int(41));
431        b.emit_load_const(0, k);
432        b.emit_load_imm(1, 1);
433        b.emit_binop(Opcode::Add, 0, 0, 1);
434        b.emit_return(0);
435        let chunk = b.finish();
436        assert!(verify(&chunk).is_ok());
437    }
438
439    /// A function the VM cannot even enter: entry copies `r0..arity`, but
440    /// the frame only has `num_registers` slots. Used to be accepted here and
441    /// then panic with an out-of-bounds index inside `Vm::new` / `Call`.
442    #[test]
443    fn rejects_arity_larger_than_the_register_file() {
444        let mut b = ChunkBuilder::new("test");
445        b.begin_function("main", 3, 1);
446        b.emit_return(0);
447        let chunk = b.finish();
448        assert_eq!(
449            verify(&chunk),
450            Err(VerifyError::ArityExceedsRegisters {
451                function: 0,
452                arity: 3,
453                num_registers: 1,
454            })
455        );
456    }
457
458    #[test]
459    fn accepts_arity_equal_to_the_register_file() {
460        let mut b = ChunkBuilder::new("test");
461        b.begin_function("main", 2, 2);
462        b.emit_return(0);
463        let chunk = b.finish();
464        assert!(verify(&chunk).is_ok());
465    }
466
467    #[test]
468    fn rejects_start_child_function_out_of_range() {
469        use crate::bytecode::instruction::Instruction;
470        let mut chunk = Chunk::default();
471        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
472            name: "main".into(),
473            entry: 0,
474            arity: 0,
475            num_registers: 1,
476        });
477        chunk
478            .code
479            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
480        assert!(matches!(
481            verify(&chunk),
482            Err(VerifyError::FunctionOutOfRange { index: 99, .. })
483        ));
484    }
485
486    #[test]
487    fn rejects_jump_into_another_function() {
488        use crate::bytecode::instruction::Instruction;
489        let mut chunk = Chunk::default();
490        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
491            name: "main".into(),
492            entry: 0,
493            arity: 0,
494            num_registers: 1,
495        });
496        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
497            name: "other".into(),
498            entry: 2,
499            arity: 0,
500            num_registers: 1,
501        });
502        // at 0, imm 1 → target 2, the other function's entry.
503        chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
504        chunk.code.push(Instruction::nullary(Opcode::Nop));
505        chunk.code.push(Instruction::nullary(Opcode::Nop));
506        assert!(matches!(
507            verify(&chunk),
508            Err(VerifyError::JumpOutOfRange { target: 2, .. })
509        ));
510    }
511
512    #[test]
513    fn rejects_out_of_range_jump() {
514        use crate::bytecode::instruction::Instruction;
515        let mut chunk = Chunk::default();
516        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
517            name: "main".into(),
518            entry: 0,
519            arity: 0,
520            num_registers: 1,
521        });
522        chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
523        assert!(matches!(
524            verify(&chunk),
525            Err(VerifyError::JumpOutOfRange { .. })
526        ));
527    }
528
529    fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
530        use crate::bytecode::instruction::Instruction;
531        let mut chunk = Chunk::default();
532        for (name, entry) in [("main", 0u32), ("other", 1)] {
533            chunk.functions.push(crate::bytecode::chunk::FunctionDef {
534                name: name.into(),
535                entry,
536                arity: 0,
537                num_registers: 1,
538            });
539        }
540        chunk.code.push(first);
541        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
542        chunk
543    }
544
545    #[test]
546    fn rejects_fallthrough_into_the_next_function() {
547        use crate::bytecode::instruction::Instruction;
548        let boundary = VerifyError::FallThrough {
549            function: 0,
550            at: 0,
551            next_entry: 1,
552        };
553        for first in [
554            Instruction::nullary(Opcode::Nop),
555            Instruction::a_imm(Opcode::Branch, 0, -1),
556            Instruction::new(Opcode::Call, 0, 0, 0, 1),
557        ] {
558            assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
559        }
560    }
561
562    #[test]
563    fn accepts_jump_closing_a_function_before_the_next() {
564        use crate::bytecode::instruction::Instruction;
565        // target = 0 + 1 + (-1) = 0, still inside `main`.
566        let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
567        assert!(verify(&chunk).is_ok());
568    }
569
570    #[test]
571    fn rejects_call_whose_argc_differs_from_the_callee() {
572        use crate::bytecode::instruction::Instruction;
573        let mut chunk = Chunk::default();
574        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
575            name: "main".into(),
576            entry: 0,
577            arity: 0,
578            num_registers: 1,
579        });
580        chunk.code.push(Instruction::new(Opcode::Call, 0, 1, 0, 0));
581        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
582        assert_eq!(
583            verify(&chunk),
584            Err(VerifyError::CallArity {
585                at: 0,
586                function: 0,
587                argc: 1,
588                arity: 0,
589            })
590        );
591    }
592
593    #[test]
594    fn rejects_spawn_whose_argc_differs_from_the_callee() {
595        use crate::bytecode::instruction::Instruction;
596        let mut chunk = Chunk::default();
597        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
598            name: "main".into(),
599            entry: 0,
600            arity: 2,
601            num_registers: 2,
602        });
603        chunk.code.push(Instruction::new(Opcode::Spawn, 0, 0, 0, 0));
604        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
605        assert_eq!(
606            verify(&chunk),
607            Err(VerifyError::CallArity {
608                at: 0,
609                function: 0,
610                argc: 0,
611                arity: 2,
612            })
613        );
614    }
615
616    #[test]
617    fn rejects_start_child_of_a_function_that_expects_arguments() {
618        use crate::bytecode::instruction::Instruction;
619        let mut chunk = Chunk::default();
620        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
621            name: "main".into(),
622            entry: 0,
623            arity: 1,
624            num_registers: 1,
625        });
626        chunk
627            .code
628            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 0));
629        chunk.code.push(Instruction::abc(Opcode::Halt, 0, 0, 0));
630        assert_eq!(
631            verify(&chunk),
632            Err(VerifyError::CallArity {
633                at: 0,
634                function: 0,
635                argc: 0,
636                arity: 1,
637            })
638        );
639    }
640
641    #[test]
642    fn accepts_implicit_return_on_the_last_function() {
643        use crate::bytecode::instruction::Instruction;
644        let mut chunk = Chunk::default();
645        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
646            name: "main".into(),
647            entry: 0,
648            arity: 0,
649            num_registers: 1,
650        });
651        chunk.code.push(Instruction::nullary(Opcode::Nop));
652        assert!(verify(&chunk).is_ok());
653    }
654
655    #[test]
656    fn untrusted_rejects_cap_pid_message_constants() {
657        use crate::bytecode::cap::CapId;
658        use crate::bytecode::value::Message;
659        for (value, kind) in [
660            (
661                crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
662                ConstantKind::Capability,
663            ),
664            (
665                crate::bytecode::value::Value::Pid(7),
666                ConstantKind::ProcessId,
667            ),
668            (
669                crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
670                ConstantKind::Message,
671            ),
672        ] {
673            let mut b = ChunkBuilder::new("forge");
674            b.begin_function("main", 0, 1);
675            let k = b.const_(value);
676            b.emit_load_const(0, k);
677            b.emit_return(0);
678            let chunk = b.finish();
679            assert_eq!(
680                verify(&chunk),
681                Err(VerifyError::ForbiddenConstant { index: 0, kind })
682            );
683            assert!(verify_with(
684                &chunk,
685                VerifyConfig {
686                    trust: TrustLevel::Trusted
687                }
688            )
689            .is_ok());
690        }
691    }
692}