Skip to content

XNU as a loadable kernel module inside Linux (macOS personality for arm64 Linux)

C

gpu/xnu-cpu-metal: deterministic direct driver loading via VK_LUNARG_direct_driver_loading

Heyang Zhoub4a1a94665eb
diff --git a/gpu/xnu-cpu-metal/REPORT.md b/gpu/xnu-cpu-metal/REPORT.md
index 0cd5cb0..a2d3d43 100644
--- a/gpu/xnu-cpu-metal/REPORT.md
+++ b/gpu/xnu-cpu-metal/REPORT.md
@@ -540,3 +540,32 @@ dist/XnuCpuMetal.bundle/
| `2560×1440` (14.06 MB) | `1.12 ms` (12530 MB/s) | `0.66 ms` | `2.77 ms` (5078 MB/s) | `4.26 ms` (est upload `1.49 ms`) |
结论:在真 GPU(MoltenVK)上,1080p 单帧 `syncToIOSurface` 约 `1.59 ms`、双向约 `2.37 ms`;1440p 单帧回写约 `2.77 ms`、双向约 `4.26 ms`。托管 VM 中经 Venus(virtio-gpu 共享内存)预计在 `2–5 ms/帧` 量级,首版接入可直接复用现有 IOSurface 同步路径满足 60fps 交互基线,后续如出现高分辨率合成瓶颈再评估基于共享内存 / `VK_EXT_external_memory_host` 的零拷贝优化。
+
+---
+
+## Round 17: 通过 `VK_LUNARG_direct_driver_loading` (`EXCLUSIVE`) 实现无环境变量、确定性单 ICD 加载(解决 `WindowServer` secure-mode 回落 lavapipe)
+
+### 根因核实
+- 核实 `metal2vulkan-runtime` 源码:`DeviceKind::preference()` 确实按 `Discrete (0) < Integrated (1) < Virtual (2) < Cpu (3) < Other (4)` 排序;但 `Device::system_default_with` 在循环尝试 `ranked()` 设备时,若首位设备失败会静默尝试下一个设备并成功返回 lavapipe,不向上层报错。
+- 在 `WindowServer`(secure mode,Vulkan-Loader 忽略 `VK_ICD_FILENAMES` / `VK_DRIVER_FILES`)下,此前 `ListedExtensions::of(&entry)` 调用 `vkEnumerateInstanceExtensionProperties(NULL)` 以及 `keeper.rs` 创建 `bare_instance` 时,Loader 仍会扫描 `Resources/vulkan/icd.d/*.json` 并同时 `dlopen` `libvulkan_virtio.dylib` 与 `libvulkan_lvp.dylib`(额外占 ~196 MB 内存并初始化 llvmpipe)。
+
+### 修复方案(`VK_LUNARG_direct_driver_loading` `EXCLUSIVE` 模式)
+1. **`patches/metal2vulkan/0003-direct-driver-loading.patch`**(改 `device/{adopt,create,keeper,mod}.rs`):
+ - `DeviceOptions` 新增 `direct_driver_pfn: Option<usize>`(以 `usize` 透传 ObjC++ 侧 `dlsym` 获得的 `PFN_vkGetInstanceProcAddr`,完整保留 `arm64e` PAC 签名且不经 Rust 侧解引用)。
+ - 启用 `direct_driver_pfn` 时:`instance_of` 跳过 `ListedExtensions::of(&entry)`(不再触发 `icd.d` 扫描),直接启用 Loader 内置扩展 `VK_KHR_portability_enumeration`、`VK_EXT_debug_utils`、`VK_LUNARG_direct_driver_loading`,并将 `VkDirectDriverLoadingListLUNARG { mode: EXCLUSIVE }` 链入 `VkInstanceCreateInfo.pNext`;`keeper.rs` 在 `direct_driver == true` 时跳过额外 `bare_instance`(驱动由插件 `dlopen` 常驻,同时省去每进程多开一个 Venus DRM 上下文)。
+2. **`src/xnu-m2v-bridge/`(`include/xnu_m2v.h`、`src/lib.rs`)**:
+ - 新增 `xm2v_device_open_direct(loader_path, direct_driver_pfn, icd_json_path, cache_dir)`,当 `direct_driver_pfn != NULL` 时完全不读写 `VK_ICD_FILENAMES` / `VK_DRIVER_FILES`。
+3. **`src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`**:
+ - 新增 `xcmLoadDirectDriver`:在 Clang `arm64`/`arm64e` 侧 `dlopen(..., RTLD_NOW | RTLD_LOCAL)` 并先调用 `vk_icdNegotiateLoaderICDInterfaceVersion` 校验接口版本 `>= 7`(Mesa Venus 与 lavapipe 均支持 v7;旧版如 MoltenVK 1.4.2 报 v5 自动退回 manifest 路径),再 `dlsym("vk_icdGetInstanceProcAddr")` 传给 `xm2v_device_open_direct`。
+ - 选 Venus 时完全不 `dlopen` `libvulkan_lvp.dylib`;若 Venus 打开失败,先通过 `os_log_error` 打出具体 `xm2v_last_error()`,仅在非强制模式下再显式打开 `libvulkan_lvp.dylib` 回退。
+ - 新增 `XNU_CPU_METAL_DRIVER` 支持直接指定驱动 dylib;重新打包基于 `main` `4e908b8` 的新版 universal `libvulkan_virtio.dylib`。
+
+### 宿主机验证结果(`test/test_round17_direct_driver.mm` + 全套回归)
+- **`VK_LOADER_DEBUG=all` 实测(`arm64e`)**:`libvulkan_virtio.dylib` 与 `libvulkan_lvp.dylib` 均以 PAC 签名函数指针走 `VK_DIRECT_DRIVER_LOADING_MODE_EXCLUSIVE_LUNARG`,Loader 明确日志 `skipping system and environment variable driver search mechanisms`。
+- **双 ICD / 恶意环境变量 / secure-mode 模拟(6 项全 PASS)**:
+ 1. 设恶意 `VK_ICD_FILENAMES=lvp` + `XNU_CPU_METAL_ICD=MoltenVK` → 选中 `Apple M5 Max`,`libvulkan_lvp` 未加载(`_dyld_image_count` 校验 `loaded=0`),blit fill PASS。
+ 2. 双 ICD 同时可见 `lvp:MoltenVK` 与 `MoltenVK:lvp` 两种顺序 → 均选中 `Apple M5 Max`,blit fill PASS。
+ 3. 设恶意 `VK_ICD_FILENAMES=MoltenVK` 下默认 lavapipe(`arm64` + `arm64e`)→ 走 `EXCLUSIVE` 选中 `llvmpipe`,`libvulkan_virtio` 与 `libMoltenVK` 均 `loaded=0`,blit fill PASS。
+ 4. 设恶意 `VK_ICD_FILENAMES=lvp` + `XNU_CPU_METAL_BACKEND=venus`(宿主机无 `XnuDrm`)→ 干净返回 `nil` (`VkResult(-3)`),`libvulkan_lvp` `loaded=0`。
+ 5. 模拟 secure-mode 双 ICD bundle(`Resources/vulkan/icd.d/` 同时放 `lvp` + `MoltenVK` 且 `unset VK_ICD_FILENAMES VK_DRIVER_FILES`)→ 默认选中 `llvmpipe`(`libMoltenVK` `loaded=0`),强选 `venus` 返回 `nil`(`libvulkan_lvp` `loaded=0`)。
+- **全套回归全通过**:`lavapipe (arm64e)` 与 `MoltenVK (arm64)` 的 `test-bundle.sh`、`test-render-ci.sh`、`test_round10`、`test_carenderer`、`test_round13`、`test_round14_vfx` 全部 PASS。
diff --git a/gpu/xnu-cpu-metal/patches/metal2vulkan/0003-direct-driver-loading.patch b/gpu/xnu-cpu-metal/patches/metal2vulkan/0003-direct-driver-loading.patch
new file mode 100644
index 0000000..0d5fc7d
--- /dev/null
+++ b/gpu/xnu-cpu-metal/patches/metal2vulkan/0003-direct-driver-loading.patch
@@ -0,0 +1,167 @@
+diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs
+index 4a81bc8..57c84bf 100644
+--- a/crates/metal2vulkan-runtime/src/device/adopt.rs
++++ b/crates/metal2vulkan-runtime/src/device/adopt.rs
+@@ -329,6 +329,7 @@ impl Device {
+ relay: None,
+ settings: [0; 32],
+ dropped_layers: Vec::new(),
++ direct_driver: false,
+ }),
+ physical: raw.physical_device,
+ raw: device,
+diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs
+index 7d83e3f..76e9c9d 100644
+--- a/crates/metal2vulkan-runtime/src/device/create.rs
++++ b/crates/metal2vulkan-runtime/src/device/create.rs
+@@ -123,6 +123,9 @@ pub struct DeviceOptions {
+ /// Homebrew's `/opt/homebrew/lib` and `/usr/local/lib`. A loader that opens from none of
+ /// them is [`Error::LoaderNotFound`], naming each.
+ pub loader: Option<PathBuf>,
++ /// Optional `PFN_vkGetInstanceProcAddr` pointer (as `usize`) for `VK_LUNARG_direct_driver_loading`
++ /// in exclusive mode, bypassing loader ICD manifest/environment discovery.
++ pub direct_driver_pfn: Option<usize>,
+ /// Only physical devices of these kinds qualify; empty admits every kind.
+ pub kinds: Vec<DeviceKind>,
+ /// Where the devices keep translated shaders: by default, the platform's per-user cache
+@@ -406,6 +409,7 @@ impl std::fmt::Debug for DeviceOptions {
+ withheld_extensions,
+ messages,
+ loader,
++ direct_driver_pfn,
+ kinds,
+ shader_cache,
+ withhold_generated_commands,
+@@ -439,6 +443,7 @@ impl std::fmt::Debug for DeviceOptions {
+ .field("withheld_extensions", withheld_extensions)
+ .field("messages", messages)
+ .field("loader", loader)
++ .field("direct_driver_pfn", direct_driver_pfn)
+ .field("kinds", kinds)
+ .field("shader_cache", shader_cache)
+ .field("withhold_generated_commands", withhold_generated_commands)
+@@ -489,6 +494,7 @@ impl Default for DeviceOptions {
+ withheld_extensions: Default::default(),
+ messages: Default::default(),
+ loader: Default::default(),
++ direct_driver_pfn: Default::default(),
+ kinds: Default::default(),
+ shader_cache: Default::default(),
+ withhold_generated_commands: Default::default(),
+@@ -962,22 +968,35 @@ pub(crate) fn instance_of(
+ entry: ash::Entry,
+ options: &DeviceOptions,
+ ) -> Result<Arc<InstanceShared>, Error> {
+- let listed = ListedExtensions::of(&entry)?;
+- let portability = listed.lists(ash::khr::portability_enumeration::NAME);
++ let (portability, relays, asks) = if options.direct_driver_pfn.is_some() {
++ // Direct driver loading bypasses `vkEnumerateInstanceExtensionProperties(NULL)` so the
++ // loader never scans `icd.d` manifests or dlopens unused ICDs (e.g., lavapipe).
++ // Khronos Vulkan-Loader always exposes portability_enumeration, debug_utils, and
++ // lunarg_direct_driver_loading directly from the loader.
++ (true, true, false)
++ } else {
++ let listed = ListedExtensions::of(&entry)?;
++ (
++ listed.lists(ash::khr::portability_enumeration::NAME),
++ listed.lists(ash::ext::debug_utils::NAME),
++ listed.lists(ash::ext::layer_settings::NAME),
++ )
++ };
+ let mut extensions: Vec<&CStr> = Vec::new();
+ if portability {
+ extensions.push(ash::khr::portability_enumeration::NAME);
+ }
++ if options.direct_driver_pfn.is_some() {
++ extensions.push(vk::LUNARG_DIRECT_DRIVER_LOADING_NAME);
++ }
+ // The relay of a driver's command-buffer failures needs a messenger of its own
+ // (`relay.rs`): debug utils wherever the instance lists them.
+- let relays = listed.lists(ash::ext::debug_utils::NAME);
+ if options.messages.is_some() || relays {
+ extensions.push(ash::ext::debug_utils::NAME);
+ }
+ // MoltenVK's Metal argument buffers, asked for where the instance can take layer settings,
+ // ahead of the consumer's own, which win (`argument_buffers.rs`); and, where the relay hears
+ // its failures, that it keep a device after a command buffer fails (`relay.rs`).
+- let asks = listed.lists(ash::ext::layer_settings::NAME);
+ let chained_settings: Vec<LayerSetting> = asks
+ .then(super::argument_buffers::setting)
+ .into_iter()
+@@ -1019,6 +1038,15 @@ pub(crate) fn instance_of(
+ 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 direct_driver_infos = options.direct_driver_pfn.map(|pfn_addr| {
++ let pfn: vk::PFN_vkGetInstanceProcAddrLUNARG = unsafe { std::mem::transmute(pfn_addr) };
++ [vk::DirectDriverLoadingInfoLUNARG::default().pfn_get_instance_proc_addr(pfn)]
++ });
++ let mut direct_driver_list = direct_driver_infos.as_ref().map(|infos| {
++ vk::DirectDriverLoadingListLUNARG::default()
++ .mode(vk::DirectDriverLoadingModeLUNARG::EXCLUSIVE)
++ .drivers(infos)
++ });
+ 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)
+@@ -1039,6 +1067,9 @@ pub(crate) fn instance_of(
+ if !settings.is_empty() {
+ info = info.push_next(&mut settings_info);
+ }
++ if let Some(ddl) = direct_driver_list.as_mut() {
++ info = info.push_next(ddl);
++ }
+ // 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
+@@ -1106,6 +1137,7 @@ pub(crate) fn instance_of(
+ relay,
+ settings,
+ dropped_layers: dropped,
++ direct_driver: options.direct_driver_pfn.is_some(),
+ }))
+ }
+
+@@ -2725,6 +2757,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool {
+ withheld_extensions,
+ messages: _,
+ loader,
++ direct_driver_pfn,
+ kinds,
+ shader_cache,
+ withhold_generated_commands,
+@@ -2756,6 +2789,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool {
+ && *withheld_features == b.withheld_features
+ && *withheld_extensions == b.withheld_extensions
+ && *loader == b.loader
++ && *direct_driver_pfn == b.direct_driver_pfn
+ && *kinds == b.kinds
+ && *shader_cache == b.shader_cache
+ && *withhold_generated_commands == b.withhold_generated_commands
+diff --git a/crates/metal2vulkan-runtime/src/device/keeper.rs b/crates/metal2vulkan-runtime/src/device/keeper.rs
+index 42b0ec6..dc07754 100644
+--- a/crates/metal2vulkan-runtime/src/device/keeper.rs
++++ b/crates/metal2vulkan-runtime/src/device/keeper.rs
+@@ -83,6 +83,9 @@ static KEEPERS: Kept<usize, Keeper> = Kept::new();
+ /// that device is primed (the module docs). A keeper that cannot be made leaves the device as it
+ /// is, and the next device tries again.
+ pub(super) fn keep_drivers_loaded(instance: &InstanceShared) {
++ if instance.direct_driver {
++ return;
++ }
+ let entry = &instance.entry;
+ let library = entry.static_fn().get_instance_proc_addr as usize;
+ let portability = instance
+diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs
+index 03073ee..a7fa608 100644
+--- a/crates/metal2vulkan-runtime/src/device/mod.rs
++++ b/crates/metal2vulkan-runtime/src/device/mod.rs
+@@ -205,6 +205,8 @@ pub(super) struct InstanceShared {
+ /// instance created with every layer asked for, for one adopted, and where none was asked
+ /// for.
+ pub(super) dropped_layers: Vec<std::ffi::CString>,
++ /// True when the instance was created via `VK_LUNARG_direct_driver_loading` exclusive mode.
++ pub(super) direct_driver: bool,
+ }
+
+ impl InstanceShared {
diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
index 922e3e3..2d61716 100644
--- a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
@@ -3191,9 +3191,53 @@ static void fillBaseLimits(id device) {
}
}
-extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json, const char *cache_dir, unsigned port) {
+static void *xcmLoadDirectDriver(const std::string &dylibPath) {
+ if (dylibPath.empty()) return nullptr;
+ void *handle = dlopen(dylibPath.c_str(), RTLD_NOW | RTLD_LOCAL);
+ if (!handle) {
+ const char *err = dlerror();
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: dlopen(%{public}s) failed: %{public}s",
+ dylibPath.c_str(), err ?: "?");
+ return nullptr;
+ }
+ // VK_LUNARG_direct_driver_loading requires ICD loader interface version >= 7
+ // (Mesa lavapipe and Venus support v7; older ICDs like MoltenVK 1.4.2 report v5
+ // and fall back to manifest-based loading).
+ uint32_t ver = 7;
+ auto negotiate = (int32_t (*)(uint32_t *))dlsym(handle, "vk_icdNegotiateLoaderICDInterfaceVersion");
+ if (!negotiate || negotiate(&ver) != 0 || ver < 7) {
+ return nullptr;
+ }
+ void *pfn = dlsym(handle, "vk_icdGetInstanceProcAddr");
+ if (!pfn) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: dlsym(vk_icdGetInstanceProcAddr) in %{public}s failed",
+ dylibPath.c_str());
+ return nullptr;
+ }
+ return pfn;
+}
+
+static std::string xcmResolveIcdLibraryPath(const std::string &icdJsonPath) {
+ if (icdJsonPath.empty() || icdJsonPath.find(':') != std::string::npos) return {};
+ NSData *data = [NSData dataWithContentsOfFile:@(icdJsonPath.c_str())];
+ if (!data) return {};
+ id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
+ if (![obj isKindOfClass:[NSDictionary class]]) return {};
+ id icd = ((NSDictionary *)obj)[@"ICD"];
+ if (![icd isKindOfClass:[NSDictionary class]]) return {};
+ id libPath = ((NSDictionary *)icd)[@"library_path"];
+ if (![libPath isKindOfClass:[NSString class]] || [(NSString *)libPath length] == 0) return {};
+ NSString *lp = (NSString *)libPath;
+ if ([lp hasPrefix:@"/"]) return lp.fileSystemRepresentation;
+ NSString *dir = [@(icdJsonPath.c_str()) stringByDeletingLastPathComponent];
+ NSString *full = [[dir stringByAppendingPathComponent:lp] stringByStandardizingPath];
+ return full.fileSystemRepresentation;
+}
+
+extern "C" id xnu_cpu_metal_open_device_direct(const char *loader, void *direct_driver_pfn,
+ const char *icd_json, const char *cache_dir, unsigned port) {
if (gSingletonDevice) return gSingletonDevice;
- gXm2vDevice = xm2v_device_open(loader, icd_json, cache_dir);
+ gXm2vDevice = xm2v_device_open_direct(loader, direct_driver_pfn, icd_json, cache_dir);
if (!gXm2vDevice) {
const char *err = xm2v_last_error();
fprintf(stderr, "XnuCpuMetal: xm2v_device_open failed (cache=%s): %s\n", cache_dir ?: "(null)", err ?: "?");
@@ -3214,6 +3258,10 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
return dev;
}
+extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json, const char *cache_dir, unsigned port) {
+ return xnu_cpu_metal_open_device_direct(loader, nullptr, icd_json, cache_dir, port);
+}
+
/* ======================== Bundle Principal Class ======================== */
@interface XnuCpuMetalDevice : IOGPUMetalDevice
@@ -3245,16 +3293,28 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
std::string loader = contentsDir.empty() ? "libvulkan.1.dylib" : (contentsDir + "/Frameworks/libvulkan.1.dylib");
std::string lvpIcd = contentsDir.empty() ? "" : (contentsDir + "/Resources/lvp_icd.aarch64.json");
std::string venusIcd = contentsDir.empty() ? "" : (contentsDir + "/Resources/virtio_icd.aarch64.json");
+ std::string lvpDylib = contentsDir.empty() ? "" : (contentsDir + "/Frameworks/libvulkan_lvp.dylib");
+ std::string venusDylib = contentsDir.empty() ? "" : (contentsDir + "/Frameworks/libvulkan_virtio.dylib");
const char *envLoader = getenv("XNU_CPU_METAL_LOADER");
if (envLoader && envLoader[0]) loader = envLoader;
+ const char *envDriver = getenv("XNU_CPU_METAL_DRIVER");
const char *envIcd = getenv("XNU_CPU_METAL_ICD");
const char *envBackend = getenv("XNU_CPU_METAL_BACKEND");
bool useVenus = false;
bool forcedBackend = false;
- bool customIcd = (envIcd && envIcd[0]);
- if (!customIcd) {
+ bool customDriver = (envDriver && envDriver[0]) || (envIcd && envIcd[0]);
+ std::string directDylib;
+ std::string icdJson;
+ if (envDriver && envDriver[0]) {
+ directDylib = envDriver;
+ } else if (envIcd && envIcd[0]) {
+ icdJson = envIcd;
+ // Single-ICD JSON: resolve library_path and load via VK_LUNARG_direct_driver_loading
+ // (works in secure mode and avoids scanning icd.d). Multi-ICD colon lists fall back to env.
+ directDylib = xcmResolveIcdLibraryPath(icdJson);
+ } else {
if (envBackend && strcasecmp(envBackend, "venus") == 0) {
useVenus = true;
forcedBackend = true;
@@ -3266,11 +3326,12 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
if (drmSvc) {
IOObjectRelease(drmSvc);
struct stat st = {};
- if (!venusIcd.empty() && stat(venusIcd.c_str(), &st) == 0) useVenus = true;
+ if (!venusDylib.empty() && stat(venusDylib.c_str(), &st) == 0) useVenus = true;
}
}
+ directDylib = useVenus ? venusDylib : lvpDylib;
+ icdJson = useVenus ? venusIcd : lvpIcd;
}
- std::string icdJson = customIcd ? std::string(envIcd) : (useVenus ? venusIcd : lvpIcd);
// IOSurfaces read/written by this Metal device must be linear uncompressed rows (WindowServer/QuartzCore).
// Use in-memory NSRegistrationDomain (never persisted to any app's plist on disk).
@@ -3347,13 +3408,19 @@ extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json
}
};
- if (!customIcd && !useVenus) configureLavapipeEnv();
+ if (!customDriver && !useVenus) configureLavapipeEnv();
- id dev = xnu_cpu_metal_open_device(loader.c_str(), icdJson.c_str(), cacheDir, port);
- if (!dev && useVenus && !forcedBackend && !customIcd && !lvpIcd.empty()) {
- os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: Venus backend open failed, falling back to lavapipe");
+ void *directPfn = directDylib.empty() ? nullptr : xcmLoadDirectDriver(directDylib);
+ id dev = nil;
+ if (directPfn || !icdJson.empty()) {
+ dev = xnu_cpu_metal_open_device_direct(loader.c_str(), directPfn, icdJson.c_str(), cacheDir, port);
+ }
+ if (!dev && useVenus && !forcedBackend && !customDriver && !lvpDylib.empty()) {
+ os_log_error(OS_LOG_DEFAULT, "XnuCpuMetal: Venus backend open failed (%{public}s), falling back to lavapipe",
+ xm2v_last_error() ?: "?");
configureLavapipeEnv();
- dev = xnu_cpu_metal_open_device(loader.c_str(), lvpIcd.c_str(), cacheDir, port);
+ void *lvpPfn = xcmLoadDirectDriver(lvpDylib);
+ dev = xnu_cpu_metal_open_device_direct(loader.c_str(), lvpPfn, lvpIcd.c_str(), cacheDir, port);
}
return dev;
}
diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
index 81bff2c..029a8f0 100644
--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
@@ -152,6 +152,8 @@ const char *xm2v_last_error(void);
/* Device */
Xm2vDevice *xm2v_device_open(const char *loader_path, const char *icd_json_path, const char *cache_dir);
+Xm2vDevice *xm2v_device_open_direct(const char *loader_path, void *direct_driver_pfn,
+ const char *icd_json_path, const char *cache_dir);
void xm2v_device_release(Xm2vDevice *dev);
size_t xm2v_device_name(const Xm2vDevice *dev, char *out, size_t size);
uint64_t xm2v_device_max_buffer_length(const Xm2vDevice *dev);
diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
index 03f80a2..d1f3d7a 100644
--- a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
@@ -296,11 +296,26 @@ pub extern "C" fn xm2v_device_open(
loader_path: *const c_char,
icd_json_path: *const c_char,
cache_dir: *const c_char,
+) -> *mut Device {
+ xm2v_device_open_direct(loader_path, std::ptr::null_mut(), icd_json_path, cache_dir)
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_open_direct(
+ loader_path: *const c_char,
+ direct_driver_pfn: *mut c_void,
+ icd_json_path: *const c_char,
+ cache_dir: *const c_char,
) -> *mut Device {
guard(std::ptr::null_mut(), || {
+ let use_direct = !direct_driver_pfn.is_null();
let prev_icd = std::env::var_os("VK_ICD_FILENAMES");
let prev_drv = std::env::var_os("VK_DRIVER_FILES");
- let icd_opt = cstr_opt(icd_json_path);
+ let icd_opt = if use_direct {
+ None
+ } else {
+ cstr_opt(icd_json_path)
+ };
if let Some(ref icd) = icd_opt {
unsafe {
std::env::set_var("VK_ICD_FILENAMES", icd);
@@ -311,6 +326,9 @@ pub extern "C" fn xm2v_device_open(
if let Some(loader) = cstr_opt(loader_path) {
opts.loader = Some(PathBuf::from(loader));
}
+ if use_direct {
+ opts.direct_driver_pfn = Some(direct_driver_pfn as usize);
+ }
if let Some(cache) = cstr_opt(cache_dir) {
let mut sc = ShaderCacheOptions::in_directory(cache);
let disk_mb: u64 = std::env::var("XNU_CPU_METAL_CACHE_MAX_MB")
diff --git a/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm b/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm
new file mode 100644
index 0000000..64b47d9
--- /dev/null
+++ b/gpu/xnu-cpu-metal/test/test_round17_direct_driver.mm
@@ -0,0 +1,101 @@
+// Round 17 verification: deterministic direct driver loading (VK_LUNARG_direct_driver_loading)
+// Verifies:
+// 1. Selected backend loads ONLY its own driver dylib (unused ICDs in icd.d are never dlopen'd).
+// 2. Hostile VK_ICD_FILENAMES / VK_DRIVER_FILES (or secure-mode ignoring env vars) cannot hijack backend.
+// 3. Multi-ICD enumeration (lvp + MoltenVK simultaneously visible) picks non-CPU GPU over lavapipe.
+// 4. lavapipe-only fallback & forced backend overrides work cleanly.
+
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#include <mach-o/dyld.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+@interface XcmBundleDeviceStub : NSObject
+- (id)initWithAcceleratorPort:(unsigned)port;
+@end
+
+static bool isImageLoaded(const char *substr) {
+ uint32_t n = _dyld_image_count();
+ for (uint32_t i = 0; i < n; i++) {
+ const char *name = _dyld_get_image_name(i);
+ if (name && strstr(name, substr)) return true;
+ }
+ return false;
+}
+
+int main(int argc, char **argv) {
+ @autoreleasepool {
+ if (argc < 4) {
+ fprintf(stderr, "Usage: %s <bundle_path> <expected_name_substr|NIL> <forbidden_dylib_substr|NONE>\n", argv[0]);
+ return 2;
+ }
+ const char *bundlePath = argv[1];
+ const char *expectSub = argv[2];
+ const char *forbidSub = argv[3];
+
+ NSBundle *b = [NSBundle bundleWithPath:@(bundlePath)];
+ if (!b || ![b load]) {
+ fprintf(stderr, "FAIL: failed to load bundle %s\n", bundlePath);
+ return 1;
+ }
+ Class cls = [b principalClass];
+ if (!cls) {
+ fprintf(stderr, "FAIL: no principalClass\n");
+ return 1;
+ }
+ id<MTLDevice> dev = (id<MTLDevice>)[(XcmBundleDeviceStub *)[cls alloc] initWithAcceleratorPort:0u];
+
+ bool expectNil = (strcmp(expectSub, "NIL") == 0);
+ if (expectNil) {
+ if (dev != nil) {
+ fprintf(stderr, "FAIL: expected nil device, got '%s'\n", dev.name.UTF8String);
+ return 1;
+ }
+ if (strcmp(forbidSub, "NONE") != 0 && isImageLoaded(forbidSub)) {
+ fprintf(stderr, "FAIL: forbidden image '%s' was loaded!\n", forbidSub);
+ return 1;
+ }
+ printf("PASS: device=nil (expected), forbidden='%s' loaded=0\n", forbidSub);
+ return 0;
+ }
+
+ if (!dev) {
+ fprintf(stderr, "FAIL: initWithAcceleratorPort: returned nil (expected '%s')\n", expectSub);
+ return 1;
+ }
+ const char *devName = dev.name.UTF8String ?: "(null)";
+ if (!strstr(devName, expectSub)) {
+ fprintf(stderr, "FAIL: device.name='%s' does not contain '%s'\n", devName, expectSub);
+ return 1;
+ }
+ if (strcmp(forbidSub, "NONE") != 0 && isImageLoaded(forbidSub)) {
+ fprintf(stderr, "FAIL: forbidden image '%s' was loaded alongside '%s'!\n", forbidSub, devName);
+ return 1;
+ }
+
+ // Smoke-test a real buffer + blit fill to confirm the selected backend executes cleanly.
+ id<MTLBuffer> buf = [dev newBufferWithLength:256 options:MTLResourceStorageModeShared];
+ id<MTLCommandQueue> q = [dev newCommandQueue];
+ id<MTLCommandBuffer> cb = [q commandBuffer];
+ id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
+ [blit fillBuffer:buf range:NSMakeRange(0, 256) value:0x5A];
+ [blit endEncoding];
+ [cb commit];
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr, "FAIL: blit fill status=%lu\n", (unsigned long)cb.status);
+ return 1;
+ }
+ const uint8_t *p = (const uint8_t *)buf.contents;
+ for (int i = 0; i < 256; i++) {
+ if (p[i] != 0x5A) {
+ fprintf(stderr, "FAIL: buf[%d]=0x%02x != 0x5A\n", i, p[i]);
+ return 1;
+ }
+ }
+ printf("PASS: device='%s', forbidden='%s' loaded=0, blitFill=OK\n", devName, forbidSub);
+ return 0;
+ }
+}