Skip to main content

js_compile/
serialize.rs

1//! Serialisation of compiled bytecode.
2//!
3//! The format is our own — it deliberately does not interoperate with the C
4//! implementation's binary blobs — but it keeps the same *semantics*: a compiled
5//! function can be written out and read back without the source, which is what
6//! `qjsc` relies on for ahead-of-time compilation.
7//!
8//! Layout, all integers big-endian:
9//!
10//! ```text
11//! magic    4 bytes  "QJSB"
12//! version  u16      format version
13//! function          one function record, recursively
14//!
15//! function record:
16//!   name        string (u32 length + UTF-8 bytes)
17//!   kind        u8
18//!   flags       u8    bit 0 = strict, bit 1 = arrow
19//!   line, column u32 each
20//!   defined_args u32  arity that counts towards `.length`
21//!   args        u32 count, then name/flags records
22//!   vars        u32 count, then name/flags/scope records
23//!   closures    u32 count, then name/flags/type/index records
24//!   cpool       u32 count, then constants
25//!   code        u32 length + bytes
26//!   stack_size  u32
27//!   var_refs    u32
28//!   positions   u32 count, then pc/line/column u32 each
29//! ```
30//!
31//! A version bump is required for any change to this layout; [`MAGIC`] plus
32//! [`VERSION`] make a stale blob fail loudly instead of being misinterpreted.
33
34use crate::bytecode::{
35    Atom, ClosureType, ClosureVar, Constant, Function, FunctionKind, LineCol, VarDef, VarKind,
36};
37use std::fmt;
38
39/// File magic.
40pub const MAGIC: [u8; 4] = *b"QJSB";
41
42/// Format version. Bumped whenever the layout below changes.
43pub const VERSION: u16 = 8;
44
45/// Why a blob could not be read.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum DecodeError {
48    /// The magic number is wrong; this is not our bytecode.
49    BadMagic,
50    /// The format version is not one this build understands.
51    BadVersion(u16),
52    /// The blob ends in the middle of a value.
53    Truncated,
54    /// A discriminant is out of range.
55    BadTag(&'static str, u8),
56    /// An atom entry has an unknown kind tag.
57    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
74/// Write a compiled function, including its nested functions.
75pub 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
83/// Read a compiled function back.
84pub 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
96/// One atom, tagged by kind so a canonical array index survives the round trip as
97/// a number rather than turning back into its decimal spelling.
98fn 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    // The eval-site table travels with the code for the same reason as the position
201    // table: it is what lets a direct `eval` resolve a shadowed name to the right slot,
202    // and it cannot be recomputed from the bytecode.
203    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    // The position table travels with the code: an AOT binary that dropped it would
217    // lose `error.stack`'s file:line:col even though the bytecode is identical.
218    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        module: None,
444    })
445}
446
447fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
448    match reader.u8()? {
449        0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
450            reader.array::<8>()?,
451        )))),
452        1 => Ok(Constant::String(reader.string()?)),
453        2 => {
454            let digits = reader.string()?;
455            let radix = reader.u8()? as u32;
456            Ok(Constant::BigInt { digits, radix })
457        }
458        3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
459        4 => {
460            let count = reader.u32()? as usize;
461            let mut cooked = Vec::with_capacity(count);
462            for _ in 0..count {
463                cooked.push(match reader.u8()? {
464                    0 => None,
465                    1 => Some(reader.string()?),
466                    other => return Err(DecodeError::BadTag("template", other)),
467                });
468            }
469            let raw_count = reader.u32()? as usize;
470            let mut raw = Vec::with_capacity(raw_count);
471            for _ in 0..raw_count {
472                raw.push(reader.string()?);
473            }
474            Ok(Constant::Template { cooked, raw })
475        }
476        other => Err(DecodeError::BadTag("constant", other)),
477    }
478}
479
480fn kind_tag(kind: FunctionKind) -> u8 {
481    match kind {
482        FunctionKind::Normal => 0,
483        FunctionKind::Generator => 1,
484        FunctionKind::Async => 2,
485        FunctionKind::AsyncGenerator => 3,
486    }
487}
488
489fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
490    Ok(match tag {
491        0 => FunctionKind::Normal,
492        1 => FunctionKind::Generator,
493        2 => FunctionKind::Async,
494        3 => FunctionKind::AsyncGenerator,
495        other => return Err(DecodeError::BadTag("function kind", other)),
496    })
497}
498
499fn var_kind_tag(kind: VarKind) -> u8 {
500    match kind {
501        VarKind::Normal => 0,
502        VarKind::FunctionDecl => 1,
503        VarKind::NewFunctionDecl => 2,
504        VarKind::Catch => 3,
505        VarKind::FunctionName => 4,
506        VarKind::PrivateField => 5,
507        VarKind::PrivateMethod => 6,
508        VarKind::PrivateGetter => 7,
509        VarKind::PrivateSetter => 8,
510        VarKind::PrivateGetterSetter => 9,
511        VarKind::GlobalFunctionDecl => 10,
512        VarKind::Using => 11,
513        VarKind::UsingMethod => 12,
514        VarKind::With => 13,
515    }
516}
517
518fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
519    Ok(match tag {
520        0 => VarKind::Normal,
521        1 => VarKind::FunctionDecl,
522        2 => VarKind::NewFunctionDecl,
523        3 => VarKind::Catch,
524        4 => VarKind::FunctionName,
525        5 => VarKind::PrivateField,
526        6 => VarKind::PrivateMethod,
527        7 => VarKind::PrivateGetter,
528        8 => VarKind::PrivateSetter,
529        9 => VarKind::PrivateGetterSetter,
530        10 => VarKind::GlobalFunctionDecl,
531        11 => VarKind::Using,
532        12 => VarKind::UsingMethod,
533        13 => VarKind::With,
534        other => return Err(DecodeError::BadTag("variable kind", other)),
535    })
536}
537
538fn closure_type_tag(kind: ClosureType) -> u8 {
539    match kind {
540        ClosureType::Local => 0,
541        ClosureType::Arg => 1,
542        ClosureType::Ref => 2,
543        ClosureType::GlobalRef => 3,
544        ClosureType::GlobalDecl => 4,
545        ClosureType::Global => 5,
546        ClosureType::ModuleDecl => 6,
547        ClosureType::ModuleImport => 7,
548    }
549}
550
551fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
552    Ok(match tag {
553        0 => ClosureType::Local,
554        1 => ClosureType::Arg,
555        2 => ClosureType::Ref,
556        3 => ClosureType::GlobalRef,
557        4 => ClosureType::GlobalDecl,
558        5 => ClosureType::Global,
559        6 => ClosureType::ModuleDecl,
560        7 => ClosureType::ModuleImport,
561        other => return Err(DecodeError::BadTag("closure type", other)),
562    })
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568
569    fn sample() -> Function {
570        Function {
571            name: "<eval>".to_string(),
572            kind: FunctionKind::Normal,
573            strict: false,
574            is_arrow: false,
575            has_parameter_expressions: false,
576            body_start: (1, 12),
577            args: vec![],
578            defined_args: 0,
579            vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
580            // A site with one binding of each shape, so the round trip covers the
581            // table a direct `eval` depends on.
582            eval_sites: vec![crate::bytecode::EvalSite {
583                line: 3,
584                column: 7,
585                bindings: vec![
586                    crate::bytecode::EvalVisible {
587                        name: "a".to_string(),
588                        is_arg: true,
589                        index: 0,
590                        owner: 0,
591                    },
592                    crate::bytecode::EvalVisible {
593                        name: "b".to_string(),
594                        is_arg: false,
595                        index: 1,
596                        owner: 2,
597                    },
598                ],
599            }],
600            closure_vars: vec![ClosureVar {
601                name: "g".to_string(),
602                is_const: false,
603                is_lexical: false,
604                closure_type: ClosureType::GlobalDecl,
605                var_idx: 0,
606            }],
607            cpool: vec![Constant::Number(1.5), Constant::String("s".to_string())],
608            // One of each kind, so the round trip covers the atom tag.
609            atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
610            code: vec![0x2c, 0x00, 0x00],
611            stack_size: 3,
612            positions: vec![
613                LineCol {
614                    pc: 0,
615                    line: 1,
616                    column: 1,
617                },
618                LineCol {
619                    pc: 2,
620                    line: 3,
621                    column: 7,
622                },
623            ],
624            var_ref_count: 0,
625            source: None,
626            line: 1,
627            column: 1,
628            filename: None,
629            module: None,
630        }
631    }
632
633    #[test]
634    fn round_trips() {
635        let function = sample();
636        let bytes = serialize(&function);
637        let back = deserialize(&bytes).expect("decode");
638        assert_eq!(back, function);
639    }
640
641    #[test]
642    fn rejects_foreign_input() {
643        assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
644    }
645
646    #[test]
647    fn rejects_a_future_version() {
648        let mut bytes = serialize(&sample());
649        bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
650        assert_eq!(
651            deserialize(&bytes),
652            Err(DecodeError::BadVersion(VERSION + 1))
653        );
654    }
655
656    #[test]
657    fn rejects_truncated_input() {
658        let bytes = serialize(&sample());
659        assert_eq!(
660            deserialize(&bytes[..bytes.len() - 1]),
661            Err(DecodeError::Truncated)
662        );
663    }
664}