1use crate::bytecode::{
35 Atom, ClosureType, ClosureVar, Constant, Function, FunctionKind, LineCol, VarDef, VarKind,
36};
37use std::fmt;
38
39pub const MAGIC: [u8; 4] = *b"QJSB";
41
42pub const VERSION: u16 = 8;
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum DecodeError {
48 BadMagic,
50 BadVersion(u16),
52 Truncated,
54 BadTag(&'static str, u8),
56 BadAtomTag(u8),
58}
59
60impl fmt::Display for DecodeError {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 DecodeError::BadMagic => f.write_str("not QuickJS-RS bytecode (bad magic)"),
64 DecodeError::BadVersion(v) => write!(f, "unsupported bytecode version {v}"),
65 DecodeError::Truncated => f.write_str("truncated bytecode"),
66 DecodeError::BadTag(what, tag) => write!(f, "invalid {what} tag {tag}"),
67 DecodeError::BadAtomTag(tag) => write!(f, "invalid atom kind tag {tag}"),
68 }
69 }
70}
71
72impl std::error::Error for DecodeError {}
73
74pub fn serialize(function: &Function) -> Vec<u8> {
76 let mut out = Vec::new();
77 out.extend_from_slice(&MAGIC);
78 out.extend_from_slice(&VERSION.to_be_bytes());
79 write_function(&mut out, function);
80 out
81}
82
83pub fn deserialize(bytes: &[u8]) -> Result<Function, DecodeError> {
85 let mut reader = Reader { bytes, pos: 0 };
86 if reader.take(4)? != MAGIC {
87 return Err(DecodeError::BadMagic);
88 }
89 let version = u16::from_be_bytes(reader.array::<2>()?);
90 if version != VERSION {
91 return Err(DecodeError::BadVersion(version));
92 }
93 read_function(&mut reader)
94}
95
96fn write_atom(out: &mut Vec<u8>, atom: &Atom) {
99 match atom {
100 Atom::Str(text) => {
101 out.push(0);
102 write_string(out, text);
103 }
104 Atom::Index(index) => {
105 out.push(1);
106 out.extend_from_slice(&index.to_be_bytes());
107 }
108 }
109}
110
111fn read_atom(reader: &mut Reader<'_>) -> Result<Atom, DecodeError> {
112 match reader.u8()? {
113 0 => Ok(Atom::Str(reader.string()?)),
114 1 => Ok(Atom::Index(u32::from_be_bytes(reader.array::<4>()?))),
115 tag => Err(DecodeError::BadAtomTag(tag)),
116 }
117}
118
119fn write_string(out: &mut Vec<u8>, text: &str) {
120 out.extend_from_slice(&(text.len() as u32).to_be_bytes());
121 out.extend_from_slice(text.as_bytes());
122}
123
124fn write_var(out: &mut Vec<u8>, var: &VarDef) {
125 write_string(out, &var.name);
126 let mut flags = 0u8;
127 if var.is_const {
128 flags |= 1;
129 }
130 if var.is_lexical {
131 flags |= 2;
132 }
133 if var.is_captured {
134 flags |= 4;
135 }
136 out.push(flags);
137 out.push(var_kind_tag(var.kind));
138 out.extend_from_slice(&var.scope_level.to_be_bytes());
139 match var.scope_next {
140 Some(next) => {
141 out.push(1);
142 out.extend_from_slice(&next.to_be_bytes());
143 }
144 None => out.push(0),
145 }
146}
147
148fn write_function(out: &mut Vec<u8>, function: &Function) {
149 write_string(out, &function.name);
150 out.push(kind_tag(function.kind));
151 out.push(
152 u8::from(function.strict)
153 | (u8::from(function.is_arrow) << 1)
154 | (u8::from(function.has_parameter_expressions) << 2),
155 );
156 out.extend_from_slice(&function.line.to_be_bytes());
157 out.extend_from_slice(&function.column.to_be_bytes());
158 out.extend_from_slice(&function.body_start.0.to_be_bytes());
159 out.extend_from_slice(&function.body_start.1.to_be_bytes());
160
161 out.extend_from_slice(&function.defined_args.to_be_bytes());
162 out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
163 for arg in &function.args {
164 write_var(out, arg);
165 }
166 out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
167 for var in &function.vars {
168 write_var(out, var);
169 }
170
171 out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
172 for closure in &function.closure_vars {
173 write_string(out, &closure.name);
174 let mut flags = 0u8;
175 if closure.is_const {
176 flags |= 1;
177 }
178 if closure.is_lexical {
179 flags |= 2;
180 }
181 out.push(flags);
182 out.push(closure_type_tag(closure.closure_type));
183 out.extend_from_slice(&closure.var_idx.to_be_bytes());
184 }
185
186 out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
187 for atom in &function.atoms {
188 write_atom(out, atom);
189 }
190
191 out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
192 for constant in &function.cpool {
193 write_constant(out, constant);
194 }
195
196 out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
197 out.extend_from_slice(&function.code);
198 out.extend_from_slice(&function.stack_size.to_be_bytes());
199 out.extend_from_slice(&function.var_ref_count.to_be_bytes());
200 out.extend_from_slice(&(function.eval_sites.len() as u32).to_be_bytes());
204 for site in &function.eval_sites {
205 out.extend_from_slice(&site.line.to_be_bytes());
206 out.extend_from_slice(&site.column.to_be_bytes());
207 out.extend_from_slice(&(site.bindings.len() as u32).to_be_bytes());
208 for binding in &site.bindings {
209 write_string(out, &binding.name);
210 out.push(u8::from(binding.is_arg));
211 out.extend_from_slice(&binding.index.to_be_bytes());
212 out.extend_from_slice(&binding.owner.to_be_bytes());
213 }
214 }
215
216 out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
219 for entry in &function.positions {
220 out.extend_from_slice(&entry.pc.to_be_bytes());
221 out.extend_from_slice(&entry.line.to_be_bytes());
222 out.extend_from_slice(&entry.column.to_be_bytes());
223 }
224}
225
226fn write_constant(out: &mut Vec<u8>, constant: &Constant) {
227 match constant {
228 Constant::Number(value) => {
229 out.push(0);
230 out.extend_from_slice(&value.to_bits().to_be_bytes());
231 }
232 Constant::String(text) => {
233 out.push(1);
234 write_string(out, text);
235 }
236 Constant::BigInt { digits, radix } => {
237 out.push(2);
238 write_string(out, digits);
239 out.push(*radix as u8);
240 }
241 Constant::Function(function) => {
242 out.push(3);
243 write_function(out, function);
244 }
245 Constant::Template { cooked, raw } => {
246 out.push(4);
247 out.extend_from_slice(&(cooked.len() as u32).to_be_bytes());
248 for quasi in cooked {
249 match quasi {
250 Some(text) => {
251 out.push(1);
252 write_string(out, text);
253 }
254 None => out.push(0),
255 }
256 }
257 out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
258 for text in raw {
259 write_string(out, text);
260 }
261 }
262 }
263}
264
265struct Reader<'a> {
266 bytes: &'a [u8],
267 pos: usize,
268}
269
270impl<'a> Reader<'a> {
271 fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
272 let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
273 if end > self.bytes.len() {
274 return Err(DecodeError::Truncated);
275 }
276 let slice = &self.bytes[self.pos..end];
277 self.pos = end;
278 Ok(slice)
279 }
280
281 fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
282 let slice = self.take(N)?;
283 let mut out = [0u8; N];
284 out.copy_from_slice(slice);
285 Ok(out)
286 }
287
288 fn u8(&mut self) -> Result<u8, DecodeError> {
289 Ok(self.array::<1>()?[0])
290 }
291
292 fn u16(&mut self) -> Result<u16, DecodeError> {
293 Ok(u16::from_be_bytes(self.array::<2>()?))
294 }
295
296 fn u32(&mut self) -> Result<u32, DecodeError> {
297 Ok(u32::from_be_bytes(self.array::<4>()?))
298 }
299
300 fn i32(&mut self) -> Result<i32, DecodeError> {
301 Ok(i32::from_be_bytes(self.array::<4>()?))
302 }
303
304 fn string(&mut self) -> Result<String, DecodeError> {
305 let length = self.u32()? as usize;
306 let bytes = self.take(length)?;
307 String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
308 }
309}
310
311fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
312 let name = reader.string()?;
313 let flags = reader.u8()?;
314 let kind = var_kind_from_tag(reader.u8()?)?;
315 let scope_level = reader.u32()?;
316 let scope_next = match reader.u8()? {
317 0 => None,
318 1 => Some(reader.i32()?),
319 other => return Err(DecodeError::BadTag("scope", other)),
320 };
321 Ok(VarDef {
322 name,
323 is_const: flags & 1 != 0,
324 is_lexical: flags & 2 != 0,
325 is_captured: flags & 4 != 0,
326 kind,
327 scope_level,
328 scope_next,
329 })
330}
331
332fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
333 let name = reader.string()?;
334 let kind = kind_from_tag(reader.u8()?)?;
335 let flags = reader.u8()?;
336 let strict = flags & 1 != 0;
337 let is_arrow = flags & 2 != 0;
338 let has_parameter_expressions = flags & 4 != 0;
339 let line = reader.u32()?;
340 let column = reader.u32()?;
341 let body_start = (reader.u32()?, reader.u32()?);
342
343 let defined_args = reader.u32()?;
344 let arg_count = reader.u32()? as usize;
345 let mut args = Vec::with_capacity(arg_count);
346 for _ in 0..arg_count {
347 args.push(read_var(reader)?);
348 }
349 let var_count = reader.u32()? as usize;
350 let mut vars = Vec::with_capacity(var_count);
351 for _ in 0..var_count {
352 vars.push(read_var(reader)?);
353 }
354
355 let closure_count = reader.u32()? as usize;
356 let mut closure_vars = Vec::with_capacity(closure_count);
357 for _ in 0..closure_count {
358 let name = reader.string()?;
359 let flags = reader.u8()?;
360 let closure_type = closure_type_from_tag(reader.u8()?)?;
361 let var_idx = reader.u16()?;
362 closure_vars.push(ClosureVar {
363 name,
364 is_const: flags & 1 != 0,
365 is_lexical: flags & 2 != 0,
366 closure_type,
367 var_idx,
368 });
369 }
370
371 let atom_count = reader.u32()? as usize;
372 let mut atoms = Vec::with_capacity(atom_count);
373 for _ in 0..atom_count {
374 atoms.push(read_atom(reader)?);
375 }
376
377 let cpool_count = reader.u32()? as usize;
378 let mut cpool = Vec::with_capacity(cpool_count);
379 for _ in 0..cpool_count {
380 cpool.push(read_constant(reader)?);
381 }
382
383 let code_length = reader.u32()? as usize;
384 let code = reader.take(code_length)?.to_vec();
385 let stack_size = reader.u32()?;
386 let var_ref_count = reader.u32()?;
387 let eval_site_count = reader.u32()? as usize;
388 let mut eval_sites = Vec::with_capacity(eval_site_count);
389 for _ in 0..eval_site_count {
390 let line = reader.u32()?;
391 let column = reader.u32()?;
392 let binding_count = reader.u32()? as usize;
393 let mut bindings = Vec::with_capacity(binding_count);
394 for _ in 0..binding_count {
395 let name = reader.string()?;
396 let is_arg = reader.take(1)?[0] != 0;
397 let index = reader.u32()?;
398 let owner = reader.u32()?;
399 bindings.push(crate::bytecode::EvalVisible {
400 name,
401 is_arg,
402 index,
403 owner,
404 });
405 }
406 eval_sites.push(crate::bytecode::EvalSite {
407 line,
408 column,
409 bindings,
410 });
411 }
412 let position_count = reader.u32()? as usize;
413 let mut positions = Vec::with_capacity(position_count);
414 for _ in 0..position_count {
415 positions.push(LineCol {
416 pc: reader.u32()?,
417 line: reader.u32()?,
418 column: reader.u32()?,
419 });
420 }
421 Ok(Function {
422 name,
423 kind,
424 strict,
425 is_arrow,
426 has_parameter_expressions,
427 body_start,
428 args,
429 defined_args,
430 vars,
431 closure_vars,
432 cpool,
433 atoms,
434 code,
435 stack_size,
436 positions,
437 var_ref_count,
438 source: None,
439 line,
440 column,
441 filename: None,
442 eval_sites,
443 })
444}
445
446fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
447 match reader.u8()? {
448 0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
449 reader.array::<8>()?,
450 )))),
451 1 => Ok(Constant::String(reader.string()?)),
452 2 => {
453 let digits = reader.string()?;
454 let radix = reader.u8()? as u32;
455 Ok(Constant::BigInt { digits, radix })
456 }
457 3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
458 4 => {
459 let count = reader.u32()? as usize;
460 let mut cooked = Vec::with_capacity(count);
461 for _ in 0..count {
462 cooked.push(match reader.u8()? {
463 0 => None,
464 1 => Some(reader.string()?),
465 other => return Err(DecodeError::BadTag("template", other)),
466 });
467 }
468 let raw_count = reader.u32()? as usize;
469 let mut raw = Vec::with_capacity(raw_count);
470 for _ in 0..raw_count {
471 raw.push(reader.string()?);
472 }
473 Ok(Constant::Template { cooked, raw })
474 }
475 other => Err(DecodeError::BadTag("constant", other)),
476 }
477}
478
479fn kind_tag(kind: FunctionKind) -> u8 {
480 match kind {
481 FunctionKind::Normal => 0,
482 FunctionKind::Generator => 1,
483 FunctionKind::Async => 2,
484 FunctionKind::AsyncGenerator => 3,
485 }
486}
487
488fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
489 Ok(match tag {
490 0 => FunctionKind::Normal,
491 1 => FunctionKind::Generator,
492 2 => FunctionKind::Async,
493 3 => FunctionKind::AsyncGenerator,
494 other => return Err(DecodeError::BadTag("function kind", other)),
495 })
496}
497
498fn var_kind_tag(kind: VarKind) -> u8 {
499 match kind {
500 VarKind::Normal => 0,
501 VarKind::FunctionDecl => 1,
502 VarKind::NewFunctionDecl => 2,
503 VarKind::Catch => 3,
504 VarKind::FunctionName => 4,
505 VarKind::PrivateField => 5,
506 VarKind::PrivateMethod => 6,
507 VarKind::PrivateGetter => 7,
508 VarKind::PrivateSetter => 8,
509 VarKind::PrivateGetterSetter => 9,
510 VarKind::GlobalFunctionDecl => 10,
511 VarKind::Using => 11,
512 VarKind::UsingMethod => 12,
513 VarKind::With => 13,
514 }
515}
516
517fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
518 Ok(match tag {
519 0 => VarKind::Normal,
520 1 => VarKind::FunctionDecl,
521 2 => VarKind::NewFunctionDecl,
522 3 => VarKind::Catch,
523 4 => VarKind::FunctionName,
524 5 => VarKind::PrivateField,
525 6 => VarKind::PrivateMethod,
526 7 => VarKind::PrivateGetter,
527 8 => VarKind::PrivateSetter,
528 9 => VarKind::PrivateGetterSetter,
529 10 => VarKind::GlobalFunctionDecl,
530 11 => VarKind::Using,
531 12 => VarKind::UsingMethod,
532 13 => VarKind::With,
533 other => return Err(DecodeError::BadTag("variable kind", other)),
534 })
535}
536
537fn closure_type_tag(kind: ClosureType) -> u8 {
538 match kind {
539 ClosureType::Local => 0,
540 ClosureType::Arg => 1,
541 ClosureType::Ref => 2,
542 ClosureType::GlobalRef => 3,
543 ClosureType::GlobalDecl => 4,
544 ClosureType::Global => 5,
545 ClosureType::ModuleDecl => 6,
546 ClosureType::ModuleImport => 7,
547 }
548}
549
550fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
551 Ok(match tag {
552 0 => ClosureType::Local,
553 1 => ClosureType::Arg,
554 2 => ClosureType::Ref,
555 3 => ClosureType::GlobalRef,
556 4 => ClosureType::GlobalDecl,
557 5 => ClosureType::Global,
558 6 => ClosureType::ModuleDecl,
559 7 => ClosureType::ModuleImport,
560 other => return Err(DecodeError::BadTag("closure type", other)),
561 })
562}
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567
568 fn sample() -> Function {
569 Function {
570 name: "<eval>".to_string(),
571 kind: FunctionKind::Normal,
572 strict: false,
573 is_arrow: false,
574 has_parameter_expressions: false,
575 body_start: (1, 12),
576 args: vec![],
577 defined_args: 0,
578 vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
579 eval_sites: vec![crate::bytecode::EvalSite {
582 line: 3,
583 column: 7,
584 bindings: vec![
585 crate::bytecode::EvalVisible {
586 name: "a".to_string(),
587 is_arg: true,
588 index: 0,
589 owner: 0,
590 },
591 crate::bytecode::EvalVisible {
592 name: "b".to_string(),
593 is_arg: false,
594 index: 1,
595 owner: 2,
596 },
597 ],
598 }],
599 closure_vars: vec![ClosureVar {
600 name: "g".to_string(),
601 is_const: false,
602 is_lexical: false,
603 closure_type: ClosureType::GlobalDecl,
604 var_idx: 0,
605 }],
606 cpool: vec![Constant::Number(1.5), Constant::String("s".to_string())],
607 atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
609 code: vec![0x2c, 0x00, 0x00],
610 stack_size: 3,
611 positions: vec![
612 LineCol {
613 pc: 0,
614 line: 1,
615 column: 1,
616 },
617 LineCol {
618 pc: 2,
619 line: 3,
620 column: 7,
621 },
622 ],
623 var_ref_count: 0,
624 source: None,
625 line: 1,
626 column: 1,
627 filename: None,
628 }
629 }
630
631 #[test]
632 fn round_trips() {
633 let function = sample();
634 let bytes = serialize(&function);
635 let back = deserialize(&bytes).expect("decode");
636 assert_eq!(back, function);
637 }
638
639 #[test]
640 fn rejects_foreign_input() {
641 assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
642 }
643
644 #[test]
645 fn rejects_a_future_version() {
646 let mut bytes = serialize(&sample());
647 bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
648 assert_eq!(
649 deserialize(&bytes),
650 Err(DecodeError::BadVersion(VERSION + 1))
651 );
652 }
653
654 #[test]
655 fn rejects_truncated_input() {
656 let bytes = serialize(&sample());
657 assert_eq!(
658 deserialize(&bytes[..bytes.len() - 1]),
659 Err(DecodeError::Truncated)
660 );
661 }
662}