Skip to main content

byteflow/bytecode/
format.rs

1use super::chunk::{Chunk, FunctionDef, ABI_VERSION, ABI_VERSION_LISTS, ABI_VERSION_MAPS, 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).
12pub(crate) const 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 {
18        found: [u8; 4],
19    },
20    UnsupportedAbi(u32),
21    Truncated,
22    LimitExceeded {
23        what: &'static str,
24        got: u32,
25    },
26    BadUtf8,
27    UnknownValueTag(u8),
28    UnknownOpcode {
29        at: usize,
30        byte: u8,
31    },
32    ForbiddenConstant(super::verify::ConstantKind),
33    ValueTooNested,
34    /// Bytes left after a complete module. Ignoring them would accept a
35    /// buffer that is not the module the caller hashed or transmitted.
36    Trailing {
37        leftover: usize,
38    },
39}
40
41impl std::fmt::Display for FormatError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            FormatError::BadMagic { found } => {
45                write!(f, "bad magic {found:?}, expected {:?}", MAGIC)
46            }
47            FormatError::UnsupportedAbi(v) => write!(f, "unsupported ABI version {v}"),
48            FormatError::Truncated => write!(f, "truncated .bf module"),
49            FormatError::LimitExceeded { what, got } => {
50                write!(f, "{what} count {got} exceeds decoder limit")
51            }
52            FormatError::BadUtf8 => write!(f, "name is not valid UTF-8"),
53            FormatError::UnknownValueTag(t) => write!(f, "unknown value tag 0x{t:02X}"),
54            FormatError::UnknownOpcode { at, byte } => {
55                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
56            }
57            FormatError::ForbiddenConstant(kind) => {
58                write!(
59                    f,
60                    "untrusted module must not embed {kind} in the constant pool"
61                )
62            }
63            FormatError::ValueTooNested => write!(f, "value nesting exceeds decoder limit"),
64            FormatError::Trailing { leftover } => {
65                write!(f, "trailing {leftover} bytes after module")
66            }
67        }
68    }
69}
70
71impl std::error::Error for FormatError {}
72
73/// Encode `chunk` as a BFV0 module (little-endian). Pure data — no I/O.
74pub fn encode(chunk: &Chunk) -> Vec<u8> {
75    let mut out = Vec::new();
76    out.extend_from_slice(&MAGIC);
77    let abi = if constants_contain_map(&chunk.constants) {
78        ABI_VERSION_MAPS
79    } else if constants_contain_list(&chunk.constants) {
80        ABI_VERSION_LISTS
81    } else {
82        ABI_VERSION
83    };
84    out.extend_from_slice(&abi.to_le_bytes());
85    write_string(&mut out, &chunk.name);
86    out.extend_from_slice(&(chunk.constants.len() as u32).to_le_bytes());
87    for value in &chunk.constants {
88        write_value(&mut out, value);
89    }
90    out.extend_from_slice(&(chunk.functions.len() as u32).to_le_bytes());
91    for def in &chunk.functions {
92        write_string(&mut out, &def.name);
93        out.extend_from_slice(&def.entry.to_le_bytes());
94        out.push(def.arity);
95        out.push(def.num_registers);
96    }
97    out.extend_from_slice(&(chunk.code.len() as u32).to_le_bytes());
98    for instr in &chunk.code {
99        out.push(instr.op.as_u8());
100        out.push(instr.a);
101        out.push(instr.b);
102        out.push(instr.c);
103        out.extend_from_slice(&instr.imm.to_le_bytes());
104    }
105    out
106}
107
108/// Decode a BFV0 module. Untrusted by default: Cap / Pid / Message constants
109/// are rejected (see [`decode_with`]).
110pub fn decode(bytes: &[u8]) -> Result<Chunk, FormatError> {
111    decode_with(bytes, TrustLevel::Untrusted)
112}
113
114/// Decode with an explicit trust level. Trusted decode is for host-packed
115/// modules that may embed authority tags in the constant pool.
116pub fn decode_with(bytes: &[u8], trust: TrustLevel) -> Result<Chunk, FormatError> {
117    let mut r = Reader {
118        data: bytes,
119        pos: 0,
120    };
121    let magic = r.read_array::<4>()?;
122    if magic != MAGIC {
123        return Err(FormatError::BadMagic { found: magic });
124    }
125    let abi = r.read_u32()?;
126    if abi != ABI_VERSION && abi != ABI_VERSION_LISTS && abi != ABI_VERSION_MAPS {
127        return Err(FormatError::UnsupportedAbi(abi));
128    }
129    let name = r.read_string()?;
130    let n_const = r.read_count("constants")?;
131    let mut constants = Vec::with_capacity(n_const as usize);
132    for _ in 0..n_const {
133        constants.push(r.read_value(trust, 0, abi)?);
134    }
135    let n_fn = r.read_count("functions")?;
136    let mut functions = Vec::with_capacity(n_fn as usize);
137    for _ in 0..n_fn {
138        functions.push(FunctionDef {
139            name: r.read_string()?,
140            entry: r.read_u32()?,
141            arity: r.read_u8()?,
142            num_registers: r.read_u8()?,
143        });
144    }
145    let n_code = r.read_count("code")?;
146    let mut code = Vec::with_capacity(n_code as usize);
147    for at in 0..n_code as usize {
148        let byte = r.read_u8()?;
149        let op = Opcode::from_u8(byte).ok_or(FormatError::UnknownOpcode { at, byte })?;
150        code.push(Instruction {
151            op,
152            a: r.read_u8()?,
153            b: r.read_u8()?,
154            c: r.read_u8()?,
155            imm: r.read_i32()?,
156        });
157    }
158    if r.pos != bytes.len() {
159        return Err(FormatError::Trailing {
160            leftover: bytes.len() - r.pos,
161        });
162    }
163    Ok(Chunk {
164        name,
165        constants,
166        code,
167        functions,
168    })
169}
170
171fn write_string(out: &mut Vec<u8>, s: &str) {
172    let bytes = s.as_bytes();
173    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
174    out.extend_from_slice(bytes);
175}
176
177fn write_value(out: &mut Vec<u8>, value: &Value) {
178    match value {
179        Value::Unit => out.push(0),
180        Value::Bool(b) => {
181            out.push(1);
182            out.push(u8::from(*b));
183        }
184        Value::Int(i) => {
185            out.push(2);
186            out.extend_from_slice(&i.to_le_bytes());
187        }
188        Value::Float(x) => {
189            out.push(3);
190            out.extend_from_slice(&x.to_le_bytes());
191        }
192        Value::Pid(p) => {
193            out.push(4);
194            out.extend_from_slice(&p.to_le_bytes());
195        }
196        Value::Message(m) => {
197            // Tag 5 — ABI v5 layout (reply_cap is 128-bit, payload is nested).
198            out.push(5);
199            out.extend_from_slice(&m.sender.to_le_bytes());
200            out.extend_from_slice(&m.reply_cap.as_u128().to_le_bytes());
201            out.extend_from_slice(&m.request_id.to_le_bytes());
202            out.extend_from_slice(&m.tag.to_le_bytes());
203            write_value(out, m.payload.as_ref());
204        }
205        Value::Cap(c) => {
206            out.push(6);
207            out.extend_from_slice(&c.as_u128().to_le_bytes());
208        }
209        Value::Str(s) => {
210            out.push(7);
211            write_blob(out, s.as_bytes());
212        }
213        Value::Bytes(b) => {
214            out.push(8);
215            write_blob(out, b);
216        }
217        Value::List(items) => {
218            out.push(9);
219            out.extend_from_slice(&(items.len() as u32).to_le_bytes());
220            for item in items.iter() {
221                write_value(out, item);
222            }
223        }
224        Value::Map(entries) => {
225            out.push(10);
226            out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
227            for (key, value) in entries.iter() {
228                match key {
229                    super::value::MapKey::Int(n) => {
230                        out.push(0);
231                        out.extend_from_slice(&n.to_le_bytes());
232                    }
233                    super::value::MapKey::Str(text) => {
234                        out.push(1);
235                        write_blob(out, text.as_bytes());
236                    }
237                }
238                write_value(out, value);
239            }
240        }
241    }
242}
243
244/// One value in the same layout as a `.bf` constant. The caller decides
245/// whether a `Cap` or `Pid` is allowed.
246pub(crate) fn encode_value(value: &Value) -> Vec<u8> {
247    let mut out = Vec::new();
248    write_value(&mut out, value);
249    out
250}
251
252/// Decode one value from the front of `bytes`. The `usize` is how many
253/// bytes that value occupied.
254pub(crate) fn decode_value(bytes: &[u8]) -> Result<(Value, usize), FormatError> {
255    let mut reader = Reader {
256        data: bytes,
257        pos: 0,
258    };
259    let value = reader.read_value(TrustLevel::Trusted, 0, ABI_VERSION_MAPS)?;
260    Ok((value, reader.pos))
261}
262
263fn constants_contain_map(constants: &[Value]) -> bool {
264    fn walk(value: &Value) -> bool {
265        match value {
266            Value::Map(_) => true,
267            Value::List(items) => items.iter().any(walk),
268            Value::Message(message) => walk(message.payload.as_ref()),
269            _ => false,
270        }
271    }
272    constants.iter().any(walk)
273}
274
275fn constants_contain_list(constants: &[Value]) -> bool {
276    fn walk(value: &Value) -> bool {
277        match value {
278            Value::List(_) => true,
279            Value::Map(entries) => entries.iter().any(|(_, value)| walk(value)),
280            Value::Message(message) => walk(message.payload.as_ref()),
281            _ => false,
282        }
283    }
284    constants.iter().any(walk)
285}
286
287fn write_blob(out: &mut Vec<u8>, bytes: &[u8]) {
288    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
289    out.extend_from_slice(bytes);
290}
291
292struct Reader<'a> {
293    data: &'a [u8],
294    pos: usize,
295}
296
297impl<'a> Reader<'a> {
298    fn rest(&self) -> usize {
299        self.data.len().saturating_sub(self.pos)
300    }
301
302    fn take(&mut self, n: usize) -> Result<&'a [u8], FormatError> {
303        if self.rest() < n {
304            return Err(FormatError::Truncated);
305        }
306        let slice = &self.data[self.pos..self.pos + n];
307        self.pos += n;
308        Ok(slice)
309    }
310
311    fn read_u8(&mut self) -> Result<u8, FormatError> {
312        Ok(self.take(1)?[0])
313    }
314
315    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
316        let slice = self.take(N)?;
317        let mut arr = [0u8; N];
318        arr.copy_from_slice(slice);
319        Ok(arr)
320    }
321
322    fn read_u32(&mut self) -> Result<u32, FormatError> {
323        Ok(u32::from_le_bytes(self.read_array()?))
324    }
325
326    fn read_u16(&mut self) -> Result<u16, FormatError> {
327        Ok(u16::from_le_bytes(self.read_array()?))
328    }
329
330    fn read_i32(&mut self) -> Result<i32, FormatError> {
331        Ok(i32::from_le_bytes(self.read_array()?))
332    }
333
334    fn read_i64(&mut self) -> Result<i64, FormatError> {
335        Ok(i64::from_le_bytes(self.read_array()?))
336    }
337
338    fn read_u64(&mut self) -> Result<u64, FormatError> {
339        Ok(u64::from_le_bytes(self.read_array()?))
340    }
341
342    fn read_u128(&mut self) -> Result<u128, FormatError> {
343        Ok(u128::from_le_bytes(self.read_array()?))
344    }
345
346    fn read_f64(&mut self) -> Result<f64, FormatError> {
347        Ok(f64::from_le_bytes(self.read_array()?))
348    }
349
350    fn read_count(&mut self, what: &'static str) -> Result<u32, FormatError> {
351        let n = self.read_u32()?;
352        if n > MAX_ITEMS {
353            return Err(FormatError::LimitExceeded { what, got: n });
354        }
355        Ok(n)
356    }
357
358    fn read_string(&mut self) -> Result<String, FormatError> {
359        let len = self.read_u32()?;
360        if len > MAX_NAME {
361            return Err(FormatError::LimitExceeded {
362                what: "name",
363                got: len,
364            });
365        }
366        let bytes = self.take(len as usize)?;
367        String::from_utf8(bytes.to_vec()).map_err(|_| FormatError::BadUtf8)
368    }
369
370    fn read_value(
371        &mut self,
372        trust: TrustLevel,
373        depth: u32,
374        abi: u32,
375    ) -> Result<Value, FormatError> {
376        if depth > MAX_VALUE_DEPTH {
377            return Err(FormatError::ValueTooNested);
378        }
379        match self.read_u8()? {
380            0 => Ok(Value::Unit),
381            1 => Ok(Value::Bool(self.read_u8()? != 0)),
382            2 => Ok(Value::Int(self.read_i64()?)),
383            3 => Ok(Value::Float(self.read_f64()?)),
384            4 => {
385                if trust == TrustLevel::Untrusted {
386                    return Err(FormatError::ForbiddenConstant(
387                        super::verify::ConstantKind::ProcessId,
388                    ));
389                }
390                Ok(Value::Pid(self.read_u64()?))
391            }
392            5 => {
393                if trust == TrustLevel::Untrusted {
394                    return Err(FormatError::ForbiddenConstant(
395                        super::verify::ConstantKind::Message,
396                    ));
397                }
398                let sender = self.read_u64()?;
399                let reply_cap = super::cap::CapId::from_raw(self.read_u128()?);
400                let request_id = self.read_u64()?;
401                let tag = self.read_u16()?;
402                let payload = self.read_value(trust, depth + 1, abi)?;
403                Ok(Value::Message(
404                    super::value::Message::new(sender, request_id, tag, payload)
405                        .authenticate(sender, reply_cap),
406                ))
407            }
408            6 => {
409                if trust == TrustLevel::Untrusted {
410                    return Err(FormatError::ForbiddenConstant(
411                        super::verify::ConstantKind::Capability,
412                    ));
413                }
414                Ok(Value::Cap(super::cap::CapId::from_raw(self.read_u128()?)))
415            }
416            7 => {
417                let bytes = self.read_blob("str")?;
418                let s = std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
419                Ok(Value::str(s))
420            }
421            8 => Ok(Value::bytes(self.read_blob("bytes")?)),
422            9 => {
423                if abi < ABI_VERSION_LISTS {
424                    return Err(FormatError::UnknownValueTag(9));
425                }
426                let n = self.read_u32()?;
427                if n > super::value::MAX_LIST_LEN as u32 {
428                    return Err(FormatError::LimitExceeded {
429                        what: "list",
430                        got: n,
431                    });
432                }
433                let mut items = Vec::with_capacity(n as usize);
434                for _ in 0..n {
435                    items.push(self.read_value(trust, depth + 1, abi)?);
436                }
437                Value::try_list(items).ok_or(FormatError::ValueTooNested)
438            }
439            10 => {
440                if abi < ABI_VERSION_MAPS {
441                    return Err(FormatError::UnknownValueTag(10));
442                }
443                let n = self.read_u32()?;
444                if n > super::value::MAX_MAP_LEN as u32 {
445                    return Err(FormatError::LimitExceeded {
446                        what: "map",
447                        got: n,
448                    });
449                }
450                let mut entries = Vec::with_capacity(n as usize);
451                for _ in 0..n {
452                    let key = match self.read_u8()? {
453                        0 => super::value::MapKey::Int(i64::from_le_bytes(self.read_array()?)),
454                        1 => {
455                            let bytes = self.read_blob("map key")?;
456                            let text =
457                                std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
458                            super::value::MapKey::str(text)
459                        }
460                        _ => return Err(FormatError::UnknownValueTag(10)),
461                    };
462                    let value = self.read_value(trust, depth + 1, abi)?;
463                    entries.push((key, value));
464                }
465                super::value::Value::try_map(entries).ok_or(FormatError::ValueTooNested)
466            }
467            tag => Err(FormatError::UnknownValueTag(tag)),
468        }
469    }
470
471    fn read_blob(&mut self, what: &'static str) -> Result<&'a [u8], FormatError> {
472        let len = self.read_u32()?;
473        if len > MAX_BLOB {
474            return Err(FormatError::LimitExceeded { what, got: len });
475        }
476        self.take(len as usize)
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483    use crate::bytecode::builder::ChunkBuilder;
484    use crate::bytecode::opcode::Opcode;
485    use crate::bytecode::verify::{verify, TrustLevel};
486
487    #[test]
488    fn roundtrip_preserves_chunk() -> Result<(), FormatError> {
489        let mut b = ChunkBuilder::new("roundtrip");
490        b.begin_function("main", 0, 2);
491        let k = b.const_(Value::Int(9));
492        b.emit_load_const(0, k);
493        b.emit_load_imm(1, 1);
494        b.emit_binop(Opcode::Add, 0, 0, 1);
495        b.emit_return(0);
496        let original = b.finish();
497        let bytes = encode(&original);
498        assert_eq!(&bytes[..4], &MAGIC);
499        let decoded = decode(&bytes)?;
500        assert!(verify(&decoded).is_ok());
501        assert_eq!(decoded.name, original.name);
502        assert_eq!(decoded.constants, original.constants);
503        assert_eq!(decoded.code, original.code);
504        assert_eq!(decoded.functions, original.functions);
505        Ok(())
506    }
507
508    #[test]
509    fn roundtrip_preserves_message_constant() -> Result<(), FormatError> {
510        use super::super::value::Message;
511        let mut b = ChunkBuilder::new("msg-const");
512        b.begin_function("main", 0, 1);
513        let k = b.const_(Value::Message(Message::new(1, 2, 3, 4u64)));
514        b.emit_load_const(0, k);
515        b.emit_return(0);
516        let original = b.finish();
517        let decoded = decode_with(&encode(&original), TrustLevel::Trusted)?;
518        assert_eq!(decoded.constants, original.constants);
519        let got = decoded.constants[0]
520            .as_message()
521            .ok_or(FormatError::Truncated)?;
522        assert_eq!(got.sender, 1);
523        assert_eq!(got.request_id, 2);
524        assert_eq!(got.tag, 3);
525        assert_eq!(got.payload.as_ref(), &Value::Int(4));
526        Ok(())
527    }
528
529    #[test]
530    fn untrusted_decode_rejects_cap_constant() {
531        use crate::bytecode::cap::CapId;
532        let mut b = ChunkBuilder::new("cap-const");
533        b.begin_function("main", 0, 1);
534        let k = b.const_(Value::Cap(CapId::from_raw(1)));
535        b.emit_load_const(0, k);
536        b.emit_return(0);
537        let bytes = encode(&b.finish());
538        assert!(matches!(
539            decode(&bytes),
540            Err(FormatError::ForbiddenConstant(_))
541        ));
542        assert!(decode_with(&bytes, TrustLevel::Trusted).is_ok());
543    }
544
545    #[test]
546    fn roundtrip_preserves_str_and_bytes_constants() -> Result<(), FormatError> {
547        let mut b = ChunkBuilder::new("blob-const");
548        b.begin_function("main", 0, 2);
549        let ks = b.const_(Value::str("olá"));
550        let kb = b.const_(Value::bytes([0u8, 255, 7]));
551        b.emit_load_const(0, ks);
552        b.emit_load_const(1, kb);
553        b.emit_return(0);
554        let original = b.finish();
555        let decoded = decode(&encode(&original))?;
556        assert_eq!(decoded.constants, original.constants);
557        assert_eq!(decoded.constants[0].as_str(), Some("olá"));
558        assert_eq!(decoded.constants[1].as_bytes(), Some(&[0, 255, 7][..]));
559        Ok(())
560    }
561
562    #[test]
563    fn rejects_bad_magic() {
564        assert!(matches!(decode(b"XXXX"), Err(FormatError::BadMagic { .. })));
565    }
566
567    #[test]
568    fn rejects_bytes_after_a_complete_module() {
569        let mut b = ChunkBuilder::new("exact");
570        b.begin_function("main", 0, 1);
571        b.emit_return(0);
572        let mut bytes = encode(&b.finish());
573        bytes.push(0xFF);
574        assert!(matches!(
575            decode(&bytes),
576            Err(FormatError::Trailing { leftover: 1 })
577        ));
578    }
579
580    #[test]
581    fn list_constant_roundtrips_as_abi_v6_and_v5_rejects_the_tag() -> Result<(), FormatError> {
582        let list = match Value::try_list(vec![Value::Int(1), Value::Int(2)]) {
583            Some(list) => list,
584            None => return Err(FormatError::ValueTooNested),
585        };
586        let mut b = ChunkBuilder::new("list");
587        b.begin_function("main", 0, 1);
588        let k = b.const_(list);
589        b.emit_load_const(0, k);
590        b.emit_return(0);
591        let original = b.finish();
592        let bytes = encode(&original);
593        assert_eq!(
594            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
595            6
596        );
597        let decoded = decode(&bytes)?;
598        assert_eq!(decoded.constants, original.constants);
599        let mut v5 = bytes.clone();
600        v5[4..8].copy_from_slice(&5u32.to_le_bytes());
601        assert!(matches!(decode(&v5), Err(FormatError::UnknownValueTag(9))));
602        let wide = Value::List(std::sync::Arc::from(vec![Value::Int(1); 33]));
603        let mut wide_chunk = Chunk {
604            name: "wide".into(),
605            ..Chunk::default()
606        };
607        wide_chunk.constants.push(wide);
608        wide_chunk.functions.push(FunctionDef {
609            name: "main".into(),
610            entry: 0,
611            arity: 0,
612            num_registers: 1,
613        });
614        wide_chunk.code.push(Instruction::nullary(Opcode::Return));
615        assert!(matches!(
616            decode(&encode(&wide_chunk)),
617            Err(FormatError::LimitExceeded { what: "list", .. })
618        ));
619        Ok(())
620    }
621
622    #[test]
623    fn map_constant_roundtrips_as_abi_v7() -> Result<(), FormatError> {
624        let map = Value::try_map(vec![
625            (super::super::value::MapKey::int(1), Value::Int(2)),
626            (super::super::value::MapKey::str("k"), Value::str("v")),
627        ])
628        .ok_or(FormatError::ValueTooNested)?;
629        let mut chunk = Chunk {
630            name: "map".into(),
631            ..Chunk::default()
632        };
633        chunk.constants.push(map);
634        chunk.functions.push(FunctionDef {
635            name: "main".into(),
636            entry: 0,
637            arity: 0,
638            num_registers: 1,
639        });
640        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
641        let bytes = encode(&chunk);
642        assert_eq!(
643            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
644            ABI_VERSION_MAPS
645        );
646        let back = decode_with(&bytes, TrustLevel::Trusted)?;
647        match back.constants.first() {
648            Some(Value::Map(entries)) => {
649                assert_eq!(entries.len(), 2);
650                assert_eq!(entries[0].1, Value::Int(2));
651                Ok(())
652            }
653            _ => Err(FormatError::Truncated),
654        }
655    }
656}