From 3a7568d5b4e2b931b8fdb19a8f23af308b6267d9 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 06:53:11 -0800 Subject: [PATCH] A device can be made to open no dynamic library's file; only regular files are read A pipeline creation loads, for each install name its stage's libraries name, the file that name names (dynamic_library.rs, `stage_with_dependencies`), and `new_dynamic_library_with_url` and a binary archive's descriptor read the file they name. Where the library bytes come from another party (a guest's metallib in a virtual GPU), its install names name any host path: `/dev/zero` grew `read_to_end` until the process ran out of memory, a FIFO blocked the creating thread for ever, opening a device file could act on the device, and any host file that parses as a dynamic metallib linked into the pipeline. - `DeviceOptions::load_no_dynamic_library_file` (and `RawDevice`'s), off by default: the device opens no file a library's install names name and refuses `new_dynamic_library_with_url` (`DynamicLibraryError::NoFileLoading`, new). A creation links only the libraries its function descriptors give (`libraries.preloaded`, `libraries.loaded` by install name); an install name `loaded` lacks loads nothing, so a creation whose import survives specialization fails `Compile(NeedsInput(DynamicLibrary))`, as Metal's does for a file it cannot load. - Without the switch, every such read goes through `container::read_file`: a regular file alone, looked at before it is opened, opened `O_NONBLOCK | O_NOCTTY` and looked at again through the handle, read once no further than its length when opened, a length the process cannot hold refused rather than allocated. A FIFO, device or directory loads nothing as an install name and is `InvalidFile` for `new_dynamic_library_with_url` and a binary archive. The stage_with_dependencies call sites (compute, render, mesh, tile creation) pass the device. Docs: the field's and variant's doc comments, the runtime README's options table, docs/API.md's accepted differences. api_signatures.tsv blessed (two fields, one variant); docs/REFUSALS.md regenerates unchanged. Tests, each failing without the change (a control commit neutralizing the gate and the regular-file read, run once): - tests::binary_archive::a_path_of_no_regular_file_is_no_archive_and_is_not_waited_on (CPU): a FIFO and /dev/zero are InvalidFile, each read bounded at 30 s. - runtime_lane::dynamic_libraries::an_install_name_of_no_regular_file_loads_nothing_and_waits_on_nothing (lavapipe): a FIFO's and /dev/zero's install names load nothing, the creation is refused NeedsInput(DynamicLibrary), new_dynamic_library_with_url is InvalidFile, each bounded at 60 s. - runtime_lane::dynamic_libraries::a_device_that_loads_no_file_links_only_the_libraries_it_is_given (lavapipe): with the switch, a client linked against A's real file is refused, A preloaded or not; given A in `libraries.loaded` it links A's values; new_dynamic_library_with_url is refused. --- crates/metal2vulkan-runtime/README.md | 1 + .../src/binary_archive/container.rs | 54 +++++++- .../metal2vulkan-runtime/src/device/adopt.rs | 8 ++ .../metal2vulkan-runtime/src/device/create.rs | 16 +++ crates/metal2vulkan-runtime/src/device/mod.rs | 7 + .../src/dynamic_library.rs | 56 +++++--- crates/metal2vulkan-runtime/src/error.rs | 14 ++ .../metal2vulkan-runtime/src/pipeline/mod.rs | 3 +- .../src/pipeline/render.rs | 23 ++-- .../metal2vulkan-runtime/src/pipeline/tile.rs | 2 +- .../src/tests/binary_archive.rs | 36 +++++ .../src/runtime_lane/dynamic_libraries.rs | 126 +++++++++++++++++- crates/metal2vulkan/tests/api_signatures.tsv | 3 + docs/API.md | 11 ++ 14 files changed, 321 insertions(+), 39 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 1fbed9f4c..7b5c9b601 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -192,6 +192,7 @@ Vulkan-side choices Metal has no counterpart for: | `announce_each` | Degradation kinds to announce at every occurrence instead of once. | | `lowering_refuses` | Degradation kinds that refuse a render encoder's call when its lowering after the call meets them (`RenderLoweringPolicy::Worker`), failing its command buffer, instead of being announced. Empty by default. | | `record_executions` | Keep, per command buffer, which pipeline each dispatch and draw ran (`CommandBuffer::executions`). Off by default. | +| `load_no_dynamic_library_file` | Open no dynamic library's file, for libraries that come from a party that must not read the host's files (a guest's). Pipeline creations link only the libraries their function descriptors give (`libraries.preloaded`, and `libraries.loaded` by install name); an install name `loaded` lacks loads nothing, so a creation whose import survives specialization fails (`Compile(NeedsInput(DynamicLibrary))`), and `Device::new_dynamic_library_with_url` is refused (`DynamicLibraryError::NoFileLoading`). Off by default: as Metal does, a creation reads the file each install name names, a regular file alone (a FIFO, a device or a directory loads nothing). Also on `RawDevice`. | **A driver short of resources.** Where the driver refuses a device with its queue plan's `VkQueue`s for want of its resources (`vkCreateDevice` answering `VK_ERROR_TOO_MANY_OBJECTS`, diff --git a/crates/metal2vulkan-runtime/src/binary_archive/container.rs b/crates/metal2vulkan-runtime/src/binary_archive/container.rs index aef6d00c6..364ccead2 100644 --- a/crates/metal2vulkan-runtime/src/binary_archive/container.rs +++ b/crates/metal2vulkan-runtime/src/binary_archive/container.rs @@ -182,9 +182,10 @@ impl<'a> Reader<'a> { /// The archive in the file `path`: an archive of ours, or a metallib, which Metal takes as an /// archive (`newBinaryArchiveWithDescriptor:error:` answers one, measured on an M3 Max under /// macOS 27.0.1) and which holds nothing of ours, so it loads as an archive holding nothing, -/// whose lookups miss as Metal's archive of a metallib does (`binary-archive-sources`). +/// whose lookups miss as Metal's archive of a metallib does (`binary-archive-sources`). A path +/// that names no regular file (a FIFO, a device or a directory) is no archive ([`read_file`]). pub(crate) fn read(path: &Path) -> Result { - let bytes = std::fs::read(path).map_err(|_| invalid_file(path))?; + let bytes = read_file(path).map_err(|_| invalid_file(path))?; if let Some(contents) = decode(&bytes) { return Ok(contents); } @@ -194,6 +195,55 @@ pub(crate) fn read(path: &Path) -> Result { } } +/// Why [`read_file`] could not read a file. +pub(crate) enum ReadFailure { + /// The path names no regular file: a FIFO, a device, a socket or a directory. + NotRegular, + /// Reading failed (a missing file, for one). + Io(std::io::Error), +} + +/// The bytes of the regular file `path`, read once and no further than the length it has when +/// opened: a binary archive's file, and a dynamic library's (`dynamic_library.rs`). A path that +/// names anything else is [`ReadFailure::NotRegular`], and nothing that could wait for a writer or +/// act on a device is done to it: it is looked at before it is opened, opened without waiting +/// (`O_NONBLOCK`, which a regular file's reads ignore) and looked at again through the handle, in +/// case it changed between the two. A length the process cannot hold is refused (`OutOfMemory`) +/// rather than allocated. +pub(crate) fn read_file(path: &Path) -> Result, ReadFailure> { + use std::io::Read as _; + if !std::fs::metadata(path).map_err(ReadFailure::Io)?.is_file() { + return Err(ReadFailure::NotRegular); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY); + } + let file = options.open(path).map_err(ReadFailure::Io)?; + let metadata = file.metadata().map_err(ReadFailure::Io)?; + if !metadata.is_file() { + return Err(ReadFailure::NotRegular); + } + let length = metadata.len(); + let mut bytes = Vec::new(); + usize::try_from(length) + .ok() + .and_then(|length| bytes.try_reserve_exact(length).ok()) + .ok_or_else(|| { + ReadFailure::Io(std::io::Error::new( + std::io::ErrorKind::OutOfMemory, + format!("{length} bytes cannot be held"), + )) + })?; + file.take(length) + .read_to_end(&mut bytes) + .map_err(ReadFailure::Io)?; + Ok(bytes) +} + /// Write `bytes`, an archive's encoding, to the file `url`, replacing what is there. pub(crate) fn write(bytes: &[u8], url: &Path) -> Result<(), Error> { write_file(bytes, url).map_err(|failure| match failure { diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index a1cd5fd97..69dc56c29 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -107,6 +107,10 @@ pub struct RawDevice { /// [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) says: `None` /// by default, no record made. Metal has no such setting. pub pipeline_records: Option>, + /// Load no dynamic library from a file, as + /// [`DeviceOptions::load_no_dynamic_library_file`](crate::DeviceOptions::load_no_dynamic_library_file) + /// says: false by default, Metal's behaviour. No Metal counterpart. + pub load_no_dynamic_library_file: bool, } impl std::fmt::Debug for RawDevice { @@ -131,6 +135,7 @@ impl std::fmt::Debug for RawDevice { announce_each, lowering_refuses, pipeline_records, + load_no_dynamic_library_file, } = self; f.debug_struct("RawDevice") .field("get_instance_proc_addr", get_instance_proc_addr) @@ -154,6 +159,7 @@ impl std::fmt::Debug for RawDevice { "pipeline_records", &pipeline_records.as_ref().map(|_| "hook"), ) + .field("load_no_dynamic_library_file", load_no_dynamic_library_file) .finish() } } @@ -188,6 +194,7 @@ impl RawDevice { announce_each: BTreeSet::new(), lowering_refuses: BTreeSet::new(), pipeline_records: None, + load_no_dynamic_library_file: false, } } } @@ -353,6 +360,7 @@ impl Device { mac_class: raw.mac_class, // An adopted device keeps no execution record: validation makes its own devices. record_executions: false, + load_no_dynamic_library_file: raw.load_no_dynamic_library_file, pipeline_records: raw.pipeline_records, fail_in_place_check: false, assume_submissions_merge: false, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 285efb656..17781c5e1 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -140,6 +140,17 @@ pub struct DeviceOptions { /// in a shadow the encoders copy (`Degradation::ShadowedTextureView`), and the subset's /// feature stays disabled. For runs of the path such a device takes. pub withhold_view_reinterpretation: bool, + /// Load no dynamic library from a file: the device opens no file a library's install names + /// name, nor the file [`Device::new_dynamic_library_with_url`](crate::Device::new_dynamic_library_with_url) + /// names. For a consumer whose libraries come from a party that must not read the host's + /// files (a guest's). A pipeline state's creation then links only the libraries its function + /// descriptors give (`libraries.preloaded`, and `libraries.loaded` by install name): an + /// install name `loaded` lacks loads nothing, and the creation fails where an import + /// survives specialization (`Compile(NeedsInput(DynamicLibrary))`), as Metal's fails for a + /// file it cannot load; `new_dynamic_library_with_url` is refused + /// (`DynamicLibrary(NoFileLoading)`). Off by default: Metal's behaviour, each install name's + /// file read at each creation. No Metal counterpart. + pub load_no_dynamic_library_file: bool, /// The Vulkan API version the instance requests (`VkApplicationInfo::apiVersion`), at which /// the runtime reads each physical device's description; Vulkan 1.2 when `None`. Metal has /// no such setting: it is a Vulkan-side option, for a consumer whose layers read later @@ -386,6 +397,7 @@ impl std::fmt::Debug for DeviceOptions { shader_cache, withhold_generated_commands, withhold_view_reinterpretation, + load_no_dynamic_library_file, instance_api_version, gpu_times_from_host, mac_class, @@ -420,6 +432,7 @@ impl std::fmt::Debug for DeviceOptions { "withhold_view_reinterpretation", withhold_view_reinterpretation, ) + .field("load_no_dynamic_library_file", load_no_dynamic_library_file) .field("instance_api_version", instance_api_version) .field("gpu_times_from_host", gpu_times_from_host) .field("mac_class", mac_class) @@ -2378,6 +2391,7 @@ pub(super) fn create_on( announce_each: options.announce_each.clone(), lowering_refuses: options.lowering_refuses.clone(), record_executions: options.record_executions, + load_no_dynamic_library_file: options.load_no_dynamic_library_file, pipeline_records: options.pipeline_records.clone(), fail_in_place_check: options.fail_in_place_check, assume_submissions_merge: options.assume_submissions_merge, @@ -2572,6 +2586,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { shader_cache, withhold_generated_commands, withhold_view_reinterpretation, + load_no_dynamic_library_file, instance_api_version, gpu_times_from_host, mac_class, @@ -2601,6 +2616,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { && *shader_cache == b.shader_cache && *withhold_generated_commands == b.withhold_generated_commands && *withhold_view_reinterpretation == b.withhold_view_reinterpretation + && *load_no_dynamic_library_file == b.load_no_dynamic_library_file && *instance_api_version == b.instance_api_version && *gpu_times_from_host == b.gpu_times_from_host && *mac_class == b.mac_class diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 075515cbd..38bb54a46 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -707,6 +707,9 @@ pub(super) struct DeviceShared { /// Its command buffers keep execution records (`DeviceOptions::record_executions`): where /// not, its encoders build none (`EncoderCore::executed`). pub(crate) record_executions: bool, + /// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`, + /// `dynamic_library.rs`). + pub(crate) load_no_dynamic_library_file: bool, /// Counts the times an image of the device let its views go, under its views lock (a /// rebind's or a storage form's new `VkImage`, a detach's stand-in, a reattach, a shadow's /// move in place, whose views go after it): a view kept by what it was made of @@ -1828,6 +1831,8 @@ pub(super) struct Parts { pub(super) lowering_refuses: BTreeSet, /// Its command buffers keep execution records (`DeviceOptions::record_executions`). pub(super) record_executions: bool, + /// It loads no dynamic library from a file (`DeviceOptions::load_no_dynamic_library_file`). + pub(super) load_no_dynamic_library_file: bool, /// Where its pipeline records go (`DeviceOptions::pipeline_records`, `warm/record.rs`). pub(super) pipeline_records: Option, /// Its check of the first move over host pages fails whatever the moves did @@ -1940,6 +1945,7 @@ impl Device { announce_each, lowering_refuses, record_executions, + load_no_dynamic_library_file, pipeline_records, fail_in_place_check, assume_submissions_merge, @@ -2753,6 +2759,7 @@ impl Device { lowering_refuses, deferred: crate::render::DeferredEncoders::default(), record_executions, + load_no_dynamic_library_file, views_epoch: AtomicU64::new(0), pipeline_recording: crate::warm::Recording::new(pipeline_records), warmer: crate::warm::Warmer::default(), diff --git a/crates/metal2vulkan-runtime/src/dynamic_library.rs b/crates/metal2vulkan-runtime/src/dynamic_library.rs index f14409113..d7fb3e2cc 100644 --- a/crates/metal2vulkan-runtime/src/dynamic_library.rs +++ b/crates/metal2vulkan-runtime/src/dynamic_library.rs @@ -16,8 +16,14 @@ //! creation, so a replaced file links its new code. A name that is not an absolute path, or //! whose file does not hold a dynamic library, loads nothing, and the creation fails only where //! an import survives specialization, as Metal's does. +//! - **Reading a file.** Only a regular file is read, once, no further than its length when +//! opened (`container::read_file`): a name of a FIFO, a device or a directory loads nothing, +//! and `new_dynamic_library_with_url` answers it `InvalidFile`, as for a file that holds no +//! library. A device made with `DeviceOptions::load_no_dynamic_library_file` opens no such file +//! at all: its creations link only the libraries their function descriptors give, and +//! `new_dynamic_library_with_url` is refused (`NoFileLoading`). -use super::binary_archive::container::{write_file, WriteFailure}; +use super::binary_archive::container::{read_file, write_file, ReadFailure, WriteFailure}; use super::device::{device_error, lock}; use super::error::{DynamicLibraryError, Error}; use super::library::Library; @@ -65,9 +71,13 @@ impl Device { /// Metal's; its install name is the file's. A file that cannot be read is /// `DynamicLibrary(Read)` (a missing one is Metal's `NSCocoaErrorDomain` 260), and one that /// holds no library `DynamicLibrary(InvalidFile)`, as Metal answers (a probe), bare AIR bitcode - /// included, raw or wrapped ("its AIR slice is missing"). A library that is not one - /// `new_dynamic_library` takes is refused as it refuses it, where Metal's answer for a file is - /// not measured. + /// included, raw or wrapped ("its AIR slice is missing"). A path that names no regular file + /// (a FIFO, a device or a directory) is not opened for reading and is + /// `DynamicLibrary(InvalidFile)` too, where Metal's answer is not measured. A library that is + /// not one `new_dynamic_library` takes is refused as it refuses it, where Metal's answer for a + /// file is not measured. On a device made with + /// [`DeviceOptions::load_no_dynamic_library_file`](crate::DeviceOptions::load_no_dynamic_library_file) + /// the file is not opened, and the call is refused (`DynamicLibrary(NoFileLoading)`). pub fn new_dynamic_library_with_url(&self, url: &Path) -> Result { self.at_serving(|device| device.new_dynamic_library_with_url_now(url)) } @@ -77,18 +87,24 @@ impl Device { &self, url: &Path, ) -> Result { - let bytes = std::fs::read(url).map_err(|error| { - Error::DynamicLibrary(DynamicLibraryError::Read { - path: url.to_path_buf(), - kind: error.kind(), - message: error.to_string(), - }) - })?; - let library = metal2vulkan::library::Library::from_metallib(&bytes).map_err(|_| { - Error::DynamicLibrary(DynamicLibraryError::InvalidFile { - path: url.to_path_buf(), + let path = url.to_path_buf(); + if self.shared().load_no_dynamic_library_file { + return Err(Error::DynamicLibrary(DynamicLibraryError::NoFileLoading { + path, + })); + } + let bytes = read_file(url).map_err(|failure| { + Error::DynamicLibrary(match failure { + ReadFailure::NotRegular => DynamicLibraryError::InvalidFile { path: path.clone() }, + ReadFailure::Io(error) => DynamicLibraryError::Read { + path: path.clone(), + kind: error.kind(), + message: error.to_string(), + }, }) })?; + let library = metal2vulkan::library::Library::from_metallib(&bytes) + .map_err(|_| Error::DynamicLibrary(DynamicLibraryError::InvalidFile { path }))?; self.dynamic_library(library) } @@ -170,9 +186,12 @@ impl DynamicLibrary { /// directory for), or a file that cannot be read or holds no dynamic library with an install /// name, loads nothing: the compile then refuses an import that survives specialization /// (`NeedsInput(DynamicLibrary)`), as Metal's creation fails, and makes the others. A stage the -/// compile layer already compiled links nothing more. -pub(crate) fn stage_with_dependencies(stage: &StageSource) -> StageSource { +/// compile layer already compiled links nothing more. On a device made with +/// `DeviceOptions::load_no_dynamic_library_file`, no file is opened: the stage is as its +/// descriptor gave it, and an install name its `libraries.loaded` lacks loads nothing. +pub(crate) fn stage_with_dependencies(device: &Device, stage: &StageSource) -> StageSource { match stage { + StageSource::Function(_) if device.shared().load_no_dynamic_library_file => stage.clone(), StageSource::Function(function) => { StageSource::Function(function.clone().with_loaded_dependencies(load)) } @@ -181,13 +200,14 @@ pub(crate) fn stage_with_dependencies(stage: &StageSource) -> StageSource { } /// The dynamic library in the file `name` names, or `None` where none loads: as -/// `new_dynamic_library_with_url`, a file of bare AIR holds none. +/// `new_dynamic_library_with_url`, a file of bare AIR holds none, nor does a path of anything but +/// a regular file (`read_file`). fn load(name: &str) -> Option { let path = Path::new(name); if !path.is_absolute() { return None; } - let bytes = std::fs::read(path).ok()?; + let bytes = read_file(path).ok()?; let library = metal2vulkan::library::Library::from_metallib(&bytes).ok()?; metal2vulkan::library::DynamicLibrary::loaded(library).ok() } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index bc25ce8f6..47e7c756c 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1321,6 +1321,13 @@ pub enum DynamicLibraryError { /// The I/O error's text. message: String, }, + /// The file to load was not opened: the device was made to load no dynamic library from a + /// file ([`DeviceOptions::load_no_dynamic_library_file`](crate::DeviceOptions::load_no_dynamic_library_file)). + /// No Metal counterpart: Metal reads the file. + NoFileLoading { + /// The file. + path: PathBuf, + }, } impl fmt::Display for DynamicLibraryError { @@ -1329,6 +1336,13 @@ impl fmt::Display for DynamicLibraryError { DynamicLibraryError::InvalidFile { path } => { write!(f, "{} is not a dynamic library's file", path.display()) } + DynamicLibraryError::NoFileLoading { path } => { + write!( + f, + "the device loads no dynamic library from a file: {} was not opened", + path.display() + ) + } DynamicLibraryError::Read { path, message, .. } => { write!( f, diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index a1d60c564..0a88a60cb 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -748,7 +748,8 @@ impl ComputePipelineState { ) -> Result { let requested = descriptor; let mut descriptor = descriptor.clone(); - descriptor.kernel = crate::dynamic_library::stage_with_dependencies(&descriptor.kernel); + descriptor.kernel = + crate::dynamic_library::stage_with_dependencies(device, &descriptor.kernel); let state = ComputePipelineState::of_kernel( device, Kernel::Compute(descriptor), diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index d848f4cf0..df741a31f 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -1465,11 +1465,10 @@ impl GraphicsState { let _noted = NoteEntries(device); let requested = descriptor; let mut loaded = descriptor.clone(); - loaded.vertex = crate::dynamic_library::stage_with_dependencies(&loaded.vertex); - loaded.fragment = loaded - .fragment - .as_ref() - .map(crate::dynamic_library::stage_with_dependencies); + let with_dependencies = + |stage: &StageSource| crate::dynamic_library::stage_with_dependencies(device, stage); + loaded.vertex = with_dependencies(&loaded.vertex); + loaded.fragment = loaded.fragment.as_ref().map(with_dependencies); let descriptor = &loaded; // Metal's descriptor validation stops an attachment in a format Metal describes none // of, first (`attachment_formats.rs`). @@ -1864,15 +1863,11 @@ impl GraphicsState { IdPlacement::Any }; let mut loaded = descriptor.clone(); - loaded.object = loaded - .object - .as_ref() - .map(crate::dynamic_library::stage_with_dependencies); - loaded.mesh = crate::dynamic_library::stage_with_dependencies(&loaded.mesh); - loaded.fragment = loaded - .fragment - .as_ref() - .map(crate::dynamic_library::stage_with_dependencies); + let with_dependencies = + |stage: &StageSource| crate::dynamic_library::stage_with_dependencies(device, stage); + loaded.object = loaded.object.as_ref().map(with_dependencies); + loaded.mesh = with_dependencies(&loaded.mesh); + loaded.fragment = loaded.fragment.as_ref().map(with_dependencies); let descriptor = &loaded; // Under `FAIL_ON_BINARY_ARCHIVE_MISS`, refused naming the mesh function where no listed // archive holds the descriptor's key (`BinaryArchive::add_mesh_render_pipeline_functions`). diff --git a/crates/metal2vulkan-runtime/src/pipeline/tile.rs b/crates/metal2vulkan-runtime/src/pipeline/tile.rs index a6f920961..3de19dd0e 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/tile.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/tile.rs @@ -148,7 +148,7 @@ impl TileState { )?; let requested = descriptor; let mut descriptor = descriptor.clone(); - descriptor.tile = crate::dynamic_library::stage_with_dependencies(&descriptor.tile); + descriptor.tile = crate::dynamic_library::stage_with_dependencies(device, &descriptor.tile); let kernel = ComputePipelineState::of_kernel( device, Kernel::Tile(descriptor.clone()), diff --git a/crates/metal2vulkan-runtime/src/tests/binary_archive.rs b/crates/metal2vulkan-runtime/src/tests/binary_archive.rs index df6102f5b..deec604b0 100644 --- a/crates/metal2vulkan-runtime/src/tests/binary_archive.rs +++ b/crates/metal2vulkan-runtime/src/tests/binary_archive.rs @@ -187,6 +187,42 @@ fn a_file_that_is_missing_or_not_an_archive_is_an_invalid_file() { } } +/// A path of no regular file is no archive, and reading it waits on nothing: a FIFO, whose open +/// for reading would wait for a writer, and a device whose reads never end (`/dev/zero`). Each +/// read runs on a thread of its own for at most 30 s; a read still waiting then is let go (the +/// FIFO opened for writing) before the test fails, so the failure ends the test. +#[cfg(unix)] +#[test] +fn a_path_of_no_regular_file_is_no_archive_and_is_not_waited_on() { + let scratch = Scratch::new(); + let fifo = scratch.path().join("fifo"); + make_fifo(&fifo); + for path in [fifo.clone(), PathBuf::from("/dev/zero")] { + let (answer, answered) = std::sync::mpsc::channel(); + let read = path.clone(); + std::thread::spawn(move || { + let _ = answer.send(container::read(&read)); + }); + match answered.recv_timeout(std::time::Duration::from_secs(30)) { + Ok(read) => assert_eq!(read, Err(invalid_file(&path)), "{}", path.display()), + Err(_) => { + drop(fs::OpenOptions::new().write(true).open(&fifo)); + panic!("reading {} waited", path.display()); + } + } + } +} + +/// A FIFO made at `path`. +#[cfg(unix)] +fn make_fifo(path: &Path) { + use std::os::unix::ffi::OsStrExt as _; + let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `name` is a NUL-terminated path. + let made = unsafe { libc::mkfifo(name.as_ptr(), 0o600) }; + assert_eq!(made, 0, "mkfifo {}", path.display()); +} + #[test] fn writing_replaces_the_file_whole_and_leaves_nothing_else() { let scratch = Scratch::new(); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dynamic_libraries.rs b/crates/metal2vulkan-validation/src/runtime_lane/dynamic_libraries.rs index 469b68f4a..f946085fc 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dynamic_libraries.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dynamic_libraries.rs @@ -343,9 +343,21 @@ fn computed( preloaded: &[&DynamicLibrary], options: &PipelineOptions, ) -> Result, Error> { - let device = library.device(); - let state = - device.new_compute_pipeline_state(&descriptor(library, kernel, preloaded), options)?; + dispatched( + library.device(), + &descriptor(library, kernel, preloaded), + options, + ) +} + +/// What the compute state of `descriptor` writes over `N` threads under `options`, or the +/// creation's error. +fn dispatched( + device: &Device, + descriptor: &ComputePipelineDescriptor, + options: &PipelineOptions, +) -> Result, Error> { + let state = device.new_compute_pipeline_state(descriptor, options)?; let out = device .new_buffer(u64::from(N) * 12, ResourceOptions::shared()) .unwrap(); @@ -664,6 +676,114 @@ fn kernels_link_their_imports_as_metal_s_do() { }); } +/// A device made to load no dynamic library from a file +/// (`DeviceOptions::load_no_dynamic_library_file`) opens none: a client linked against A, whose +/// install name names A's file, is refused as for a file that loads nothing, A preloaded or not, +/// and links A where its descriptor gives A for that install name (`libraries.loaded`); a kernel +/// whose imports specialization deletes is made; and `new_dynamic_library_with_url` of A's file +/// is refused. +#[test] +fn a_device_that_loads_no_file_links_only_the_libraries_it_is_given() { + on_device_with( + |options| { + at_plan(options); + options.load_no_dynamic_library_file = true; + }, + |device| { + let dir = Scratch::new(); + let na = dir.name("A"); + let a = dylib( + device, + &dir, + "A", + &library_a(false), + &[SCALE, ADD, TWICE], + (&[], &[]), + ); + assert!(Path::new(&na).is_file(), "A's file is there"); + let cl1 = client_cl1(device, &[&na]); + let options = PipelineOptions::default(); + assert_eq!(computed(&cl1, "cl1", &[], &options), Err(unloaded(&na))); + assert_eq!(computed(&cl1, "cl1", &[&a], &options), Err(unloaded(&na))); + assert_eq!(plain(&cl1, "cl_none", &[]), rows(|x| [x, 0.0, 0.0])); + let given = DynamicLibraries::new().with_loaded(na.clone(), a.preloaded_library()); + let function = cl1.new_function_with_name("cl1").unwrap(); + let kernel = + StageSource::Function(function.function_descriptor().with_libraries(given)); + assert_eq!( + dispatched(device, &ComputePipelineDescriptor::new(kernel), &options), + Ok(rows(|x| [3.0 * x + 1.0, 102.0 + x, 6.0 * x + 2.0])) + ); + assert_eq!( + device + .new_dynamic_library_with_url(Path::new(&na)) + .map(|_| ()), + Err(Error::DynamicLibrary(DynamicLibraryError::NoFileLoading { + path: PathBuf::from(&na) + })) + ); + }, + ); +} + +/// An install name of a FIFO, or of a device whose reads never end (`/dev/zero`), loads nothing +/// and waits on nothing: the creation is refused as for a file that holds no library, and +/// `new_dynamic_library_with_url` answers `InvalidFile`. Each call runs on a thread of its own for +/// at most 60 s; a call still waiting then is let go (the FIFO opened for writing) before the test +/// fails, so the failure ends the test. +#[test] +fn an_install_name_of_no_regular_file_loads_nothing_and_waits_on_nothing() { + on_device_with(at_plan, |device| { + let dir = Scratch::new(); + let fifo = dir.name("fifo"); + make_fifo(Path::new(&fifo)); + let bounded = |name: &str, call: Box Result<(), Error> + Send>| { + let (answer, answered) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = answer.send(call()); + }); + answered + .recv_timeout(std::time::Duration::from_secs(60)) + .unwrap_or_else(|_| { + drop(std::fs::OpenOptions::new().write(true).open(&fifo)); + panic!("{name} waited"); + }) + }; + for name in [fifo.as_str(), "/dev/zero"] { + let client = client_cl1(device, &[name]); + let created = bounded( + name, + Box::new(move || { + computed(&client, "cl1", &[], &PipelineOptions::default()).map(|_| ()) + }), + ); + assert_eq!(created, Err(unloaded(name))); + let loader = device.clone(); + let path = PathBuf::from(name); + let url = path.clone(); + let loaded = bounded( + name, + Box::new(move || loader.new_dynamic_library_with_url(&url).map(|_| ())), + ); + assert_eq!( + loaded, + Err(Error::DynamicLibrary(DynamicLibraryError::InvalidFile { + path + })) + ); + } + }); +} + +/// A FIFO made at `path`. +fn make_fifo(path: &Path) { + use std::os::unix::ffi::OsStrExt as _; + let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + // SAFETY: `name` is a NUL-terminated path. + let made = unsafe { libc::mkfifo(name.as_ptr(), 0o600) }; + assert_eq!(made, 0, "mkfifo {}", path.display()); +} + /// Neither a preloaded library nor a dependency's contents is in a binary archive's key, as on /// Metal (probe 2b's section 4): a creation that preloads other libraries hits an archive the /// kernel was added to without them, and links them; a client linked against other install diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 3c9638f86..bc83ce022 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2104,6 +2104,7 @@ field metal2vulkan-runtime::DeviceOptions.instance_extensions pub instance_exten field metal2vulkan-runtime::DeviceOptions.kinds pub kinds: Vec field metal2vulkan-runtime::DeviceOptions.layer_settings pub layer_settings: Vec field metal2vulkan-runtime::DeviceOptions.layers pub layers: Vec +field metal2vulkan-runtime::DeviceOptions.load_no_dynamic_library_file pub load_no_dynamic_library_file: bool field metal2vulkan-runtime::DeviceOptions.loader pub loader: Option field metal2vulkan-runtime::DeviceOptions.lowering_refuses pub lowering_refuses: BTreeSet field metal2vulkan-runtime::DeviceOptions.mac_class pub mac_class: Option @@ -2360,6 +2361,7 @@ field metal2vulkan-runtime::RawDevice.gpu_times_from_host pub gpu_times_from_hos field metal2vulkan-runtime::RawDevice.host_image_copy pub host_image_copy: bool field metal2vulkan-runtime::RawDevice.instance pub instance: vk::Instance field metal2vulkan-runtime::RawDevice.instance_api_version pub instance_api_version: metal2vulkan::vk::ApiVersion +field metal2vulkan-runtime::RawDevice.load_no_dynamic_library_file pub load_no_dynamic_library_file: bool field metal2vulkan-runtime::RawDevice.lowering_refuses pub lowering_refuses: BTreeSet field metal2vulkan-runtime::RawDevice.mac_class pub mac_class: Option field metal2vulkan-runtime::RawDevice.physical_device pub physical_device: vk::PhysicalDevice @@ -11987,6 +11989,7 @@ variant metal2vulkan-runtime::DriverFact::TimestampsWaitForEveryQueue Timestamps variant metal2vulkan-runtime::DriverFact::UnstoredClearNoSlower UnstoredClearNoSlower variant metal2vulkan-runtime::DriverSetting::MoltenVkArgumentBuffersOff MoltenVkArgumentBuffersOff variant metal2vulkan-runtime::DynamicLibraryError::InvalidFile InvalidFile { path: PathBuf } +variant metal2vulkan-runtime::DynamicLibraryError::NoFileLoading NoFileLoading { path: PathBuf } variant metal2vulkan-runtime::DynamicLibraryError::Read Read { path: PathBuf, kind: std::io::ErrorKind, message: String } variant metal2vulkan-runtime::DynamicLibraryError::Write Write { path: PathBuf, kind: std::io::ErrorKind, message: String } variant metal2vulkan-runtime::EncoderKind::Blit Blit diff --git a/docs/API.md b/docs/API.md index 9d1083e5a..c9683ff0e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -4746,6 +4746,17 @@ each item named states the rule in full. path, not a URL. - **A dynamic library's file is its metallib.** `DynamicLibrary::serialize_to_url` writes the bytes the library was made from, without a slice of GPU code; the runtime loads either form. +- **Only a regular file is read.** A pipeline creation's install name, a + `Device::new_dynamic_library_with_url` path or a binary archive's path that names a FIFO, a + device or a directory is not opened for reading: the install name loads nothing, and the other + two are `InvalidFile`. A file is read once, no further than its length when opened. Metal's + answer for such paths is not measured. +- **A device can be made to open no dynamic library's file.** Under + `DeviceOptions::load_no_dynamic_library_file` (and `RawDevice`'s), a creation links only the + libraries its function descriptors give, an install name `libraries.loaded` lacks fails a + creation whose import survives specialization (`Compile(NeedsInput(DynamicLibrary))`) where Metal + would read the file, and `new_dynamic_library_with_url` is refused + (`DynamicLibraryError::NoFileLoading`). Off by default. **Resource IDs and identifiers**