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    /// Untrusted chunk embedded a Cap, Pid, or Message in the constant pool.
118    ForbiddenConstant {
119        index: usize,
120        kind: ConstantKind,
121    },
122    /// The instruction before the next function's `entry` can continue, so
123    /// the VM would run that body on this function's register window.
124    /// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` close the span.
125    /// `Branch` and `Call` do not: both can execute the following instruction.
126    FallThrough {
127        function: usize,
128        at: usize,
129        next_entry: usize,
130    },
131}
132
133impl fmt::Display for VerifyError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            VerifyError::UnknownOpcode { at, byte } => {
137                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
138            }
139            VerifyError::ConstOutOfRange { at, index, len } => write!(
140                f,
141                "instruction {at} references constant {index}, pool has {len} entries"
142            ),
143            VerifyError::FunctionOutOfRange { at, index, len } => write!(
144                f,
145                "instruction {at} references function {index}, table has {len} entries"
146            ),
147            VerifyError::JumpOutOfRange { at, target, len } => write!(
148                f,
149                "instruction {at} jumps to {target}, out of code bounds (len={len})"
150            ),
151            VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
152            VerifyError::EntryOutOfRange {
153                function,
154                entry,
155                len,
156            } => write!(
157                f,
158                "function {function} entry point {entry} is out of code bounds (len={len})"
159            ),
160            VerifyError::ArityExceedsRegisters {
161                function,
162                arity,
163                num_registers,
164            } => write!(
165                f,
166                "function {function} declares arity {arity} but only {num_registers} registers"
167            ),
168            VerifyError::ForbiddenConstant { index, kind } => {
169                write!(f, "untrusted constant[{index}] must not embed {kind}")
170            }
171            VerifyError::FallThrough {
172                function,
173                at,
174                next_entry,
175            } => write!(
176                f,
177                "function {function} falls through at instruction {at} into the function at {next_entry}"
178            ),
179        }
180    }
181}
182
183impl std::error::Error for VerifyError {}
184
185/// Verify structural invariants of `chunk`. See [`VerifyError`] for what is
186/// checked. This does **not** perform full dataflow/register-liveness
187/// verification (unlike, say, the JVM verifier) — v0 trades that off
188/// against implementation complexity, and instead the VM bounds-checks
189/// register indices at runtime (cheap: it's an array index against a fixed
190/// small register file, not worth statically proving away yet).
191///
192/// The one register fact that *is* settled statically is
193/// [`VerifyError::ArityExceedsRegisters`]. It belongs here rather than in
194/// the VM because it is a property of the function table, not of an
195/// execution: such a function cannot be entered at all, so letting it reach
196/// the interpreter only moves the same rejection later and per call.
197/// [`VerifyError::FallThrough`] is the same kind of fact for control flow:
198/// a span that reaches the next `entry` runs that body on the wrong frame.
199///
200/// `Opcode::CallNative` targets are deliberately **not** range-checked
201/// here: native functions live in a `byteflow_vm::NativeTable` supplied by
202/// the embedder at `Vm` construction time, entirely outside this crate's
203/// (and this `Chunk`'s) knowledge. An out-of-range `CallNative` is instead
204/// caught at runtime as `Fault::BadNative`.
205pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
206    verify_with(chunk, VerifyConfig::default())
207}
208
209/// Like [`verify`], with an explicit [`VerifyConfig`].
210pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
211    if chunk.functions.is_empty() {
212        return Err(VerifyError::EmptyFunctionTable);
213    }
214
215    for (index, value) in chunk.constants.iter().enumerate() {
216        validate_constant(value, config.trust, index)?;
217    }
218
219    let len = chunk.code.len();
220
221    // `enumerate` rather than looking the index back up by name: two
222    // functions may share a name, and a search would then report the wrong
223    // one (and cost O(n²) doing it).
224    for (function, def) in chunk.functions.iter().enumerate() {
225        if def.entry as usize >= len {
226            return Err(VerifyError::EntryOutOfRange {
227                function,
228                entry: def.entry,
229                len,
230            });
231        }
232        if def.arity > def.num_registers {
233            return Err(VerifyError::ArityExceedsRegisters {
234                function,
235                arity: def.arity,
236                num_registers: def.num_registers,
237            });
238        }
239    }
240
241    for (at, instr) in chunk.code.iter().enumerate() {
242        match instr.op {
243            Opcode::LoadConst => {
244                let idx = instr.imm as u32;
245                if idx as usize >= chunk.constants.len() {
246                    return Err(VerifyError::ConstOutOfRange {
247                        at,
248                        index: idx,
249                        len: chunk.constants.len(),
250                    });
251                }
252            }
253            Opcode::Spawn | Opcode::Call | Opcode::StartChild => {
254                let idx = instr.imm as u32;
255                if idx as usize >= chunk.functions.len() {
256                    return Err(VerifyError::FunctionOutOfRange {
257                        at,
258                        index: idx,
259                        len: chunk.functions.len(),
260                    });
261                }
262            }
263            // `CallNative` targets a `byteflow_vm::NativeTable` supplied at
264            // runtime, outside this chunk — see this function's doc
265            // comment. Not checked here; checked as `Fault::BadNative` at
266            // call time instead.
267            Opcode::CallNative => {}
268            Opcode::Jump | Opcode::Branch => {
269                let target = at as i64 + 1 + instr.imm as i64;
270                if target < 0 || target as usize > len {
271                    // == len is allowed: jumping to "one past the end" is a
272                    // valid way to fall off the end of the chunk.
273                    return Err(VerifyError::JumpOutOfRange { at, target, len });
274                }
275                // A jump may stay inside the function that contains `at`, or
276                // land exactly at `code.len()` (implicit return). Landing on
277                // another function's body would run that code with this frame.
278                if let Some((start, end)) = function_span(&chunk.functions, at, len) {
279                    let t = target as usize;
280                    if t != len && (t < start || t >= end) {
281                        return Err(VerifyError::JumpOutOfRange { at, target, len });
282                    }
283                }
284            }
285            _ => {}
286        }
287    }
288
289    reject_fallthrough(chunk)?;
290    Ok(())
291}
292
293/// `Jump`, `Return`, `Halt`, `Exit`, and `Trap` never execute the next
294/// instruction. Every other opcode can: `Branch` falls through when the
295/// condition is false, and `Call` / `Yield` / `Send` resume at `pc + 1`.
296fn is_terminator(op: Opcode) -> bool {
297    matches!(
298        op,
299        Opcode::Jump | Opcode::Return | Opcode::Halt | Opcode::Exit | Opcode::Trap
300    )
301}
302
303/// Smallest function `entry` strictly after `start`, or `code_len` when
304/// this span runs to the end of the chunk.
305fn exclusive_end(functions: &[super::chunk::FunctionDef], start: usize, code_len: usize) -> usize {
306    let mut end = code_len;
307    for def in functions {
308        let entry = def.entry as usize;
309        if entry > start && entry < end {
310            end = entry;
311        }
312    }
313    end
314}
315
316/// Each function whose span ends at another `entry` must close with a
317/// terminator. Falling off `code.len()` is the implicit return and stays
318/// legal. A span that does not extend past `start` has no instruction to
319/// check (two functions sharing an `entry`).
320fn reject_fallthrough(chunk: &Chunk) -> Result<(), VerifyError> {
321    let len = chunk.code.len();
322    for (function, def) in chunk.functions.iter().enumerate() {
323        let start = def.entry as usize;
324        let end = exclusive_end(&chunk.functions, start, len);
325        if end >= len || end <= start {
326            continue;
327        }
328        let at = end - 1;
329        if !is_terminator(chunk.code[at].op) {
330            return Err(VerifyError::FallThrough {
331                function,
332                at,
333                next_entry: end,
334            });
335        }
336    }
337    Ok(())
338}
339
340/// Instruction range owned by the function whose `entry` is the greatest
341/// entry `<= at`. The end is the next function entry, or `code_len`.
342fn function_span(
343    functions: &[super::chunk::FunctionDef],
344    at: usize,
345    code_len: usize,
346) -> Option<(usize, usize)> {
347    let mut start = None;
348    for def in functions {
349        let entry = def.entry as usize;
350        if entry <= at {
351            start = Some(match start {
352                Some(prev) if prev >= entry => prev,
353                _ => entry,
354            });
355        }
356    }
357    let start = start?;
358    let end = exclusive_end(functions, start, code_len);
359    if at >= end {
360        None
361    } else {
362        Some((start, end))
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369    use crate::bytecode::builder::ChunkBuilder;
370    use crate::bytecode::opcode::Opcode;
371
372    #[test]
373    fn rejects_empty_function_table() {
374        let chunk = Chunk::default();
375        assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
376    }
377
378    #[test]
379    fn accepts_well_formed_chunk() {
380        let mut b = ChunkBuilder::new("test");
381        b.begin_function("main", 0, 2);
382        let k = b.const_(crate::bytecode::value::Value::Int(41));
383        b.emit_load_const(0, k);
384        b.emit_load_imm(1, 1);
385        b.emit_binop(Opcode::Add, 0, 0, 1);
386        b.emit_return(0);
387        let chunk = b.finish();
388        assert!(verify(&chunk).is_ok());
389    }
390
391    /// A function the VM cannot even enter: entry copies `r0..arity`, but
392    /// the frame only has `num_registers` slots. Used to be accepted here and
393    /// then panic with an out-of-bounds index inside `Vm::new` / `Call`.
394    #[test]
395    fn rejects_arity_larger_than_the_register_file() {
396        let mut b = ChunkBuilder::new("test");
397        b.begin_function("main", 3, 1);
398        b.emit_return(0);
399        let chunk = b.finish();
400        assert_eq!(
401            verify(&chunk),
402            Err(VerifyError::ArityExceedsRegisters {
403                function: 0,
404                arity: 3,
405                num_registers: 1,
406            })
407        );
408    }
409
410    #[test]
411    fn accepts_arity_equal_to_the_register_file() {
412        let mut b = ChunkBuilder::new("test");
413        b.begin_function("main", 2, 2);
414        b.emit_return(0);
415        let chunk = b.finish();
416        assert!(verify(&chunk).is_ok());
417    }
418
419    #[test]
420    fn rejects_start_child_function_out_of_range() {
421        use crate::bytecode::instruction::Instruction;
422        let mut chunk = Chunk::default();
423        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
424            name: "main".into(),
425            entry: 0,
426            arity: 0,
427            num_registers: 1,
428        });
429        chunk
430            .code
431            .push(Instruction::new(Opcode::StartChild, 0, 0, 0, 99));
432        assert!(matches!(
433            verify(&chunk),
434            Err(VerifyError::FunctionOutOfRange { index: 99, .. })
435        ));
436    }
437
438    #[test]
439    fn rejects_jump_into_another_function() {
440        use crate::bytecode::instruction::Instruction;
441        let mut chunk = Chunk::default();
442        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
443            name: "main".into(),
444            entry: 0,
445            arity: 0,
446            num_registers: 1,
447        });
448        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
449            name: "other".into(),
450            entry: 2,
451            arity: 0,
452            num_registers: 1,
453        });
454        // at 0, imm 1 → target 2, the other function's entry.
455        chunk.code.push(Instruction::only_imm(Opcode::Jump, 1));
456        chunk.code.push(Instruction::nullary(Opcode::Nop));
457        chunk.code.push(Instruction::nullary(Opcode::Nop));
458        assert!(matches!(
459            verify(&chunk),
460            Err(VerifyError::JumpOutOfRange { target: 2, .. })
461        ));
462    }
463
464    #[test]
465    fn rejects_out_of_range_jump() {
466        use crate::bytecode::instruction::Instruction;
467        let mut chunk = Chunk::default();
468        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
469            name: "main".into(),
470            entry: 0,
471            arity: 0,
472            num_registers: 1,
473        });
474        chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
475        assert!(matches!(
476            verify(&chunk),
477            Err(VerifyError::JumpOutOfRange { .. })
478        ));
479    }
480
481    fn two_functions(first: crate::bytecode::instruction::Instruction) -> Chunk {
482        use crate::bytecode::instruction::Instruction;
483        let mut chunk = Chunk::default();
484        for (name, entry) in [("main", 0u32), ("other", 1)] {
485            chunk.functions.push(crate::bytecode::chunk::FunctionDef {
486                name: name.into(),
487                entry,
488                arity: 0,
489                num_registers: 1,
490            });
491        }
492        chunk.code.push(first);
493        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
494        chunk
495    }
496
497    #[test]
498    fn rejects_fallthrough_into_the_next_function() {
499        use crate::bytecode::instruction::Instruction;
500        let boundary = VerifyError::FallThrough {
501            function: 0,
502            at: 0,
503            next_entry: 1,
504        };
505        for first in [
506            Instruction::nullary(Opcode::Nop),
507            Instruction::a_imm(Opcode::Branch, 0, -1),
508            Instruction::new(Opcode::Call, 0, 0, 0, 1),
509        ] {
510            assert_eq!(verify(&two_functions(first)), Err(boundary.clone()));
511        }
512    }
513
514    #[test]
515    fn accepts_jump_closing_a_function_before_the_next() {
516        use crate::bytecode::instruction::Instruction;
517        // target = 0 + 1 + (-1) = 0, still inside `main`.
518        let chunk = two_functions(Instruction::only_imm(Opcode::Jump, -1));
519        assert!(verify(&chunk).is_ok());
520    }
521
522    #[test]
523    fn accepts_implicit_return_on_the_last_function() {
524        use crate::bytecode::instruction::Instruction;
525        let mut chunk = Chunk::default();
526        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
527            name: "main".into(),
528            entry: 0,
529            arity: 0,
530            num_registers: 1,
531        });
532        chunk.code.push(Instruction::nullary(Opcode::Nop));
533        assert!(verify(&chunk).is_ok());
534    }
535
536    #[test]
537    fn untrusted_rejects_cap_pid_message_constants() {
538        use crate::bytecode::cap::CapId;
539        use crate::bytecode::value::Message;
540        for (value, kind) in [
541            (
542                crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
543                ConstantKind::Capability,
544            ),
545            (
546                crate::bytecode::value::Value::Pid(7),
547                ConstantKind::ProcessId,
548            ),
549            (
550                crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
551                ConstantKind::Message,
552            ),
553        ] {
554            let mut b = ChunkBuilder::new("forge");
555            b.begin_function("main", 0, 1);
556            let k = b.const_(value);
557            b.emit_load_const(0, k);
558            b.emit_return(0);
559            let chunk = b.finish();
560            assert_eq!(
561                verify(&chunk),
562                Err(VerifyError::ForbiddenConstant { index: 0, kind })
563            );
564            assert!(verify_with(
565                &chunk,
566                VerifyConfig {
567                    trust: TrustLevel::Trusted
568                }
569            )
570            .is_ok());
571        }
572    }
573}