Container: read a metallib of format 2.2, whose entries carry no MDSZ and which has no extended header

What: MDSZ is no longer a required function-entry tag. An entry without it
holds its module from its start (OFFT) to the next module's start, the
nearest larger bitcode start of any entry, or to the bitcode section's end
for the last. And where a section holding bytes starts at the last entry's
end, the library has no extended header and no extended tags. The entries'
bitcode ranges are resolved once every entry's start is known (a new
Entry, read from the tags, then with_bitcode). NAME, TYPE, HASH, OFFT and
VERS stay required. The overlap, section-bounds and HASH checks are as
before, and HASH is verified over the resolved range.

Why: a guest's library, an app's precompiled metallib of format 2.2 from
an older toolchain, was refused as Container(MissingTag) at its first
entry, and every pipeline made from it was dropped. Its seven entries are
NAME, TYPE, HASH, OFFT, VERS. The length rule comes from what the file
itself states and is exact. In Apple's output every module is a bitcode
wrapper padded to a multiple of 16 bytes, written right after the one
before it, and MDSZ is the distance to the next module's start, not the
wrapper's offset plus size (probe m3-max-73748, 4 of 4 modules). In the
guest's file, read for structure only on its lab host (m3-max-73749), each
HASH is the SHA-256 of the bytes up to the next module's start for 7 of 7
functions. The wrapper's own size gives that range for only 4 of 7, so
reading it would have refused 3 with HashMismatch. Since HASH is checked
over the range, a module of any other length is still refused. Behind the
MDSZ refusal the same file met a second one: its public metadata starts
right at the end of its function list (939), so there is no extended
header, and the reader would have parsed the metadata as tags (BadTag).
Metal takes such a library and runs it: m3-max-73748 made a library from
our own MSL with MDSZ removed from every entry, at header 2.9 and 2.2,
made all its functions, and ran both kernels and the render pipeline as
expected, with MTL_DEBUG_LAYER on and off. Without any of the other five
tags Metal makes no function that runs as written, so they stay required.

Docs: mtlb.rs's module docs (the 2.2 layout, the length rule and why it is
exact, Metal's answers); ContainerError::MissingTag's doc. No refusal
kind, public type or cached artifact changes: a library that parsed before
parses to the same functions.

Fixture: metal2vulkan-devtools' metallib_2_2 writes the 2.2 layout (header
2.2 with os and os version 0, no MDSZ, no extended header) around the
modules a test supplies.

Tests: container::tests::format_2_2_entries_hold_their_module_to_the_next_start
(padded and unpadded modules, the table equal to the MDSZ layout's, one
entry without MDSZ among entries with it, a HASH of the unpadded wrapper
refused as HashMismatch); malformed_function_tags no longer lists MDSZ;
tests::format_2_2_libraries (three owned fixtures padded to 16 bytes, one
past its wrapper's end, in metallib_2_2: same content keys, compile keys
and SPIR-V words as in today's layout). Both new tests fail without the
reader change (MissingTag).
This commit is contained in:
Anees Iqbal committed 2026-11-25 12:25:48 -08:00
1 parent b9e8caacce
commit 4bcb58dbb1
6 files changed
+372 -54

No files matched your search

+117 -33
View File
@@ -1,7 +1,8 @@
//! MTLB: header, function table, extended header, per-function public/private metadata, and the
//! bitcode section.
//!
//! Layout (little-endian, packed), as observed in Apple output of formats 2.7–2.9:
//! Layout (little-endian, packed), as observed in Apple output of formats 2.7–2.9, and where
//! format 2.2 (an older toolchain's) differs, as observed in one library of that format:
//!
//! - Header (0x58 bytes): `MTLB`, `platform u16`, `version u16 u16`, `file_type u8` (0 an
//! executable library, 1 a Core Image kernel library, 2 a dynamic library), `os u8`,
@@ -10,11 +11,26 @@
//! metadata, and bitcode sections.
//! - Function list: `u32 count`, then `count` entries of `u32 entry_size` (counting itself) and a
//! tag list; the list size in the header is the sum of the entry sizes. The extended-header tag
//! list follows the last entry.
//! list follows the last entry. Format 2.2 has none: its public-metadata section starts where
//! the last entry ends. So where a section that holds bytes starts at the last entry's end, the
//! library has no extended-header tags.
//! - Per function, `OFFT` holds its public-metadata, private-metadata, and bitcode offsets relative
//! to their section bases. Each metadata record is `u32 size` and a tag list of exactly that
//! size. The bitcode is `MDSZ` bytes of wrapped bitcode, and `HASH` is its SHA-256, except in a
//! Core Image kernel library (below).
//! - Format 2.2's entries carry no `MDSZ` (`NAME`, `TYPE`, `HASH`, `OFFT`, `VERS`). Such a
//! function's bitcode runs from its start to the next function's start, or to the bitcode
//! section's end for the last module. That is the length `MDSZ` states where it is written: the
//! modules lie one after another, each a bitcode wrapper padded to a multiple of 16 bytes, and
//! `MDSZ` counts the padding (a probe, an M3 Max under macOS 27.0.1: in each module of a library
//! Apple's toolchain wrote, `MDSZ` is the distance to the next module's start and not the
//! wrapper's offset plus size). In the format 2.2 library, every function's `HASH` is the
//! SHA-256 of exactly those bytes, three of its seven modules being padded past the wrapper's
//! end. `HASH` is verified over that range as over an `MDSZ` range, so a module of any other
//! length is `HashMismatch`. Metal takes a library without `MDSZ` and runs its functions; without
//! any of the other five tags it makes no function that runs as written (the same probe,
//! `metal2vulkan-conformance`'s `probes/metallib_without_entry_tags.m`), and those stay
//! required.
//! - A Core Image kernel library's `HASH` is 32 bytes that are not, in general, the SHA-256 of
//! the module its functions share. Apple's `metallib -cikernel` writes one value for every
//! function, which for some modules is the written module's SHA-256 and for others is not (the
@@ -331,7 +347,7 @@ pub(super) fn parse(bytes: &[u8]) -> Result<Metallib<'_>, Error> {
}
// `count` is untrusted and only loosely bounded above, so nothing is reserved from it: the
// list grows one entry at a time, and each entry is pushed only after its own bytes parsed.
let mut parsed = Vec::new();
let mut read = Vec::new();
let mut at = entries_start;
for _ in 0..count {
let size = offset(u64::from(read_u32(file, at)?))?;
@@ -343,13 +359,33 @@ pub(super) fn parse(bytes: &[u8]) -> Result<Metallib<'_>, Error> {
if list_end != end {
return Err(container_error(ContainerError::BadTag, at as u64));
}
parsed.push(function(file, &header, at as u64, &list)?);
read.push(function(&header, at as u64, &list)?);
at = end;
}
if at != entries_end {
return Err(container_error(ContainerError::BadOffset, 32));
}
let (extended, _) = tags::read_list(file, at, file.len())?;
// A module without `MDSZ` ends where the next one starts (the module docs).
let mut starts: Vec<u64> = read.iter().map(|e| e.bitcode_start).collect();
starts.sort_unstable();
starts.dedup();
let mut parsed = Vec::with_capacity(read.len());
for e in read {
parsed.push(e.with_bitcode(file, &header, &starts)?);
}
// No extended header where a section starts at the last entry's end (format 2.2).
let follows = [
header.public_metadata,
header.private_metadata,
header.bitcode,
]
.into_iter()
.any(|s| s.size > 0 && s.offset == at as u64);
let extended = if follows {
Vec::new()
} else {
tags::read_list(file, at, file.len())?.0
};
let mut linkage = linkage(file, &extended)?;
if header.file_type == FILE_TYPE_DYNAMIC {
let section = header.bitcode;
@@ -545,14 +581,75 @@ struct Parsed<'a> {
private_at: u64,
}
/// Parse one function-table entry starting at `entry` from its tags. Metadata records are not read
/// here (see [`records`]).
fn function<'a>(
file: &'a [u8],
header: &MtlbHeader,
/// A function-table entry's tags, read, before its bitcode range is known: a module without `MDSZ`
/// ends where the next module starts, so its range waits for every entry's start.
struct Entry<'a> {
name: &'a str,
stage: FunctionStage,
hash: Hash256,
air_version: (u16, u16),
language_version: (u16, u16),
raw_tags: Vec<RawTag<'a>>,
/// The function-table entry.
entry: u64,
list: &[Tag<'a>],
) -> Result<Parsed<'a>, Error> {
/// The function's bitcode, from `OFFT`.
bitcode_start: u64,
/// `MDSZ`, where the entry has one.
size: Option<u64>,
/// `OFFT`'s public-metadata offset, relative to the section.
public_at: u64,
/// `OFFT`'s private-metadata offset, relative to the section.
private_at: u64,
}
impl<'a> Entry<'a> {
/// The function over its bitcode: `MDSZ` bytes from its start, or without `MDSZ` the bytes up
/// to the next of `starts` (every function's start, sorted and deduplicated) or to the bitcode
/// section's end (the module docs).
fn with_bitcode(
self,
file: &'a [u8],
header: &MtlbHeader,
starts: &[u64],
) -> Result<Parsed<'a>, Error> {
let start = self.bitcode_start;
let end = match self.size {
Some(size) => start.checked_add(size),
None => Some(
starts
.get(starts.partition_point(|s| *s <= start))
.copied()
.unwrap_or_else(|| header.bitcode.end()),
),
};
let bitcode = end
.filter(|e| *e <= header.bitcode.end())
.and_then(|e| Some((usize::try_from(start).ok()?, usize::try_from(e).ok()?)))
.and_then(|(s, e)| file.get(s..e))
.ok_or_else(|| container_error(ContainerError::BadOffset, self.entry))?;
Ok(Parsed {
function: LibraryFunction {
name: self.name,
stage: self.stage,
hash: self.hash,
air_version: self.air_version,
language_version: self.language_version,
bitcode,
public: FunctionPublicMetadata::default(),
private: Vec::new(),
raw_tags: self.raw_tags,
},
entry: self.entry,
bitcode_start: start,
public_at: self.public_at,
private_at: self.private_at,
})
}
}
/// Read one function-table entry starting at `entry` from its tags. Its bitcode range is resolved
/// by [`Entry::with_bitcode`], and metadata records are read by [`records`].
fn function<'a>(header: &MtlbHeader, entry: u64, list: &[Tag<'a>]) -> Result<Entry<'a>, Error> {
let mut name = None;
let mut stage = None;
let mut hash = None;
@@ -589,35 +686,22 @@ fn function<'a>(
}
let missing = || container_error(ContainerError::MissingTag, entry);
let (public_at, private_at, bitcode_at) = offsets.ok_or_else(missing)?;
let size = size.ok_or_else(missing)?;
let (air_version, language_version) = versions.ok_or_else(missing)?;
let bitcode_start = header
.bitcode
.offset
.checked_add(bitcode_at)
.ok_or_else(|| container_error(ContainerError::BadOffset, entry))?;
let bitcode = bitcode_start
.checked_add(size)
.map(|e| (bitcode_start, e))
.filter(|(_, e)| *e <= header.bitcode.end())
.and_then(|(s, e)| Some((usize::try_from(s).ok()?, usize::try_from(e).ok()?)))
.and_then(|(s, e)| file.get(s..e))
.ok_or_else(|| container_error(ContainerError::BadOffset, entry))?;
Ok(Parsed {
function: LibraryFunction {
name: name.ok_or_else(missing)?,
stage: stage.ok_or_else(missing)?,
hash: hash.ok_or_else(missing)?,
air_version,
language_version,
bitcode,
public: FunctionPublicMetadata::default(),
private: Vec::new(),
raw_tags,
},
Ok(Entry {
name: name.ok_or_else(missing)?,
stage: stage.ok_or_else(missing)?,
hash: hash.ok_or_else(missing)?,
air_version,
language_version,
raw_tags,
entry,
bitcode_start,
size,
public_at,
private_at,
})
+95 -9
View File
@@ -89,6 +89,8 @@ struct Builder {
/// Extended-header tags holding the `(offset, size)` of a region written after the trailer,
/// with the region's bytes (`HDYN`, `ILST`).
regions: Vec<([u8; 4], Vec<u8>)>,
/// The extended header is written (its tags and `ENDT`); format 2.2 writes none.
extended_header: bool,
}
impl Builder {
@@ -103,6 +105,7 @@ impl Builder {
shared_bitcode: false,
shared_private: false,
regions: vec![],
extended_header: true,
}
}
@@ -167,13 +170,20 @@ impl Builder {
}
let entries_len: usize = entries.iter().map(Vec::len).sum();
// Each region tag is 6 + 16 bytes; its offset is known once the layout is.
let ext_len = self
.extended
.iter()
.map(|(_, b)| 6 + b.len())
.sum::<usize>()
+ self.regions.len() * 22
+ 4;
assert!(
self.extended_header || (self.extended.is_empty() && self.regions.is_empty()),
"tags need an extended header"
);
let ext_len = if self.extended_header {
self.extended
.iter()
.map(|(_, b)| 6 + b.len())
.sum::<usize>()
+ self.regions.len() * 22
+ 4
} else {
0
};
let list_off = 0x58usize;
let pub_off = list_off + 4 + entries_len + ext_len;
let priv_off = pub_off + public.len();
@@ -189,7 +199,9 @@ impl Builder {
tag(&mut ext, fourcc, &at);
region_at += bytes.len();
}
ext.extend_from_slice(b"ENDT");
if self.extended_header {
ext.extend_from_slice(b"ENDT");
}
assert_eq!(ext.len(), ext_len);
let file_size = region_at;
@@ -781,7 +793,8 @@ fn malformed_function_tags() {
let err = parse(&b.build()).unwrap_err();
assert_eq!(container_kind(&err), want, "{err:?}");
};
for missing in [*b"NAME", *b"TYPE", *b"HASH", *b"MDSZ", *b"OFFT", *b"VERS"] {
// `MDSZ` is not required (`format_2_2_entries_hold_their_module_to_the_next_start`).
for missing in [*b"NAME", *b"TYPE", *b"HASH", *b"OFFT", *b"VERS"] {
check(&|f| f.omit.push(missing), ContainerError::MissingTag);
}
check(
@@ -1128,3 +1141,76 @@ fn both_metadata_size_conventions_parse_and_nothing_else() {
);
}
}
/// `functions` in format 2.2's layout, an older toolchain's: header version 2.2, no `MDSZ` in any
/// entry, and no extended header, the public metadata starting where the last entry ends.
fn format_2_2(functions: Vec<FnSpec>) -> Builder {
let mut b = Builder::new(functions);
b.version = (2, 2);
b.extended_header = false;
for f in &mut b.functions {
f.omit.push(*b"MDSZ");
}
b
}
/// The bytes a bitcode wrapper's offset and size cover.
fn wrapper_end(module: &[u8]) -> usize {
let word = |at: usize| u32::from_le_bytes(module[at..at + 4].try_into().unwrap()) as usize;
word(8) + word(12)
}
/// Without `MDSZ` (format 2.2), a function's bitcode runs from its start to the next module's
/// start, or to the bitcode section's end for the last module: the padding after each wrapper's
/// stream included, which its `HASH` covers. Without an extended header the library has no
/// extended tags. The table is the one the same functions with `MDSZ` give.
#[test]
fn format_2_2_entries_hold_their_module_to_the_next_start() {
let mut functions = vec![
FnSpec::new("v", 0, 1),
FnSpec::new("f", 1, 2),
FnSpec::new("g", 1, 3),
];
// Pads of 12, none and 4 bytes past the wrapper's stream.
functions[1].bitcode = wrap(&module_stream(2), 0);
functions[2].bitcode = wrap(&module_stream(3), 4);
let modules: Vec<Vec<u8>> = functions.iter().map(|f| f.bitcode.clone()).collect();
assert!(modules.iter().any(|m| wrapper_end(m) < m.len()));
let old = format_2_2(functions.clone()).build();
let lib = metallib(&old);
assert_eq!(lib.header.version, (2, 2));
assert!(lib.extended.is_empty());
assert_eq!(
lib.header.public_metadata.offset,
0x58 + 4 + lib.header.function_list.size
);
for (f, module) in lib.functions.iter().zip(&modules) {
assert_eq!(f.bitcode, &module[..], "{}", f.name);
assert_eq!(f.hash, sha256(module));
f.stream().expect("its stream");
}
let table = |l: &Metallib<'_>| {
l.functions
.iter()
.map(|f| (f.name, f.stage, f.hash, f.bitcode))
.collect::<Vec<_>>()
};
let current = Builder::new(functions.clone()).build();
assert_eq!(table(&lib), table(&metallib(&current)));
// One entry without `MDSZ` among entries with it.
let mut mixed = Builder::new(functions.clone());
mixed.functions[1].omit.push(*b"MDSZ");
assert_eq!(table(&metallib(&mixed.build())), table(&lib));
// A `HASH` of the wrapper's bytes alone, short of the padding, is not the module's.
let mut short = format_2_2(functions);
let unpadded = sha256(&modules[0][..wrapper_end(&modules[0])]);
short.functions[0].hash = Some(unpadded);
let err = parse(&short.build()).unwrap_err();
assert_eq!(
container_kind(&err),
ContainerError::HashMismatch,
"{err:?}"
);
}
+3 -1
View File
@@ -390,7 +390,9 @@ pub enum ContainerError {
BadTag,
/// A tag that may appear once per function appears twice.
DuplicateTag,
/// A function entry lacks a required tag (`NAME`, `TYPE`, `HASH`, `MDSZ`, `OFFT`, `VERS`).
/// A function entry lacks a required tag (`NAME`, `TYPE`, `HASH`, `OFFT`, `VERS`). `MDSZ` is not
/// required: without it, a function's bitcode runs to the next module's start (`container`'s
/// docs).
MissingTag,
/// Metal's own universal metallib (`0xCBFEBABE`) without the slice of its AIR.
NoAirSlice,
+51 -11
View File
@@ -66,19 +66,42 @@ pub fn metallib(functions: &[MtlbFunction<'_>]) -> Vec<u8> {
/// [`metallib`] with `linkage`: its regions follow the bitcode, as in Apple's output.
pub fn metallib_linked(functions: &[MtlbFunction<'_>], linkage: &MtlbLinkage<'_>) -> Vec<u8> {
let file_type = if linkage.dynamic { 2 } else { 0 };
write(functions, linkage, file_type)
write(functions, linkage, file_type, Format::Current)
}
/// A Core Image kernel library (`metal -fcikernel`, `metallib -cikernel`): file type 1, its
/// functions (Apple's toolchain tags each `TYPE` 5) sharing the first one's bitcode, written once,
/// as in Apple's output (a probe).
pub fn core_image_metallib(functions: &[MtlbFunction<'_>]) -> Vec<u8> {
write(functions, &MtlbLinkage::default(), 1)
write(functions, &MtlbLinkage::default(), 1, Format::Current)
}
/// The metallib of `functions` and `linkage` with header `file_type`; every type but an
/// executable library's (0) shares the first function's bitcode.
fn write(functions: &[MtlbFunction<'_>], linkage: &MtlbLinkage<'_>, file_type: u8) -> Vec<u8> {
/// An executable library in the layout of format 2.2, an older toolchain's (as one library of that
/// format is written): the header's version 2.2 with its os and os version 0, no `MDSZ` in any
/// entry, and no extended header, the public metadata starting where the last entry ends. Each
/// function's bitcode is written as given, the next one's following it, so a test that pads a
/// module (as Apple's toolchain pads each to a multiple of 16 bytes) writes that padding into it.
pub fn metallib_2_2(functions: &[MtlbFunction<'_>]) -> Vec<u8> {
write(functions, &MtlbLinkage::default(), 0, Format::V2_2)
}
/// The container layout [`write`] writes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Format {
/// Today's toolchain's: format 2.9, `MDSZ` in every entry, an extended header.
Current,
/// Format 2.2's ([`metallib_2_2`]).
V2_2,
}
/// The metallib of `functions` and `linkage` with header `file_type`, in `format`; every type but
/// an executable library's (0) shares the first function's bitcode.
fn write(
functions: &[MtlbFunction<'_>],
linkage: &MtlbLinkage<'_>,
file_type: u8,
format: Format,
) -> Vec<u8> {
let (mut public, mut private, mut bitcode, mut entries) =
(Vec::new(), Vec::new(), Vec::new(), Vec::new());
let md = |tags: &[([u8; 4], Vec<u8>)]| {
@@ -122,7 +145,9 @@ fn write(functions: &[MtlbFunction<'_>], linkage: &MtlbLinkage<'_>, file_type: u
tag(&mut list, b"NAME", &name);
tag(&mut list, b"TYPE", &[f.type_code]);
tag(&mut list, b"HASH", &sha256(&f.bitcode));
tag(&mut list, b"MDSZ", &(f.bitcode.len() as u64).to_le_bytes());
if format == Format::Current {
tag(&mut list, b"MDSZ", &(f.bitcode.len() as u64).to_le_bytes());
}
let mut offt = Vec::new();
for v in [pub_at, priv_at, bc_at] {
offt.extend_from_slice(&(v as u64).to_le_bytes());
@@ -170,7 +195,14 @@ fn write(functions: &[MtlbFunction<'_>], linkage: &MtlbLinkage<'_>, file_type: u
}
regions.push((*b"ILST", out));
}
let ext_len = regions.len() * 22 + 4;
assert!(
format == Format::Current || regions.is_empty(),
"format 2.2 has no extended header for regions"
);
let ext_len = match format {
Format::Current => regions.len() * 22 + 4,
Format::V2_2 => 0,
};
let list_off = 0x58usize;
let pub_off = list_off + 4 + entries_len + ext_len;
let priv_off = pub_off + public.len();
@@ -183,16 +215,24 @@ fn write(functions: &[MtlbFunction<'_>], linkage: &MtlbLinkage<'_>, file_type: u
tag(&mut ext, fourcc, &at);
region_at += bytes.len();
}
ext.extend_from_slice(b"ENDT");
if format == Format::Current {
ext.extend_from_slice(b"ENDT");
}
assert_eq!(ext.len(), ext_len);
let file_size = region_at;
// The version, the os byte and the os version.
let (minor, os, os_major) = match format {
Format::Current => (9u16, 0x81, 26u16),
Format::V2_2 => (2, 0, 0),
};
let mut out = Vec::new();
out.extend_from_slice(b"MTLB");
out.extend_from_slice(&0x8001u16.to_le_bytes());
out.extend_from_slice(&2u16.to_le_bytes());
out.extend_from_slice(&9u16.to_le_bytes());
out.extend_from_slice(&minor.to_le_bytes());
out.push(file_type);
out.push(0x81);
out.extend_from_slice(&26u16.to_le_bytes());
out.push(os);
out.extend_from_slice(&os_major.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
for v in [
file_size,
@@ -0,0 +1,105 @@
//! A library in format 2.2's layout, an older toolchain's, through the public API.
//!
//! Format 2.2's entries carry no `MDSZ` and it has no extended header (`container`'s `mtlb` docs);
//! `metal2vulkan-devtools` writes the container in that layout here, around owned fixtures'
//! modules padded to a multiple of 16 bytes, as Apple's toolchain pads each module. Metal takes a
//! library without `MDSZ` and runs its functions (the conformance crate's
//! `probes/metallib_without_entry_tags.m`, an M3 Max under macOS 27.0.1). Each function holds its
//! module to the next one's start, so it has the content key, and compiles to the words, that the
//! same module has in today's layout. `llvm-as` assembles the fixtures; without it the test skips
//! visibly. No GPU is used.
use metal2vulkan_devtools::metallib::{metallib, metallib_2_2, wrap, MtlbFunction};
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::library::{FunctionStage, Library};
use crate::pipeline::lower_inputs::LoweringInputs;
use crate::pipeline::testing::{fixtures_dir, llvm_assemble, AssembleError};
use crate::pipeline::FunctionDescriptor;
/// Owned fixture `stem`'s module, wrapped and padded to a multiple of 16 bytes, or `None`
/// (skipped visibly) without `llvm-as`.
fn module(stem: &str) -> Option<Vec<u8>> {
match llvm_assemble(&fixtures_dir().join(format!("{stem}.ll"))) {
Ok(bc) => {
let mut m = wrap(&bc);
m.resize(m.len().next_multiple_of(16), 0);
Some(m)
}
Err(AssembleError::Missing(why)) => {
eprintln!("SKIPPED: {why}");
None
}
Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}.ll: {why}"),
}
}
/// The bytes a bitcode wrapper's offset and size cover.
fn wrapper_end(module: &[u8]) -> usize {
let word =
|at: usize| u32::from_le_bytes(module[at..at + 4].try_into().expect("word")) as usize;
word(8) + word(12)
}
fn device() -> Device {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles/runtime-floor.json");
let text = std::fs::read_to_string(path).expect("profile");
let desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device")
}
#[test]
fn a_format_2_2_library_compiles_as_today_s_layout() {
let stages = [
("vertex_varying_triangle", 0u8, FunctionStage::Vertex),
("fragment_varying_color", 1, FunctionStage::Fragment),
("fragment_constant_color", 1, FunctionStage::Fragment),
];
let mut modules = Vec::new();
for (stem, _, _) in stages {
let Some(m) = module(stem) else {
return;
};
modules.push(m);
}
assert!(
modules.iter().any(|m| wrapper_end(m) < m.len()),
"a module is padded past its wrapper's end"
);
let functions: Vec<MtlbFunction<'_>> = stages
.iter()
.zip(&modules)
.map(|((name, type_code, _), m)| MtlbFunction {
name: *name,
type_code: *type_code,
bitcode: m.clone(),
constants: Vec::new(),
public: Vec::new(),
tags: Vec::new(),
})
.collect();
let old = Library::parse(&metallib_2_2(&functions)).expect("the format 2.2 library");
let today = Library::parse(&metallib(&functions)).expect("today's library");
let dev = device();
for (name, _, stage) in stages {
let (a, b) = (
old.function(name).expect("function"),
today.function(name).expect("function"),
);
assert_eq!(a.info().stage, stage, "{name}");
assert_eq!(a.info().air_hash, b.info().air_hash, "{name}");
let compile = |f| {
dev.compile_function(
&FunctionDescriptor::new(f),
&LoweringInputs::new(),
&Budget::standard(),
)
.expect(name)
};
let (a, b) = (compile(a), compile(b));
assert_eq!(a.key(), b.key(), "{name}");
assert_eq!(a.artifact().spirv, b.artifact().spirv, "{name}");
}
}
+1
View File
@@ -209,6 +209,7 @@ mod engine_zero_factors;
mod engine_zeroed_colors;
mod engine_zeroed_threadgroup;
mod env_registry;
mod format_2_2_libraries;
mod fuzz_interp;
mod fuzz_soak;
mod golden_hashes;