From b4a3540c9da04853eb69cb4166ee227f6d25fb1a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 1 Nov 2026 11:48:17 -0800 Subject: [PATCH] Keep a Core Image kernel library's HASH as read instead of verifying it Core Image's own kernel libraries (ci_stdlib, ci_filters, ci_raw: file type 1, extern functions over one module) were refused as Container(HashMismatch), so Library::from_metallib, the runtime's new_library_with_data and the command line ("FALLBACK (input not read)") refused what Metal reads, in every process that uses Core Image. The function table, metadata, extended header (HDYN, UUID) and shared module were all in the shape the reader already takes; only the HASH check failed. What the HASH is, measured with libraries written from scratch under Xcode 27.2's toolchain (metal -fcikernel, metallib -cikernel) on an M3 Max under macOS 27.0.1: - metallib -cikernel writes one HASH for every function. For some modules it is the SHA-256 of the module it writes (the two-kernel library the file-type-1 support was first measured with, kernels with short loops); for others it is not, e.g. one kernel with a three-iteration loop of sin and cos. Not the digest of the input .air, of the stream without the wrapper, of the module without its zero padding or with other padding, or of the module round-tripped through metal-opt. metallib is deterministic, and feeding the written module back through it gives the same module and the same HASH. What it is a digest of is not known, so it is not interpreted. - Metal checks no HASH: the new probe (crates/metal2vulkan-conformance/probes/metallib_function_hashes.m) loads an executable library and a Core Image kernel library with one bit of every HASH flipped exactly as written (the kernel's pipeline stores 1,4,7,10 both ways), and the Core Image library whose HASH is not its module's digest as well. So a Core Image kernel library's HASH is read as 32 bytes, once, present (as before), kept as read in LibraryFunction::raw_tags, and each function's content key (LibraryFunction::hash, FunctionInfo::air_hash) is its module's SHA-256, computed once for the shared range. Every other library's HASH stays verified (HashMismatch), which is stricter than Metal; docs/API.md says so. The same probe found that Metal's externFunctionNames order is not the reverse of the table's in general: a two-kernel library (tint, shift) answers it, but a four-kernel library written from scratch, libraries of 10 to 200 kernels and Core Image's own answer the same names in an order that is neither the table's, its reverse, nor sorted. The runtime keeps the reverse; Library::extern_function_names' doc now says the order differs from Metal's (doc only). No cache version moves: a type-1 library whose HASH matched keeps the same content key, and one whose HASH did not was refused before. No translation output changes. The runtime-sources pin moves for the doc comment in the runtime's library.rs (no behaviour): re-pinned to d000eb23746160492052af4ff3e62bb81ab598b44fc8684b3cf36105d2c67026. Verified (M3 Max, macOS 27.0.1): - New test container::tests::a_core_image_library_hash_is_kept_as_read: a synthetic type-1 library of three extern functions over one module whose HASH is not the module's SHA-256 parses, each function's hash is the module's digest and its HASH is kept raw; one whose HASH is the digest reads the same; a missing, duplicate or 31-byte HASH is still MissingTag, DuplicateTag, BadTag; the same table as a dynamic library is HashMismatch. Negative control: with the exception disabled (every library verified) the test fails (HashMismatch at parse), the other 18 container tests pass. - cargo nextest -p metal2vulkan-air --all-features: 482 passed. - Locally only, nothing of it committed: Core Image's ci_stdlib, ci_filters, ci_raw (and ci_stdlib_h) now read through the command line and through the runtime on MoltenVK: each lists only extern functions (as many as its table holds), function_names empty, every name made by new_extern_function_with_name and new_function_with_name with FunctionType::Extern, a sample of six per library refused as a compute pipeline (Compile, EntryNotFound), as Metal answers; Metal's own answers for the same files through the probe agree (type executable, no function names, the same count of extern names, functionType 4 for each). - metal2vulkan core_image_libraries and api_signatures (3), the validation runtime-sources guard after the re-pin: pass. clippy --workspace --all-targets --all-features -D warnings, plain and under --cfg m2v_gpu (own target): clean. rustdoc -D warnings for the three published crates: clean. - Not run: the other suites, the device tests, golden tables (no translation output changes), a corpus census. Core Image's link of these extern functions into ciKernelMain was not reached locally: rendering ten built-in filters did not go through Metal's image-filter link calls on this Mac. (Carried to development from steelbrain/reims-graphics-kext 2d3259adbf.) --- crates/metal2vulkan-air/src/container/mod.rs | 6 +- crates/metal2vulkan-air/src/container/mtlb.rs | 41 ++++- .../metal2vulkan-air/src/container/tests.rs | 83 ++++++++++ crates/metal2vulkan-air/src/error.rs | 3 +- .../probes/metallib_function_hashes.m | 153 ++++++++++++++++++ crates/metal2vulkan-runtime/src/library.rs | 9 +- .../src/tests/core_image_libraries.rs | 2 +- .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/library/function.rs | 7 +- docs/API.md | 10 ++ 10 files changed, 299 insertions(+), 17 deletions(-) create mode 100644 crates/metal2vulkan-conformance/probes/metallib_function_hashes.m diff --git a/crates/metal2vulkan-air/src/container/mod.rs b/crates/metal2vulkan-air/src/container/mod.rs index 55223a358..a63bde2d8 100644 --- a/crates/metal2vulkan-air/src/container/mod.rs +++ b/crates/metal2vulkan-air/src/container/mod.rs @@ -32,8 +32,10 @@ //! A metallib's functions are enumerated from its function table, every known tag is validated //! strictly, unknown tags are kept as raw tags (translation semantics come from the bitcode and //! AIR metadata, never from container tags), and every function's `HASH` is verified against its -//! bitcode (linear: function bitcode ranges must be disjoint). Selecting a function by name is the -//! Metal contract (`newFunctionWithName:`), not a name-keyed heuristic. +//! bitcode (linear: function bitcode ranges must be disjoint), but a Core Image kernel library's: +//! Apple's toolchain writes one that is not its module's SHA-256, so it is kept raw and the +//! module's digest is computed (`mtlb`'s docs). Selecting a function by name is the Metal contract +//! (`newFunctionWithName:`), not a name-keyed heuristic. //! //! A wrapper or raw module may hold several entry points; enumerating them needs its AIR metadata, //! which is decoded by `air::bitcode`/`air::abi`, so this layer only locates the stream. diff --git a/crates/metal2vulkan-air/src/container/mtlb.rs b/crates/metal2vulkan-air/src/container/mtlb.rs index 26fdbba29..f8d599ae7 100644 --- a/crates/metal2vulkan-air/src/container/mtlb.rs +++ b/crates/metal2vulkan-air/src/container/mtlb.rs @@ -13,7 +13,18 @@ //! list follows the last entry. //! - 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. +//! size. The bitcode is `MDSZ` bytes of wrapped bitcode, and `HASH` is its SHA-256, except in a +//! Core Image kernel library (below). +//! - 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 +//! same input gives the same value; observed with modules written from scratch under Xcode +//! 27.2's toolchain, and in each of Core Image's own libraries on macOS 27.0.1); what it is a +//! digest of is not known. Metal does not check `HASH` (a probe, an M3 Max under macOS 27.0.1: +//! an executable library and a Core Image kernel library with one bit of every `HASH` flipped +//! load, and the executable library's kernel runs). So a Core Image kernel library's `HASH` is +//! read as 32 bytes and kept raw, uninterpreted, and each of its functions' content key is the +//! SHA-256 of its bitcode, computed here; every other library's `HASH` is verified. //! - No two functions share or overlap a public-metadata record, a private-metadata record, or a //! bitcode range. Apple output never does, and requiring it keeps parsing (and the parsed //! result) linear in the file size: otherwise many entries could re-parse one large record. @@ -139,7 +150,10 @@ pub struct LibraryFunction<'a> { pub name: &'a str, /// `TYPE`: the function's stage. pub stage: FunctionStage, - /// The verified SHA-256 of [`LibraryFunction::bitcode`]: the function's content key. + /// The SHA-256 of [`LibraryFunction::bitcode`]: the function's content key. It is the + /// function's `HASH`, verified, in every library but a Core Image kernel library, whose + /// `HASH` is not its module's SHA-256 (the module docs): there it is computed, and `HASH` is + /// kept as read in [`LibraryFunction::raw_tags`]. pub hash: Hash256, /// `VERS`: the AIR version, major and minor. pub air_version: (u16, u16), @@ -151,7 +165,8 @@ pub struct LibraryFunction<'a> { pub public: FunctionPublicMetadata<'a>, /// Private metadata tags, kept raw (no content observed). pub private: Vec>, - /// Function-table tags this layer does not interpret (`LAYR`, `TESS`, `RFLT`, …). + /// Function-table tags this layer does not interpret (`LAYR`, `TESS`, `RFLT`, …; a Core Image + /// kernel library's `HASH`). pub raw_tags: Vec>, } @@ -344,8 +359,10 @@ pub(super) fn parse(bytes: &[u8]) -> Result, Error> { // Function bitcode ranges are disjoint, so verifying every hash is linear in the file size. A // dynamic library's functions, and a Core Image kernel library's, may share one range exactly, - // which is hashed once. + // which is hashed once. A Core Image kernel library's `HASH` is not its module's SHA-256 (the + // module docs), so its functions take the computed digest instead of having it verified. let shared = matches!(header.file_type, FILE_TYPE_DYNAMIC | FILE_TYPE_CORE_IMAGE); + let verified = header.file_type != FILE_TYPE_CORE_IMAGE; let mut ranges: Vec<(u64, u64, u64, usize)> = parsed .iter() .enumerate() @@ -363,7 +380,7 @@ pub(super) fn parse(bytes: &[u8]) -> Result, Error> { let mut hashed: Option<(u64, u64, Hash256)> = None; for &(start, len, entry, i) in &ranges { let p = parsed - .get(i) + .get_mut(i) .ok_or_else(|| container_error(ContainerError::BadOffset, entry))?; let digest = match hashed { Some((s, l, digest)) if s == start && l == len => digest, @@ -373,7 +390,9 @@ pub(super) fn parse(bytes: &[u8]) -> Result, Error> { digest } }; - if digest != p.function.hash { + if !verified { + p.function.hash = digest; + } else if digest != p.function.hash { return Err(container_error(ContainerError::HashMismatch, entry)); } } @@ -541,7 +560,15 @@ fn function<'a>( let slot_filled = match &tag.raw.fourcc { b"NAME" => set(&mut name, r.cstr()?), b"TYPE" => set(&mut stage, FunctionStage::from_type_tag(r.u8()?)), - b"HASH" => set(&mut hash, r.array::<32>()?), + b"HASH" => { + let value = r.array::<32>()?; + if header.file_type == FILE_TYPE_CORE_IMAGE { + // Not the module's SHA-256 (the module docs): kept as read, and the content + // key is computed once the bitcode ranges are checked. + raw_tags.push(tag.raw); + } + set(&mut hash, value) + } b"MDSZ" => set(&mut size, r.u64()?), b"OFFT" => set(&mut offsets, (r.u64()?, r.u64()?, r.u64()?)), b"VERS" => set(&mut versions, ((r.u16()?, r.u16()?), (r.u16()?, r.u16()?))), diff --git a/crates/metal2vulkan-air/src/container/tests.rs b/crates/metal2vulkan-air/src/container/tests.rs index 5b5cf52e3..98078d012 100644 --- a/crates/metal2vulkan-air/src/container/tests.rs +++ b/crates/metal2vulkan-air/src/container/tests.rs @@ -610,6 +610,89 @@ fn hash_is_verified() { ); } +/// A Core Image kernel library in `metallib -cikernel`'s layout (file type 1; extern functions, +/// `TYPE` 5, over one module; `HDYN` naming the file and a `UUID`), every function's `HASH` set +/// to `hash`. +fn core_image(names: &[&str], hash: [u8; 32]) -> Builder { + let functions = names + .iter() + .map(|name| FnSpec { + hash: Some(hash), + ..FnSpec::new(name, 5, 4) + }) + .collect(); + let mut b = Builder::new(functions); + b.file_type = 1; + b.shared_bitcode = true; + b.inclusive_md_size = true; + b.regions = vec![(*b"HDYN", hdyn("ci.metallib", &[]))]; + b.extended.push((*b"UUID", vec![7; 16])); + b +} + +/// Apple's `metallib -cikernel` writes a `HASH` that, for some modules, is not the SHA-256 of the +/// module the library's functions share, and Metal reads the library (the `mtlb` docs). The value +/// is read as 32 bytes and kept raw; each function's content key is the module's SHA-256. Every +/// other library's `HASH` stays verified. +#[test] +fn a_core_image_library_hash_is_kept_as_read() { + let module = FnSpec::new("m", 5, 4).bitcode; + let digest = sha256(&module); + let names = ["tint", "shift", "invert"]; + let written = [0x5A; 32]; + assert_ne!(written, digest); + for hash in [written, digest] { + let bytes = core_image(&names, hash).build(); + let lib = metallib(&bytes); + assert_eq!(lib.library_type(), LibraryType::Executable); + let read: Vec<_> = lib.functions.iter().map(|f| (f.name, f.stage)).collect(); + assert_eq!(read, names.map(|n| (n, FunctionStage::Extern))); + for f in &lib.functions { + assert_eq!(f.bitcode, module.as_slice()); + assert_eq!(f.hash, digest, "{}: the module's own digest", f.name); + let kept: Vec<&[u8]> = f + .raw_tags + .iter() + .filter(|t| &t.fourcc == b"HASH") + .map(|t| t.bytes) + .collect(); + assert_eq!(kept, [&hash[..]], "{}", f.name); + } + assert_eq!(lib.linkage.install_name, Some("ci.metallib")); + } + // The tag is still read strictly: 32 bytes, once, present. + let check = |edit: &dyn Fn(&mut FnSpec), want: ContainerError| { + let mut b = core_image(&names, written); + edit(&mut b.functions[1]); + let err = parse(&b.build()).unwrap_err(); + assert_eq!(container_kind(&err), want, "{err:?}"); + }; + check(&|f| f.omit.push(*b"HASH"), ContainerError::MissingTag); + check( + &|f| f.extra.push((*b"HASH", vec![0; 32])), + ContainerError::DuplicateTag, + ); + check( + &|f| { + f.omit.push(*b"HASH"); + f.extra.push((*b"HASH", vec![0; 31])); + }, + ContainerError::BadTag, + ); + // The same table as a dynamic library's exports is verified, and refused. + let mut dynamic = core_image(&names, written); + dynamic.file_type = 2; + for f in &mut dynamic.functions { + f.type_code = 3; + } + let err = parse(&dynamic.build()).unwrap_err(); + assert_eq!( + container_kind(&err), + ContainerError::HashMismatch, + "{err:?}" + ); +} + #[test] fn unsupported_versions_and_library_kinds() { let mut b = sample(); diff --git a/crates/metal2vulkan-air/src/error.rs b/crates/metal2vulkan-air/src/error.rs index f5ccd3727..72a83f918 100644 --- a/crates/metal2vulkan-air/src/error.rs +++ b/crates/metal2vulkan-air/src/error.rs @@ -359,7 +359,8 @@ pub enum ContainerError { /// The header's minor version. minor: u16, }, - /// A function's bitcode does not hash to its `HASH` tag (SHA-256). + /// A function's bitcode does not hash to its `HASH` tag (SHA-256), in any library but a Core + /// Image kernel library, whose `HASH` is not checked (`container`'s docs). HashMismatch, /// An offset or size that points outside the file or its section, or ranges of two /// functions' bitcode or metadata that overlap. diff --git a/crates/metal2vulkan-conformance/probes/metallib_function_hashes.m b/crates/metal2vulkan-conformance/probes/metallib_function_hashes.m new file mode 100644 index 000000000..e74dc9e2a --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/metallib_function_hashes.m @@ -0,0 +1,153 @@ +// What plain Metal answers for a metallib whose function table's `HASH` tags are not the SHA-256 +// of the bitcode the functions name: as written (a Core Image kernel library's, which Apple's +// `metallib -cikernel` writes so for some modules), and with one bit of every `HASH` flipped (an +// executable library's and a Core Image kernel library's). +// +// Measured on an Apple M3 Max under macOS 27.0.1, `MTL_DEBUG_LAYER` out of the environment; +// docs/API.md ("A library") states the answers. +// +// Build (no cargo target needed): +// clang -fobjc-arc -O1 -fmodules -o metallib_function_hashes metallib_function_hashes.m \ +// -framework Foundation -framework Metal +// +// The libraries are written from scratch with Apple's toolchain, in a scratch directory: +// kernel.metal: #include +// using namespace metal; +// kernel void k(device uint *o [[buffer(0)]], uint t [[thread_position_in_grid]]) +// { o[t] = t * 3 + 1; } +// xcrun metal -c kernel.metal -o kernel.air && xcrun metallib kernel.air -o kernel.metallib +// ci.metal: #include +// using namespace metal; +// extern "C" { namespace coreimage { +// float4 k2(sample_t s, float a, float b) { float4 x = s * a + b; +// for (int j = 0; j < 3; j++) x = sin(x) * 2.0 + cos(x*b); return x; } +// }} +// xcrun metal -fcikernel -c ci.metal -o ci.air && xcrun metallib -cikernel ci.air -o ci.metallib +// four.metal: ci.metal's prelude, then four kernels: +// float4 tint(sample_t s, float4 c) { return s * c; } +// float4 shift(sample_t s, float k) { return s + k; } +// float4 invert(sample_t s) { return float4(1.0 - s.rgb, s.a); } +// float4 scale(sample_t s, float k) { return s * k; } +// (built as ci.metal is) +// (`ci.metallib`'s `HASH` is not its module's SHA-256 under Xcode 27.2's toolchain; +// `kernel.metallib`'s and `four.metallib`'s are.) Any other metallib may be named, the system's +// own included; the probe reads it at run time and keeps nothing of it. +// +// Usage: metallib_function_hashes . Prints whether +// `newLibraryWithData:error:` made a library, its type, `functionNames`, the private +// `externFunctionNames` (its order: the table's, its reverse, sorted, or other), how many table +// entries `newFunctionWithName:` makes and of which `functionType`s, and for the first kernel +// (`functionType` 3) a compute pipeline's creation and the first four words a four-thread dispatch +// stores. +// +// Measured: every case makes its library, as written and with every `HASH` flipped alike. +// `kernel.metallib`: type 0, one function name, no extern names, `k` of `functionType` 3, whose +// pipeline stores 1,4,7,10. `ci.metallib`: type 0, no function names, one extern name, `k2` of +// `functionType` 4. `four.metallib`: the four extern names, in an order that is neither the +// table's, its reverse, nor sorted; each of `functionType` 4. +#import +#import +#include +#include +#include + +static uint32_t u32(const uint8_t *p) { return p[0] | p[1] << 8 | p[2] << 16 | (uint32_t)p[3] << 24; } +static uint16_t u16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); } + +int main(int argc, char **argv) { + if (argc < 3) return 2; + @autoreleasepool { + NSMutableData *bytes = [NSMutableData dataWithContentsOfFile:@(argv[1])]; + if (!bytes || bytes.length < 0x58) { printf("RESULT unreadable\n"); return 1; } + uint8_t *b = bytes.mutableBytes; + size_t len = bytes.length; + BOOL flip = strcmp(argv[2], "flip-hash") == 0; + printf("RESULT file=%s mode=%s file_type=%u debug_layer=%s\n", argv[1], argv[2], b[10], + getenv("MTL_DEBUG_LAYER") ? getenv("MTL_DEBUG_LAYER") : "unset"); + + // The function table: a u32 count, then entries of a u32 size (counting itself) and a tag + // list (`fourcc`, u16 length, bytes; `ENDT` ends it). + uint64_t list = 0; + memcpy(&list, b + 24, 8); + NSMutableArray *names = [NSMutableArray array]; + if (list + 4 > len) { printf("RESULT bad-table\n"); return 1; } + uint32_t count = u32(b + list); + size_t at = list + 4; + for (uint32_t i = 0; i < count && at + 4 <= len; i++) { + size_t end = at + u32(b + at), t = at + 4; + while (t + 4 <= end && memcmp(b + t, "ENDT", 4) != 0 && t + 6 <= end) { + uint16_t n = u16(b + t + 4); + if (memcmp(b + t, "NAME", 4) == 0 && n > 0) + [names addObject:[NSString stringWithUTF8String:(const char *)b + t + 6]]; + if (memcmp(b + t, "HASH", 4) == 0 && n == 32 && flip) b[t + 6] ^= 1; + t += 6 + n; + } + at = end; + } + + id D = MTLCreateSystemDefaultDevice(); + dispatch_data_t data = dispatch_data_create(b, len, nil, DISPATCH_DATA_DESTRUCTOR_DEFAULT); + NSError *err = nil; + id lib = [D newLibraryWithData:data error:&err]; + if (!lib) { + printf("RESULT library=nil error=%s\n", err.localizedDescription.UTF8String); + return 0; + } + printf("RESULT library=ok type=%ld functionNames=%lu", (long)lib.type, + (unsigned long)lib.functionNames.count); + SEL extern_names = NSSelectorFromString(@"externFunctionNames"); + if ([lib respondsToSelector:extern_names]) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + NSArray *e = [(id)lib performSelector:extern_names]; +#pragma clang diagnostic pop + BOOL same = e.count == names.count, reversed = same; + for (NSUInteger i = 0; same && i < e.count; i++) same = [e[i] isEqual:names[i]]; + for (NSUInteger i = 0; reversed && i < e.count; i++) + reversed = [e[i] isEqual:names[names.count - 1 - i]]; + BOOL sorted = YES; + for (NSUInteger i = 1; sorted && i < e.count; i++) sorted = [e[i - 1] compare:e[i]] < 0; + BOOL set = [[NSSet setWithArray:e] isEqual:[NSSet setWithArray:names]]; + printf(" externFunctionNames=%lu order=%s same_set=%s", (unsigned long)e.count, + e.count < 2 ? "one" : same ? "table" : reversed ? "reverse" : sorted ? "sorted" : "other", + set ? "yes" : "no"); + } + printf(" table=%lu\n", (unsigned long)names.count); + // Every table entry through `newFunctionWithName:`, tallied by `functionType`; the first + // kernel's pipeline is made and dispatched. + long made = 0, types[16] = {0}; + BOOL dispatched = NO; + for (NSString *name in names) { + id f = [lib newFunctionWithName:name]; + if (!f) continue; + made++; + if ((unsigned long)f.functionType < 16) types[f.functionType]++; + if (dispatched || f.functionType != MTLFunctionTypeKernel) continue; + dispatched = YES; + id p = [D newComputePipelineStateWithFunction:f error:&err]; + if (!p) { + printf("RESULT pipeline=nil error=%s\n", err.localizedDescription.UTF8String); + continue; + } + id out = [D newBufferWithLength:16 options:MTLResourceStorageModeShared]; + memset(out.contents, 0xAB, 16); + id Q = [D newCommandQueue]; + id cb = [Q commandBuffer]; + id enc = [cb computeCommandEncoder]; + [enc setComputePipelineState:p]; + [enc setBuffer:out offset:0 atIndex:0]; + [enc dispatchThreads:MTLSizeMake(4, 1, 1) threadsPerThreadgroup:MTLSizeMake(4, 1, 1)]; + [enc endEncoding]; + [cb commit]; + [cb waitUntilCompleted]; + const uint32_t *w = out.contents; + printf("RESULT pipeline=ok words=%u,%u,%u,%u\n", w[0], w[1], w[2], w[3]); + } + printf("RESULT newFunctionWithName made=%ld of %lu functionType", made, + (unsigned long)names.count); + for (int t = 0; t < 16; t++) + if (types[t]) printf(" %d:%ld", t, types[t]); + printf("\n"); + } + return 0; +} diff --git a/crates/metal2vulkan-runtime/src/library.rs b/crates/metal2vulkan-runtime/src/library.rs index b96d52ef5..63c817421 100644 --- a/crates/metal2vulkan-runtime/src/library.rs +++ b/crates/metal2vulkan-runtime/src/library.rs @@ -182,9 +182,12 @@ impl Library { /// `externFunctionNames` (private to Metal's own library class): the extern functions of a /// Core Image kernel library (`metal -fcikernel`, `metallib -cikernel`), the kernels Core Image /// takes with [`new_extern_function_with_name`](Self::new_extern_function_with_name) and links - /// into a kernel of its own; none for any other library. In the reverse of the library's table - /// order, as Metal answers (libraries of two and of four kernels, an M3 Max under macOS - /// 27.0.1). + /// into a kernel of its own; none for any other library. The names are Metal's; their order is + /// the reverse of the library's table order, which differs from Metal's: Metal answers that + /// order for some libraries (one of the kernels `tint` and `shift`), and for others (libraries + /// of 4 to 200 kernels written from scratch, and Core Image's own) an order of its own, + /// neither the table's, its reverse, nor sorted (an M3 Max under macOS 27.0.1, the + /// conformance crate's `probes/metallib_function_hashes.m`). pub fn extern_function_names(&self) -> Vec { let mut names: Vec = self .library diff --git a/crates/metal2vulkan-runtime/src/tests/core_image_libraries.rs b/crates/metal2vulkan-runtime/src/tests/core_image_libraries.rs index bdbaa39ed..95c52e9bc 100644 --- a/crates/metal2vulkan-runtime/src/tests/core_image_libraries.rs +++ b/crates/metal2vulkan-runtime/src/tests/core_image_libraries.rs @@ -35,7 +35,7 @@ fn a_core_image_library_answers_its_extern_functions() { let bytes = core_image_metallib(&[function("tint", 5, &module), function("shift", 5, &module)]); let library = device.new_library_with_data(&bytes).expect("library"); assert!(library.function_names().is_empty()); - // The reverse of the table's order, as Metal lists them. + // The reverse of the table's order, which is Metal's order for these two names. assert_eq!(library.extern_function_names(), ["shift", "tint"]); for name in ["tint", "shift"] { for f in [ diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 32a0faf14..bafb67abd 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -23766690fd75227c5333e976bfc1fdfafa6ff78f43e0c5ba8fa5183574cd9371 +d000eb23746160492052af4ff3e62bb81ab598b44fc8684b3cf36105d2c67026 diff --git a/crates/metal2vulkan/src/library/function.rs b/crates/metal2vulkan/src/library/function.rs index 2165281f9..a99ef701c 100644 --- a/crates/metal2vulkan/src/library/function.rs +++ b/crates/metal2vulkan/src/library/function.rs @@ -5,7 +5,9 @@ //! //! - [`Library::parse`] accepts a metallib, a bitcode wrapper, or a raw bitcode module. A //! metallib's table comes from its container tags (every function `HASH` is verified, linear in -//! the input); its bitcode and AIR metadata are decoded only when a function is compiled. +//! the input, but a Core Image kernel library's, which Apple's toolchain does not write as its +//! module's SHA-256: that digest is computed instead); its bitcode and AIR metadata are decoded +//! only when a function is compiled. //! - A wrapper or raw module ([`Library::from_air`]) is one bitcode module that may hold several //! entry points. Enumerating them needs the module's AIR metadata, so construction decodes the //! module once under the standard budget and records **every** entry. @@ -677,7 +679,8 @@ pub struct FunctionInfo<'a> { pub name: &'a str, pub stage: FunctionStage, /// SHA-256 of the function's bitcode (its content key): a metallib function's verified - /// `HASH`, or the hash of the whole wrapper or raw module its entries share. + /// `HASH` (a Core Image kernel library's module's SHA-256, computed, since its `HASH` is not + /// that), or the hash of the whole wrapper or raw module its entries share. pub air_hash: Hash256, /// Function constants from the metallib `CNST` tag, or from the module's AIR metadata. pub constants: &'a [FunctionConstant], diff --git a/docs/API.md b/docs/API.md index 35d15bf6d..ffd8f95ce 100644 --- a/docs/API.md +++ b/docs/API.md @@ -322,6 +322,16 @@ for info in sampling.functions() { - `library.function(name)` finds a function like `newFunctionWithName:`; a missing name is `Error::InvalidDescriptor(EntryNotFound)`. +- A metallib function's `info.air_hash` is the SHA-256 of its bitcode, its content key. In every + library but a Core Image kernel library it is the function's `HASH` tag, checked against the + bitcode: a mismatch is `InvalidInput(Container(HashMismatch))`, though Metal checks no `HASH` + and loads such a library. A Core Image kernel library (file type 1, `metallib -cikernel`) + lists its kernels as extern functions (`FunctionStage::Extern`, no stage) over one module, and + Apple's toolchain writes them a `HASH` that, for some modules, is not that module's SHA-256 + (what it digests is not known); Core Image's own libraries are such. Its `HASH` is read as 32 + bytes and kept as read, and `air_hash` is the module's SHA-256, computed. The conformance + crate's `probes/metallib_function_hashes.m` measures what Metal answers for both kinds of + library. - `function.reflection(&budget)` answers as `reflectionForFunctionWithName:` does: the function's arguments in declaration order with their types, access, indices and use, in Metal's shape (module `reflection`). It is `None` for a metallib function whose library carries no reflection,