Skip to main content

byteflow/bytecode/
format.rs

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