Skip to main content

byteflow/bytecode/
format.rs

1// Docs ratchet: public items here predate `missing_docs`. Delete this
2// allow once they are documented; new files get the lint by default.
3#![allow(missing_docs)]
4
5use super::chunk::{
6    Chunk, FunctionDef, ABI_VERSION, ABI_VERSION_LISTS, ABI_VERSION_MAPS, ABI_VERSION_RECORDS,
7    MAGIC,
8};
9use super::instruction::Instruction;
10use super::opcode::Opcode;
11use super::value::Value;
12use super::verify::TrustLevel;
13
14const MAX_NAME: u32 = 64 * 1024;
15const MAX_ITEMS: u32 = 1_000_000;
16/// Max length for [`Value::Str`] / [`Value::Bytes`] constant payloads.
17const MAX_BLOB: u32 = 1_048_576;
18/// Nested `Message.payload` depth (defense against hostile `.bf` files).
19pub(crate) const MAX_VALUE_DEPTH: u32 = 16;
20
21/// Why a `.bf` buffer failed to decode.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum FormatError {
24    BadMagic {
25        found: [u8; 4],
26    },
27    UnsupportedAbi(u32),
28    Truncated,
29    LimitExceeded {
30        what: &'static str,
31        got: u32,
32    },
33    BadUtf8,
34    UnknownValueTag(u8),
35    /// The byte after a map tag is not a key kind (`0` = `Int`, `1` = `Str`).
36    /// This used to be reported as [`FormatError::UnknownValueTag`]`(10)`,
37    /// which is the map's own tag.
38    UnknownMapKey(u8),
39    /// Tag `1` was followed by a byte other than `0` or `1`. The encoder
40    /// writes only those two. Any other byte used to decode as `true`.
41    NonCanonicalBool(u8),
42    UnknownOpcode {
43        at: usize,
44        byte: u8,
45    },
46    ForbiddenConstant(super::verify::ConstantKind),
47    ValueTooNested,
48    /// A map constant repeats a key. [`Value::try_map`] also rejects this,
49    /// but the decoder used to report it as [`FormatError::ValueTooNested`].
50    DuplicateMapKey,
51    /// Bytes left after a complete module. Ignoring them would accept a
52    /// buffer that is not the module the caller hashed or transmitted.
53    Trailing {
54        leftover: usize,
55    },
56}
57
58impl std::fmt::Display for FormatError {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        match self {
61            FormatError::BadMagic { found } => {
62                write!(f, "bad magic {found:?}, expected {:?}", MAGIC)
63            }
64            FormatError::UnsupportedAbi(v) => write!(f, "unsupported ABI version {v}"),
65            FormatError::Truncated => write!(f, "truncated .bf module"),
66            FormatError::LimitExceeded { what, got } => {
67                write!(f, "{what} count {got} exceeds decoder limit")
68            }
69            FormatError::BadUtf8 => write!(f, "name is not valid UTF-8"),
70            FormatError::UnknownValueTag(t) => write!(f, "unknown value tag 0x{t:02X}"),
71            FormatError::UnknownMapKey(t) => write!(f, "unknown map key tag 0x{t:02X}"),
72            FormatError::NonCanonicalBool(b) => {
73                write!(f, "non-canonical bool byte 0x{b:02X}")
74            }
75            FormatError::UnknownOpcode { at, byte } => {
76                write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
77            }
78            FormatError::ForbiddenConstant(kind) => {
79                write!(
80                    f,
81                    "untrusted module must not embed {kind} in the constant pool"
82                )
83            }
84            FormatError::ValueTooNested => write!(f, "value nesting exceeds decoder limit"),
85            FormatError::DuplicateMapKey => write!(f, "map constant repeats a key"),
86            FormatError::Trailing { leftover } => {
87                write!(f, "trailing {leftover} bytes after module")
88            }
89        }
90    }
91}
92
93impl std::error::Error for FormatError {}
94
95/// Oldest ABI that can hold `constants`: v8 for a record, otherwise v7 for a
96/// map, otherwise v6 for a list, otherwise v5.
97pub(crate) fn module_abi(constants: &[Value]) -> u32 {
98    if constants_contain_record(constants) {
99        ABI_VERSION_RECORDS
100    } else if constants_contain_map(constants) {
101        ABI_VERSION_MAPS
102    } else if constants_contain_list(constants) {
103        ABI_VERSION_LISTS
104    } else {
105        ABI_VERSION
106    }
107}
108
109/// Encode `chunk` as a BFV0 module (little-endian). Pure data — no I/O.
110///
111/// The header is the oldest ABI that can represent the constant pool.
112pub fn encode(chunk: &Chunk) -> Vec<u8> {
113    let mut out = Vec::new();
114    out.extend_from_slice(&MAGIC);
115    let abi = module_abi(&chunk.constants);
116    out.extend_from_slice(&abi.to_le_bytes());
117    write_string(&mut out, &chunk.name);
118    out.extend_from_slice(&(chunk.constants.len() as u32).to_le_bytes());
119    for value in &chunk.constants {
120        write_value(&mut out, value);
121    }
122    out.extend_from_slice(&(chunk.functions.len() as u32).to_le_bytes());
123    for def in &chunk.functions {
124        write_string(&mut out, &def.name);
125        out.extend_from_slice(&def.entry.to_le_bytes());
126        out.push(def.arity);
127        out.push(def.num_registers);
128    }
129    out.extend_from_slice(&(chunk.code.len() as u32).to_le_bytes());
130    for instr in &chunk.code {
131        out.push(instr.op.as_u8());
132        out.push(instr.a);
133        out.push(instr.b);
134        out.push(instr.c);
135        out.extend_from_slice(&instr.imm.to_le_bytes());
136    }
137    out
138}
139
140/// Decode a BFV0 module. Untrusted by default: Cap / Pid / Message constants
141/// are rejected (see [`decode_with`]).
142pub fn decode(bytes: &[u8]) -> Result<Chunk, FormatError> {
143    decode_with(bytes, TrustLevel::Untrusted)
144}
145
146/// Decode with an explicit trust level. Trusted decode is for host-packed
147/// modules that may embed authority tags in the constant pool.
148pub fn decode_with(bytes: &[u8], trust: TrustLevel) -> Result<Chunk, FormatError> {
149    let mut r = Reader {
150        data: bytes,
151        pos: 0,
152    };
153    let magic = r.read_array::<4>()?;
154    if magic != MAGIC {
155        return Err(FormatError::BadMagic { found: magic });
156    }
157    let abi = r.read_u32()?;
158    if abi != ABI_VERSION
159        && abi != ABI_VERSION_LISTS
160        && abi != ABI_VERSION_MAPS
161        && abi != ABI_VERSION_RECORDS
162    {
163        return Err(FormatError::UnsupportedAbi(abi));
164    }
165    let name = r.read_string()?;
166    // A hostile header can claim up to `MAX_ITEMS` items after a few bytes.
167    // Reserving the claimed capacity before any payload byte is read would
168    // let a ~16-byte buffer drive a multi-megabyte allocation. Cap every
169    // reserve by the smallest possible encoded size of one item; the reads
170    // below fail fast with `Truncated` either way.
171    let remaining = bytes.len().saturating_sub(r.pos);
172    let n_const = r.read_count("constants")?;
173    let mut constants = Vec::with_capacity(reserved_for(n_const, remaining, 1));
174    for _ in 0..n_const {
175        constants.push(r.read_value(trust, 0, abi)?);
176    }
177    let n_fn = r.read_count("functions")?;
178    // FunctionDef: 4 bytes of name length + the name + 4 (entry) + 1 + 1.
179    let remaining = bytes.len().saturating_sub(r.pos);
180    let mut functions = Vec::with_capacity(reserved_for(n_fn, remaining, 10));
181    for _ in 0..n_fn {
182        functions.push(FunctionDef {
183            name: r.read_string()?,
184            entry: r.read_u32()?,
185            arity: r.read_u8()?,
186            num_registers: r.read_u8()?,
187        });
188    }
189    let n_code = r.read_count("code")?;
190    // Instruction: op + a + b + c + imm, 8 bytes fixed.
191    let remaining = bytes.len().saturating_sub(r.pos);
192    let mut code = Vec::with_capacity(reserved_for(n_code, remaining, 8));
193    for at in 0..n_code as usize {
194        let byte = r.read_u8()?;
195        let op = Opcode::from_u8(byte).ok_or(FormatError::UnknownOpcode { at, byte })?;
196        code.push(Instruction {
197            op,
198            a: r.read_u8()?,
199            b: r.read_u8()?,
200            c: r.read_u8()?,
201            imm: r.read_i32()?,
202        });
203    }
204    if r.pos != bytes.len() {
205        return Err(FormatError::Trailing {
206            leftover: bytes.len() - r.pos,
207        });
208    }
209    Ok(Chunk {
210        name,
211        constants,
212        code,
213        functions,
214    })
215}
216
217/// Reserve capacity bounded by the bytes that could plausibly carry
218/// `count` items: at most `remaining / min_bytes_per_item` items are
219/// decodable before `Truncated`, so a larger claim cannot justify the
220/// heap reserve.
221fn reserved_for(count: u32, remaining: usize, min_bytes_per_item: usize) -> usize {
222    let plausible = remaining / min_bytes_per_item.max(1);
223    (count as usize).min(plausible)
224}
225
226fn write_string(out: &mut Vec<u8>, s: &str) {
227    let bytes = s.as_bytes();
228    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
229    out.extend_from_slice(bytes);
230}
231
232fn write_value(out: &mut Vec<u8>, value: &Value) {
233    match value {
234        Value::Unit => out.push(0),
235        Value::Bool(b) => {
236            out.push(1);
237            out.push(u8::from(*b));
238        }
239        Value::Int(i) => {
240            out.push(2);
241            out.extend_from_slice(&i.to_le_bytes());
242        }
243        Value::Float(x) => {
244            out.push(3);
245            out.extend_from_slice(&x.to_le_bytes());
246        }
247        Value::Pid(p) => {
248            out.push(4);
249            out.extend_from_slice(&p.to_le_bytes());
250        }
251        Value::Message(m) => {
252            // Tag 5 — ABI v5 layout (reply_cap is 128-bit, payload is nested).
253            out.push(5);
254            out.extend_from_slice(&m.sender.to_le_bytes());
255            out.extend_from_slice(&m.reply_cap.as_u128().to_le_bytes());
256            out.extend_from_slice(&m.request_id.to_le_bytes());
257            out.extend_from_slice(&m.tag.to_le_bytes());
258            write_value(out, m.payload.as_ref());
259        }
260        Value::Cap(c) => {
261            out.push(6);
262            out.extend_from_slice(&c.as_u128().to_le_bytes());
263        }
264        Value::Str(s) => {
265            out.push(7);
266            write_blob(out, s.as_bytes());
267        }
268        Value::Bytes(b) => {
269            out.push(8);
270            write_blob(out, b);
271        }
272        Value::List(items) => {
273            out.push(9);
274            out.extend_from_slice(&(items.len() as u32).to_le_bytes());
275            for item in items.iter() {
276                write_value(out, item);
277            }
278        }
279        Value::Map(entries) => {
280            out.push(10);
281            out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
282            for (key, value) in entries.iter() {
283                match key {
284                    super::value::MapKey::Int(n) => {
285                        out.push(0);
286                        out.extend_from_slice(&n.to_le_bytes());
287                    }
288                    super::value::MapKey::Str(text) => {
289                        out.push(1);
290                        write_blob(out, text.as_bytes());
291                    }
292                }
293                write_value(out, value);
294            }
295        }
296        Value::Record(fields) => {
297            out.push(11);
298            out.extend_from_slice(&(fields.len() as u32).to_le_bytes());
299            for field in fields.iter() {
300                write_value(out, field);
301            }
302        }
303    }
304}
305
306/// One value in the same layout as a `.bf` constant. The caller decides
307/// whether a `Cap` or `Pid` is allowed.
308pub(crate) fn encode_value(value: &Value) -> Vec<u8> {
309    let mut out = Vec::new();
310    write_value(&mut out, value);
311    out
312}
313
314/// Decode one value from the front of `bytes`. The `usize` is how many
315/// bytes that value occupied.
316pub(crate) fn decode_value(bytes: &[u8]) -> Result<(Value, usize), FormatError> {
317    let mut reader = Reader {
318        data: bytes,
319        pos: 0,
320    };
321    let value = reader.read_value(TrustLevel::Trusted, 0, ABI_VERSION_RECORDS)?;
322    Ok((value, reader.pos))
323}
324
325fn constants_contain_record(constants: &[Value]) -> bool {
326    fn walk(value: &Value) -> bool {
327        match value {
328            Value::Record(_) => true,
329            Value::List(items) => items.iter().any(walk),
330            Value::Map(entries) => entries.iter().any(|(_, value)| walk(value)),
331            Value::Message(message) => walk(message.payload.as_ref()),
332            _ => false,
333        }
334    }
335    constants.iter().any(walk)
336}
337
338fn constants_contain_map(constants: &[Value]) -> bool {
339    fn walk(value: &Value) -> bool {
340        match value {
341            Value::Map(_) => true,
342            Value::List(items) | Value::Record(items) => items.iter().any(walk),
343            Value::Message(message) => walk(message.payload.as_ref()),
344            _ => false,
345        }
346    }
347    constants.iter().any(walk)
348}
349
350fn constants_contain_list(constants: &[Value]) -> bool {
351    fn walk(value: &Value) -> bool {
352        match value {
353            Value::List(_) => true,
354            Value::Record(fields) => fields.iter().any(walk),
355            Value::Map(entries) => entries.iter().any(|(_, value)| walk(value)),
356            Value::Message(message) => walk(message.payload.as_ref()),
357            _ => false,
358        }
359    }
360    constants.iter().any(walk)
361}
362
363fn write_blob(out: &mut Vec<u8>, bytes: &[u8]) {
364    out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
365    out.extend_from_slice(bytes);
366}
367
368struct Reader<'a> {
369    data: &'a [u8],
370    pos: usize,
371}
372
373impl<'a> Reader<'a> {
374    fn rest(&self) -> usize {
375        self.data.len().saturating_sub(self.pos)
376    }
377
378    fn take(&mut self, n: usize) -> Result<&'a [u8], FormatError> {
379        if self.rest() < n {
380            return Err(FormatError::Truncated);
381        }
382        let slice = &self.data[self.pos..self.pos + n];
383        self.pos += n;
384        Ok(slice)
385    }
386
387    fn read_u8(&mut self) -> Result<u8, FormatError> {
388        Ok(self.take(1)?[0])
389    }
390
391    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
392        let slice = self.take(N)?;
393        let mut arr = [0u8; N];
394        arr.copy_from_slice(slice);
395        Ok(arr)
396    }
397
398    fn read_u32(&mut self) -> Result<u32, FormatError> {
399        Ok(u32::from_le_bytes(self.read_array()?))
400    }
401
402    fn read_u16(&mut self) -> Result<u16, FormatError> {
403        Ok(u16::from_le_bytes(self.read_array()?))
404    }
405
406    fn read_i32(&mut self) -> Result<i32, FormatError> {
407        Ok(i32::from_le_bytes(self.read_array()?))
408    }
409
410    fn read_i64(&mut self) -> Result<i64, FormatError> {
411        Ok(i64::from_le_bytes(self.read_array()?))
412    }
413
414    fn read_u64(&mut self) -> Result<u64, FormatError> {
415        Ok(u64::from_le_bytes(self.read_array()?))
416    }
417
418    fn read_u128(&mut self) -> Result<u128, FormatError> {
419        Ok(u128::from_le_bytes(self.read_array()?))
420    }
421
422    fn read_f64(&mut self) -> Result<f64, FormatError> {
423        Ok(f64::from_le_bytes(self.read_array()?))
424    }
425
426    fn read_count(&mut self, what: &'static str) -> Result<u32, FormatError> {
427        let n = self.read_u32()?;
428        if n > MAX_ITEMS {
429            return Err(FormatError::LimitExceeded { what, got: n });
430        }
431        Ok(n)
432    }
433
434    fn read_string(&mut self) -> Result<String, FormatError> {
435        let len = self.read_u32()?;
436        if len > MAX_NAME {
437            return Err(FormatError::LimitExceeded {
438                what: "name",
439                got: len,
440            });
441        }
442        let bytes = self.take(len as usize)?;
443        String::from_utf8(bytes.to_vec()).map_err(|_| FormatError::BadUtf8)
444    }
445
446    fn read_value(
447        &mut self,
448        trust: TrustLevel,
449        depth: u32,
450        abi: u32,
451    ) -> Result<Value, FormatError> {
452        if depth > MAX_VALUE_DEPTH {
453            return Err(FormatError::ValueTooNested);
454        }
455        match self.read_u8()? {
456            0 => Ok(Value::Unit),
457            1 => match self.read_u8()? {
458                0 => Ok(Value::Bool(false)),
459                1 => Ok(Value::Bool(true)),
460                byte => Err(FormatError::NonCanonicalBool(byte)),
461            },
462            2 => Ok(Value::Int(self.read_i64()?)),
463            3 => Ok(Value::Float(self.read_f64()?)),
464            4 => {
465                if trust.forbids_authority_constants() {
466                    return Err(FormatError::ForbiddenConstant(
467                        super::verify::ConstantKind::ProcessId,
468                    ));
469                }
470                Ok(Value::Pid(self.read_u64()?))
471            }
472            5 => {
473                if trust.forbids_authority_constants() {
474                    return Err(FormatError::ForbiddenConstant(
475                        super::verify::ConstantKind::Message,
476                    ));
477                }
478                let sender = self.read_u64()?;
479                let reply_cap = super::cap::CapId::from_raw(self.read_u128()?);
480                let request_id = self.read_u64()?;
481                let tag = self.read_u16()?;
482                let payload = self.read_value(trust, depth + 1, abi)?;
483                Ok(Value::Message(
484                    super::value::Message::new(sender, request_id, tag, payload)
485                        .authenticate(sender, reply_cap),
486                ))
487            }
488            6 => {
489                if trust.forbids_authority_constants() {
490                    return Err(FormatError::ForbiddenConstant(
491                        super::verify::ConstantKind::Capability,
492                    ));
493                }
494                Ok(Value::Cap(super::cap::CapId::from_raw(self.read_u128()?)))
495            }
496            7 => {
497                let bytes = self.read_blob("str")?;
498                let s = std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
499                Ok(Value::str(s))
500            }
501            8 => Ok(Value::bytes(self.read_blob("bytes")?)),
502            9 => {
503                if abi < ABI_VERSION_LISTS {
504                    return Err(FormatError::UnknownValueTag(9));
505                }
506                let n = self.read_u32()?;
507                if n > super::value::MAX_LIST_LEN as u32 {
508                    return Err(FormatError::LimitExceeded {
509                        what: "list",
510                        got: n,
511                    });
512                }
513                let mut items = Vec::with_capacity(n as usize);
514                for _ in 0..n {
515                    items.push(self.read_value(trust, depth + 1, abi)?);
516                }
517                Value::try_list(items).ok_or(FormatError::ValueTooNested)
518            }
519            10 => {
520                if abi < ABI_VERSION_MAPS {
521                    return Err(FormatError::UnknownValueTag(10));
522                }
523                let n = self.read_u32()?;
524                if n > super::value::MAX_MAP_LEN as u32 {
525                    return Err(FormatError::LimitExceeded {
526                        what: "map",
527                        got: n,
528                    });
529                }
530                let mut entries = Vec::with_capacity(n as usize);
531                for _ in 0..n {
532                    let key = match self.read_u8()? {
533                        0 => super::value::MapKey::Int(i64::from_le_bytes(self.read_array()?)),
534                        1 => {
535                            let bytes = self.read_blob("map key")?;
536                            let text =
537                                std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
538                            super::value::MapKey::str(text)
539                        }
540                        tag => return Err(FormatError::UnknownMapKey(tag)),
541                    };
542                    let value = self.read_value(trust, depth + 1, abi)?;
543                    entries.push((key, value));
544                }
545                if super::value::map_has_duplicate_key(&entries) {
546                    return Err(FormatError::DuplicateMapKey);
547                }
548                super::value::Value::try_map(entries).ok_or(FormatError::ValueTooNested)
549            }
550            11 => {
551                if abi < ABI_VERSION_RECORDS {
552                    return Err(FormatError::UnknownValueTag(11));
553                }
554                let n = self.read_u32()?;
555                if n > super::value::MAX_RECORD_LEN as u32 {
556                    return Err(FormatError::LimitExceeded {
557                        what: "record",
558                        got: n,
559                    });
560                }
561                let mut fields = Vec::with_capacity(n as usize);
562                for _ in 0..n {
563                    fields.push(self.read_value(trust, depth + 1, abi)?);
564                }
565                super::value::Value::try_record(fields).ok_or(FormatError::ValueTooNested)
566            }
567            tag => Err(FormatError::UnknownValueTag(tag)),
568        }
569    }
570
571    fn read_blob(&mut self, what: &'static str) -> Result<&'a [u8], FormatError> {
572        let len = self.read_u32()?;
573        if len > MAX_BLOB {
574            return Err(FormatError::LimitExceeded { what, got: len });
575        }
576        self.take(len as usize)
577    }
578}
579
580#[cfg(test)]
581mod tests {
582    use super::super::value::MapKey;
583    use super::*;
584    use crate::bytecode::builder::ChunkBuilder;
585    use crate::bytecode::opcode::Opcode;
586    use crate::bytecode::verify::{verify, TrustLevel};
587
588    #[test]
589    fn roundtrip_preserves_chunk() -> Result<(), FormatError> {
590        let mut b = ChunkBuilder::new("roundtrip");
591        b.begin_function("main", 0, 2);
592        let k = b.const_(Value::Int(9));
593        b.emit_load_const(0, k);
594        b.emit_load_imm(1, 1);
595        b.emit_binop(Opcode::Add, 0, 0, 1);
596        b.emit_return(0);
597        let original = b.finish();
598        let bytes = encode(&original);
599        assert_eq!(&bytes[..4], &MAGIC);
600        let decoded = decode(&bytes)?;
601        assert!(verify(&decoded).is_ok());
602        assert_eq!(decoded.name, original.name);
603        assert_eq!(decoded.constants, original.constants);
604        assert_eq!(decoded.code, original.code);
605        assert_eq!(decoded.functions, original.functions);
606        Ok(())
607    }
608
609    #[test]
610    fn roundtrip_preserves_message_constant() -> Result<(), FormatError> {
611        use super::super::value::Message;
612        let mut b = ChunkBuilder::new("msg-const");
613        b.begin_function("main", 0, 1);
614        let k = b.const_(Value::Message(Message::new(1, 2, 3, 4u64)));
615        b.emit_load_const(0, k);
616        b.emit_return(0);
617        let original = b.finish();
618        let decoded = decode_with(&encode(&original), TrustLevel::Trusted)?;
619        assert_eq!(decoded.constants, original.constants);
620        let got = decoded.constants[0]
621            .as_message()
622            .ok_or(FormatError::Truncated)?;
623        assert_eq!(got.sender, 1);
624        assert_eq!(got.request_id, 2);
625        assert_eq!(got.tag, 3);
626        assert_eq!(got.payload.as_ref(), &Value::Int(4));
627        Ok(())
628    }
629
630    #[test]
631    fn untrusted_decode_rejects_cap_constant() {
632        use crate::bytecode::cap::CapId;
633        let mut b = ChunkBuilder::new("cap-const");
634        b.begin_function("main", 0, 1);
635        let k = b.const_(Value::Cap(CapId::from_raw(1)));
636        b.emit_load_const(0, k);
637        b.emit_return(0);
638        let bytes = encode(&b.finish());
639        assert!(matches!(
640            decode(&bytes),
641            Err(FormatError::ForbiddenConstant(_))
642        ));
643        assert!(decode_with(&bytes, TrustLevel::Trusted).is_ok());
644    }
645
646    #[test]
647    fn roundtrip_preserves_str_and_bytes_constants() -> Result<(), FormatError> {
648        let mut b = ChunkBuilder::new("blob-const");
649        b.begin_function("main", 0, 2);
650        let ks = b.const_(Value::str("olá"));
651        let kb = b.const_(Value::bytes([0u8, 255, 7]));
652        b.emit_load_const(0, ks);
653        b.emit_load_const(1, kb);
654        b.emit_return(0);
655        let original = b.finish();
656        let decoded = decode(&encode(&original))?;
657        assert_eq!(decoded.constants, original.constants);
658        assert_eq!(decoded.constants[0].as_str(), Some("olá"));
659        assert_eq!(decoded.constants[1].as_bytes(), Some(&[0, 255, 7][..]));
660        Ok(())
661    }
662
663    #[test]
664    fn rejects_bad_magic() {
665        assert!(matches!(decode(b"XXXX"), Err(FormatError::BadMagic { .. })));
666    }
667
668    #[test]
669    fn rejects_bytes_after_a_complete_module() {
670        let mut b = ChunkBuilder::new("exact");
671        b.begin_function("main", 0, 1);
672        b.emit_return(0);
673        let mut bytes = encode(&b.finish());
674        bytes.push(0xFF);
675        assert!(matches!(
676            decode(&bytes),
677            Err(FormatError::Trailing { leftover: 1 })
678        ));
679    }
680
681    #[test]
682    fn list_constant_roundtrips_as_abi_v6_and_v5_rejects_the_tag() -> Result<(), FormatError> {
683        let list = match Value::try_list(vec![Value::Int(1), Value::Int(2)]) {
684            Some(list) => list,
685            None => return Err(FormatError::ValueTooNested),
686        };
687        let mut b = ChunkBuilder::new("list");
688        b.begin_function("main", 0, 1);
689        let k = b.const_(list);
690        b.emit_load_const(0, k);
691        b.emit_return(0);
692        let original = b.finish();
693        let bytes = encode(&original);
694        assert_eq!(
695            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
696            6
697        );
698        let decoded = decode(&bytes)?;
699        assert_eq!(decoded.constants, original.constants);
700        let mut v5 = bytes.clone();
701        v5[4..8].copy_from_slice(&5u32.to_le_bytes());
702        assert!(matches!(decode(&v5), Err(FormatError::UnknownValueTag(9))));
703        let wide = Value::List(std::sync::Arc::from(vec![Value::Int(1); 257]));
704        let mut wide_chunk = Chunk {
705            name: "wide".into(),
706            ..Chunk::default()
707        };
708        wide_chunk.constants.push(wide);
709        wide_chunk.functions.push(FunctionDef {
710            name: "main".into(),
711            entry: 0,
712            arity: 0,
713            num_registers: 1,
714        });
715        wide_chunk.code.push(Instruction::nullary(Opcode::Return));
716        assert!(matches!(
717            decode(&encode(&wide_chunk)),
718            Err(FormatError::LimitExceeded { what: "list", .. })
719        ));
720        Ok(())
721    }
722
723    #[test]
724    fn map_constant_roundtrips_as_abi_v7() -> Result<(), FormatError> {
725        let map = Value::try_map(vec![
726            (super::super::value::MapKey::int(1), Value::Int(2)),
727            (super::super::value::MapKey::str("k"), Value::str("v")),
728        ])
729        .ok_or(FormatError::ValueTooNested)?;
730        let mut chunk = Chunk {
731            name: "map".into(),
732            ..Chunk::default()
733        };
734        chunk.constants.push(map);
735        chunk.functions.push(FunctionDef {
736            name: "main".into(),
737            entry: 0,
738            arity: 0,
739            num_registers: 1,
740        });
741        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
742        let bytes = encode(&chunk);
743        assert_eq!(
744            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
745            ABI_VERSION_MAPS
746        );
747        let back = decode_with(&bytes, TrustLevel::Trusted)?;
748        match back.constants.first() {
749            Some(Value::Map(entries)) => {
750                assert_eq!(entries.len(), 2);
751                assert_eq!(entries[0].1, Value::Int(2));
752            }
753            _ => return Err(FormatError::Truncated),
754        }
755        let pairs = (0..256)
756            .map(|n| (super::super::value::MapKey::Int(n), Value::Int(n)))
757            .collect();
758        let full = Value::try_map(pairs).ok_or(FormatError::LimitExceeded {
759            what: "map",
760            got: 256,
761        })?;
762        let (decoded, _) = decode_value(&encode_value(&full))?;
763        match decoded {
764            Value::Map(entries) if entries.len() == 256 => {}
765            _ => return Err(FormatError::Truncated),
766        }
767        let too_big = Value::Map(std::sync::Arc::from(vec![
768            (
769                super::super::value::MapKey::Int(0),
770                Value::Int(0),
771            );
772            257
773        ]));
774        match decode_value(&encode_value(&too_big)) {
775            Err(FormatError::LimitExceeded {
776                what: "map",
777                got: 257,
778            }) => Ok(()),
779            Err(err) => Err(err),
780            Ok(_) => Err(FormatError::LimitExceeded {
781                what: "map",
782                got: 257,
783            }),
784        }
785    }
786
787    #[test]
788    fn list_of_256_round_trips_and_257_is_rejected() -> Result<(), FormatError> {
789        let items: Vec<Value> = (0..256).map(Value::Int).collect();
790        let list = Value::try_list(items).ok_or(FormatError::LimitExceeded {
791            what: "list",
792            got: 256,
793        })?;
794        let mut chunk = Chunk {
795            name: "cap".into(),
796            ..Chunk::default()
797        };
798        chunk.constants.push(list);
799        chunk.functions.push(FunctionDef {
800            name: "main".into(),
801            entry: 0,
802            arity: 0,
803            num_registers: 1,
804        });
805        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
806        let bytes = encode(&chunk);
807        assert_eq!(
808            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
809            ABI_VERSION_LISTS
810        );
811        let back = decode_with(&bytes, TrustLevel::Trusted)?;
812        match back.constants.first() {
813            Some(Value::List(items)) if items.len() == 256 => {}
814            _ => return Err(FormatError::Truncated),
815        }
816        let too_big = Value::List(std::sync::Arc::from(vec![Value::Int(1); 257]));
817        let encoded = encode_value(&too_big);
818        match decode_value(&encoded) {
819            Err(FormatError::LimitExceeded {
820                what: "list",
821                got: 257,
822            }) => Ok(()),
823            Err(err) => Err(err),
824            Ok(_) => Err(FormatError::LimitExceeded {
825                what: "list",
826                got: 257,
827            }),
828        }
829    }
830
831    #[test]
832    fn duplicate_map_key_is_not_reported_as_nesting() {
833        let mut bytes = Vec::new();
834        bytes.push(10);
835        bytes.extend_from_slice(&2u32.to_le_bytes());
836        for _ in 0..2 {
837            bytes.push(0);
838            bytes.extend_from_slice(&1i64.to_le_bytes());
839            bytes.push(2);
840            bytes.extend_from_slice(&7i64.to_le_bytes());
841        }
842        assert_eq!(decode_value(&bytes), Err(FormatError::DuplicateMapKey));
843    }
844
845    #[test]
846    fn unknown_map_key_keeps_the_discriminant() {
847        let mut bytes = Vec::new();
848        bytes.push(10);
849        bytes.extend_from_slice(&1u32.to_le_bytes());
850        bytes.push(2);
851        assert_eq!(decode_value(&bytes), Err(FormatError::UnknownMapKey(2)));
852    }
853
854    #[test]
855    fn bool_false_and_true_round_trip_as_zero_and_one() -> Result<(), FormatError> {
856        for (value, byte) in [(Value::Bool(false), 0u8), (Value::Bool(true), 1)] {
857            let bytes = encode_value(&value);
858            if bytes != [1, byte] {
859                return Err(FormatError::NonCanonicalBool(byte));
860            }
861            let (back, used) = decode_value(&bytes)?;
862            if used != 2 || back != value {
863                return Err(FormatError::Truncated);
864            }
865        }
866        Ok(())
867    }
868
869    #[test]
870    fn non_canonical_bool_bytes_are_rejected() {
871        for byte in [2u8, 127, 255] {
872            assert_eq!(
873                decode_value(&[1, byte]),
874                Err(FormatError::NonCanonicalBool(byte))
875            );
876        }
877    }
878
879    #[test]
880    fn encoded_header_is_module_abi() -> Result<(), FormatError> {
881        let list = Value::try_list(vec![Value::Int(1)]).ok_or(FormatError::ValueTooNested)?;
882        let map = Value::try_map(vec![(MapKey::Int(1), list.clone())])
883            .ok_or(FormatError::ValueTooNested)?;
884        let record = Value::try_record(vec![map.clone()]).ok_or(FormatError::ValueTooNested)?;
885        for value in [Value::Int(1), list, map, record] {
886            let mut chunk = Chunk {
887                name: "abi".into(),
888                ..Chunk::default()
889            };
890            chunk.constants.push(value);
891            chunk.functions.push(FunctionDef {
892                name: "main".into(),
893                entry: 0,
894                arity: 0,
895                num_registers: 1,
896            });
897            chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
898            let bytes = encode(&chunk);
899            let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4]));
900            if header != module_abi(&chunk.constants) {
901                return Err(FormatError::UnsupportedAbi(header));
902            }
903        }
904        Ok(())
905    }
906
907    #[test]
908    fn list_of_32_still_decodes() -> Result<(), FormatError> {
909        let list = Value::try_list((0..32).map(Value::Int).collect()).ok_or(
910            FormatError::LimitExceeded {
911                what: "list",
912                got: 32,
913            },
914        )?;
915        let (back, _) = decode_value(&encode_value(&list))?;
916        match back {
917            Value::List(items) if items.len() == 32 => Ok(()),
918            _ => Err(FormatError::Truncated),
919        }
920    }
921
922    #[test]
923    fn record_selects_abi_v8_and_older_headers_reject_the_tag() -> Result<(), FormatError> {
924        let record = Value::try_record(vec![Value::Int(1), Value::Int(2)])
925            .ok_or(FormatError::ValueTooNested)?;
926        let mut chunk = Chunk {
927            name: "rec".into(),
928            ..Chunk::default()
929        };
930        chunk.constants.push(record);
931        chunk.functions.push(FunctionDef {
932            name: "main".into(),
933            entry: 0,
934            arity: 0,
935            num_registers: 1,
936        });
937        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
938        let mut bytes = encode(&chunk);
939        assert_eq!(
940            u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
941            ABI_VERSION_RECORDS
942        );
943        let back = decode_with(&bytes, TrustLevel::Trusted)?;
944        match back.constants.first() {
945            Some(Value::Record(fields)) if fields.len() == 2 => {}
946            _ => return Err(FormatError::Truncated),
947        }
948        bytes[4..8].copy_from_slice(&ABI_VERSION_MAPS.to_le_bytes());
949        match decode_with(&bytes, TrustLevel::Trusted) {
950            Err(FormatError::UnknownValueTag(11)) => Ok(()),
951            Err(err) => Err(err),
952            Ok(_) => Err(FormatError::UnknownValueTag(11)),
953        }
954    }
955
956    #[test]
957    fn record_nested_in_a_list_or_holding_a_map_selects_abi_v8() -> Result<(), FormatError> {
958        let record = Value::try_record(vec![Value::Int(1)]).ok_or(FormatError::ValueTooNested)?;
959        let list = Value::try_list(vec![record]).ok_or(FormatError::ValueTooNested)?;
960        abi_v8_rejects_a_v7_header(list)?;
961
962        let map = Value::try_map(vec![(MapKey::Int(1), Value::Int(2))])
963            .ok_or(FormatError::ValueTooNested)?;
964        let holding = Value::try_record(vec![map]).ok_or(FormatError::ValueTooNested)?;
965        abi_v8_rejects_a_v7_header(holding)
966    }
967
968    fn abi_v8_rejects_a_v7_header(constant: Value) -> Result<(), FormatError> {
969        let mut chunk = Chunk {
970            name: "nested".into(),
971            ..Chunk::default()
972        };
973        chunk.constants.push(constant);
974        chunk.functions.push(FunctionDef {
975            name: "main".into(),
976            entry: 0,
977            arity: 0,
978            num_registers: 1,
979        });
980        chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
981        let mut bytes = encode(&chunk);
982        if u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])) != ABI_VERSION_RECORDS {
983            return Err(FormatError::UnsupportedAbi(0));
984        }
985        bytes[4..8].copy_from_slice(&ABI_VERSION_MAPS.to_le_bytes());
986        match decode_with(&bytes, TrustLevel::Trusted) {
987            Err(FormatError::UnknownValueTag(11)) => Ok(()),
988            Err(err) => Err(err),
989            Ok(_) => Err(FormatError::UnknownValueTag(11)),
990        }
991    }
992
993    /// A tiny header claiming a million items must fail with `Truncated`
994    /// without the decoder reserving for the claim. Used to reserve a
995    /// million constants / functions / instructions *before* reading any
996    /// payload byte, so a ~16-byte buffer drove an 8–40 MB allocation per
997    /// decode attempt.
998    fn tiny_module_claiming(count: u32) -> Vec<u8> {
999        let mut bytes = Vec::new();
1000        bytes.extend_from_slice(&MAGIC);
1001        bytes.extend_from_slice(&ABI_VERSION.to_le_bytes());
1002        bytes.extend_from_slice(&0u32.to_le_bytes()); // empty name
1003        bytes.extend_from_slice(&count.to_le_bytes());
1004        bytes
1005    }
1006
1007    #[test]
1008    fn a_small_buffer_claiming_a_million_constants_fails_without_reserving(
1009    ) -> Result<(), FormatError> {
1010        let bytes = tiny_module_claiming(1_000_000);
1011        match decode(&bytes) {
1012            Err(FormatError::Truncated) => Ok(()),
1013            other => other.map(|_| ()),
1014        }
1015    }
1016
1017    #[test]
1018    fn a_small_buffer_claiming_a_million_functions_fails_without_reserving(
1019    ) -> Result<(), FormatError> {
1020        let mut bytes = tiny_module_claiming(0);
1021        // 0 constants, then the functions claim.
1022        bytes.extend_from_slice(&1_000_000u32.to_le_bytes());
1023        match decode(&bytes) {
1024            Err(FormatError::Truncated) => Ok(()),
1025            other => other.map(|_| ()),
1026        }
1027    }
1028
1029    #[test]
1030    fn a_small_buffer_claiming_a_million_instructions_fails_without_reserving(
1031    ) -> Result<(), FormatError> {
1032        let mut bytes = tiny_module_claiming(0);
1033        bytes.extend_from_slice(&0u32.to_le_bytes()); // 0 functions
1034        bytes.extend_from_slice(&1_000_000u32.to_le_bytes());
1035        match decode(&bytes) {
1036            Err(FormatError::Truncated) => Ok(()),
1037            other => other.map(|_| ()),
1038        }
1039    }
1040}