Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 2 additions & 12 deletions src/api_diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,8 @@ pub const NOT_COMPARED: &str =
/// Read the interface that `vxc --emit-interface` wrote to `path`.
pub fn read_interface(path: &Path) -> Result<ImmutableGlobalRegistry, String> {
let bytes = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
// The file starts with a count of 32-byte entries. Check it here, because the decoder
// trusts it and would panic on a short file.
let fits = bytes.len() >= 8 && {
let count = u64::from_le_bytes(bytes[..8].try_into().unwrap());
count
.checked_mul(std::mem::size_of::<TypeId>() as u64)
.is_some_and(|size| size <= (bytes.len() - 8) as u64)
};
if !fits {
return Err(format!("{} is not a .vxlib file", path.display()));
}
let metadata = crate::metadata::VxMetadata::load_from_buffer(&bytes);
let metadata = crate::metadata::VxMetadata::load_from_buffer(&bytes)
.map_err(|e| format!("{} is not a .vxlib file: {e}", path.display()))?;
crate::metadata::deserialize_registry_interface(metadata.interface_data)
.map_err(|e| format!("{}: {e}", path.display()))
}
Expand Down
12 changes: 3 additions & 9 deletions src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,15 +1156,9 @@ impl CompilerDriver {
let Some(path) = &self.options.link_interface else {
return Ok(None);
};
let buf = std::fs::read(path).map_err(|e| {
format!(
"Failed to read --link-interface '{}': {}",
path.display(),
e
)
})?;
let meta = crate::metadata::VxMetadata::load_from_buffer(&buf);
Ok(Some(meta.interface_data.to_vec()))
crate::metadata::read_interface_file(path)
.map(Some)
.map_err(|e| format!("--link-interface: {e}"))
}

fn prepare_semantic_analysis(
Expand Down
27 changes: 18 additions & 9 deletions src/gid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,17 +403,26 @@ pub fn serialize_metadata_symbols<W: std::io::Write>(
}

/// Instantly maps a byte array back into a slice of `TypeId`s without allocating
/// new memory or chasing pointers.
pub fn deserialize_metadata_symbols(bytes: &[u8]) -> (&[TypeId], &[u8]) {
let (len_bytes, remaining) = bytes.split_at(8);
let len = u64::from_le_bytes(len_bytes.try_into().unwrap()) as usize;

let byte_len = len * std::mem::size_of::<TypeId>();
/// new memory or chasing pointers. The bytes come from a file, so a short file is an error.
pub fn deserialize_metadata_symbols(bytes: &[u8]) -> Result<(&[TypeId], &[u8]), String> {
let Some((len_bytes, remaining)) = bytes.split_first_chunk::<8>() else {
return Err(format!(
"the file has {} bytes, and its header alone needs 8",
bytes.len()
));
};
let len = u64::from_le_bytes(*len_bytes);
let byte_len = usize::try_from(len)
.ok()
.and_then(|n| n.checked_mul(std::mem::size_of::<TypeId>()))
.filter(|&n| n <= remaining.len())
.ok_or_else(|| format!("the file is too short for the {len} types that it counts"))?;
let (dict_bytes, rest) = remaining.split_at(byte_len);

// Cast raw file bytes straight into a Rust slice with zero overhead
let types: &[TypeId] = bytemuck::cast_slice(dict_bytes);
(types, rest)
let types: &[TypeId] = bytemuck::try_cast_slice(dict_bytes)
.map_err(|e| format!("the types of the file cannot be read in place: {e}"))?;
Ok((types, rest))
}

#[cfg(test)]
Expand Down Expand Up @@ -662,7 +671,7 @@ mod tests {
// The length header is 8 bytes, plus 2 TypeIds (32 bytes each) = 72 bytes total.
assert_eq!(buffer.len(), 72);

let (deserialized, remaining) = deserialize_metadata_symbols(&buffer);
let (deserialized, remaining) = deserialize_metadata_symbols(&buffer).unwrap();
assert_eq!(remaining.len(), 0);
assert_eq!(deserialized.len(), 2);

Expand Down
134 changes: 115 additions & 19 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,34 @@ impl<'a> VxMetadata<'a> {
/// Load the Type Dictionary directly from disk using a Zero-Copy memory cast.
/// This requires the caller to own the `[u8]` backing buffer, returning
/// a struct containing slice references mapped over that buffer.
pub fn load_from_buffer(buffer: &'a [u8]) -> Self {
let (type_dictionary, interface_data) = deserialize_metadata_symbols(buffer);
Self {
pub fn load_from_buffer(buffer: &'a [u8]) -> Result<Self, String> {
let (type_dictionary, interface_data) = deserialize_metadata_symbols(buffer)?;
Ok(Self {
type_dictionary,
interface_data,
}
})
}
}

/// Read the `.vxlib` file at `path` and return its module interface, after a check that the
/// interface decodes. A file that is not a valid interface is an error that names the file.
pub fn read_interface_file(path: &Path) -> Result<Vec<u8>, String> {
let file = path.display();
let buffer = fs::read(path).map_err(|e| format!("cannot read {file}: {e}"))?;
let check = |buffer: &[u8]| -> Result<Vec<u8>, String> {
let interface = VxMetadata::load_from_buffer(buffer)?.interface_data;
deserialize_registry_interface(interface)?;
Ok(interface.to_vec())
};
check(&buffer).map_err(|reason| {
let reason = reason.strip_prefix("vxlib: ").unwrap_or(&reason);
format!(
"{file} is not a valid module interface: {reason}. Remove the file, or write it \
again with `vxc --emit-interface`"
)
})
}

// ---- Module interface serialization (the `.vxlib` payload) ---------------------------------------
//
// A hand-rolled little-endian binary codec for the frozen registry's import-oracle surface. There is
Expand Down Expand Up @@ -131,11 +150,31 @@ impl Writer {
struct Reader<'a> {
buf: &'a [u8],
pos: usize,
/// How many types `read_type` is inside now.
depth: usize,
}

/// The deepest type that `read_type` reads. A deeper one in a file is an error, so a file cannot
/// make the decoder recurse until the stack overflows.
const MAX_TYPE_DEPTH: usize = 256;

impl<'a> Reader<'a> {
fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0 }
Self {
buf,
pos: 0,
depth: 0,
}
}
/// A count of the items that follow. Each item takes at least one byte, so a count larger
/// than the bytes left is an error. Then a vector can reserve the count without risk.
fn count(&mut self) -> Result<usize, String> {
let n = self.u64()?;
let left = self.buf.len() - self.pos;
usize::try_from(n)
.ok()
.filter(|&n| n <= left)
.ok_or_else(|| format!("vxlib: a count of {n} items, with {left} bytes left"))
}
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
let end = self
Expand Down Expand Up @@ -299,7 +338,7 @@ fn read_type_definition(r: &mut Reader) -> Result<TypeDefinition, String> {
let name = r.sym()?.to_string();
let size_bytes = r.u64()? as usize;
let align_bytes = r.u64()? as usize;
let n_fields = r.u64()? as usize;
let n_fields = r.count()?;
let mut fields = Vec::with_capacity(n_fields);
for _ in 0..n_fields {
let fname = r.sym()?;
Expand All @@ -313,7 +352,7 @@ fn read_type_definition(r: &mut Reader) -> Result<TypeDefinition, String> {
ty,
});
}
let n_deps = r.u64()? as usize;
let n_deps = r.count()?;
let mut by_value_dependencies = Vec::with_capacity(n_deps);
for _ in 0..n_deps {
by_value_dependencies.push(r.typeid()?);
Expand Down Expand Up @@ -619,6 +658,18 @@ fn write_type(w: &mut Writer, ty: &Type) -> Result<(), String> {
}

fn read_type(r: &mut Reader) -> Result<Type, String> {
if r.depth == MAX_TYPE_DEPTH {
return Err(format!(
"vxlib: a type nested more than {MAX_TYPE_DEPTH} deep"
));
}
r.depth += 1;
let ty = read_type_at_this_depth(r);
r.depth -= 1;
ty
}

fn read_type_at_this_depth(r: &mut Reader) -> Result<Type, String> {
use Type::*;
Ok(match r.u8()? {
0 => Scalar(read_element_type(r)?),
Expand Down Expand Up @@ -654,7 +705,7 @@ fn read_type(r: &mut Reader) -> Result<Type, String> {
8 => Verified(Box::new(read_type(r)?)),
9 => {
let base = Box::new(read_type(r)?);
let n = r.u64()? as usize;
let n = r.count()?;
let mut args = Vec::with_capacity(n);
for _ in 0..n {
args.push(read_type(r)?);
Expand All @@ -663,7 +714,7 @@ fn read_type(r: &mut Reader) -> Result<Type, String> {
}
10 => {
let unsafe_fn = r.u8()? != 0;
let n = r.u64()? as usize;
let n = r.count()?;
let mut params = Vec::with_capacity(n);
for _ in 0..n {
params.push(read_type(r)?);
Expand All @@ -672,7 +723,7 @@ fn read_type(r: &mut Reader) -> Result<Type, String> {
Function(params, ret, unsafe_fn)
}
11 => {
let n = r.u64()? as usize;
let n = r.count()?;
let mut params = Vec::with_capacity(n);
for _ in 0..n {
params.push(read_type(r)?);
Expand All @@ -686,7 +737,7 @@ fn read_type(r: &mut Reader) -> Result<Type, String> {
15 => {
let e = read_element_type(r)?;
let top = read_opt_placement(r)?;
let n = r.u64()? as usize;
let n = r.count()?;
let mut dims = Vec::with_capacity(n);
for _ in 0..n {
dims.push(match r.u8()? {
Expand Down Expand Up @@ -769,19 +820,19 @@ fn write_fn_body(w: &mut Writer, gid: &TypeId, body: &FnBody) -> Result<(), Stri
fn read_fn_body(r: &mut Reader) -> Result<(TypeId, FnBody), String> {
let gid = r.typeid()?;
let name = r.sym()?;
let n_params = r.u64()? as usize;
let n_params = r.count()?;
let mut params = Vec::with_capacity(n_params);
for _ in 0..n_params {
params.push(read_type(r)?);
}
let ret_ty = read_type(r)?;
let exported = r.u8()? != 0;
let n_hir = r.u64()? as usize;
let n_hir = r.count()?;
let mut hir = Vec::with_capacity(n_hir);
for _ in 0..n_hir {
hir.push(read_hir_instruction(r)?);
}
let n_types = r.u64()? as usize;
let n_types = r.count()?;
let mut types = Vec::with_capacity(n_types);
for _ in 0..n_types {
types.push(r.typeid()?);
Expand Down Expand Up @@ -844,7 +895,7 @@ fn encode_sig_record(sig: &FnSig) -> Result<Vec<u8>, String> {
/// Decode the payload written by [`encode_sig_record`] into the signature of the function `gid`.
/// The caller reads the name/gid/receiver that precede it.
fn read_sig_record(r: &mut Reader, gid: TypeId) -> Result<FnSig, String> {
let n_params = r.u64()? as usize;
let n_params = r.count()?;
let mut params = Vec::new();
for _ in 0..n_params {
params.push(read_type(r)?);
Expand Down Expand Up @@ -1216,12 +1267,12 @@ pub fn deserialize_registry_interface(bytes: &[u8]) -> Result<ImmutableGlobalReg
let n_structs = r.u64()?;
for _ in 0..n_structs {
let gid = r.typeid()?;
let n_generics = r.u64()? as usize;
let n_generics = r.count()?;
let mut generics = Vec::new();
for _ in 0..n_generics {
generics.push(r.sym()?);
}
let n_fields = r.u64()? as usize;
let n_fields = r.count()?;
let mut fields = Vec::new();
for _ in 0..n_fields {
let fname = r.sym()?;
Expand All @@ -1235,7 +1286,7 @@ pub fn deserialize_registry_interface(bytes: &[u8]) -> Result<ImmutableGlobalReg
let n_enums = r.u64()?;
for _ in 0..n_enums {
let name = r.sym()?;
let n_variants = r.u64()? as usize;
let n_variants = r.count()?;
let mut variants = vec![None; n_variants];
for _ in 0..n_variants {
let v = r.sym()?;
Expand Down Expand Up @@ -1500,7 +1551,7 @@ mod tests {
let path = std::env::temp_dir().join(format!("vx_iface_{}.vxlib", std::process::id()));
VxMetadata::save_with_interface(&dict, &bytes, &path).expect("save");
let buffer = fs::read(&path).expect("read");
let loaded = VxMetadata::load_from_buffer(&buffer);
let loaded = VxMetadata::load_from_buffer(&buffer).expect("load");
assert_eq!(loaded.interface_data, bytes.as_slice());
let round = deserialize_registry_interface(loaded.interface_data).expect("deserialize");
let _ = fs::remove_file(&path);
Expand Down Expand Up @@ -1798,6 +1849,51 @@ mod tests {
assert!(deserialize_registry_interface(&good[..good.len() - 4]).is_err());
}

/// An interface with no modules, layouts, functions or methods, and one body that starts
/// with the name `f` and continues with `rest`.
fn interface_with_one_body(rest: &[u8]) -> Vec<u8> {
let mut w = Writer::new();
w.buf.extend_from_slice(VXLIB_MAGIC);
w.u64(crate::hash::compute_module_hash(VXLIB_FORMAT_TAG));
for _ in 0..4 {
w.u64(0);
}
w.u64(1);
w.typeid(&TypeId::new(1, 1, 0, 0));
w.sym("f");
w.buf.extend_from_slice(rest);
w.buf
}

/// A short file, a count larger than the file, and a type nested too deep are errors. The
/// decoder does not slice past the end, reserve memory for the count, or overflow the stack.
#[rstest::rstest]
#[case::empty_file(Vec::new(), "its header alone needs 8")]
#[case::header_counts_too_many_types(
u64::MAX.to_le_bytes().to_vec(),
"too short for the 18446744073709551615 types"
)]
#[case::body_counts_too_many_parameters(
[0u64.to_le_bytes().to_vec(), interface_with_one_body(&u64::MAX.to_le_bytes())].concat(),
"a count of 18446744073709551615 items"
)]
#[case::type_nested_too_deep(
[
0u64.to_le_bytes().to_vec(),
interface_with_one_body(&[1u64.to_le_bytes().to_vec(), vec![8u8; 100_000]].concat()),
]
.concat(),
"a type nested more than 256 deep"
)]
fn a_broken_file_is_an_error(#[case] file: Vec<u8>, #[case] expected: &str) {
let decoded = VxMetadata::load_from_buffer(&file)
.and_then(|m| deserialize_registry_interface(m.interface_data));
let Err(error) = decoded else {
panic!("a broken file decoded");
};
assert!(error.contains(expected), "unexpected error: {error}");
}

/// The #292 acceptance: a deliberately unencodable signature is skipped from the artifact AND
/// reported — named, counted, with the codec's reason — instead of silently dropped.
#[test]
Expand Down
11 changes: 7 additions & 4 deletions src/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ pub enum ModuleError {
/// The error names its file and position itself.
Parse(crate::error::Error),
Resolution(String),
/// A `.vxlib` that cannot be read, or that is not a valid module interface. The message
/// names the file.
Interface(String),
}

impl std::fmt::Display for ModuleError {
Expand All @@ -36,6 +39,7 @@ impl std::fmt::Display for ModuleError {
ModuleError::IO(file, err) => write!(f, "Failed to open file '{}': {}", file, err),
ModuleError::Parse(err) => write!(f, "{}", err),
ModuleError::Resolution(err) => write!(f, "Resolution error: {}", err),
ModuleError::Interface(err) => write!(f, "{}", err),
}
}
}
Expand Down Expand Up @@ -336,10 +340,9 @@ impl ModuleLoader {
/// resolution is left for the caller to do serially.
fn resolve_import(&self, path: &[Symbol]) -> Result<Resolved, ModuleError> {
if let Some(artifact) = self.resolve_artifact_path(path) {
let buf = fs::read(&artifact)
.map_err(|e| ModuleError::IO(artifact.to_string_lossy().into_owned(), e))?;
let meta = crate::metadata::VxMetadata::load_from_buffer(&buf);
return Ok(Resolved::Interface(meta.interface_data.to_vec()));
let bytes =
crate::metadata::read_interface_file(&artifact).map_err(ModuleError::Interface)?;
return Ok(Resolved::Interface(bytes));
}
match self.resolve_module_path(path) {
Some(p) => Ok(Resolved::Source(p)),
Expand Down
Loading
Loading