byteflow/vm/fault.rs
1use std::fmt;
2
3use crate::bytecode::NativeIdx;
4
5/// Why a `CallNative` was refused before the function pointer ran.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum NativeCallError {
8 NoNativeRight,
9 IndexNotAllowlisted(NativeIdx),
10 IndexOutOfRange(NativeIdx),
11 Revoked,
12}
13
14impl fmt::Display for NativeCallError {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 match self {
17 NativeCallError::NoNativeRight => f.write_str("CALL_NATIVE: flow lacks NATIVE right"),
18 NativeCallError::IndexNotAllowlisted(idx) => {
19 write!(f, "CALL_NATIVE: index {idx} not on allowlist")
20 }
21 NativeCallError::IndexOutOfRange(idx) => {
22 write!(f, "CALL_NATIVE: index {idx} out of range")
23 }
24 NativeCallError::Revoked => f.write_str("CALL_NATIVE: capability revoked"),
25 }
26 }
27}
28
29impl std::error::Error for NativeCallError {}
30
31/// Anything that can go wrong *inside* a running Flow's VM.
32///
33/// A `Fault` is never a Rust panic — panics are reserved for genuine host
34/// bugs and are caught at the worker boundary (see
35/// `crate::scheduler::worker`) precisely so that one Flow's
36/// bug (division by zero, a corrupt jump target that slipped past the
37/// verifier, an out-of-range register) can never take down a worker thread,
38/// let alone the whole runtime. A `Fault` instead becomes
39/// [`crate::FlowOutcome::Failed`] and is handed to the Flow's supervisor, which
40/// decides whether to restart it (design notes §15-16).
41#[derive(Clone, Debug, PartialEq, Eq)]
42pub enum Fault {
43 DivideByZero,
44 RegisterOutOfRange { reg: u8, frame_size: u8 },
45 /// An instruction's register operand plus the offset it gathers at does
46 /// not fit the register index space *at all* — e.g. `Spawn a=255`, which
47 /// reads its arguments from `a+1..`.
48 ///
49 /// Distinct from [`Fault::RegisterOutOfRange`], which is about an index
50 /// that is perfectly representable and merely absent from this frame.
51 /// Kept separate so the fault cannot lie: reporting "register 255 is out
52 /// of range" for a request that was really for register 256 would send
53 /// whoever reads it looking in the wrong place.
54 RegisterIndexOverflow { base: u8, offset: u8 },
55 BadConstant { index: u32, pool_size: u32 },
56 BadFunction { index: u32, table_size: u32 },
57 /// Function call nesting exceeded `Vm::MAX_CALL_DEPTH`. Bytecode has no
58 /// native stack overflow (frames are heap-allocated `Vec<Value>`s), so
59 /// this is a deliberate, checked limit rather than a segfault.
60 CallStackOverflow { depth: usize },
61 TypeMismatch { expected: &'static str, got: &'static str },
62 /// `CallNative` referenced a slot outside the runtime's registered
63 /// native function table (design notes §30-31). Distinct from
64 /// `BadFunction`, which is about the *bytecode* function table baked
65 /// into the chunk — natives are supplied by the embedder at `Vm`
66 /// construction time and can't be range-checked by
67 /// `crate::bytecode::verify`, which has no visibility into them.
68 BadNative { index: u32, table_size: u32 },
69 /// A native function returned an error (host-side failure — I/O,
70 /// invalid argument the Rust side rejected, capability denied, etc).
71 /// The message is native-function-defined.
72 NativeError(String),
73 /// S7: `CallNative` failed the allowlist / NATIVE-right / revocation
74 /// check before the function pointer was touched.
75 NativeDenied(NativeCallError),
76 /// Explicit `Trap` opcode, e.g. an assertion emitted by a compiler.
77 Explicit(i32),
78 /// Broken VM invariant (e.g. empty frame stack while running). Category D
79 /// in the error model — surfaced as a Flow fault, never as `unwrap`.
80 Invariant(&'static str),
81 /// Per-flow heap quota refused a `Str` / `Bytes` register write.
82 QuotaExceeded(String),
83 /// Relative `Jump` / `Branch` target outside the code (paranoid mode only).
84 ///
85 /// Verified chunks never hit this — `verify` already proved every offset.
86 /// Without paranoid mode, a corrupt jump fail-opens as an implicit
87 /// `return Unit` (see `docs::vm_safety`).
88 BadJump { target: usize, code_len: usize },
89}
90
91impl fmt::Display for Fault {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 match self {
94 Fault::DivideByZero => write!(f, "division by zero"),
95 Fault::RegisterOutOfRange { reg, frame_size } => {
96 write!(f, "register r{reg} out of range (frame has {frame_size} registers)")
97 }
98 Fault::BadConstant { index, pool_size } => {
99 write!(f, "constant index {index} out of range (pool size {pool_size})")
100 }
101 Fault::BadFunction { index, table_size } => {
102 write!(f, "function index {index} out of range (table size {table_size})")
103 }
104 Fault::RegisterIndexOverflow { base, offset } => write!(
105 f,
106 "register index r{base}+{offset} overflows the register index space (max r255)"
107 ),
108 Fault::CallStackOverflow { depth } => write!(f, "call stack overflow at depth {depth}"),
109 Fault::TypeMismatch { expected, got } => {
110 write!(f, "type mismatch: expected {expected}, got {got}")
111 }
112 Fault::BadNative { index, table_size } => {
113 write!(f, "native function index {index} out of range (table size {table_size})")
114 }
115 Fault::NativeError(msg) => write!(f, "native function error: {msg}"),
116 Fault::NativeDenied(err) => write!(f, "{err}"),
117 Fault::Explicit(code) => write!(f, "explicit trap (code {code})"),
118 Fault::Invariant(msg) => write!(f, "vm invariant broken: {msg}"),
119 Fault::QuotaExceeded(msg) => write!(f, "{msg}"),
120 Fault::BadJump { target, code_len } => {
121 write!(f, "jump target {target} out of range (code length {code_len})")
122 }
123 }
124 }
125}
126
127impl std::error::Error for Fault {}