use thiserror::Error;
use crate::{const_table::ConstTable, ir::CompiledCode};
const MAGIC: &[u8; 7] = b"MACHA!\0";
pub const CURRENT_BYTECODE_VERSION: u8 = 0x02u8;
pub const UNSAFE_CODE_OFFSET: usize = 7 + 1 + 4;
#[derive(Error, Debug, PartialEq)]
pub enum Error {
#[error("Invalid version: {0} (Maximum supported version: {max_version})", max_version = CURRENT_BYTECODE_VERSION)]
InvalidVersion(u8),
#[error("Invalid magic header")]
InvalidMagic,
#[error("Invalid length (corrupted data?)")]
InvalidLength,
}
fn unpack_v1<'a>(bytes: &'a [u8]) -> Result<&'a [u8], Error> {
let length_bytes = bytes.get(8..12).ok_or(Error::InvalidLength)?;
let length = u32::from_le_bytes(length_bytes.try_into().unwrap()) as usize;
let code_start = 7 + 1 + 4;
let code = bytes
.get(code_start..code_start + length)
.ok_or(Error::InvalidLength)?;
Ok(code)
}
fn unpack_v2<'a>(bytes: &'a [u8]) -> Result<CompiledCode, Error> {
let mut compiled = CompiledCode {
bytecode: Vec::new(),
consts: Default::default(),
};
let bytes = &bytes[8..];
let consts_len_bytes = bytes.get(0..4).ok_or(Error::InvalidLength)?;
let consts_len = u32::from_le_bytes(consts_len_bytes.try_into().unwrap()) as usize;
compiled.consts = ConstTable::from_bytes(&bytes[4..]);
let bytes = &bytes[consts_len+4..];
let length_bytes = bytes.get(0..4).ok_or(Error::InvalidLength)?;
let length = u32::from_le_bytes(length_bytes.try_into().unwrap()) as usize;
compiled
.bytecode
.extend_from_slice(bytes.get(4..4 + length).ok_or(Error::InvalidLength)?);
Ok(compiled)
}
pub fn unpack<'a>(bytes: &'a [u8]) -> Result<(u8, CompiledCode), Error> {
if bytes.len() < 12 {
return Err(Error::InvalidLength);
}
if &bytes[0..7] != MAGIC {
return Err(Error::InvalidMagic);
}
let bytecode_version = bytes.get(7).copied().ok_or(Error::InvalidLength)?;
let code = match bytecode_version {
0x01 => CompiledCode {
bytecode: unpack_v1(bytes)?.to_vec(),
consts: Default::default(),
},
0x02 => unpack_v2(bytes)?,
_ => return Err(Error::InvalidVersion(bytecode_version)),
};
Ok((bytecode_version, code))
}
pub fn unpack_code_unchecked<'a>(bytes: &'a [u8]) -> &'a [u8] {
let length_bytes = &bytes[8..12];
let length = u32::from_le_bytes(length_bytes.try_into().unwrap()) as usize;
let code_start = 7 + 1 + 4;
&bytes[code_start..code_start + length]
}
pub fn pack(code: CompiledCode) -> Vec<u8> {
let consts = code.consts.to_bytes();
let mut packed = Vec::with_capacity(7 + 1 + 4 + code.bytecode.len() + consts.len());
packed.extend_from_slice(MAGIC);
packed.push(CURRENT_BYTECODE_VERSION);
packed.extend_from_slice(&(consts.len() as u32).to_le_bytes());
packed.extend_from_slice(&consts);
packed.extend_from_slice(&(code.bytecode.len() as u32).to_le_bytes());
packed.extend_from_slice(&code.bytecode);
packed
}
pub fn hash(bytes: &[u8]) -> sha1_smol::Digest {
sha1_smol::Sha1::from(bytes).digest()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_packer_pack_and_from_bytes() {
let code = [0u8; 8];
let compiled_code = CompiledCode {
bytecode: code.to_vec(),
consts: ConstTable::default(),
};
let packed = pack(compiled_code);
assert_eq!(&packed[0..7], MAGIC);
assert_eq!(packed[7], CURRENT_BYTECODE_VERSION);
assert_eq!(u32::from_le_bytes(packed[8..12].try_into().unwrap()), 8);
assert_eq!(&packed[12..], &code);
let (unpacked_version, unpacked_code) = unpack(&packed).unwrap();
assert_eq!(unpacked_version, CURRENT_BYTECODE_VERSION);
assert_eq!(unpacked_code.bytecode, &code);
}
#[test]
fn test_invalid_magic() {
let mut packed = vec![0u8; 20];
packed[0..7].copy_from_slice(b"INVALID");
packed[7] = CURRENT_BYTECODE_VERSION;
packed[8..12].copy_from_slice(&(8u32.to_le_bytes()));
let code = [0u8; 8];
packed[12..20].copy_from_slice(&code);
let err = unpack(&packed).unwrap_err();
assert_eq!(err, Error::InvalidMagic);
}
#[test]
fn test_invalid_version() {
let code = [0u8; 8];
let mut packed = Vec::new();
packed.extend_from_slice(MAGIC);
packed.push(0xFF);
packed.extend_from_slice(&(code.len() as u32).to_le_bytes());
packed.extend_from_slice(&code);
let err = unpack(&packed).unwrap_err();
assert_eq!(err, Error::InvalidVersion(0xFF));
}
#[test]
fn test_invalid_length_too_short() {
let packed = vec![0u8; 5];
let err = unpack(&packed).unwrap_err();
assert_eq!(err, Error::InvalidLength);
}
}