use crate::bytecode::{
Atom, ClosureType, ClosureVar, Constant, ExportEntry, Function, FunctionKind, ImportEntry,
LineCol, ModuleMeta, ModuleRequest, VarDef, VarKind,
};
use std::fmt;
pub const MAGIC: [u8; 4] = *b"QJSB";
pub const VERSION: u16 = 9;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
BadMagic,
BadVersion(u16),
Truncated,
BadTag(&'static str, u8),
BadAtomTag(u8),
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecodeError::BadMagic => f.write_str("not QuickJS-RS bytecode (bad magic)"),
DecodeError::BadVersion(v) => write!(f, "unsupported bytecode version {v}"),
DecodeError::Truncated => f.write_str("truncated bytecode"),
DecodeError::BadTag(what, tag) => write!(f, "invalid {what} tag {tag}"),
DecodeError::BadAtomTag(tag) => write!(f, "invalid atom kind tag {tag}"),
}
}
}
impl std::error::Error for DecodeError {}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
pub keep_source: bool,
}
pub fn serialize(function: &Function) -> Vec<u8> {
serialize_with(function, Options::default())
}
pub fn serialize_with(function: &Function, options: Options) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&MAGIC);
out.extend_from_slice(&VERSION.to_be_bytes());
write_function(&mut out, function, options);
out
}
pub fn deserialize(bytes: &[u8]) -> Result<Function, DecodeError> {
let mut reader = Reader { bytes, pos: 0 };
if reader.take(4)? != MAGIC {
return Err(DecodeError::BadMagic);
}
let version = u16::from_be_bytes(reader.array::<2>()?);
if version != VERSION {
return Err(DecodeError::BadVersion(version));
}
read_function(&mut reader)
}
fn write_atom(out: &mut Vec<u8>, atom: &Atom) {
match atom {
Atom::Str(text) => {
out.push(0);
write_string(out, text);
}
Atom::Index(index) => {
out.push(1);
out.extend_from_slice(&index.to_be_bytes());
}
Atom::Null => out.push(2),
}
}
fn read_atom(reader: &mut Reader<'_>) -> Result<Atom, DecodeError> {
match reader.u8()? {
0 => Ok(Atom::Str(reader.string()?)),
1 => Ok(Atom::Index(u32::from_be_bytes(reader.array::<4>()?))),
2 => Ok(Atom::Null),
tag => Err(DecodeError::BadAtomTag(tag)),
}
}
fn write_string(out: &mut Vec<u8>, text: &str) {
out.extend_from_slice(&(text.len() as u32).to_be_bytes());
out.extend_from_slice(text.as_bytes());
}
fn write_var(out: &mut Vec<u8>, var: &VarDef) {
write_string(out, &var.name);
let mut flags = 0u8;
if var.is_const {
flags |= 1;
}
if var.is_lexical {
flags |= 2;
}
if var.is_captured {
flags |= 4;
}
out.push(flags);
out.push(var_kind_tag(var.kind));
out.extend_from_slice(&var.scope_level.to_be_bytes());
match var.scope_next {
Some(next) => {
out.push(1);
out.extend_from_slice(&next.to_be_bytes());
}
None => out.push(0),
}
}
fn write_function(out: &mut Vec<u8>, function: &Function, options: Options) {
write_string(out, &function.name);
out.push(kind_tag(function.kind));
out.push(
u8::from(function.strict)
| (u8::from(function.is_arrow) << 1)
| (u8::from(function.has_parameter_expressions) << 2),
);
out.extend_from_slice(&function.line.to_be_bytes());
out.extend_from_slice(&function.column.to_be_bytes());
out.extend_from_slice(&function.body_start.0.to_be_bytes());
out.extend_from_slice(&function.body_start.1.to_be_bytes());
out.extend_from_slice(&function.defined_args.to_be_bytes());
out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
for arg in &function.args {
write_var(out, arg);
}
out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
for var in &function.vars {
write_var(out, var);
}
out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
for closure in &function.closure_vars {
write_string(out, &closure.name);
let mut flags = 0u8;
if closure.is_const {
flags |= 1;
}
if closure.is_lexical {
flags |= 2;
}
out.push(flags);
out.push(closure_type_tag(closure.closure_type));
out.extend_from_slice(&closure.var_idx.to_be_bytes());
}
out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
for atom in &function.atoms {
write_atom(out, atom);
}
out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
for constant in &function.cpool {
write_constant(out, constant, options);
}
out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
out.extend_from_slice(&function.code);
out.extend_from_slice(&function.stack_size.to_be_bytes());
out.extend_from_slice(&function.var_ref_count.to_be_bytes());
out.extend_from_slice(&(function.eval_sites.len() as u32).to_be_bytes());
for site in &function.eval_sites {
out.extend_from_slice(&site.line.to_be_bytes());
out.extend_from_slice(&site.column.to_be_bytes());
out.extend_from_slice(&(site.bindings.len() as u32).to_be_bytes());
for binding in &site.bindings {
write_string(out, &binding.name);
out.push(u8::from(binding.is_arg));
out.extend_from_slice(&binding.index.to_be_bytes());
out.extend_from_slice(&binding.owner.to_be_bytes());
}
}
out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
for entry in &function.positions {
out.extend_from_slice(&entry.pc.to_be_bytes());
out.extend_from_slice(&entry.line.to_be_bytes());
out.extend_from_slice(&entry.column.to_be_bytes());
}
write_optional_string(out, function.filename.as_deref());
write_optional_string(
out,
if options.keep_source {
function.source.as_deref()
} else {
None
},
);
write_module_meta(out, function.module.as_deref());
}
fn write_optional_string(out: &mut Vec<u8>, text: Option<&str>) {
match text {
Some(text) => {
out.push(1);
write_string(out, text);
}
None => out.push(0),
}
}
fn write_module_meta(out: &mut Vec<u8>, meta: Option<&ModuleMeta>) {
let Some(meta) = meta else {
out.push(0);
return;
};
out.push(1);
out.extend_from_slice(&(meta.requests.len() as u32).to_be_bytes());
for request in &meta.requests {
write_string(out, &request.specifier);
out.extend_from_slice(&(request.attributes.len() as u32).to_be_bytes());
for (key, value) in &request.attributes {
write_string(out, key);
write_string(out, value);
}
}
out.extend_from_slice(&(meta.imports.len() as u32).to_be_bytes());
for import in &meta.imports {
out.extend_from_slice(&import.module.to_be_bytes());
write_string(out, &import.name);
out.extend_from_slice(&import.var_idx.to_be_bytes());
out.push(u8::from(import.is_star));
}
out.extend_from_slice(&(meta.exports.len() as u32).to_be_bytes());
for export in &meta.exports {
match export {
ExportEntry::Local {
export_name,
var_idx,
} => {
out.push(0);
write_string(out, export_name);
out.extend_from_slice(&var_idx.to_be_bytes());
}
ExportEntry::Indirect {
export_name,
module,
import_name,
} => {
out.push(1);
write_string(out, export_name);
out.extend_from_slice(&module.to_be_bytes());
write_string(out, import_name);
}
ExportEntry::Star { module } => {
out.push(2);
out.extend_from_slice(&module.to_be_bytes());
}
ExportEntry::StarAs {
export_name,
module,
} => {
out.push(3);
write_string(out, export_name);
out.extend_from_slice(&module.to_be_bytes());
}
}
}
}
fn write_constant(out: &mut Vec<u8>, constant: &Constant, options: Options) {
match constant {
Constant::Number(value) => {
out.push(0);
out.extend_from_slice(&value.to_bits().to_be_bytes());
}
Constant::String(text) => {
out.push(1);
write_string(out, text);
}
Constant::BigInt { digits, radix } => {
out.push(2);
write_string(out, digits);
out.push(*radix as u8);
}
Constant::Function(function) => {
out.push(3);
write_function(out, function, options);
}
Constant::Template { cooked, raw } => {
out.push(4);
out.extend_from_slice(&(cooked.len() as u32).to_be_bytes());
for quasi in cooked {
match quasi {
Some(text) => {
out.push(1);
write_string(out, text);
}
None => out.push(0),
}
}
out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
for text in raw {
write_string(out, text);
}
}
}
}
struct Reader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
if end > self.bytes.len() {
return Err(DecodeError::Truncated);
}
let slice = &self.bytes[self.pos..end];
self.pos = end;
Ok(slice)
}
fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
let slice = self.take(N)?;
let mut out = [0u8; N];
out.copy_from_slice(slice);
Ok(out)
}
fn u8(&mut self) -> Result<u8, DecodeError> {
Ok(self.array::<1>()?[0])
}
fn u16(&mut self) -> Result<u16, DecodeError> {
Ok(u16::from_be_bytes(self.array::<2>()?))
}
fn u32(&mut self) -> Result<u32, DecodeError> {
Ok(u32::from_be_bytes(self.array::<4>()?))
}
fn i32(&mut self) -> Result<i32, DecodeError> {
Ok(i32::from_be_bytes(self.array::<4>()?))
}
fn string(&mut self) -> Result<String, DecodeError> {
let length = self.u32()? as usize;
let bytes = self.take(length)?;
String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
}
}
fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
let name = reader.string()?;
let flags = reader.u8()?;
let kind = var_kind_from_tag(reader.u8()?)?;
let scope_level = reader.u32()?;
let scope_next = match reader.u8()? {
0 => None,
1 => Some(reader.i32()?),
other => return Err(DecodeError::BadTag("scope", other)),
};
Ok(VarDef {
name,
is_const: flags & 1 != 0,
is_lexical: flags & 2 != 0,
is_captured: flags & 4 != 0,
kind,
scope_level,
scope_next,
})
}
fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
let name = reader.string()?;
let kind = kind_from_tag(reader.u8()?)?;
let flags = reader.u8()?;
let strict = flags & 1 != 0;
let is_arrow = flags & 2 != 0;
let has_parameter_expressions = flags & 4 != 0;
let line = reader.u32()?;
let column = reader.u32()?;
let body_start = (reader.u32()?, reader.u32()?);
let defined_args = reader.u32()?;
let arg_count = reader.u32()? as usize;
let mut args = Vec::with_capacity(arg_count);
for _ in 0..arg_count {
args.push(read_var(reader)?);
}
let var_count = reader.u32()? as usize;
let mut vars = Vec::with_capacity(var_count);
for _ in 0..var_count {
vars.push(read_var(reader)?);
}
let closure_count = reader.u32()? as usize;
let mut closure_vars = Vec::with_capacity(closure_count);
for _ in 0..closure_count {
let name = reader.string()?;
let flags = reader.u8()?;
let closure_type = closure_type_from_tag(reader.u8()?)?;
let var_idx = reader.u16()?;
closure_vars.push(ClosureVar {
name,
is_const: flags & 1 != 0,
is_lexical: flags & 2 != 0,
closure_type,
var_idx,
});
}
let atom_count = reader.u32()? as usize;
let mut atoms = Vec::with_capacity(atom_count);
for _ in 0..atom_count {
atoms.push(read_atom(reader)?);
}
let cpool_count = reader.u32()? as usize;
let mut cpool = Vec::with_capacity(cpool_count);
for _ in 0..cpool_count {
cpool.push(read_constant(reader)?);
}
let code_length = reader.u32()? as usize;
let code = reader.take(code_length)?.to_vec();
let stack_size = reader.u32()?;
let var_ref_count = reader.u32()?;
let eval_site_count = reader.u32()? as usize;
let mut eval_sites = Vec::with_capacity(eval_site_count);
for _ in 0..eval_site_count {
let line = reader.u32()?;
let column = reader.u32()?;
let binding_count = reader.u32()? as usize;
let mut bindings = Vec::with_capacity(binding_count);
for _ in 0..binding_count {
let name = reader.string()?;
let is_arg = reader.take(1)?[0] != 0;
let index = reader.u32()?;
let owner = reader.u32()?;
bindings.push(crate::bytecode::EvalVisible {
name,
is_arg,
index,
owner,
});
}
eval_sites.push(crate::bytecode::EvalSite {
line,
column,
bindings,
});
}
let position_count = reader.u32()? as usize;
let mut positions = Vec::with_capacity(position_count);
for _ in 0..position_count {
positions.push(LineCol {
pc: reader.u32()?,
line: reader.u32()?,
column: reader.u32()?,
});
}
let filename = read_optional_string(reader)?;
let source = read_optional_string(reader)?;
let module = read_module_meta(reader)?;
Ok(Function {
name,
kind,
strict,
is_arrow,
has_parameter_expressions,
body_start,
args,
defined_args,
vars,
closure_vars,
cpool,
atoms,
code,
stack_size,
positions,
var_ref_count,
source,
line,
column,
filename,
eval_sites,
module,
})
}
fn read_optional_string(reader: &mut Reader<'_>) -> Result<Option<String>, DecodeError> {
match reader.u8()? {
0 => Ok(None),
1 => Ok(Some(reader.string()?)),
other => Err(DecodeError::BadTag("optional string", other)),
}
}
fn read_module_meta(reader: &mut Reader<'_>) -> Result<Option<Box<ModuleMeta>>, DecodeError> {
match reader.u8()? {
0 => return Ok(None),
1 => {}
other => return Err(DecodeError::BadTag("module", other)),
}
let request_count = reader.u32()? as usize;
let mut requests = Vec::with_capacity(request_count);
for _ in 0..request_count {
let specifier = reader.string()?;
let attribute_count = reader.u32()? as usize;
let mut attributes = Vec::with_capacity(attribute_count);
for _ in 0..attribute_count {
let key = reader.string()?;
let value = reader.string()?;
attributes.push((key, value));
}
requests.push(ModuleRequest {
specifier,
attributes,
});
}
let import_count = reader.u32()? as usize;
let mut imports = Vec::with_capacity(import_count);
for _ in 0..import_count {
let module = reader.u32()?;
let name = reader.string()?;
let var_idx = reader.u32()?;
let is_star = reader.u8()? != 0;
imports.push(ImportEntry {
module,
name,
var_idx,
is_star,
});
}
let export_count = reader.u32()? as usize;
let mut exports = Vec::with_capacity(export_count);
for _ in 0..export_count {
exports.push(match reader.u8()? {
0 => ExportEntry::Local {
export_name: reader.string()?,
var_idx: reader.u32()?,
},
1 => ExportEntry::Indirect {
export_name: reader.string()?,
module: reader.u32()?,
import_name: reader.string()?,
},
2 => ExportEntry::Star {
module: reader.u32()?,
},
3 => ExportEntry::StarAs {
export_name: reader.string()?,
module: reader.u32()?,
},
other => return Err(DecodeError::BadTag("export", other)),
});
}
Ok(Some(Box::new(ModuleMeta {
requests,
imports,
exports,
})))
}
fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
match reader.u8()? {
0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
reader.array::<8>()?,
)))),
1 => Ok(Constant::String(reader.string()?)),
2 => {
let digits = reader.string()?;
let radix = reader.u8()? as u32;
Ok(Constant::BigInt { digits, radix })
}
3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
4 => {
let count = reader.u32()? as usize;
let mut cooked = Vec::with_capacity(count);
for _ in 0..count {
cooked.push(match reader.u8()? {
0 => None,
1 => Some(reader.string()?),
other => return Err(DecodeError::BadTag("template", other)),
});
}
let raw_count = reader.u32()? as usize;
let mut raw = Vec::with_capacity(raw_count);
for _ in 0..raw_count {
raw.push(reader.string()?);
}
Ok(Constant::Template { cooked, raw })
}
other => Err(DecodeError::BadTag("constant", other)),
}
}
fn kind_tag(kind: FunctionKind) -> u8 {
match kind {
FunctionKind::Normal => 0,
FunctionKind::Generator => 1,
FunctionKind::Async => 2,
FunctionKind::AsyncGenerator => 3,
}
}
fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
Ok(match tag {
0 => FunctionKind::Normal,
1 => FunctionKind::Generator,
2 => FunctionKind::Async,
3 => FunctionKind::AsyncGenerator,
other => return Err(DecodeError::BadTag("function kind", other)),
})
}
fn var_kind_tag(kind: VarKind) -> u8 {
match kind {
VarKind::Normal => 0,
VarKind::FunctionDecl => 1,
VarKind::NewFunctionDecl => 2,
VarKind::Catch => 3,
VarKind::FunctionName => 4,
VarKind::PrivateField => 5,
VarKind::PrivateMethod => 6,
VarKind::PrivateGetter => 7,
VarKind::PrivateSetter => 8,
VarKind::PrivateGetterSetter => 9,
VarKind::GlobalFunctionDecl => 10,
VarKind::Using => 11,
VarKind::UsingMethod => 12,
VarKind::With => 13,
VarKind::LexicalCatch => 14,
}
}
fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
Ok(match tag {
0 => VarKind::Normal,
1 => VarKind::FunctionDecl,
2 => VarKind::NewFunctionDecl,
3 => VarKind::Catch,
4 => VarKind::FunctionName,
5 => VarKind::PrivateField,
6 => VarKind::PrivateMethod,
7 => VarKind::PrivateGetter,
8 => VarKind::PrivateSetter,
9 => VarKind::PrivateGetterSetter,
10 => VarKind::GlobalFunctionDecl,
11 => VarKind::Using,
12 => VarKind::UsingMethod,
13 => VarKind::With,
14 => VarKind::LexicalCatch,
other => return Err(DecodeError::BadTag("variable kind", other)),
})
}
fn closure_type_tag(kind: ClosureType) -> u8 {
match kind {
ClosureType::Local => 0,
ClosureType::Arg => 1,
ClosureType::Ref => 2,
ClosureType::GlobalRef => 3,
ClosureType::GlobalDecl => 4,
ClosureType::Global => 5,
ClosureType::ModuleDecl => 6,
ClosureType::ModuleImport => 7,
}
}
fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
Ok(match tag {
0 => ClosureType::Local,
1 => ClosureType::Arg,
2 => ClosureType::Ref,
3 => ClosureType::GlobalRef,
4 => ClosureType::GlobalDecl,
5 => ClosureType::Global,
6 => ClosureType::ModuleDecl,
7 => ClosureType::ModuleImport,
other => return Err(DecodeError::BadTag("closure type", other)),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> Function {
Function {
name: "<eval>".to_string(),
kind: FunctionKind::Normal,
strict: false,
is_arrow: false,
has_parameter_expressions: false,
body_start: (1, 12),
args: vec![],
defined_args: 0,
vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
eval_sites: vec![crate::bytecode::EvalSite {
line: 3,
column: 7,
bindings: vec![
crate::bytecode::EvalVisible {
name: "a".to_string(),
is_arg: true,
index: 0,
owner: 0,
},
crate::bytecode::EvalVisible {
name: "b".to_string(),
is_arg: false,
index: 1,
owner: 2,
},
],
}],
closure_vars: vec![ClosureVar {
name: "g".to_string(),
is_const: false,
is_lexical: false,
closure_type: ClosureType::GlobalDecl,
var_idx: 0,
}],
cpool: vec![Constant::Number(1.5), Constant::String("s".to_string())],
atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
code: vec![0x2c, 0x00, 0x00],
stack_size: 3,
positions: vec![
LineCol {
pc: 0,
line: 1,
column: 1,
},
LineCol {
pc: 2,
line: 3,
column: 7,
},
],
var_ref_count: 0,
source: None,
line: 1,
column: 1,
filename: None,
module: None,
}
}
#[test]
fn round_trips() {
let function = sample();
let bytes = serialize(&function);
let back = deserialize(&bytes).expect("decode");
assert_eq!(back, function);
}
#[test]
fn rejects_foreign_input() {
assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
}
#[test]
fn rejects_a_future_version() {
let mut bytes = serialize(&sample());
bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
assert_eq!(
deserialize(&bytes),
Err(DecodeError::BadVersion(VERSION + 1))
);
}
#[test]
fn rejects_truncated_input() {
let bytes = serialize(&sample());
assert_eq!(
deserialize(&bytes[..bytes.len() - 1]),
Err(DecodeError::Truncated)
);
}
}