Open a device although a layer asked for is one the loader cannot provide

The steps this packet landed as, in order:
- Recompute the pin for the instance that opens without a missing layer

Content: the tree of `development` at 47dc841a33, unchanged.
This commit is contained in:
Anees Iqbal committed 2026-10-26 13:19:15 +02:00
1 parent ca3043daf7
commit fa4442bbd5
8 files changed
+230 -11

No files matched your search

@@ -263,6 +263,7 @@ impl Device {
messenger: None,
relay: None,
settings: [0; 32],
dropped_layers: Vec::new(),
}),
physical: raw.physical_device,
raw: device,
@@ -598,7 +598,6 @@ fn create_instance(options: &DeviceOptions) -> Result<Arc<InstanceShared>, Error
// not enable refuses the options before the instance is made, where a driver need not.
instance_requirements_met(&options.device_extensions, &extensions)?;
let extension_names: Vec<*const c_char> = extensions.iter().map(|n| n.as_ptr()).collect();
let layer_names: Vec<*const c_char> = options.layers.iter().map(|n| n.as_ptr()).collect();
let api_version = instance_version(options.instance_api_version, || {
// SAFETY: a global command of a loaded entry.
let version = unsafe { entry.try_enumerate_instance_version() }.map_err(vulkan)?;
@@ -622,6 +621,7 @@ fn create_instance(options: &DeviceOptions) -> Result<Arc<InstanceShared>, Error
let (bools, strings) = setting_values(&chained_settings);
let settings = layer_settings(&chained_settings, &bools, &strings);
let mut settings_info = vk::LayerSettingsCreateInfoEXT::default().settings(&settings);
let layer_names: Vec<*const c_char> = options.layers.iter().map(|n| n.as_ptr()).collect();
let mut info = vk::InstanceCreateInfo::default()
.application_info(&application)
.enabled_extension_names(&extension_names)
@@ -631,17 +631,36 @@ fn create_instance(options: &DeviceOptions) -> Result<Arc<InstanceShared>, Error
} else {
vk::InstanceCreateFlags::empty()
});
// The chain is built once, before the attempts below: `push_next` writes the pushed
// structure's own `pNext`, so pushing these onto a second create info would leave the one
// pushed last pointing at the one pushed first, whose `pNext` the second push then sets to
// itself -- a cycle the loader walks without end, allocating as it goes.
if let Some(chained) = chained.as_mut() {
info = info.push_next(chained);
}
if !settings.is_empty() {
info = info.push_next(&mut settings_info);
}
// SAFETY: `info` and everything it points at live for the call.
let raw = match unsafe { new_instance(&entry, &info) } {
Ok(raw) => raw,
Err(vk::Result::ERROR_INCOMPATIBLE_DRIVER) => return Err(Error::NoDevice),
Err(error) => return Err(vulkan(error)),
// A layer the loader cannot provide is not something the device lacks: the layers are
// diagnostics, so a caller that asked for a device gets one. The instance of the layers asked
// for and, where the loader answers `VK_ERROR_LAYER_NOT_PRESENT` ([`drops_layers`]), of no
// layer at all, whose answer is the caller's: two `vkCreateInstance` calls at most, the same
// create info but for its layer list, which the second has none of, so the arm cannot run
// twice. What was left out is announced as each device is made ([`layers_dropped`]).
let mut layers: &[CString] = &options.layers;
let mut dropped: Vec<CString> = Vec::new();
let raw = loop {
// SAFETY: `info` and everything it points at live for the call.
match unsafe { new_instance(&entry, &info) } {
Ok(raw) => break raw,
Err(vk::Result::ERROR_INCOMPATIBLE_DRIVER) => return Err(Error::NoDevice),
Err(error) if drops_layers(error, layers) => {
dropped = options.layers.clone();
layers = &[];
info = info.enabled_layer_names(&[]);
}
Err(error) => return Err(vulkan(error)),
}
};
let messenger = match (sink, messenger_info.as_mut()) {
(Some(sink), Some(info)) => {
@@ -688,9 +707,39 @@ fn create_instance(options: &DeviceOptions) -> Result<Arc<InstanceShared>, Error
messenger,
relay,
settings,
dropped_layers: dropped,
}))
}
/// Whether `error`, which `vkCreateInstance` of `layers` answered, is answered by creating the
/// instance again with no layer at all: a missing layer's answer alone, and only where a layer was
/// asked for (`VK_ERROR_LAYER_NOT_PRESENT` with none asked for is the loader's own answer, with
/// nothing of ours to drop). Every other failure is the caller's.
pub(crate) fn drops_layers(error: vk::Result, layers: &[CString]) -> bool {
error == vk::Result::ERROR_LAYER_NOT_PRESENT && !layers.is_empty()
}
/// The informational message a device of an instance created without the layers `dropped`, which
/// its caller asked for and the loader could not provide, sends as it is made: no degrade notice,
/// as nothing of Metal's answers differs (the layers are diagnostics). `None` where none was
/// dropped.
pub(crate) fn layers_dropped(dropped: &[CString], device: &str) -> Option<String> {
if dropped.is_empty() {
return None;
}
let names: Vec<String> = dropped
.iter()
.map(|name| name.to_string_lossy().into_owned())
.collect();
Some(format!(
"metal2vulkan: the device on {device} was made without the instance layer(s) {}, which the loader answered VK_ERROR_LAYER_NOT_PRESENT for: a layer it does not list, or one it lists and cannot load (a layer manifest naming its library by a bare filename, which the loader looks for on the system library search path). The device is the same in every other way and its answers are Metal's; what those layers would have reported is missing [{LAYERS_DROPPED}]"
, names.join(", ")))
}
/// The id name of the informational message a device made without the layers its caller asked for
/// sends as it is made ([`layers_dropped`]).
pub(crate) const LAYERS_DROPPED: &str = "metal2vulkan-instance-layers-dropped";
/// The physical devices of `instance` that `options` admit, in the order
/// `Device::system_default` prefers them (by [`DeviceKind`], then enumeration order).
fn ranked(
@@ -1388,6 +1437,9 @@ fn create_on(
};
// SAFETY: the device was made from these parts just now.
let device = unsafe { Device::assemble(parts) }?;
if let Some(text) = layers_dropped(&instance.dropped_layers, device.name()) {
device.inform(LAYERS_DROPPED, text);
}
if let Some(why) = cache_kept {
let object = format!("the device, on {}", device.name());
if kept_cache_is_metals(device.properties().description.driver_id) {
@@ -128,6 +128,12 @@ pub(super) struct InstanceShared {
/// an adopted instance): part of a making's pipeline cache record's name
/// (`shader_cache/driver.rs`).
pub(super) settings: metal2vulkan::cache::Hash256,
/// The instance layers the caller asked for that the loader could not provide, which the
/// instance was created without (`create::layers_after`), in the order asked: each device
/// made of the instance says so as it is made (`create::layers_dropped`). Empty for an
/// instance created with every layer asked for, for one adopted, and where none was asked
/// for.
pub(super) dropped_layers: Vec<std::ffi::CString>,
}
impl InstanceShared {
@@ -17,9 +17,9 @@ fn the_registry_id_folds_the_uuid_and_is_never_zero() {
}
use crate::device::create::{
default_loaders, dma_buf_image_names, dma_buf_names, enable_set, host_image_copy,
instance_version, layer_settings, linear_color_attachment, open_loader, queue_plan,
setting_values, timeline_difference, QueuePlan,
default_loaders, dma_buf_image_names, dma_buf_names, drops_layers, enable_set, host_image_copy,
instance_version, layer_settings, layers_dropped, linear_color_attachment, open_loader,
queue_plan, setting_values, timeline_difference, QueuePlan, LAYERS_DROPPED,
};
use crate::enables::host_image_copy_names;
use crate::{DeviceOptions, Error, InstanceApiVersion, LayerSetting, LayerSettingValue};
@@ -721,3 +721,47 @@ fn native_device_maths_rounds_a_tiny_product_before_its_flush_off_moltenvk() {
"{rounding} rounding, {metals} Metal's own"
);
}
/// Only a `vkCreateInstance` that answered `VK_ERROR_LAYER_NOT_PRESENT` with a layer asked for is
/// answered by creating the instance again without the layers; every other failure, and that
/// answer with no layer asked for, is the caller's. The creation clears the list to drop them, so
/// the second attempt cannot answer so again: two `vkCreateInstance` calls at most.
#[test]
fn only_a_missing_layer_drops_the_layers_asked_for() {
let asked = vec![CString::new("VK_LAYER_KHRONOS_validation").unwrap()];
let missing = vk::Result::ERROR_LAYER_NOT_PRESENT;
assert!(drops_layers(missing, &asked));
// The list cleared: the guard is false, so the attempts end at two.
assert!(!drops_layers(missing, &[]));
// Every other failure, which the caller answers: the fallback is this error code's alone.
for error in [
vk::Result::ERROR_OUT_OF_HOST_MEMORY,
vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
vk::Result::ERROR_INITIALIZATION_FAILED,
vk::Result::ERROR_EXTENSION_NOT_PRESENT,
vk::Result::ERROR_INCOMPATIBLE_DRIVER,
vk::Result::ERROR_DEVICE_LOST,
vk::Result::SUCCESS,
] {
assert!(!drops_layers(error, &asked), "{error:?} dropped the layers");
}
}
/// The message a device of such an instance sends as it is made names its layers, its device and
/// the id name; a device whose instance dropped none sends nothing.
#[test]
fn the_dropped_layers_are_announced_by_name() {
assert_eq!(layers_dropped(&[], "a device"), None);
let dropped = vec![
CString::new("VK_LAYER_KHRONOS_validation").unwrap(),
CString::new("VK_LAYER_absent").unwrap(),
];
let text = layers_dropped(&dropped, "an Apple M3 Max").expect("the message");
assert!(
text.contains("VK_LAYER_KHRONOS_validation, VK_LAYER_absent"),
"{text}"
);
assert!(text.contains("an Apple M3 Max"), "{text}");
assert!(text.contains(LAYERS_DROPPED), "{text}");
assert_eq!(LAYERS_DROPPED, "metal2vulkan-instance-layers-dropped");
}
@@ -0,0 +1,114 @@
//! A device opens although a layer its caller asked for is one the loader cannot provide
//! (`device/create.rs`): the layers are diagnostics, so `VK_ERROR_LAYER_NOT_PRESENT` never
//! reaches a caller that asked for a device. The device says as it is made which layers it was
//! made without, and a device whose layers the loader provides says nothing.
//!
//! Bounded by construction: each test opens one device, so at most two `vkCreateInstance` calls
//! (the layers asked for, then none) and one `VkInstance`, dropped with the device before the test
//! ends.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. Nothing runs on the GPU.
use crate::device::create::{open_loader, LAYERS_DROPPED};
use crate::{DebugMessage, Device, DeviceKind, DeviceOptions, MessageSink};
use std::ffi::{CStr, CString};
use std::sync::{Arc, Mutex};
/// A layer name no loader lists, which the runtime must drop rather than fail on.
const ABSENT: &CStr = c"VK_LAYER_metal2vulkan_absent_for_this_test";
/// The validation layer, which this host may or may not provide.
const VALIDATION: &CStr = c"VK_LAYER_KHRONOS_validation";
/// Whether the loader lists `name`, read before any instance is created: the loader's layer
/// enumeration is a two-call sequence that retries while it answers `VK_INCOMPLETE`, so it is
/// never run after a failed creation.
fn lists(name: &CStr) -> bool {
let Ok(entry) = open_loader(None) else {
return false;
};
// SAFETY: the loader is open; listing its layers needs nothing else.
let listed = unsafe { entry.enumerate_instance_layer_properties() };
let Ok(layers) = listed else {
return false;
};
(layers.iter()).any(|layer| layer.layer_name_as_c_str().is_ok_and(|n| n == name))
}
/// The messages a device reports, and options of the kind the cfg selects that ask for `layers`
/// and report to them: a group of one device, which no other test shares (a sink is compared by
/// its identity).
fn watched(layers: Vec<CString>) -> (Arc<Mutex<Vec<DebugMessage>>>, DeviceOptions) {
let said: Arc<Mutex<Vec<DebugMessage>>> = Arc::new(Mutex::new(Vec::new()));
let reported = Arc::clone(&said);
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
layers,
messages: Some(MessageSink::new(move |message: &DebugMessage| {
let mut said = reported.lock().unwrap_or_else(|p| p.into_inner());
// Bounded: a message list a flood cannot grow.
if said.len() < 64 {
said.push(message.clone());
}
})),
..DeviceOptions::default()
};
(said, options)
}
#[test]
fn a_device_opens_without_the_layers_the_loader_cannot_provide() {
// One the loader cannot provide, beside one it may: the creation drops the layers it asked
// for and creates the instance once more with none.
let (said, options) = watched(vec![VALIDATION.to_owned(), ABSENT.to_owned()]);
let device = Device::system_default_with(&options)
.expect("a device opens although a layer asked for is missing");
let name = device.name();
let said = said.lock().unwrap_or_else(|p| p.into_inner()).clone();
let dropped: Vec<&DebugMessage> = (said.iter())
.filter(|message| message.id_name == LAYERS_DROPPED)
.collect();
assert_eq!(
dropped.len(),
1,
"the device said once which layers it was made without: {said:#?}"
);
let text = &dropped[0].text;
assert!(
dropped[0].degradation.is_none(),
"no degrade notice: nothing of Metal's answers differs"
);
// Every layer asked for is named, and the device.
for layer in [VALIDATION, ABSENT] {
let layer = layer.to_string_lossy();
assert!(text.contains(layer.as_ref()), "{text}");
}
assert!(text.contains(&name), "{text}");
drop(device);
}
/// Every layer asked for provided: the device is made with them and says nothing. Where the
/// loader lists none (this host), the device asks for none, which is the same answer.
#[test]
fn a_device_made_with_its_layers_says_nothing() {
let layers: Vec<CString> = match lists(VALIDATION) {
true => vec![VALIDATION.to_owned()],
false => Vec::new(),
};
let (said, options) = watched(layers);
let device = Device::system_default_with(&options).expect("a device opens");
let said = said.lock().unwrap_or_else(|p| p.into_inner()).clone();
assert!(
!said.iter().any(|message| message.id_name == LAYERS_DROPPED),
"nothing was dropped, so nothing is said: {said:#?}"
);
drop(device);
}
@@ -141,6 +141,8 @@ mod mipmap;
mod mipmap_plan;
mod mipmap_scratch;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod missing_layer;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod multisample_buffer_copy;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod multisample_buffer_layouts;
@@ -1 +1 @@
94b3cddb8ece39a2bee70bc7f71bbddfcd2cbb55c5718a584f04b7505a2bac01
82f545fe9eb5f7f8ad269624f3fe47f3e8b5b772a312d5cb25cb1e002e1bafe7
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 448;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1548;
pub const RUNTIME_VERSION: u32 = 1549;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles