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