Skip to main content

byteflow/bytecode/
format.rs

1use super::chunk::{Chunk, FunctionDef, ABI_VERSION, MAGIC};
2use super::instruction::Instruction;
3use super::opcode::Opcode;
4use super::value::Value;
5use super::verify::TrustLevel;
6
7const MAX_NAME: u32 = 64 * 1024;
8const MAX_ITEMS: u32 = 1_000_000;
9/// Max length for [`Value::Str`] / [`Value::Bytes`] constant payloads.
10const MAX_BLOB: u32 = 1_048_576;
11/// Nested `Message.payload` depth (defense against hostile `.bf` files).
12const MAX_VALUE_DEPTH: u32 = 16;
13
14/// Why a `.bf` buffer failed to decode.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum FormatError {
17    BadMagic { found: [u8; 4] },
18    UnsupportedAbi(u32),
19    Truncated,
20    LimitExceeded { what: &'static str, got: u32 },
21    BadUtf8,
22    UnknownValueTag(u8),
23    UnknownOpcode { at: usize, byte: u8 },
24    ForbiddenConstant(super::verify::ConstantKind),
25    ValueTooNested,
26}
27
28impl std::fmt::Display for FormatError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        match self {
31            FormatError::BadMagic { found } => {
32                write!(f, "bad magic {found:?}, expected {:?}", MAGIC)
33            }
34            FormatError::UnsupportedAbi(v) => write!(f, "unsupported ABI version {v}"),
35            FormatError::Truncated => write!(f, "truncated .bf module"),
36            FormatError::LimitExceeded { what, got } => {
37                write!(f, "{what} count {got} exceeds decoder limit")
38            }
39            FormatError::BadUtf8 => write!(f, "name is not valid UTF-8"),
40            FormatError::UnknownValueTag(t) => write!(f, "unknown value tag 0x{t:02X}"),
41            FormatError::UnknownOpcode { at, byte } => {
42                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
43            }
44            FormatError::ForbiddenConstant(kind) => {
45                write!(
46                    f,
47                    "untrusted module must not embed {kind} in the constant pool"
48                )
49            }
50            FormatError::ValueTooNested => write!(f, "value nesting exceeds decoder limit"),
51        }
52    }
53}
54
55impl std::error::Error for FormatError {}
56
57/// Encode `chunk` as a BFV0 module (little-endian). Pure data — no I/O.
58pub fn encode(chunk: &Chunk) -> Vec<u8> {
59    let mut out = Vec::new();
60    out.extend_from_slice(&MAGIC);
61    out.extend_from_slice(&ABI_VERSION.to_le_bytes());
62    write_string(&mut out, &chunk.name);
63    out.extend_from_slice(&(chunk.constants.len() as u32).to_le_bytes());
64    for value in &chunk.constants {
65        write_value(&mut out, value);
66    }
67    out.extend_from_slice(&(chunk.functions.len() as u32).to_le_bytes());
68    for def in &chunk.functions {
69        write_string(&mut out, &def.name);
70        out.extend_from_slice(&def.entry.to_le_bytes());
71        out.push(def.arity);
72        out.push(def.num_registers);
73    }
74    out.extend_from_slice(&(chunk.code.len() as u32).to_le_bytes());
75    for instr in &chunk.code {
76        out.push(instr.op.as_u8());
77        out.push(instr.a);
78        out.push(instr.b);
79        out.push(instr.c);
80        out.extend_from_slice(&instr.imm.to_le_bytes());
81    }
82    out
83}
84
85/// Decode a BFV0 module. Untrusted by default: Cap / Pid / Message constants
86/// are rejected (see [`decode_with`]).
87pub fn decode(bytes: &[u8]) -> Result<Chunk, FormatError> {
88    decode_with(bytes, TrustLevel::Untrusted)
89}
90
91/// Decode with an explicit trust level. Trusted decode is for host-packed
92/// modules that may embed authority tags in the constant pool.
93pub fn decode_with(bytes: &[u8], trust: TrustLevel) -> Result<Chunk, FormatError> {
94    let mut r = Reader {
95        data: bytes,
96        pos: 0,
97    };
98    let magic = r.read_array::<4>()?;
99    if magic != MAGIC {
100        return Err(FormatError::BadMagic { found: magic });
101    }
102    let abi = r.read_u32()?;
103    if abi != ABI_VERSION {
104        return Err(FormatError::UnsupportedAbi(abi));
105    }
106    let name = r.read_string()?;
107    let n_const = r.read_count("constants")?;
108    let mut constants = Vec::with_capacity(n_const as usize);
109    for _ in 0..n_const {
110        constants.push(r.read_value(trust, 0)?);
111    }
112    let n_fn = r.read_count("functions")?;
113    let mut functions = Vec::with_capacity(n_fn as usize);
114    for _ in 0..n_fn {
115        functions.push(FunctionDef {
116            name: r.read_string()?,
117            entry: r.read_u32()?,
118            arity: r.read_u8()?,
119            num_registers: r.read_u8()?,
120        });
121    }
122    let n_code = r.read_count("code")?;
123    let mut code = Vec::with_capacity(n_code as usize);
124    for at in 0..n_code as usize {
125        let byte = r.read_u8()?;
126        let op = Opcode::from_u8(byte).ok_or(FormatError::UnknownOpcode { at, byte })?;
127        code.push(Instruction {
128            op,
129            a: r.read_u8()?,
130            b: r.read_u8()?,
131            c: r.read_u8()?,
132            imm: r.read_i32()?,
133        });
134    }
135    Ok(Chunk {
136        name,
137        constants,
138        code,
139        functions,
140    })
141}
142
143fn write_string(out: &mut Vec<u8>, s: &str) {
144    let bytes = s.as_bytes();
145    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
146    out.extend_from_slice(bytes);
147}
148
149fn write_value(out: &mut Vec<u8>, value: &Value) {
150    match value {
151        Value::Unit => out.push(0),
152        Value::Bool(b) => {
153            out.push(1);
154            out.push(u8::from(*b));
155        }
156        Value::Int(i) => {
157            out.push(2);
158            out.extend_from_slice(&i.to_le_bytes());
159        }
160        Value::Float(x) => {
161            out.push(3);
162            out.extend_from_slice(&x.to_le_bytes());
163        }
164        Value::Pid(p) => {
165            out.push(4);
166            out.extend_from_slice(&p.to_le_bytes());
167        }
168        Value::Message(m) => {
169            // Tag 5 — ABI v5 layout (reply_cap is 128-bit, payload is nested).
170            out.push(5);
171            out.extend_from_slice(&m.sender.to_le_bytes());
172            out.extend_from_slice(&m.reply_cap.as_u128().to_le_bytes());
173            out.extend_from_slice(&m.request_id.to_le_bytes());
174            out.extend_from_slice(&m.tag.to_le_bytes());
175            write_value(out, m.payload.as_ref());
176        }
177        Value::Cap(c) => {
178            out.push(6);
179            out.extend_from_slice(&c.as_u128().to_le_bytes());
180        }
181        Value::Str(s) => {
182            out.push(7);
183            write_blob(out, s.as_bytes());
184        }
185        Value::Bytes(b) => {
186            out.push(8);
187            write_blob(out, b);
188        }
189    }
190}
191
192fn write_blob(out: &mut Vec<u8>, bytes: &[u8]) {
193    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
194    out.extend_from_slice(bytes);
195}
196
197struct Reader<'a> {
198    data: &'a [u8],
199    pos: usize,
200}
201
202impl<'a> Reader<'a> {
203    fn rest(&self) -> usize {
204        self.data.len().saturating_sub(self.pos)
205    }
206
207    fn take(&mut self, n: usize) -> Result<&'a [u8], FormatError> {
208        if self.rest() < n {
209            return Err(FormatError::Truncated);
210        }
211        let slice = &self.data[self.pos..self.pos + n];
212        self.pos += n;
213        Ok(slice)
214    }
215
216    fn read_u8(&mut self) -> Result<u8, FormatError> {
217        Ok(self.take(1)?[0])
218    }
219
220    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
221        let slice = self.take(N)?;
222        let mut arr = [0u8; N];
223        arr.copy_from_slice(slice);
224        Ok(arr)
225    }
226
227    fn read_u32(&mut self) -> Result<u32, FormatError> {
228        Ok(u32::from_le_bytes(self.read_array()?))
229    }
230
231    fn read_u16(&mut self) -> Result<u16, FormatError> {
232        Ok(u16::from_le_bytes(self.read_array()?))
233    }
234
235    fn read_i32(&mut self) -> Result<i32, FormatError> {
236        Ok(i32::from_le_bytes(self.read_array()?))
237    }
238
239    fn read_i64(&mut self) -> Result<i64, FormatError> {
240        Ok(i64::from_le_bytes(self.read_array()?))
241    }
242
243    fn read_u64(&mut self) -> Result<u64, FormatError> {
244        Ok(u64::from_le_bytes(self.read_array()?))
245    }
246
247    fn read_u128(&mut self) -> Result<u128, FormatError> {
248        Ok(u128::from_le_bytes(self.read_array()?))
249    }
250
251    fn read_f64(&mut self) -> Result<f64, FormatError> {
252        Ok(f64::from_le_bytes(self.read_array()?))
253    }
254
255    fn read_count(&mut self, what: &'static str) -> Result<u32, FormatError> {
256        let n = self.read_u32()?;
257        if n > MAX_ITEMS {
258            return Err(FormatError::LimitExceeded { what, got: n });
259        }
260        Ok(n)
261    }
262
263    fn read_string(&mut self) -> Result<String, FormatError> {
264        let len = self.read_u32()?;
265        if len > MAX_NAME {
266            return Err(FormatError::LimitExceeded {
267                what: "name",
268                got: len,
269            });
270        }
271        let bytes = self.take(len as usize)?;
272        String::from_utf8(bytes.to_vec()).map_err(|_| FormatError::BadUtf8)
273    }
274
275    fn read_value(&mut self, trust: TrustLevel, depth: u32) -> Result<Value, FormatError> {
276        if depth > MAX_VALUE_DEPTH {
277            return Err(FormatError::ValueTooNested);
278        }
279        match self.read_u8()? {
280            0 => Ok(Value::Unit),
281            1 => Ok(Value::Bool(self.read_u8()? != 0)),
282            2 => Ok(Value::Int(self.read_i64()?)),
283            3 => Ok(Value::Float(self.read_f64()?)),
284            4 => {
285                if trust == TrustLevel::Untrusted {
286                    return Err(FormatError::ForbiddenConstant(
287                        super::verify::ConstantKind::ProcessId,
288                    ));
289                }
290                Ok(Value::Pid(self.read_u64()?))
291            }
292            5 => {
293                if trust == TrustLevel::Untrusted {
294                    return Err(FormatError::ForbiddenConstant(
295                        super::verify::ConstantKind::Message,
296                    ));
297                }
298                let sender = self.read_u64()?;
299                let reply_cap = super::cap::CapId::from_raw(self.read_u128()?);
300                let request_id = self.read_u64()?;
301                let tag = self.read_u16()?;
302                let payload = self.read_value(trust, depth + 1)?;
303                Ok(Value::Message(
304                    super::value::Message::new(sender, request_id, tag, payload)
305                        .authenticate(sender, reply_cap),
306                ))
307            }
308            6 => {
309                if trust == TrustLevel::Untrusted {
310                    return Err(FormatError::ForbiddenConstant(
311                        super::verify::ConstantKind::Capability,
312                    ));
313                }
314                Ok(Value::Cap(super::cap::CapId::from_raw(self.read_u128()?)))
315            }
316            7 => {
317                let bytes = self.read_blob("str")?;
318                let s = std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
319                Ok(Value::str(s))
320            }
321            8 => Ok(Value::bytes(self.read_blob("bytes")?)),
322            tag => Err(FormatError::UnknownValueTag(tag)),
323        }
324    }
325
326    fn read_blob(&mut self, what: &'static str) -> Result<&'a [u8], FormatError> {
327        let len = self.read_u32()?;
328        if len > MAX_BLOB {
329            return Err(FormatError::LimitExceeded { what, got: len });
330        }
331        self.take(len as usize)
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::bytecode::builder::ChunkBuilder;
339    use crate::bytecode::opcode::Opcode;
340    use crate::bytecode::verify::{verify, TrustLevel};
341
342    #[test]
343    fn roundtrip_preserves_chunk() -> Result<(), FormatError> {
344        let mut b = ChunkBuilder::new("roundtrip");
345        b.begin_function("main", 0, 2);
346        let k = b.const_(Value::Int(9));
347        b.emit_load_const(0, k);
348        b.emit_load_imm(1, 1);
349        b.emit_binop(Opcode::Add, 0, 0, 1);
350        b.emit_return(0);
351        let original = b.finish();
352        let bytes = encode(&original);
353        assert_eq!(&bytes[..4], &MAGIC);
354        let decoded = decode(&bytes)?;
355        assert!(verify(&decoded).is_ok());
356        assert_eq!(decoded.name, original.name);
357        assert_eq!(decoded.constants, original.constants);
358        assert_eq!(decoded.code, original.code);
359        assert_eq!(decoded.functions, original.functions);
360        Ok(())
361    }
362
363    #[test]
364    fn roundtrip_preserves_message_constant() -> Result<(), FormatError> {
365        use super::super::value::Message;
366        let mut b = ChunkBuilder::new("msg-const");
367        b.begin_function("main", 0, 1);
368        let k = b.const_(Value::Message(Message::new(1, 2, 3, 4u64)));
369        b.emit_load_const(0, k);
370        b.emit_return(0);
371        let original = b.finish();
372        let decoded = decode_with(&encode(&original), TrustLevel::Trusted)?;
373        assert_eq!(decoded.constants, original.constants);
374        let got = decoded.constants[0]
375            .as_message()
376            .ok_or(FormatError::Truncated)?;
377        assert_eq!(got.sender, 1);
378        assert_eq!(got.request_id, 2);
379        assert_eq!(got.tag, 3);
380        assert_eq!(got.payload.as_ref(), &Value::Int(4));
381        Ok(())
382    }
383
384    #[test]
385    fn untrusted_decode_rejects_cap_constant() {
386        use crate::bytecode::cap::CapId;
387        let mut b = ChunkBuilder::new("cap-const");
388        b.begin_function("main", 0, 1);
389        let k = b.const_(Value::Cap(CapId::from_raw(1)));
390        b.emit_load_const(0, k);
391        b.emit_return(0);
392        let bytes = encode(&b.finish());
393        assert!(matches!(
394            decode(&bytes),
395            Err(FormatError::ForbiddenConstant(_))
396        ));
397        assert!(decode_with(&bytes, TrustLevel::Trusted).is_ok());
398    }
399
400    #[test]
401    fn roundtrip_preserves_str_and_bytes_constants() -> Result<(), FormatError> {
402        let mut b = ChunkBuilder::new("blob-const");
403        b.begin_function("main", 0, 2);
404        let ks = b.const_(Value::str("olá"));
405        let kb = b.const_(Value::bytes([0u8, 255, 7]));
406        b.emit_load_const(0, ks);
407        b.emit_load_const(1, kb);
408        b.emit_return(0);
409        let original = b.finish();
410        let decoded = decode(&encode(&original))?;
411        assert_eq!(decoded.constants, original.constants);
412        assert_eq!(decoded.constants[0].as_str(), Some("olá"));
413        assert_eq!(decoded.constants[1].as_bytes(), Some(&[0, 255, 7][..]));
414        Ok(())
415    }
416
417    #[test]
418    fn rejects_bad_magic() {
419        assert!(matches!(decode(b"XXXX"), Err(FormatError::BadMagic { .. })));
420    }
421}