1use super::chunk::{Chunk, FunctionDef, ABI_VERSION, ABI_VERSION_LISTS, MAGIC};
2use super::instruction::Instruction;
3use super::opcode::Opcode;
4use super::value::Value;
5use super::verify::TrustLevel;
6
7const MAX_NAME: u32 = 64 * 1024;
8const MAX_ITEMS: u32 = 1_000_000;
9const MAX_BLOB: u32 = 1_048_576;
11pub(crate) const MAX_VALUE_DEPTH: u32 = 16;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum FormatError {
17 BadMagic {
18 found: [u8; 4],
19 },
20 UnsupportedAbi(u32),
21 Truncated,
22 LimitExceeded {
23 what: &'static str,
24 got: u32,
25 },
26 BadUtf8,
27 UnknownValueTag(u8),
28 UnknownOpcode {
29 at: usize,
30 byte: u8,
31 },
32 ForbiddenConstant(super::verify::ConstantKind),
33 ValueTooNested,
34 Trailing {
37 leftover: usize,
38 },
39}
40
41impl std::fmt::Display for FormatError {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 match self {
44 FormatError::BadMagic { found } => {
45 write!(f, "bad magic {found:?}, expected {:?}", MAGIC)
46 }
47 FormatError::UnsupportedAbi(v) => write!(f, "unsupported ABI version {v}"),
48 FormatError::Truncated => write!(f, "truncated .bf module"),
49 FormatError::LimitExceeded { what, got } => {
50 write!(f, "{what} count {got} exceeds decoder limit")
51 }
52 FormatError::BadUtf8 => write!(f, "name is not valid UTF-8"),
53 FormatError::UnknownValueTag(t) => write!(f, "unknown value tag 0x{t:02X}"),
54 FormatError::UnknownOpcode { at, byte } => {
55 write!(f, "unknown opcode 0x{byte:02X} at instruction {at}")
56 }
57 FormatError::ForbiddenConstant(kind) => {
58 write!(
59 f,
60 "untrusted module must not embed {kind} in the constant pool"
61 )
62 }
63 FormatError::ValueTooNested => write!(f, "value nesting exceeds decoder limit"),
64 FormatError::Trailing { leftover } => {
65 write!(f, "trailing {leftover} bytes after module")
66 }
67 }
68 }
69}
70
71impl std::error::Error for FormatError {}
72
73pub fn encode(chunk: &Chunk) -> Vec<u8> {
75 let mut out = Vec::new();
76 out.extend_from_slice(&MAGIC);
77 let abi = if constants_contain_list(&chunk.constants) {
78 ABI_VERSION_LISTS
79 } else {
80 ABI_VERSION
81 };
82 out.extend_from_slice(&abi.to_le_bytes());
83 write_string(&mut out, &chunk.name);
84 out.extend_from_slice(&(chunk.constants.len() as u32).to_le_bytes());
85 for value in &chunk.constants {
86 write_value(&mut out, value);
87 }
88 out.extend_from_slice(&(chunk.functions.len() as u32).to_le_bytes());
89 for def in &chunk.functions {
90 write_string(&mut out, &def.name);
91 out.extend_from_slice(&def.entry.to_le_bytes());
92 out.push(def.arity);
93 out.push(def.num_registers);
94 }
95 out.extend_from_slice(&(chunk.code.len() as u32).to_le_bytes());
96 for instr in &chunk.code {
97 out.push(instr.op.as_u8());
98 out.push(instr.a);
99 out.push(instr.b);
100 out.push(instr.c);
101 out.extend_from_slice(&instr.imm.to_le_bytes());
102 }
103 out
104}
105
106pub fn decode(bytes: &[u8]) -> Result<Chunk, FormatError> {
109 decode_with(bytes, TrustLevel::Untrusted)
110}
111
112pub fn decode_with(bytes: &[u8], trust: TrustLevel) -> Result<Chunk, FormatError> {
115 let mut r = Reader {
116 data: bytes,
117 pos: 0,
118 };
119 let magic = r.read_array::<4>()?;
120 if magic != MAGIC {
121 return Err(FormatError::BadMagic { found: magic });
122 }
123 let abi = r.read_u32()?;
124 if abi != ABI_VERSION && abi != ABI_VERSION_LISTS {
125 return Err(FormatError::UnsupportedAbi(abi));
126 }
127 let name = r.read_string()?;
128 let n_const = r.read_count("constants")?;
129 let mut constants = Vec::with_capacity(n_const as usize);
130 for _ in 0..n_const {
131 constants.push(r.read_value(trust, 0, abi)?);
132 }
133 let n_fn = r.read_count("functions")?;
134 let mut functions = Vec::with_capacity(n_fn as usize);
135 for _ in 0..n_fn {
136 functions.push(FunctionDef {
137 name: r.read_string()?,
138 entry: r.read_u32()?,
139 arity: r.read_u8()?,
140 num_registers: r.read_u8()?,
141 });
142 }
143 let n_code = r.read_count("code")?;
144 let mut code = Vec::with_capacity(n_code as usize);
145 for at in 0..n_code as usize {
146 let byte = r.read_u8()?;
147 let op = Opcode::from_u8(byte).ok_or(FormatError::UnknownOpcode { at, byte })?;
148 code.push(Instruction {
149 op,
150 a: r.read_u8()?,
151 b: r.read_u8()?,
152 c: r.read_u8()?,
153 imm: r.read_i32()?,
154 });
155 }
156 if r.pos != bytes.len() {
157 return Err(FormatError::Trailing {
158 leftover: bytes.len() - r.pos,
159 });
160 }
161 Ok(Chunk {
162 name,
163 constants,
164 code,
165 functions,
166 })
167}
168
169fn write_string(out: &mut Vec<u8>, s: &str) {
170 let bytes = s.as_bytes();
171 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
172 out.extend_from_slice(bytes);
173}
174
175fn write_value(out: &mut Vec<u8>, value: &Value) {
176 match value {
177 Value::Unit => out.push(0),
178 Value::Bool(b) => {
179 out.push(1);
180 out.push(u8::from(*b));
181 }
182 Value::Int(i) => {
183 out.push(2);
184 out.extend_from_slice(&i.to_le_bytes());
185 }
186 Value::Float(x) => {
187 out.push(3);
188 out.extend_from_slice(&x.to_le_bytes());
189 }
190 Value::Pid(p) => {
191 out.push(4);
192 out.extend_from_slice(&p.to_le_bytes());
193 }
194 Value::Message(m) => {
195 out.push(5);
197 out.extend_from_slice(&m.sender.to_le_bytes());
198 out.extend_from_slice(&m.reply_cap.as_u128().to_le_bytes());
199 out.extend_from_slice(&m.request_id.to_le_bytes());
200 out.extend_from_slice(&m.tag.to_le_bytes());
201 write_value(out, m.payload.as_ref());
202 }
203 Value::Cap(c) => {
204 out.push(6);
205 out.extend_from_slice(&c.as_u128().to_le_bytes());
206 }
207 Value::Str(s) => {
208 out.push(7);
209 write_blob(out, s.as_bytes());
210 }
211 Value::Bytes(b) => {
212 out.push(8);
213 write_blob(out, b);
214 }
215 Value::List(items) => {
216 out.push(9);
217 out.extend_from_slice(&(items.len() as u32).to_le_bytes());
218 for item in items.iter() {
219 write_value(out, item);
220 }
221 }
222 }
223}
224
225fn constants_contain_list(constants: &[Value]) -> bool {
226 fn walk(value: &Value) -> bool {
227 match value {
228 Value::List(_) => true,
229 Value::Message(message) => walk(message.payload.as_ref()),
230 _ => false,
231 }
232 }
233 constants.iter().any(walk)
234}
235
236fn write_blob(out: &mut Vec<u8>, bytes: &[u8]) {
237 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
238 out.extend_from_slice(bytes);
239}
240
241struct Reader<'a> {
242 data: &'a [u8],
243 pos: usize,
244}
245
246impl<'a> Reader<'a> {
247 fn rest(&self) -> usize {
248 self.data.len().saturating_sub(self.pos)
249 }
250
251 fn take(&mut self, n: usize) -> Result<&'a [u8], FormatError> {
252 if self.rest() < n {
253 return Err(FormatError::Truncated);
254 }
255 let slice = &self.data[self.pos..self.pos + n];
256 self.pos += n;
257 Ok(slice)
258 }
259
260 fn read_u8(&mut self) -> Result<u8, FormatError> {
261 Ok(self.take(1)?[0])
262 }
263
264 fn read_array<const N: usize>(&mut self) -> Result<[u8; N], FormatError> {
265 let slice = self.take(N)?;
266 let mut arr = [0u8; N];
267 arr.copy_from_slice(slice);
268 Ok(arr)
269 }
270
271 fn read_u32(&mut self) -> Result<u32, FormatError> {
272 Ok(u32::from_le_bytes(self.read_array()?))
273 }
274
275 fn read_u16(&mut self) -> Result<u16, FormatError> {
276 Ok(u16::from_le_bytes(self.read_array()?))
277 }
278
279 fn read_i32(&mut self) -> Result<i32, FormatError> {
280 Ok(i32::from_le_bytes(self.read_array()?))
281 }
282
283 fn read_i64(&mut self) -> Result<i64, FormatError> {
284 Ok(i64::from_le_bytes(self.read_array()?))
285 }
286
287 fn read_u64(&mut self) -> Result<u64, FormatError> {
288 Ok(u64::from_le_bytes(self.read_array()?))
289 }
290
291 fn read_u128(&mut self) -> Result<u128, FormatError> {
292 Ok(u128::from_le_bytes(self.read_array()?))
293 }
294
295 fn read_f64(&mut self) -> Result<f64, FormatError> {
296 Ok(f64::from_le_bytes(self.read_array()?))
297 }
298
299 fn read_count(&mut self, what: &'static str) -> Result<u32, FormatError> {
300 let n = self.read_u32()?;
301 if n > MAX_ITEMS {
302 return Err(FormatError::LimitExceeded { what, got: n });
303 }
304 Ok(n)
305 }
306
307 fn read_string(&mut self) -> Result<String, FormatError> {
308 let len = self.read_u32()?;
309 if len > MAX_NAME {
310 return Err(FormatError::LimitExceeded {
311 what: "name",
312 got: len,
313 });
314 }
315 let bytes = self.take(len as usize)?;
316 String::from_utf8(bytes.to_vec()).map_err(|_| FormatError::BadUtf8)
317 }
318
319 fn read_value(
320 &mut self,
321 trust: TrustLevel,
322 depth: u32,
323 abi: u32,
324 ) -> Result<Value, FormatError> {
325 if depth > MAX_VALUE_DEPTH {
326 return Err(FormatError::ValueTooNested);
327 }
328 match self.read_u8()? {
329 0 => Ok(Value::Unit),
330 1 => Ok(Value::Bool(self.read_u8()? != 0)),
331 2 => Ok(Value::Int(self.read_i64()?)),
332 3 => Ok(Value::Float(self.read_f64()?)),
333 4 => {
334 if trust == TrustLevel::Untrusted {
335 return Err(FormatError::ForbiddenConstant(
336 super::verify::ConstantKind::ProcessId,
337 ));
338 }
339 Ok(Value::Pid(self.read_u64()?))
340 }
341 5 => {
342 if trust == TrustLevel::Untrusted {
343 return Err(FormatError::ForbiddenConstant(
344 super::verify::ConstantKind::Message,
345 ));
346 }
347 let sender = self.read_u64()?;
348 let reply_cap = super::cap::CapId::from_raw(self.read_u128()?);
349 let request_id = self.read_u64()?;
350 let tag = self.read_u16()?;
351 let payload = self.read_value(trust, depth + 1, abi)?;
352 Ok(Value::Message(
353 super::value::Message::new(sender, request_id, tag, payload)
354 .authenticate(sender, reply_cap),
355 ))
356 }
357 6 => {
358 if trust == TrustLevel::Untrusted {
359 return Err(FormatError::ForbiddenConstant(
360 super::verify::ConstantKind::Capability,
361 ));
362 }
363 Ok(Value::Cap(super::cap::CapId::from_raw(self.read_u128()?)))
364 }
365 7 => {
366 let bytes = self.read_blob("str")?;
367 let s = std::str::from_utf8(bytes).map_err(|_| FormatError::BadUtf8)?;
368 Ok(Value::str(s))
369 }
370 8 => Ok(Value::bytes(self.read_blob("bytes")?)),
371 9 => {
372 if abi < ABI_VERSION_LISTS {
373 return Err(FormatError::UnknownValueTag(9));
374 }
375 let n = self.read_u32()?;
376 if n > super::value::MAX_LIST_LEN as u32 {
377 return Err(FormatError::LimitExceeded {
378 what: "list",
379 got: n,
380 });
381 }
382 let mut items = Vec::with_capacity(n as usize);
383 for _ in 0..n {
384 items.push(self.read_value(trust, depth + 1, abi)?);
385 }
386 Value::try_list(items).ok_or(FormatError::ValueTooNested)
387 }
388 tag => Err(FormatError::UnknownValueTag(tag)),
389 }
390 }
391
392 fn read_blob(&mut self, what: &'static str) -> Result<&'a [u8], FormatError> {
393 let len = self.read_u32()?;
394 if len > MAX_BLOB {
395 return Err(FormatError::LimitExceeded { what, got: len });
396 }
397 self.take(len as usize)
398 }
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404 use crate::bytecode::builder::ChunkBuilder;
405 use crate::bytecode::opcode::Opcode;
406 use crate::bytecode::verify::{verify, TrustLevel};
407
408 #[test]
409 fn roundtrip_preserves_chunk() -> Result<(), FormatError> {
410 let mut b = ChunkBuilder::new("roundtrip");
411 b.begin_function("main", 0, 2);
412 let k = b.const_(Value::Int(9));
413 b.emit_load_const(0, k);
414 b.emit_load_imm(1, 1);
415 b.emit_binop(Opcode::Add, 0, 0, 1);
416 b.emit_return(0);
417 let original = b.finish();
418 let bytes = encode(&original);
419 assert_eq!(&bytes[..4], &MAGIC);
420 let decoded = decode(&bytes)?;
421 assert!(verify(&decoded).is_ok());
422 assert_eq!(decoded.name, original.name);
423 assert_eq!(decoded.constants, original.constants);
424 assert_eq!(decoded.code, original.code);
425 assert_eq!(decoded.functions, original.functions);
426 Ok(())
427 }
428
429 #[test]
430 fn roundtrip_preserves_message_constant() -> Result<(), FormatError> {
431 use super::super::value::Message;
432 let mut b = ChunkBuilder::new("msg-const");
433 b.begin_function("main", 0, 1);
434 let k = b.const_(Value::Message(Message::new(1, 2, 3, 4u64)));
435 b.emit_load_const(0, k);
436 b.emit_return(0);
437 let original = b.finish();
438 let decoded = decode_with(&encode(&original), TrustLevel::Trusted)?;
439 assert_eq!(decoded.constants, original.constants);
440 let got = decoded.constants[0]
441 .as_message()
442 .ok_or(FormatError::Truncated)?;
443 assert_eq!(got.sender, 1);
444 assert_eq!(got.request_id, 2);
445 assert_eq!(got.tag, 3);
446 assert_eq!(got.payload.as_ref(), &Value::Int(4));
447 Ok(())
448 }
449
450 #[test]
451 fn untrusted_decode_rejects_cap_constant() {
452 use crate::bytecode::cap::CapId;
453 let mut b = ChunkBuilder::new("cap-const");
454 b.begin_function("main", 0, 1);
455 let k = b.const_(Value::Cap(CapId::from_raw(1)));
456 b.emit_load_const(0, k);
457 b.emit_return(0);
458 let bytes = encode(&b.finish());
459 assert!(matches!(
460 decode(&bytes),
461 Err(FormatError::ForbiddenConstant(_))
462 ));
463 assert!(decode_with(&bytes, TrustLevel::Trusted).is_ok());
464 }
465
466 #[test]
467 fn roundtrip_preserves_str_and_bytes_constants() -> Result<(), FormatError> {
468 let mut b = ChunkBuilder::new("blob-const");
469 b.begin_function("main", 0, 2);
470 let ks = b.const_(Value::str("olá"));
471 let kb = b.const_(Value::bytes([0u8, 255, 7]));
472 b.emit_load_const(0, ks);
473 b.emit_load_const(1, kb);
474 b.emit_return(0);
475 let original = b.finish();
476 let decoded = decode(&encode(&original))?;
477 assert_eq!(decoded.constants, original.constants);
478 assert_eq!(decoded.constants[0].as_str(), Some("olá"));
479 assert_eq!(decoded.constants[1].as_bytes(), Some(&[0, 255, 7][..]));
480 Ok(())
481 }
482
483 #[test]
484 fn rejects_bad_magic() {
485 assert!(matches!(decode(b"XXXX"), Err(FormatError::BadMagic { .. })));
486 }
487
488 #[test]
489 fn rejects_bytes_after_a_complete_module() {
490 let mut b = ChunkBuilder::new("exact");
491 b.begin_function("main", 0, 1);
492 b.emit_return(0);
493 let mut bytes = encode(&b.finish());
494 bytes.push(0xFF);
495 assert!(matches!(
496 decode(&bytes),
497 Err(FormatError::Trailing { leftover: 1 })
498 ));
499 }
500
501 #[test]
502 fn list_constant_roundtrips_as_abi_v6_and_v5_rejects_the_tag() -> Result<(), FormatError> {
503 let list = match Value::try_list(vec![Value::Int(1), Value::Int(2)]) {
504 Some(list) => list,
505 None => return Err(FormatError::ValueTooNested),
506 };
507 let mut b = ChunkBuilder::new("list");
508 b.begin_function("main", 0, 1);
509 let k = b.const_(list);
510 b.emit_load_const(0, k);
511 b.emit_return(0);
512 let original = b.finish();
513 let bytes = encode(&original);
514 assert_eq!(
515 u32::from_le_bytes(bytes[4..8].try_into().unwrap_or([0; 4])),
516 6
517 );
518 let decoded = decode(&bytes)?;
519 assert_eq!(decoded.constants, original.constants);
520 let mut v5 = bytes.clone();
521 v5[4..8].copy_from_slice(&5u32.to_le_bytes());
522 assert!(matches!(decode(&v5), Err(FormatError::UnknownValueTag(9))));
523 let wide = Value::List(std::sync::Arc::from(vec![Value::Int(1); 33]));
524 let mut wide_chunk = Chunk {
525 name: "wide".into(),
526 ..Chunk::default()
527 };
528 wide_chunk.constants.push(wide);
529 wide_chunk.functions.push(FunctionDef {
530 name: "main".into(),
531 entry: 0,
532 arity: 0,
533 num_registers: 1,
534 });
535 wide_chunk.code.push(Instruction::nullary(Opcode::Return));
536 assert!(matches!(
537 decode(&encode(&wide_chunk)),
538 Err(FormatError::LimitExceeded { what: "list", .. })
539 ));
540 Ok(())
541 }
542}