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;
12const MAX_BLOB: u32 = 1_048_576;
14pub(crate) const MAX_VALUE_DEPTH: u32 = 16;
16
17#[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 UnknownMapKey(u8),
35 NonCanonicalBool(u8),
38 UnknownOpcode {
39 at: usize,
40 byte: u8,
41 },
42 ForbiddenConstant(super::verify::ConstantKind),
43 ValueTooNested,
44 DuplicateMapKey,
47 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
91pub(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
105pub 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
136pub fn decode(bytes: &[u8]) -> Result<Chunk, FormatError> {
139 decode_with(bytes, TrustLevel::Untrusted)
140}
141
142pub 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 let n_const = r.read_count("constants")?;
163 let mut constants = Vec::with_capacity(n_const as usize);
164 for _ in 0..n_const {
165 constants.push(r.read_value(trust, 0, abi)?);
166 }
167 let n_fn = r.read_count("functions")?;
168 let mut functions = Vec::with_capacity(n_fn as usize);
169 for _ in 0..n_fn {
170 functions.push(FunctionDef {
171 name: r.read_string()?,
172 entry: r.read_u32()?,
173 arity: r.read_u8()?,
174 num_registers: r.read_u8()?,
175 });
176 }
177 let n_code = r.read_count("code")?;
178 let mut code = Vec::with_capacity(n_code as usize);
179 for at in 0..n_code as usize {
180 let byte = r.read_u8()?;
181 let op = Opcode::from_u8(byte).ok_or(FormatError::UnknownOpcode { at, byte })?;
182 code.push(Instruction {
183 op,
184 a: r.read_u8()?,
185 b: r.read_u8()?,
186 c: r.read_u8()?,
187 imm: r.read_i32()?,
188 });
189 }
190 if r.pos != bytes.len() {
191 return Err(FormatError::Trailing {
192 leftover: bytes.len() - r.pos,
193 });
194 }
195 Ok(Chunk {
196 name,
197 constants,
198 code,
199 functions,
200 })
201}
202
203fn write_string(out: &mut Vec<u8>, s: &str) {
204 let bytes = s.as_bytes();
205 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
206 out.extend_from_slice(bytes);
207}
208
209fn write_value(out: &mut Vec<u8>, value: &Value) {
210 match value {
211 Value::Unit => out.push(0),
212 Value::Bool(b) => {
213 out.push(1);
214 out.push(u8::from(*b));
215 }
216 Value::Int(i) => {
217 out.push(2);
218 out.extend_from_slice(&i.to_le_bytes());
219 }
220 Value::Float(x) => {
221 out.push(3);
222 out.extend_from_slice(&x.to_le_bytes());
223 }
224 Value::Pid(p) => {
225 out.push(4);
226 out.extend_from_slice(&p.to_le_bytes());
227 }
228 Value::Message(m) => {
229 out.push(5);
231 out.extend_from_slice(&m.sender.to_le_bytes());
232 out.extend_from_slice(&m.reply_cap.as_u128().to_le_bytes());
233 out.extend_from_slice(&m.request_id.to_le_bytes());
234 out.extend_from_slice(&m.tag.to_le_bytes());
235 write_value(out, m.payload.as_ref());
236 }
237 Value::Cap(c) => {
238 out.push(6);
239 out.extend_from_slice(&c.as_u128().to_le_bytes());
240 }
241 Value::Str(s) => {
242 out.push(7);
243 write_blob(out, s.as_bytes());
244 }
245 Value::Bytes(b) => {
246 out.push(8);
247 write_blob(out, b);
248 }
249 Value::List(items) => {
250 out.push(9);
251 out.extend_from_slice(&(items.len() as u32).to_le_bytes());
252 for item in items.iter() {
253 write_value(out, item);
254 }
255 }
256 Value::Map(entries) => {
257 out.push(10);
258 out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
259 for (key, value) in entries.iter() {
260 match key {
261 super::value::MapKey::Int(n) => {
262 out.push(0);
263 out.extend_from_slice(&n.to_le_bytes());
264 }
265 super::value::MapKey::Str(text) => {
266 out.push(1);
267 write_blob(out, text.as_bytes());
268 }
269 }
270 write_value(out, value);
271 }
272 }
273 Value::Record(fields) => {
274 out.push(11);
275 out.extend_from_slice(&(fields.len() as u32).to_le_bytes());
276 for field in fields.iter() {
277 write_value(out, field);
278 }
279 }
280 }
281}
282
283pub(crate) fn encode_value(value: &Value) -> Vec<u8> {
286 let mut out = Vec::new();
287 write_value(&mut out, value);
288 out
289}
290
291pub(crate) fn decode_value(bytes: &[u8]) -> Result<(Value, usize), FormatError> {
294 let mut reader = Reader {
295 data: bytes,
296 pos: 0,
297 };
298 let value = reader.read_value(TrustLevel::Trusted, 0, ABI_VERSION_RECORDS)?;
299 Ok((value, reader.pos))
300}
301
302fn constants_contain_record(constants: &[Value]) -> bool {
303 fn walk(value: &Value) -> bool {
304 match value {
305 Value::Record(_) => true,
306 Value::List(items) => items.iter().any(walk),
307 Value::Map(entries) => entries.iter().any(|(_, value)| walk(value)),
308 Value::Message(message) => walk(message.payload.as_ref()),
309 _ => false,
310 }
311 }
312 constants.iter().any(walk)
313}
314
315fn constants_contain_map(constants: &[Value]) -> bool {
316 fn walk(value: &Value) -> bool {
317 match value {
318 Value::Map(_) => true,
319 Value::List(items) | Value::Record(items) => items.iter().any(walk),
320 Value::Message(message) => walk(message.payload.as_ref()),
321 _ => false,
322 }
323 }
324 constants.iter().any(walk)
325}
326
327fn constants_contain_list(constants: &[Value]) -> bool {
328 fn walk(value: &Value) -> bool {
329 match value {
330 Value::List(_) => true,
331 Value::Record(fields) => fields.iter().any(walk),
332 Value::Map(entries) => entries.iter().any(|(_, value)| walk(value)),
333 Value::Message(message) => walk(message.payload.as_ref()),
334 _ => false,
335 }
336 }
337 constants.iter().any(walk)
338}
339
340fn write_blob(out: &mut Vec<u8>, bytes: &[u8]) {
341 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
342 out.extend_from_slice(bytes);
343}
344
345struct Reader<'a> {
346 data: &'a [u8],
347 pos: usize,
348}
349
350impl<'a> Reader<'a> {
351 fn rest(&self) -> usize {
352 self.data.len().saturating_sub(self.pos)
353 }
354
355 fn take(&mut self, n: usize) -> Result<&'a [u8], FormatError> {
356 if self.rest() < n {
357 return Err(FormatError::Truncated);
358 }
359 let slice = &self.data[self.pos..self.pos + n];
360 self.pos += n;
361 Ok(slice)
362 }
363
364 fn read_u8(&mut self) -> Result<u8, FormatError> {
365 Ok(self.take(1)?[0])
366 }
367
368 fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
369 let slice = self.take(N)?;
370 let mut arr = [0u8; N];
371 arr.copy_from_slice(slice);
372 Ok(arr)
373 }
374
375 fn read_u32(&mut self) -> Result<u32, FormatError> {
376 Ok(u32::from_le_bytes(self.read_array()?))
377 }
378
379 fn read_u16(&mut self) -> Result<u16, FormatError> {
380 Ok(u16::from_le_bytes(self.read_array()?))
381 }
382
383 fn read_i32(&mut self) -> Result<i32, FormatError> {
384 Ok(i32::from_le_bytes(self.read_array()?))
385 }
386
387 fn read_i64(&mut self) -> Result<i64, FormatError> {
388 Ok(i64::from_le_bytes(self.read_array()?))
389 }
390
391 fn read_u64(&mut self) -> Result<u64, FormatError> {
392 Ok(u64::from_le_bytes(self.read_array()?))
393 }
394
395 fn read_u128(&mut self) -> Result<u128, FormatError> {
396 Ok(u128::from_le_bytes(self.read_array()?))
397 }
398
399 fn read_f64(&mut self) -> Result<f64, FormatError> {
400 Ok(f64::from_le_bytes(self.read_array()?))
401 }
402
403 fn read_count(&mut self, what: &'static str) -> Result<u32, FormatError> {
404 let n = self.read_u32()?;
405 if n > MAX_ITEMS {
406 return Err(FormatError::LimitExceeded { what, got: n });
407 }
408 Ok(n)
409 }
410
411 fn read_string(&mut self) -> Result<String, FormatError> {
412 let len = self.read_u32()?;
413 if len > MAX_NAME {
414 return Err(FormatError::LimitExceeded {
415 what: "name",
416 got: len,
417 });
418 }
419 let bytes = self.take(len as usize)?;
420 String::from_utf8(bytes.to_vec()).map_err(|_| FormatError::BadUtf8)
421 }
422
423 fn read_value(
424 &mut self,
425 trust: TrustLevel,
426 depth: u32,
427 abi: u32,
428 ) -> Result<Value, FormatError> {
429 if depth > MAX_VALUE_DEPTH {
430 return Err(FormatError::ValueTooNested);
431 }
432 match self.read_u8()? {
433 0 => Ok(Value::Unit),
434 1 => match self.read_u8()? {
435 0 => Ok(Value::Bool(false)),
436 1 => Ok(Value::Bool(true)),
437 byte => Err(FormatError::NonCanonicalBool(byte)),
438 },
439 2 => Ok(Value::Int(self.read_i64()?)),
440 3 => Ok(Value::Float(self.read_f64()?)),
441 4 => {
442 if trust == TrustLevel::Untrusted {
443 return Err(FormatError::ForbiddenConstant(
444 super::verify::ConstantKind::ProcessId,
445 ));
446 }
447 Ok(Value::Pid(self.read_u64()?))
448 }
449 5 => {
450 if trust == TrustLevel::Untrusted {
451 return Err(FormatError::ForbiddenConstant(
452 super::verify::ConstantKind::Message,
453 ));
454 }
455 let sender = self.read_u64()?;
456 let reply_cap = super::cap::CapId::from_raw(self.read_u128()?);
457 let request_id = self.read_u64()?;
458 let tag = self.read_u16()?;
459 let payload = self.read_value(trust, depth + 1, abi)?;
460 Ok(Value::Message(
461 super::value::Message::new(sender, request_id, tag, payload)
462 .authenticate(sender, reply_cap),
463 ))
464 }
465 6 => {
466 if trust == TrustLevel::Untrusted {
467 return Err(FormatError::ForbiddenConstant(
468 super::verify::ConstantKind::Capability,
469 ));
470 }
471 Ok(Value::Cap(super::cap::CapId::from_raw(self.read_u128()?)))
472 }
473 7 => {
474 let bytes = self.read_blob("str")?;
475 let s = std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
476 Ok(Value::str(s))
477 }
478 8 => Ok(Value::bytes(self.read_blob("bytes")?)),
479 9 => {
480 if abi < ABI_VERSION_LISTS {
481 return Err(FormatError::UnknownValueTag(9));
482 }
483 let n = self.read_u32()?;
484 if n > super::value::MAX_LIST_LEN as u32 {
485 return Err(FormatError::LimitExceeded {
486 what: "list",
487 got: n,
488 });
489 }
490 let mut items = Vec::with_capacity(n as usize);
491 for _ in 0..n {
492 items.push(self.read_value(trust, depth + 1, abi)?);
493 }
494 Value::try_list(items).ok_or(FormatError::ValueTooNested)
495 }
496 10 => {
497 if abi < ABI_VERSION_MAPS {
498 return Err(FormatError::UnknownValueTag(10));
499 }
500 let n = self.read_u32()?;
501 if n > super::value::MAX_MAP_LEN as u32 {
502 return Err(FormatError::LimitExceeded {
503 what: "map",
504 got: n,
505 });
506 }
507 let mut entries = Vec::with_capacity(n as usize);
508 for _ in 0..n {
509 let key = match self.read_u8()? {
510 0 => super::value::MapKey::Int(i64::from_le_bytes(self.read_array()?)),
511 1 => {
512 let bytes = self.read_blob("map key")?;
513 let text =
514 std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
515 super::value::MapKey::str(text)
516 }
517 tag => return Err(FormatError::UnknownMapKey(tag)),
518 };
519 let value = self.read_value(trust, depth + 1, abi)?;
520 entries.push((key, value));
521 }
522 if super::value::map_has_duplicate_key(&entries) {
523 return Err(FormatError::DuplicateMapKey);
524 }
525 super::value::Value::try_map(entries).ok_or(FormatError::ValueTooNested)
526 }
527 11 => {
528 if abi < ABI_VERSION_RECORDS {
529 return Err(FormatError::UnknownValueTag(11));
530 }
531 let n = self.read_u32()?;
532 if n > super::value::MAX_RECORD_LEN as u32 {
533 return Err(FormatError::LimitExceeded {
534 what: "record",
535 got: n,
536 });
537 }
538 let mut fields = Vec::with_capacity(n as usize);
539 for _ in 0..n {
540 fields.push(self.read_value(trust, depth + 1, abi)?);
541 }
542 super::value::Value::try_record(fields).ok_or(FormatError::ValueTooNested)
543 }
544 tag => Err(FormatError::UnknownValueTag(tag)),
545 }
546 }
547
548 fn read_blob(&mut self, what: &'static str) -> Result<&'a [u8], FormatError> {
549 let len = self.read_u32()?;
550 if len > MAX_BLOB {
551 return Err(FormatError::LimitExceeded { what, got: len });
552 }
553 self.take(len as usize)
554 }
555}
556
557#[cfg(test)]
558mod tests {
559 use super::super::value::MapKey;
560 use super::*;
561 use crate::bytecode::builder::ChunkBuilder;
562 use crate::bytecode::opcode::Opcode;
563 use crate::bytecode::verify::{verify, TrustLevel};
564
565 #[test]
566 fn roundtrip_preserves_chunk() -> Result<(), FormatError> {
567 let mut b = ChunkBuilder::new("roundtrip");
568 b.begin_function("main", 0, 2);
569 let k = b.const_(Value::Int(9));
570 b.emit_load_const(0, k);
571 b.emit_load_imm(1, 1);
572 b.emit_binop(Opcode::Add, 0, 0, 1);
573 b.emit_return(0);
574 let original = b.finish();
575 let bytes = encode(&original);
576 assert_eq!(&bytes[..4], &MAGIC);
577 let decoded = decode(&bytes)?;
578 assert!(verify(&decoded).is_ok());
579 assert_eq!(decoded.name, original.name);
580 assert_eq!(decoded.constants, original.constants);
581 assert_eq!(decoded.code, original.code);
582 assert_eq!(decoded.functions, original.functions);
583 Ok(())
584 }
585
586 #[test]
587 fn roundtrip_preserves_message_constant() -> Result<(), FormatError> {
588 use super::super::value::Message;
589 let mut b = ChunkBuilder::new("msg-const");
590 b.begin_function("main", 0, 1);
591 let k = b.const_(Value::Message(Message::new(1, 2, 3, 4u64)));
592 b.emit_load_const(0, k);
593 b.emit_return(0);
594 let original = b.finish();
595 let decoded = decode_with(&encode(&original), TrustLevel::Trusted)?;
596 assert_eq!(decoded.constants, original.constants);
597 let got = decoded.constants[0]
598 .as_message()
599 .ok_or(FormatError::Truncated)?;
600 assert_eq!(got.sender, 1);
601 assert_eq!(got.request_id, 2);
602 assert_eq!(got.tag, 3);
603 assert_eq!(got.payload.as_ref(), &Value::Int(4));
604 Ok(())
605 }
606
607 #[test]
608 fn untrusted_decode_rejects_cap_constant() {
609 use crate::bytecode::cap::CapId;
610 let mut b = ChunkBuilder::new("cap-const");
611 b.begin_function("main", 0, 1);
612 let k = b.const_(Value::Cap(CapId::from_raw(1)));
613 b.emit_load_const(0, k);
614 b.emit_return(0);
615 let bytes = encode(&b.finish());
616 assert!(matches!(
617 decode(&bytes),
618 Err(FormatError::ForbiddenConstant(_))
619 ));
620 assert!(decode_with(&bytes, TrustLevel::Trusted).is_ok());
621 }
622
623 #[test]
624 fn roundtrip_preserves_str_and_bytes_constants() -> Result<(), FormatError> {
625 let mut b = ChunkBuilder::new("blob-const");
626 b.begin_function("main", 0, 2);
627 let ks = b.const_(Value::str("olá"));
628 let kb = b.const_(Value::bytes([0u8, 255, 7]));
629 b.emit_load_const(0, ks);
630 b.emit_load_const(1, kb);
631 b.emit_return(0);
632 let original = b.finish();
633 let decoded = decode(&encode(&original))?;
634 assert_eq!(decoded.constants, original.constants);
635 assert_eq!(decoded.constants[0].as_str(), Some("olá"));
636 assert_eq!(decoded.constants[1].as_bytes(), Some(&[0, 255, 7][..]));
637 Ok(())
638 }
639
640 #[test]
641 fn rejects_bad_magic() {
642 assert!(matches!(decode(b"XXXX"), Err(FormatError::BadMagic { .. })));
643 }
644
645 #[test]
646 fn rejects_bytes_after_a_complete_module() {
647 let mut b = ChunkBuilder::new("exact");
648 b.begin_function("main", 0, 1);
649 b.emit_return(0);
650 let mut bytes = encode(&b.finish());
651 bytes.push(0xFF);
652 assert!(matches!(
653 decode(&bytes),
654 Err(FormatError::Trailing { leftover: 1 })
655 ));
656 }
657
658 #[test]
659 fn list_constant_roundtrips_as_abi_v6_and_v5_rejects_the_tag() -> Result<(), FormatError> {
660 let list = match Value::try_list(vec![Value::Int(1), Value::Int(2)]) {
661 Some(list) => list,
662 None => return Err(FormatError::ValueTooNested),
663 };
664 let mut b = ChunkBuilder::new("list");
665 b.begin_function("main", 0, 1);
666 let k = b.const_(list);
667 b.emit_load_const(0, k);
668 b.emit_return(0);
669 let original = b.finish();
670 let bytes = encode(&original);
671 assert_eq!(
672 u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
673 6
674 );
675 let decoded = decode(&bytes)?;
676 assert_eq!(decoded.constants, original.constants);
677 let mut v5 = bytes.clone();
678 v5[4..8].copy_from_slice(&5u32.to_le_bytes());
679 assert!(matches!(decode(&v5), Err(FormatError::UnknownValueTag(9))));
680 let wide = Value::List(std::sync::Arc::from(vec![Value::Int(1); 257]));
681 let mut wide_chunk = Chunk {
682 name: "wide".into(),
683 ..Chunk::default()
684 };
685 wide_chunk.constants.push(wide);
686 wide_chunk.functions.push(FunctionDef {
687 name: "main".into(),
688 entry: 0,
689 arity: 0,
690 num_registers: 1,
691 });
692 wide_chunk.code.push(Instruction::nullary(Opcode::Return));
693 assert!(matches!(
694 decode(&encode(&wide_chunk)),
695 Err(FormatError::LimitExceeded { what: "list", .. })
696 ));
697 Ok(())
698 }
699
700 #[test]
701 fn map_constant_roundtrips_as_abi_v7() -> Result<(), FormatError> {
702 let map = Value::try_map(vec![
703 (super::super::value::MapKey::int(1), Value::Int(2)),
704 (super::super::value::MapKey::str("k"), Value::str("v")),
705 ])
706 .ok_or(FormatError::ValueTooNested)?;
707 let mut chunk = Chunk {
708 name: "map".into(),
709 ..Chunk::default()
710 };
711 chunk.constants.push(map);
712 chunk.functions.push(FunctionDef {
713 name: "main".into(),
714 entry: 0,
715 arity: 0,
716 num_registers: 1,
717 });
718 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
719 let bytes = encode(&chunk);
720 assert_eq!(
721 u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
722 ABI_VERSION_MAPS
723 );
724 let back = decode_with(&bytes, TrustLevel::Trusted)?;
725 match back.constants.first() {
726 Some(Value::Map(entries)) => {
727 assert_eq!(entries.len(), 2);
728 assert_eq!(entries[0].1, Value::Int(2));
729 }
730 _ => return Err(FormatError::Truncated),
731 }
732 let pairs = (0..256)
733 .map(|n| (super::super::value::MapKey::Int(n), Value::Int(n)))
734 .collect();
735 let full = Value::try_map(pairs).ok_or(FormatError::LimitExceeded {
736 what: "map",
737 got: 256,
738 })?;
739 let (decoded, _) = decode_value(&encode_value(&full))?;
740 match decoded {
741 Value::Map(entries) if entries.len() == 256 => {}
742 _ => return Err(FormatError::Truncated),
743 }
744 let too_big = Value::Map(std::sync::Arc::from(vec![
745 (
746 super::super::value::MapKey::Int(0),
747 Value::Int(0),
748 );
749 257
750 ]));
751 match decode_value(&encode_value(&too_big)) {
752 Err(FormatError::LimitExceeded {
753 what: "map",
754 got: 257,
755 }) => Ok(()),
756 Err(err) => Err(err),
757 Ok(_) => Err(FormatError::LimitExceeded {
758 what: "map",
759 got: 257,
760 }),
761 }
762 }
763
764 #[test]
765 fn list_of_256_round_trips_and_257_is_rejected() -> Result<(), FormatError> {
766 let items: Vec<Value> = (0..256).map(Value::Int).collect();
767 let list = Value::try_list(items).ok_or(FormatError::LimitExceeded {
768 what: "list",
769 got: 256,
770 })?;
771 let mut chunk = Chunk {
772 name: "cap".into(),
773 ..Chunk::default()
774 };
775 chunk.constants.push(list);
776 chunk.functions.push(FunctionDef {
777 name: "main".into(),
778 entry: 0,
779 arity: 0,
780 num_registers: 1,
781 });
782 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
783 let bytes = encode(&chunk);
784 assert_eq!(
785 u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
786 ABI_VERSION_LISTS
787 );
788 let back = decode_with(&bytes, TrustLevel::Trusted)?;
789 match back.constants.first() {
790 Some(Value::List(items)) if items.len() == 256 => {}
791 _ => return Err(FormatError::Truncated),
792 }
793 let too_big = Value::List(std::sync::Arc::from(vec![Value::Int(1); 257]));
794 let encoded = encode_value(&too_big);
795 match decode_value(&encoded) {
796 Err(FormatError::LimitExceeded {
797 what: "list",
798 got: 257,
799 }) => Ok(()),
800 Err(err) => Err(err),
801 Ok(_) => Err(FormatError::LimitExceeded {
802 what: "list",
803 got: 257,
804 }),
805 }
806 }
807
808 #[test]
809 fn duplicate_map_key_is_not_reported_as_nesting() {
810 let mut bytes = Vec::new();
811 bytes.push(10);
812 bytes.extend_from_slice(&2u32.to_le_bytes());
813 for _ in 0..2 {
814 bytes.push(0);
815 bytes.extend_from_slice(&1i64.to_le_bytes());
816 bytes.push(2);
817 bytes.extend_from_slice(&7i64.to_le_bytes());
818 }
819 assert_eq!(decode_value(&bytes), Err(FormatError::DuplicateMapKey));
820 }
821
822 #[test]
823 fn unknown_map_key_keeps_the_discriminant() {
824 let mut bytes = Vec::new();
825 bytes.push(10);
826 bytes.extend_from_slice(&1u32.to_le_bytes());
827 bytes.push(2);
828 assert_eq!(decode_value(&bytes), Err(FormatError::UnknownMapKey(2)));
829 }
830
831 #[test]
832 fn bool_false_and_true_round_trip_as_zero_and_one() -> Result<(), FormatError> {
833 for (value, byte) in [(Value::Bool(false), 0u8), (Value::Bool(true), 1)] {
834 let bytes = encode_value(&value);
835 if bytes != [1, byte] {
836 return Err(FormatError::NonCanonicalBool(byte));
837 }
838 let (back, used) = decode_value(&bytes)?;
839 if used != 2 || back != value {
840 return Err(FormatError::Truncated);
841 }
842 }
843 Ok(())
844 }
845
846 #[test]
847 fn non_canonical_bool_bytes_are_rejected() {
848 for byte in [2u8, 127, 255] {
849 assert_eq!(
850 decode_value(&[1, byte]),
851 Err(FormatError::NonCanonicalBool(byte))
852 );
853 }
854 }
855
856 #[test]
857 fn encoded_header_is_module_abi() -> Result<(), FormatError> {
858 let list = Value::try_list(vec![Value::Int(1)]).ok_or(FormatError::ValueTooNested)?;
859 let map = Value::try_map(vec![(MapKey::Int(1), list.clone())])
860 .ok_or(FormatError::ValueTooNested)?;
861 let record = Value::try_record(vec![map.clone()]).ok_or(FormatError::ValueTooNested)?;
862 for value in [Value::Int(1), list, map, record] {
863 let mut chunk = Chunk {
864 name: "abi".into(),
865 ..Chunk::default()
866 };
867 chunk.constants.push(value);
868 chunk.functions.push(FunctionDef {
869 name: "main".into(),
870 entry: 0,
871 arity: 0,
872 num_registers: 1,
873 });
874 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
875 let bytes = encode(&chunk);
876 let header = u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4]));
877 if header != module_abi(&chunk.constants) {
878 return Err(FormatError::UnsupportedAbi(header));
879 }
880 }
881 Ok(())
882 }
883
884 #[test]
885 fn list_of_32_still_decodes() -> Result<(), FormatError> {
886 let list = Value::try_list((0..32).map(Value::Int).collect()).ok_or(
887 FormatError::LimitExceeded {
888 what: "list",
889 got: 32,
890 },
891 )?;
892 let (back, _) = decode_value(&encode_value(&list))?;
893 match back {
894 Value::List(items) if items.len() == 32 => Ok(()),
895 _ => Err(FormatError::Truncated),
896 }
897 }
898
899 #[test]
900 fn record_selects_abi_v8_and_older_headers_reject_the_tag() -> Result<(), FormatError> {
901 let record = Value::try_record(vec![Value::Int(1), Value::Int(2)])
902 .ok_or(FormatError::ValueTooNested)?;
903 let mut chunk = Chunk {
904 name: "rec".into(),
905 ..Chunk::default()
906 };
907 chunk.constants.push(record);
908 chunk.functions.push(FunctionDef {
909 name: "main".into(),
910 entry: 0,
911 arity: 0,
912 num_registers: 1,
913 });
914 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
915 let mut bytes = encode(&chunk);
916 assert_eq!(
917 u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
918 ABI_VERSION_RECORDS
919 );
920 let back = decode_with(&bytes, TrustLevel::Trusted)?;
921 match back.constants.first() {
922 Some(Value::Record(fields)) if fields.len() == 2 => {}
923 _ => return Err(FormatError::Truncated),
924 }
925 bytes[4..8].copy_from_slice(&ABI_VERSION_MAPS.to_le_bytes());
926 match decode_with(&bytes, TrustLevel::Trusted) {
927 Err(FormatError::UnknownValueTag(11)) => Ok(()),
928 Err(err) => Err(err),
929 Ok(_) => Err(FormatError::UnknownValueTag(11)),
930 }
931 }
932
933 #[test]
934 fn record_nested_in_a_list_or_holding_a_map_selects_abi_v8() -> Result<(), FormatError> {
935 let record = Value::try_record(vec![Value::Int(1)]).ok_or(FormatError::ValueTooNested)?;
936 let list = Value::try_list(vec![record]).ok_or(FormatError::ValueTooNested)?;
937 abi_v8_rejects_a_v7_header(list)?;
938
939 let map = Value::try_map(vec![(MapKey::Int(1), Value::Int(2))])
940 .ok_or(FormatError::ValueTooNested)?;
941 let holding = Value::try_record(vec![map]).ok_or(FormatError::ValueTooNested)?;
942 abi_v8_rejects_a_v7_header(holding)
943 }
944
945 fn abi_v8_rejects_a_v7_header(constant: Value) -> Result<(), FormatError> {
946 let mut chunk = Chunk {
947 name: "nested".into(),
948 ..Chunk::default()
949 };
950 chunk.constants.push(constant);
951 chunk.functions.push(FunctionDef {
952 name: "main".into(),
953 entry: 0,
954 arity: 0,
955 num_registers: 1,
956 });
957 chunk.code.push(Instruction::abc(Opcode::Return, 0, 0, 0));
958 let mut bytes = encode(&chunk);
959 if u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])) != ABI_VERSION_RECORDS {
960 return Err(FormatError::UnsupportedAbi(0));
961 }
962 bytes[4..8].copy_from_slice(&ABI_VERSION_MAPS.to_le_bytes());
963 match decode_with(&bytes, TrustLevel::Trusted) {
964 Err(FormatError::UnknownValueTag(11)) => Ok(()),
965 Err(err) => Err(err),
966 Ok(_) => Err(FormatError::UnknownValueTag(11)),
967 }
968 }
969}