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
19//!   line, column u32 each
20//!   args        u32 count, then name/flags records
21//!   vars        u32 count, then name/flags/scope records
22//!   closures    u32 count, then name/flags/type/index records
23//!   cpool       u32 count, then constants
24//!   code        u32 length + bytes
25//!   stack_size  u32
26//!   var_refs    u32
27//!   positions   u32 count, then pc/line/column u32 each
28//! ```
29//!
30//! A version bump is required for any change to this layout; [`MAGIC`] plus
31//! [`VERSION`] make a stale blob fail loudly instead of being misinterpreted.
32
33use crate::bytecode::{
34    Atom, ClosureType, ClosureVar, Constant, Function, FunctionKind, LineCol, VarDef, VarKind,
35};
36use std::fmt;
37
38/// File magic.
39pub const MAGIC: [u8; 4] = *b"QJSB";
40
41/// Format version. Bumped whenever the layout below changes.
42pub const VERSION: u16 = 4;
43
44/// Why a blob could not be read.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum DecodeError {
47    /// The magic number is wrong; this is not our bytecode.
48    BadMagic,
49    /// The format version is not one this build understands.
50    BadVersion(u16),
51    /// The blob ends in the middle of a value.
52    Truncated,
53    /// A discriminant is out of range.
54    BadTag(&'static str, u8),
55    /// An atom entry has an unknown kind tag.
56    BadAtomTag(u8),
57}
58
59impl fmt::Display for DecodeError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            DecodeError::BadMagic => f.write_str("not QuickJS-RS bytecode (bad magic)"),
63            DecodeError::BadVersion(v) => write!(f, "unsupported bytecode version {v}"),
64            DecodeError::Truncated => f.write_str("truncated bytecode"),
65            DecodeError::BadTag(what, tag) => write!(f, "invalid {what} tag {tag}"),
66            DecodeError::BadAtomTag(tag) => write!(f, "invalid atom kind tag {tag}"),
67        }
68    }
69}
70
71impl std::error::Error for DecodeError {}
72
73/// Write a compiled function, including its nested functions.
74pub fn serialize(function: &Function) -> Vec<u8> {
75    let mut out = Vec::new();
76    out.extend_from_slice(&MAGIC);
77    out.extend_from_slice(&VERSION.to_be_bytes());
78    write_function(&mut out, function);
79    out
80}
81
82/// Read a compiled function back.
83pub fn deserialize(bytes: &[u8]) -> Result<Function, DecodeError> {
84    let mut reader = Reader { bytes, pos: 0 };
85    if reader.take(4)? != MAGIC {
86        return Err(DecodeError::BadMagic);
87    }
88    let version = u16::from_be_bytes(reader.array::<2>()?);
89    if version != VERSION {
90        return Err(DecodeError::BadVersion(version));
91    }
92    read_function(&mut reader)
93}
94
95/// One atom, tagged by kind so a canonical array index survives the round trip as
96/// a number rather than turning back into its decimal spelling.
97fn write_atom(out: &mut Vec<u8>, atom: &Atom) {
98    match atom {
99        Atom::Str(text) => {
100            out.push(0);
101            write_string(out, text);
102        }
103        Atom::Index(index) => {
104            out.push(1);
105            out.extend_from_slice(&index.to_be_bytes());
106        }
107    }
108}
109
110fn read_atom(reader: &mut Reader<'_>) -> Result<Atom, DecodeError> {
111    match reader.u8()? {
112        0 => Ok(Atom::Str(reader.string()?)),
113        1 => Ok(Atom::Index(u32::from_be_bytes(reader.array::<4>()?))),
114        tag => Err(DecodeError::BadAtomTag(tag)),
115    }
116}
117
118fn write_string(out: &mut Vec<u8>, text: &str) {
119    out.extend_from_slice(&(text.len() as u32).to_be_bytes());
120    out.extend_from_slice(text.as_bytes());
121}
122
123fn write_var(out: &mut Vec<u8>, var: &VarDef) {
124    write_string(out, &var.name);
125    let mut flags = 0u8;
126    if var.is_const {
127        flags |= 1;
128    }
129    if var.is_lexical {
130        flags |= 2;
131    }
132    if var.is_captured {
133        flags |= 4;
134    }
135    out.push(flags);
136    out.push(var_kind_tag(var.kind));
137    out.extend_from_slice(&var.scope_level.to_be_bytes());
138    match var.scope_next {
139        Some(next) => {
140            out.push(1);
141            out.extend_from_slice(&next.to_be_bytes());
142        }
143        None => out.push(0),
144    }
145}
146
147fn write_function(out: &mut Vec<u8>, function: &Function) {
148    write_string(out, &function.name);
149    out.push(kind_tag(function.kind));
150    out.push(u8::from(function.strict));
151    out.extend_from_slice(&function.line.to_be_bytes());
152    out.extend_from_slice(&function.column.to_be_bytes());
153
154    out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
155    for arg in &function.args {
156        write_var(out, arg);
157    }
158    out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
159    for var in &function.vars {
160        write_var(out, var);
161    }
162
163    out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
164    for closure in &function.closure_vars {
165        write_string(out, &closure.name);
166        let mut flags = 0u8;
167        if closure.is_const {
168            flags |= 1;
169        }
170        if closure.is_lexical {
171            flags |= 2;
172        }
173        out.push(flags);
174        out.push(closure_type_tag(closure.closure_type));
175        out.extend_from_slice(&closure.var_idx.to_be_bytes());
176    }
177
178    out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
179    for atom in &function.atoms {
180        write_atom(out, atom);
181    }
182
183    out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
184    for constant in &function.cpool {
185        write_constant(out, constant);
186    }
187
188    out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
189    out.extend_from_slice(&function.code);
190    out.extend_from_slice(&function.stack_size.to_be_bytes());
191    out.extend_from_slice(&function.var_ref_count.to_be_bytes());
192    // The position table travels with the code: an AOT binary that dropped it would
193    // lose `error.stack`'s file:line:col even though the bytecode is identical.
194    out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
195    for entry in &function.positions {
196        out.extend_from_slice(&entry.pc.to_be_bytes());
197        out.extend_from_slice(&entry.line.to_be_bytes());
198        out.extend_from_slice(&entry.column.to_be_bytes());
199    }
200}
201
202fn write_constant(out: &mut Vec<u8>, constant: &Constant) {
203    match constant {
204        Constant::Number(value) => {
205            out.push(0);
206            out.extend_from_slice(&value.to_bits().to_be_bytes());
207        }
208        Constant::String(text) => {
209            out.push(1);
210            write_string(out, text);
211        }
212        Constant::BigInt { digits, radix } => {
213            out.push(2);
214            write_string(out, digits);
215            out.push(*radix as u8);
216        }
217        Constant::Function(function) => {
218            out.push(3);
219            write_function(out, function);
220        }
221        Constant::Template(quasis) => {
222            out.push(4);
223            out.extend_from_slice(&(quasis.len() as u32).to_be_bytes());
224            for quasi in quasis {
225                match quasi {
226                    Some(text) => {
227                        out.push(1);
228                        write_string(out, text);
229                    }
230                    None => out.push(0),
231                }
232            }
233        }
234    }
235}
236
237struct Reader<'a> {
238    bytes: &'a [u8],
239    pos: usize,
240}
241
242impl<'a> Reader<'a> {
243    fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
244        let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
245        if end > self.bytes.len() {
246            return Err(DecodeError::Truncated);
247        }
248        let slice = &self.bytes[self.pos..end];
249        self.pos = end;
250        Ok(slice)
251    }
252
253    fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
254        let slice = self.take(N)?;
255        let mut out = [0u8; N];
256        out.copy_from_slice(slice);
257        Ok(out)
258    }
259
260    fn u8(&mut self) -> Result<u8, DecodeError> {
261        Ok(self.array::<1>()?[0])
262    }
263
264    fn u16(&mut self) -> Result<u16, DecodeError> {
265        Ok(u16::from_be_bytes(self.array::<2>()?))
266    }
267
268    fn u32(&mut self) -> Result<u32, DecodeError> {
269        Ok(u32::from_be_bytes(self.array::<4>()?))
270    }
271
272    fn i32(&mut self) -> Result<i32, DecodeError> {
273        Ok(i32::from_be_bytes(self.array::<4>()?))
274    }
275
276    fn string(&mut self) -> Result<String, DecodeError> {
277        let length = self.u32()? as usize;
278        let bytes = self.take(length)?;
279        String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
280    }
281}
282
283fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
284    let name = reader.string()?;
285    let flags = reader.u8()?;
286    let kind = var_kind_from_tag(reader.u8()?)?;
287    let scope_level = reader.u32()?;
288    let scope_next = match reader.u8()? {
289        0 => None,
290        1 => Some(reader.i32()?),
291        other => return Err(DecodeError::BadTag("scope", other)),
292    };
293    Ok(VarDef {
294        name,
295        is_const: flags & 1 != 0,
296        is_lexical: flags & 2 != 0,
297        is_captured: flags & 4 != 0,
298        kind,
299        scope_level,
300        scope_next,
301    })
302}
303
304fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
305    let name = reader.string()?;
306    let kind = kind_from_tag(reader.u8()?)?;
307    let strict = reader.u8()? != 0;
308    let line = reader.u32()?;
309    let column = reader.u32()?;
310
311    let arg_count = reader.u32()? as usize;
312    let mut args = Vec::with_capacity(arg_count);
313    for _ in 0..arg_count {
314        args.push(read_var(reader)?);
315    }
316    let var_count = reader.u32()? as usize;
317    let mut vars = Vec::with_capacity(var_count);
318    for _ in 0..var_count {
319        vars.push(read_var(reader)?);
320    }
321
322    let closure_count = reader.u32()? as usize;
323    let mut closure_vars = Vec::with_capacity(closure_count);
324    for _ in 0..closure_count {
325        let name = reader.string()?;
326        let flags = reader.u8()?;
327        let closure_type = closure_type_from_tag(reader.u8()?)?;
328        let var_idx = reader.u16()?;
329        closure_vars.push(ClosureVar {
330            name,
331            is_const: flags & 1 != 0,
332            is_lexical: flags & 2 != 0,
333            closure_type,
334            var_idx,
335        });
336    }
337
338    let atom_count = reader.u32()? as usize;
339    let mut atoms = Vec::with_capacity(atom_count);
340    for _ in 0..atom_count {
341        atoms.push(read_atom(reader)?);
342    }
343
344    let cpool_count = reader.u32()? as usize;
345    let mut cpool = Vec::with_capacity(cpool_count);
346    for _ in 0..cpool_count {
347        cpool.push(read_constant(reader)?);
348    }
349
350    let code_length = reader.u32()? as usize;
351    let code = reader.take(code_length)?.to_vec();
352    let stack_size = reader.u32()?;
353    let var_ref_count = reader.u32()?;
354    let position_count = reader.u32()? as usize;
355    let mut positions = Vec::with_capacity(position_count);
356    for _ in 0..position_count {
357        positions.push(LineCol {
358            pc: reader.u32()?,
359            line: reader.u32()?,
360            column: reader.u32()?,
361        });
362    }
363    Ok(Function {
364        name,
365        kind,
366        strict,
367        args,
368        vars,
369        closure_vars,
370        cpool,
371        atoms,
372        code,
373        stack_size,
374        positions,
375        var_ref_count,
376        source: None,
377        line,
378        column,
379        filename: None,
380    })
381}
382
383fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
384    match reader.u8()? {
385        0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
386            reader.array::<8>()?,
387        )))),
388        1 => Ok(Constant::String(reader.string()?)),
389        2 => {
390            let digits = reader.string()?;
391            let radix = reader.u8()? as u32;
392            Ok(Constant::BigInt { digits, radix })
393        }
394        3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
395        4 => {
396            let count = reader.u32()? as usize;
397            let mut quasis = Vec::with_capacity(count);
398            for _ in 0..count {
399                quasis.push(match reader.u8()? {
400                    0 => None,
401                    1 => Some(reader.string()?),
402                    other => return Err(DecodeError::BadTag("template", other)),
403                });
404            }
405            Ok(Constant::Template(quasis))
406        }
407        other => Err(DecodeError::BadTag("constant", other)),
408    }
409}
410
411fn kind_tag(kind: FunctionKind) -> u8 {
412    match kind {
413        FunctionKind::Normal => 0,
414        FunctionKind::Generator => 1,
415        FunctionKind::Async => 2,
416        FunctionKind::AsyncGenerator => 3,
417    }
418}
419
420fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
421    Ok(match tag {
422        0 => FunctionKind::Normal,
423        1 => FunctionKind::Generator,
424        2 => FunctionKind::Async,
425        3 => FunctionKind::AsyncGenerator,
426        other => return Err(DecodeError::BadTag("function kind", other)),
427    })
428}
429
430fn var_kind_tag(kind: VarKind) -> u8 {
431    match kind {
432        VarKind::Normal => 0,
433        VarKind::FunctionDecl => 1,
434        VarKind::NewFunctionDecl => 2,
435        VarKind::Catch => 3,
436        VarKind::FunctionName => 4,
437        VarKind::PrivateField => 5,
438        VarKind::PrivateMethod => 6,
439        VarKind::PrivateGetter => 7,
440        VarKind::PrivateSetter => 8,
441        VarKind::PrivateGetterSetter => 9,
442        VarKind::GlobalFunctionDecl => 10,
443        VarKind::Using => 11,
444        VarKind::UsingMethod => 12,
445    }
446}
447
448fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
449    Ok(match tag {
450        0 => VarKind::Normal,
451        1 => VarKind::FunctionDecl,
452        2 => VarKind::NewFunctionDecl,
453        3 => VarKind::Catch,
454        4 => VarKind::FunctionName,
455        5 => VarKind::PrivateField,
456        6 => VarKind::PrivateMethod,
457        7 => VarKind::PrivateGetter,
458        8 => VarKind::PrivateSetter,
459        9 => VarKind::PrivateGetterSetter,
460        10 => VarKind::GlobalFunctionDecl,
461        11 => VarKind::Using,
462        12 => VarKind::UsingMethod,
463        other => return Err(DecodeError::BadTag("variable kind", other)),
464    })
465}
466
467fn closure_type_tag(kind: ClosureType) -> u8 {
468    match kind {
469        ClosureType::Local => 0,
470        ClosureType::Arg => 1,
471        ClosureType::Ref => 2,
472        ClosureType::GlobalRef => 3,
473        ClosureType::GlobalDecl => 4,
474        ClosureType::Global => 5,
475        ClosureType::ModuleDecl => 6,
476        ClosureType::ModuleImport => 7,
477    }
478}
479
480fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
481    Ok(match tag {
482        0 => ClosureType::Local,
483        1 => ClosureType::Arg,
484        2 => ClosureType::Ref,
485        3 => ClosureType::GlobalRef,
486        4 => ClosureType::GlobalDecl,
487        5 => ClosureType::Global,
488        6 => ClosureType::ModuleDecl,
489        7 => ClosureType::ModuleImport,
490        other => return Err(DecodeError::BadTag("closure type", other)),
491    })
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497
498    fn sample() -> Function {
499        Function {
500            name: "<eval>".to_string(),
501            kind: FunctionKind::Normal,
502            strict: false,
503            args: vec![],
504            vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
505            closure_vars: vec![ClosureVar {
506                name: "g".to_string(),
507                is_const: false,
508                is_lexical: false,
509                closure_type: ClosureType::GlobalDecl,
510                var_idx: 0,
511            }],
512            cpool: vec![Constant::Number(1.5), Constant::String("s".to_string())],
513            // One of each kind, so the round trip covers the atom tag.
514            atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
515            code: vec![0x2c, 0x00, 0x00],
516            stack_size: 3,
517            positions: vec![
518                LineCol {
519                    pc: 0,
520                    line: 1,
521                    column: 1,
522                },
523                LineCol {
524                    pc: 2,
525                    line: 3,
526                    column: 7,
527                },
528            ],
529            var_ref_count: 0,
530            source: None,
531            line: 1,
532            column: 1,
533            filename: None,
534        }
535    }
536
537    #[test]
538    fn round_trips() {
539        let function = sample();
540        let bytes = serialize(&function);
541        let back = deserialize(&bytes).expect("decode");
542        assert_eq!(back, function);
543    }
544
545    #[test]
546    fn rejects_foreign_input() {
547        assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
548    }
549
550    #[test]
551    fn rejects_a_future_version() {
552        let mut bytes = serialize(&sample());
553        bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
554        assert_eq!(
555            deserialize(&bytes),
556            Err(DecodeError::BadVersion(VERSION + 1))
557        );
558    }
559
560    #[test]
561    fn rejects_truncated_input() {
562        let bytes = serialize(&sample());
563        assert_eq!(
564            deserialize(&bytes[..bytes.len() - 1]),
565            Err(DecodeError::Truncated)
566        );
567    }
568}