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}
123
124impl fmt::Display for VerifyError {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            VerifyError::UnknownOpcode { at, byte } => {
128                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
129            }
130            VerifyError::ConstOutOfRange { at, index, len } => write!(
131                f,
132                "instruction {at} references constant {index}, pool has {len} entries"
133            ),
134            VerifyError::FunctionOutOfRange { at, index, len } => write!(
135                f,
136                "instruction {at} references function {index}, table has {len} entries"
137            ),
138            VerifyError::JumpOutOfRange { at, target, len } => write!(
139                f,
140                "instruction {at} jumps to {target}, out of code bounds (len={len})"
141            ),
142            VerifyError::EmptyFunctionTable => write!(f, "chunk has no entry function"),
143            VerifyError::EntryOutOfRange {
144                function,
145                entry,
146                len,
147            } => write!(
148                f,
149                "function {function} entry point {entry} is out of code bounds (len={len})"
150            ),
151            VerifyError::ArityExceedsRegisters {
152                function,
153                arity,
154                num_registers,
155            } => write!(
156                f,
157                "function {function} declares arity {arity} but only {num_registers} registers"
158            ),
159            VerifyError::ForbiddenConstant { index, kind } => {
160                write!(f, "untrusted constant[{index}] must not embed {kind}")
161            }
162        }
163    }
164}
165
166impl std::error::Error for VerifyError {}
167
168/// Verify structural invariants of `chunk`. See [`VerifyError`] for what is
169/// checked. This does **not** perform full dataflow/register-liveness
170/// verification (unlike, say, the JVM verifier) — v0 trades that off
171/// against implementation complexity, and instead the VM bounds-checks
172/// register indices at runtime (cheap: it's an array index against a fixed
173/// small register file, not worth statically proving away yet).
174///
175/// The one register fact that *is* settled statically is
176/// [`VerifyError::ArityExceedsRegisters`]. It belongs here rather than in
177/// the VM because it is a property of the function table, not of an
178/// execution: such a function cannot be entered at all, so letting it reach
179/// the interpreter only moves the same rejection later and per call.
180///
181/// `Opcode::CallNative` targets are deliberately **not** range-checked
182/// here: native functions live in a `byteflow_vm::NativeTable` supplied by
183/// the embedder at `Vm` construction time, entirely outside this crate's
184/// (and this `Chunk`'s) knowledge. An out-of-range `CallNative` is instead
185/// caught at runtime as `Fault::BadNative`.
186pub fn verify(chunk: &Chunk) -> Result<(), VerifyError> {
187    verify_with(chunk, VerifyConfig::default())
188}
189
190/// Like [`verify`], with an explicit [`VerifyConfig`].
191pub fn verify_with(chunk: &Chunk, config: VerifyConfig) -> Result<(), VerifyError> {
192    if chunk.functions.is_empty() {
193        return Err(VerifyError::EmptyFunctionTable);
194    }
195
196    for (index, value) in chunk.constants.iter().enumerate() {
197        validate_constant(value, config.trust, index)?;
198    }
199
200    let len = chunk.code.len();
201
202    // `enumerate` rather than looking the index back up by name: two
203    // functions may share a name, and a search would then report the wrong
204    // one (and cost O(n²) doing it).
205    for (function, def) in chunk.functions.iter().enumerate() {
206        if def.entry as usize >= len {
207            return Err(VerifyError::EntryOutOfRange {
208                function,
209                entry: def.entry,
210                len,
211            });
212        }
213        if def.arity > def.num_registers {
214            return Err(VerifyError::ArityExceedsRegisters {
215                function,
216                arity: def.arity,
217                num_registers: def.num_registers,
218            });
219        }
220    }
221
222    for (at, instr) in chunk.code.iter().enumerate() {
223        match instr.op {
224            Opcode::LoadConst => {
225                let idx = instr.imm as u32;
226                if idx as usize >= chunk.constants.len() {
227                    return Err(VerifyError::ConstOutOfRange {
228                        at,
229                        index: idx,
230                        len: chunk.constants.len(),
231                    });
232                }
233            }
234            Opcode::Spawn | Opcode::Call => {
235                let idx = instr.imm as u32;
236                if idx as usize >= chunk.functions.len() {
237                    return Err(VerifyError::FunctionOutOfRange {
238                        at,
239                        index: idx,
240                        len: chunk.functions.len(),
241                    });
242                }
243            }
244            // `CallNative` targets a `byteflow_vm::NativeTable` supplied at
245            // runtime, outside this chunk — see this function's doc
246            // comment. Not checked here; checked as `Fault::BadNative` at
247            // call time instead.
248            Opcode::CallNative => {}
249            Opcode::Jump | Opcode::Branch => {
250                let target = at as i64 + 1 + instr.imm as i64;
251                if target < 0 || target as usize > len {
252                    // == len is allowed: jumping to "one past the end" is a
253                    // valid way to fall off the end of a function body.
254                    return Err(VerifyError::JumpOutOfRange { at, target, len });
255                }
256            }
257            _ => {}
258        }
259    }
260
261    Ok(())
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267    use crate::bytecode::builder::ChunkBuilder;
268    use crate::bytecode::opcode::Opcode;
269
270    #[test]
271    fn rejects_empty_function_table() {
272        let chunk = Chunk::default();
273        assert_eq!(verify(&chunk), Err(VerifyError::EmptyFunctionTable));
274    }
275
276    #[test]
277    fn accepts_well_formed_chunk() {
278        let mut b = ChunkBuilder::new("test");
279        b.begin_function("main", 0, 2);
280        let k = b.const_(crate::bytecode::value::Value::Int(41));
281        b.emit_load_const(0, k);
282        b.emit_load_imm(1, 1);
283        b.emit_binop(Opcode::Add, 0, 0, 1);
284        b.emit_return(0);
285        let chunk = b.finish();
286        assert!(verify(&chunk).is_ok());
287    }
288
289    /// A function the VM cannot even enter: entry copies `r0..arity`, but
290    /// the frame only has `num_registers` slots. Used to be accepted here and
291    /// then panic with an out-of-bounds index inside `Vm::new` / `Call`.
292    #[test]
293    fn rejects_arity_larger_than_the_register_file() {
294        let mut b = ChunkBuilder::new("test");
295        b.begin_function("main", 3, 1);
296        b.emit_return(0);
297        let chunk = b.finish();
298        assert_eq!(
299            verify(&chunk),
300            Err(VerifyError::ArityExceedsRegisters {
301                function: 0,
302                arity: 3,
303                num_registers: 1,
304            })
305        );
306    }
307
308    #[test]
309    fn accepts_arity_equal_to_the_register_file() {
310        let mut b = ChunkBuilder::new("test");
311        b.begin_function("main", 2, 2);
312        b.emit_return(0);
313        let chunk = b.finish();
314        assert!(verify(&chunk).is_ok());
315    }
316
317    #[test]
318    fn rejects_out_of_range_jump() {
319        use crate::bytecode::instruction::Instruction;
320        let mut chunk = Chunk::default();
321        chunk.functions.push(crate::bytecode::chunk::FunctionDef {
322            name: "main".into(),
323            entry: 0,
324            arity: 0,
325            num_registers: 1,
326        });
327        chunk.code.push(Instruction::only_imm(Opcode::Jump, 999));
328        assert!(matches!(
329            verify(&chunk),
330            Err(VerifyError::JumpOutOfRange { .. })
331        ));
332    }
333
334    #[test]
335    fn untrusted_rejects_cap_pid_message_constants() {
336        use crate::bytecode::cap::CapId;
337        use crate::bytecode::value::Message;
338        for (value, kind) in [
339            (
340                crate::bytecode::value::Value::Cap(CapId::from_raw(1)),
341                ConstantKind::Capability,
342            ),
343            (
344                crate::bytecode::value::Value::Pid(7),
345                ConstantKind::ProcessId,
346            ),
347            (
348                crate::bytecode::value::Value::Message(Message::new(1, 2, 3, 4u64)),
349                ConstantKind::Message,
350            ),
351        ] {
352            let mut b = ChunkBuilder::new("forge");
353            b.begin_function("main", 0, 1);
354            let k = b.const_(value);
355            b.emit_load_const(0, k);
356            b.emit_return(0);
357            let chunk = b.finish();
358            assert_eq!(
359                verify(&chunk),
360                Err(VerifyError::ForbiddenConstant { index: 0, kind })
361            );
362            assert!(verify_with(
363                &chunk,
364                VerifyConfig {
365                    trust: TrustLevel::Trusted
366                }
367            )
368            .is_ok());
369        }
370    }
371}