Skip to content

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

C

gpu/xnu-cpu-metal: the CPU Metal plugin XnuCpuMetal.bundle (Objective-C++ device over a Rust bridge to metal2vulkan, Vulkan loader, Mesa lavapipe), its build and host test scripts, and fetch-sources.sh pinning the upstream sources (metal2vulkan v0.2.0 GPL-2.0+/LGPL-3.0+, Vulkan-Loader 1.4.363, Mesa 26.3.1, LLVM 22.1.8), which are fetched at build time and never committed. In the hosted macOS: MTLCreateSystemDefaultDevice returns XnuCpuMetal (llvmpipe) and ictool renders Stats.icon (exit 0)

Heyang Zhoudf526af2cfef
diff --git a/gpu/xnu-cpu-metal/.gitignore b/gpu/xnu-cpu-metal/.gitignore
new file mode 100644
index 0000000..c23ea22
--- /dev/null
+++ b/gpu/xnu-cpu-metal/.gitignore
@@ -0,0 +1,7 @@
+src/metal2vulkan/
+src/Vulkan-Loader/
+src/llvm-project/
+src/mesa/
+build/
+dist/
+src/xnu-m2v-bridge/target/
diff --git a/gpu/xnu-cpu-metal/README.md b/gpu/xnu-cpu-metal/README.md
new file mode 100644
index 0000000..bad56c5
--- /dev/null
+++ b/gpu/xnu-cpu-metal/README.md
@@ -0,0 +1,29 @@
+# XnuCpuMetal: a CPU Metal device for the hosted macOS
+
+`XnuCpuMetal.bundle` is a Metal plugin (`/Library/GPUBundles`) whose device runs in the calling process:
+Metal API → `XnuCpuMetalDevice` (an `IOGPUMetalDevice` subclass) → metal2vulkan (AIR → SPIR-V, Metal runtime on Vulkan) →
+Vulkan loader → Mesa lavapipe (llvmpipe JIT on the CPU). The kernel side is `kexts/XnuCpuMetal` (an `IOAccelerator` naming the plugin).
+It gives the hosted macOS a working `MTLCreateSystemDefaultDevice()` with no GPU and no window server: enough for Xcode's
+build-time renderers (`ictool`/Icon Composer, `actool`, CoreImage).
+
+## What is here (ours) and what is fetched
+- `src/xnu-cpu-metal-bundle/`: the plugin (Objective-C++); `XnuCpuMetalShim.h` adapts UniXNU/AdrenoMetal's shim (BSD-2-Clause-Patent).
+- `src/xnu-m2v-bridge/`: the Rust C-ABI bridge over metal2vulkan (`libxnu_m2v.dylib`).
+- `scripts/`: builds (arm64 and arm64e), host-side tests.
+- `scripts/fetch-sources.sh` fetches, at pinned revisions and **never committed**: metal2vulkan (GPL-2.0-or-later / LGPL-3.0-or-later),
+ Vulkan-Loader (Apache-2.0), Mesa 26.3.1 (lavapipe, MIT), LLVM 22.1.8. None of it goes into XNU or the Linux kernel.
+
+## Build (on a Mac with Xcode and a Rust toolchain)
+ scripts/fetch-sources.sh
+ scripts/build-lavapipe.sh && scripts/build-lavapipe-arm64e.sh # needs llvm-arm64e: scripts/build-llvm-arm64e.sh
+ scripts/build-m2v.sh && scripts/build-m2v-arm64e.sh
+ scripts/build-vkloader-arm64e.sh
+ scripts/build-bundle-universal.sh # -> dist/XnuCpuMetal.bundle
+Install: `scripts/vm-gpu-prep.sh` (repo root) puts the bundle on the system disk; the hosted kernel needs the boot-arg `lp-sip0=2`.
+
+## Hosted-system findings (what Metal requires of a plugin, beyond the host tests)
+- The accelerator service must not carry `Removable` / `SafeEjectRequested` at all (Metal skips a service on which either exists).
+- `/Library/GPUBundles` is trusted only with `CSR_ALLOW_UNRESTRICTED_FS` (boot-arg `lp-sip0=2` in the hosted kernel).
+- The device class must conform to `MTLDeviceSPI` (`MTLAddDevice` asserts it).
+- `targetDeviceArchitecture` must be an `MTLTargetDeviceArchitecture` (the AIR type here), or binary archives assert.
+`REPORT.md` is the development log (host-side reproduction and pixel comparisons against an M5 Max GPU).
diff --git a/gpu/xnu-cpu-metal/REPORT.md b/gpu/xnu-cpu-metal/REPORT.md
new file mode 100644
index 0000000..b63ec02
--- /dev/null
+++ b/gpu/xnu-cpu-metal/REPORT.md
@@ -0,0 +1,250 @@
+# xnulinux 纯 CPU Metal 设备用户态构建报告
+
+构建机:`tokyo-mac-studio-0`(macOS 27.0.1 / Build 26A434,Apple M5 Max 18 核 64 GB,Xcode 27.0,Rust 1.100.0)
+工作目录:`/Users/admin/.stillfail/sessions/chat/c-73ef26e7b6/workspace`
+
+---
+
+## 1. 产物路径清单
+
+| 组件 | 路径 | 大小 | 架构 | 外部运行时依赖 |
+|---|---|---|---|---|
+| Mesa lavapipe ICD | `dist/lavapipe/lib/libvulkan_lvp.dylib` | 125 MB | `arm64` | 仅 Apple 系统库(`libSystem.B`、`libz.1`、`libc++.1`);LLVM 22.1.8 与 `libzstd.a` 已静态链入 |
+| Khronos Vulkan Loader | `dist/lavapipe/lib/libvulkan.1.dylib` | 663 KB | `arm64` | 仅 Apple 系统库(`libSystem.B`、`CoreFoundation`) |
+| Vulkan ICD 描述 | `dist/lavapipe/share/vulkan/icd.d/lvp_icd.aarch64.json` | 247 B | — | 指向 `libvulkan_lvp.dylib` |
+| metal2vulkan C ABI 动态库 | `dist/m2v/lib/libxnu_m2v.dylib` | 32 MB | `arm64` | 仅 Apple 系统库(`libiconv.2`、`libSystem.B`);基于上游 `steelbrain/metal2vulkan` 0.2.0 零补丁构建 |
+| metal2vulkan C 头文件 | `dist/m2v/include/xnu_m2v.h` | 12 KB | — | — |
+| **Metal 插件 Bundle(自包含可重定位)** | **`dist/XnuCpuMetal.bundle`** | ~158 MB | `arm64` | 仅 Apple 系统框架(`Foundation`、`Metal`、`IOKit`、`IOSurface`、`IOGPU`、`CoreFoundation`、`libobjc`、`libc++`、`libSystem`)及内置 `@loader_path/../Frameworks/libxnu_m2v.dylib` |
+
+`dist/XnuCpuMetal.bundle` 内部布局(可直接拷贝到托管 macOS 的 `/Library/GPUBundles/XnuCpuMetal.bundle`,无硬编码宿主机路径):
+```
+dist/XnuCpuMetal.bundle/
+ Contents/
+ Info.plist (NSPrincipalClass = XnuCpuMetalDevice)
+ MacOS/XnuCpuMetal (MH_BUNDLE, arm64)
+ Frameworks/
+ libxnu_m2v.dylib
+ libvulkan.1.dylib
+ libvulkan_lvp.dylib
+ Resources/
+ lvp_icd.aarch64.json (library_path = "../Frameworks/libvulkan_lvp.dylib")
+```
+
+---
+
+## 2. 可复现构建与验证脚本
+
+所有脚本均在工作目录 `scripts/` 下,按顺序执行即可复现全部 3 步产物与验证:
+
+1. **第 1 步(Mesa lavapipe)**:
+ - 构建:`bash scripts/build-lavapipe.sh`
+ - 验证:`bash scripts/test-lavapipe.sh`
+ - 实测结果:`Vulkan device: llvmpipe (LLVM 22.1.8, 128 bits) (type=4, api=1.4.363, driver=0x6803001)`,`Compute vecadd N=1024: bad=0`
+2. **第 2 步(metal2vulkan + AIR→SPIR-V)**:
+ - 构建:`bash scripts/build-m2v.sh`
+ - 验证:`bash scripts/test-m2v.sh`(使用 `xcrun -sdk macosx metal` + `metallib` 编译 `test/vecadd.metal`)
+ - 实测结果:`m2v device: llvmpipe (LLVM 22.1.8, 128 bits) (maxBufferLength=2147483648)`,`pipeline: maxThreads=1024, simdWidth=32`,`Metal->metal2vulkan->lavapipe vecadd N=1024: status=4, bad=0`
+3. **第 3 步(`XnuCpuMetal.bundle`)**:
+ - 构建:`bash scripts/build-bundle.sh`
+ - 验证:`bash scripts/test-bundle.sh`(通过 `NSBundle` 加载 `XnuCpuMetal.bundle`,检查 `principalClass == XnuCpuMetalDevice` 且为 `IOGPUMetalDevice` 子类,调用 `initWithAcceleratorPort:0` 并走标准 ObjC `MTLDevice` API 执行 `vecadd.metallib`)
+ - 实测结果:`Bundle loaded: principalClass=XnuCpuMetalDevice, isSubclassOf(IOGPUMetalDevice)=YES`,`Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0`(进程干净退出,退出码 0)
+
+---
+
+## 3. 插件 Metal API 接入与空实现清单
+
+### 已接入(经 `libxnu_m2v.dylib` 到达 `metal2vulkan-runtime` → `lavapipe`)
+- **插件注册与 IOGPU 兼容层**(`XnuCpuMetalDevice` + `XnuCpuMetalShim.h`):
+ - `XnuCpuMetalDevice : IOGPUMetalDevice`、`initWithAcceleratorPort:`(保留自身避免 `-[IOGPUMetalDevice dealloc]` 破坏未初始化状态,返回动态创建的 `_MTLDevice` 子类 `XcmBackendDevice`)
+ - IOGPU 必需 selector:`_setAcceleratorService:`、`acceleratorPort`、`_setDeviceWrapper:`、`_deviceWrapper`、`isBuiltIn`、`recommendedMaxWorkingSetSize`、`sharedMemorySize`、`gpuCoreCount`、`cmdBufArgsSize`、`featureProfile`、queue GPU priorities、`userDictionary`、`bitCodeHash` 及全部 `MTL*` 协议声明
+- **MTLDevice**:`name`、`registryID`、`isLowPower`、`isHeadless`、`isRemovable`、`hasUnifiedMemory`、`maxBufferLength`、`maxThreadsPerThreadgroup`、`supportsFamily:`、`newCommandQueue`、`newCommandQueueWithMaxCommandBufferCount:`、`newBufferWithLength:options:`、`newBufferWithBytes:length:options:`、`newBufferWithBytesNoCopy:length:options:deallocator:`(失败自动回退拷贝)、`newTextureWithDescriptor:`、`newLibraryWithData:error:`、`newLibraryWithURL:error:`、`newLibraryWithFile:error:`、`newComputePipelineStateWithFunction:error:`(含 options/descriptor/completionHandler 重载)、`newRenderPipelineStateWithDescriptor:error:`(含 options 重载)、`newSamplerStateWithDescriptor:`、`newDepthStencilStateWithDescriptor:`、`newEvent`、`newFence`;并从 `_MTLDevice` 继承 `newDefaultLibrary` / `newLibraryWithSource:options:error:` 等上层框架入口
+- **MTLBuffer**:`contents`、`length`、`gpuAddress`、`didModifyRange:`、storage/cache/hazard/options/allocatedSize 属性
+- **MTLTexture**:基本元数据属性、`replaceRegion:...`、`getBytes:...`、`newTextureViewWithPixelFormat:...`(含 level/slice 重载)
+- **MTLLibrary / MTLFunction**:`functionNames`、`newFunctionWithName:`、`functionType`、`name`
+- **MTLComputePipelineState / MTLRenderPipelineState / MTLSamplerState / MTLDepthStencilState / MTLEvent / MTLFence**:创建、销毁与 compute 线程组查询属性
+- **MTLCommandQueue / MTLCommandBuffer**:`commandBuffer`、`status`、`error`、`commit`、`waitUntilScheduled`、`waitUntilCompleted`、`addScheduledHandler:`、`addCompletedHandler:`、`computeCommandEncoder`、`renderCommandEncoderWithDescriptor:`、`blitCommandEncoder`、`encodeSignalEvent:value:`、`encodeWaitForEvent:value:`
+- **MTLComputeCommandEncoder**:`setComputePipelineState:`、`setBuffer/setBuffers/setBufferOffset`、`setBytes`、`setTexture/setTextures`、`setSamplerState/setSamplerStates`、`setThreadgroupMemoryLength:atIndex:`、`dispatchThreadgroups:`、`dispatchThreads:`、`endEncoding`
+- **MTLRenderCommandEncoder**:`setRenderPipelineState:`、`setDepthStencilState:`、`setViewport:`、`setScissorRect:`、`setCullMode:`、`setFrontFacingWinding:`、vertex/fragment buffer/bytes/texture/sampler 绑定、`drawPrimitives:...`、`drawIndexedPrimitives:...`、`endEncoding`
+- **MTLBlitCommandEncoder**:buffer↔buffer、buffer↔texture、texture↔buffer、texture↔texture 拷贝、`fillBuffer:range:value:`、`generateMipmapsForTexture:`、`synchronizeResource:`、`endEncoding`
+
+### 尚未实现 / 桩实现(Stub)
+- **IOSurface 零拷贝导入**:`newTextureWithDescriptor:iosurface:plane:` 目前仅创建普通后端纹理并保存 `IOSurfaceRef` 引用,未将 IOSurface 内存直接映射/回写到纹理(CoreImage 若经 IOSurface 交付结果需要补齐锁面读写或 no-copy 导入)
+- **Function Constants 特化**:`newFunctionWithName:constantValues:error:` 目前忽略 `constantValues`,直接按函数名查找(`metal2vulkan-runtime` 自身支持 `new_function_with_name_constant_values`,后续若 `ictool`/CoreImage 触发可直接补接线)
+- **高级 Metal 对象**:`MTLHeap`、`MTLSharedEvent`、`MTLBinaryArchive`、`MTLIndirectCommandBuffer`、`MTLArgumentEncoder`、`MTLCounterSampleBuffer`、`MTLAccelerationStructure`、stitched library / dynamic library、render pipeline `vertexDescriptor`(目前 `Xm2vRenderPipelineDesc` 未传递 `MTLVertexDescriptor`)、`MTLComputePipelineReflection` / `MTLRenderPipelineReflection`(目前返回 `nil`)
+- **Purgeable 内存真实回收**:`setPurgeableState:` 仅记录状态,不触发后端释放
+- **兜底机制**:任何未覆盖的 `IOGPUMetal*` selector 由 `resolveInstanceMethod:` 拦截,打印一次 `XnuCpuMetal: <prog>: stubbed <class> <sel>` 到 stderr 并返回 0,便于托管系统联调时定位实际缺口
+
+---
+
+## 4. `arm64` vs `arm64e` 确认结论
+
+1. **宿主与目标进程架构实测**:
+ - Xcode 工具链进程(本次首要目标)均为 **`arm64`**(非 `arm64e`):
+ - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/ictool` → `Mach-O 64-bit executable arm64`
+ - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/actool` → `Mach-O 64-bit executable arm64`
+ - `/Applications/Xcode_27.app/Contents/Developer/usr/bin/xcodebuild` → `Mach-O 64-bit executable arm64`
+ - macOS 系统工具与守护进程为 **`arm64e`**(例如 `/usr/bin/sips`、`WindowServer`、`iconservicesagent`)。
+ - dyld shared cache 中的 `Metal.framework` 是 `arm64e`,但 **arm64 进程加载 dyld shared cache 中的 `arm64e` 系统框架时,dyld 要求进程内动态加载的 bundle 匹配进程自身架构(即 `arm64`)**——这已在本机 `test_bundle`(arm64 进程链接系统 `Metal.framework`)加载 `arm64` `XnuCpuMetal.bundle` 中实测通过。
+2. **`arm64e` 进程的限制(已实测确认)**:
+ - `arm64e` 进程无法 `dlopen` 仅含 `arm64` 切片的 `XnuCpuMetal.bundle`(dyld 拒绝:`incompatible architecture (have 'arm64', need 'arm64e')`)。
+ - 若后续需要同时服务 `arm64`(`ictool`/`xcodebuild`)和 `arm64e`(`sips`/系统守护进程),需将整条链编成 **universal fat(`arm64` + `arm64e`)**:
+ - `XnuCpuMetal`(ObjC++):Xcode 27 `clang++ -arch arm64e` 已实测直接支持。
+ - `libxnu_m2v.dylib`(Rust):`rustc 1.100.0` 含 tier-3 目标 `arm64e-apple-darwin`(需 nightly `-Zbuild-std`,且需像 `AdrenoMetal/bridge/RustPacBoundary.c` 那样处理 Rust↔C 的 PAC 指针签名边界)。
+ - `libvulkan_lvp.dylib` + `libvulkan.1.dylib`:Homebrew 预编译的 `llvm@22`、`zstd`、`vulkan-loader` 均为 `arm64`-only,编 `arm64e` 切片需从源码用 `-arch arm64e` 交叉/原生编译 LLVM、Vulkan-Loader 和 Mesa。
+3. **建议**:当前阶段为了尽快在托管 XNU 里打通 `ictool`(本身是 `arm64` 进程)和 CoreImage 探针,**先用这份自包含的 `arm64` `XnuCpuMetal.bundle` 接入内核 stub kext 联调**;若联调发现 `ictool` 会经 XPC 调到某个 `arm64e` 守护进程或需要支持 `arm64e` 进程,再补 `arm64e` 切片做成 fat bundle。
+
+---
+
+## 5. 已知缺口与联调注意事项
+
+- **CoreImage / `ictool` 常见需求**:CoreImage 常使用 `newLibraryWithSource:options:error:`(由 `_MTLDevice` 走 `MTLCompilerService` 产出 AIR/metallib 后回调 `newLibraryWithData:error:`)、`MTLVertexDescriptor`、Function Constants 以及 `IOSurface` 纹理。若联调日志中出现 `XnuCpuMetal: <prog>: stubbed ...` 或 `newTextureWithDescriptor:iosurface:plane:` 数据为空,优先补齐对应项。
+- **lavapipe 精度降级提示**:`metal2vulkan` 在 stderr 会打印 2–4 条 `PrecisionNote` / `DegradeNotice`(llvmpipe 无 `VK_KHR_pipeline_binary`、denormals、NaN encoding、float tininess);按 `metal2vulkan` 规则均为非致命提示。
+- **许可证**:`src/mesa`、`src/metal2vulkan` 仅用于本机构建,未提交或推送至任何仓库。
+
+---
+
+## 6. 第二轮成果:整链 Universal(`arm64 + arm64e`)与 Render / CoreImage 冒烟测试
+
+### 6.1 Universal (`arm64 + arm64e`) 产物与构建脚本
+`dist/XnuCpuMetal.bundle` 现已全部合成为 **`arm64 + arm64e` universal fat**(`lipo -info` 全部确认为 `arm64 arm64e`,无任何 Homebrew 运行时依赖):
+- `dist/XnuCpuMetal.bundle/Contents/MacOS/XnuCpuMetal`(323 KB,`arm64 arm64e`)
+- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libxnu_m2v.dylib`(71 MB,`arm64 arm64e`)
+- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libvulkan.1.dylib`(1.4 MB,`arm64 arm64e`)
+- `dist/XnuCpuMetal.bundle/Contents/Frameworks/libvulkan_lvp.dylib`(196 MB,`arm64 arm64e`)
+
+新增可复现构建脚本:
+1. `scripts/build-llvm-arm64e.sh`:从 `llvmorg-22.1.8`(sparse 仅 `llvm`/`cmake`/`third-party`)编译 `arm64e` AArch64 静态库与 `llvm-config`(关闭 zstd/libxml2/terminfo/tests)。
+2. `scripts/build-vkloader-arm64e.sh`:从 Khronos `Vulkan-Loader` `vulkan-sdk-1.4.363.0` 编译 `arm64e` `libvulkan.1.dylib`。
+3. `scripts/build-lavapipe-arm64e.sh`:基于 `arm64e` LLVM 22 编译 `arm64e` Mesa 26.3.1 lavapipe。
+ - **关键 PAC 修复**(`src/mesa/src/gallium/auxiliary/gallivm/lp_bld_init.c` 与 `lp_bld_init_orc.cpp` 中的 `gallivm_jit_function`):LLVM MCJIT/ORCJIT 返回未签名代码指针,`arm64e` 下 C 侧经 `blraaz` 调用 JIT shader 会触发 `SIGBUS`(多线程下表现为 `VkQueue` 超时 20.2s)。在 `gallivm_jit_function` 返回前用 `__builtin_ptrauth_sign_unauthenticated(__builtin_ptrauth_strip(code, 0), 0, 0)` 签名后,单线程与多线程 `arm64e` lavapipe 均一次通过。
+4. `scripts/build-m2v-arm64e.sh` + `scripts/rust-pac-rewrite.py`:用 `nightly-aarch64-apple-darwin`(`rustc 1.102.0-nightly`)+ `-Zbuild-std=std,panic_unwind --target arm64e-apple-darwin` 编译 `libxnu_m2v.a`;实测 nightly 仍输出无 PAC 的 `blr`/`br`,因此按 `AdrenoMetal/bridge/RustPacBoundary.c` 方案:
+ - 用 `llvm-objcopy --redefine-sym` 将 Rust 目标文件中 7 个接收 C 回调的导入(`_pthread_create`、`__tlv_atexit`、`_atexit`、`___cxa_atexit`、`__dyld_register_func_for_add_image`、`__Unwind_Backtrace`、`_dlsym`)重定向到 `nmb_pac_*` 包装器;
+ - 链接 `RustPacBoundary.o` 后,由 `scripts/rust-pac-rewrite.py` 将 Rust `__TEXT,__text` 中的 `9528` 条 `blr` 与 `2734` 条 `br` 重写为 `bl`/`b _nmb_pac_call_xN`(跳过 40 个 PAC 边界函数),再 ad-hoc 签名。
+5. `scripts/build-bundle-universal.sh`:编译 `arm64` + `arm64e` 两份 `XnuCpuMetal` 并用 `lipo -create` 合成全部 4 个 universal 二进制。
+
+### 6.2 双架构验收实测结果
+- **`arm64` 进程**(`bash scripts/test-bundle.sh arm64`):
+ `Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0 (c[0]=256.00, c[10]=283.50, c[1023]=3069.25)`,退出码 0。
+- **`arm64e` 进程**(`bash scripts/test-bundle.sh arm64e`):
+ `Bundle ObjC MTLDevice vecadd N=1024: status=4, completedHandler=1, bad=0 (c[0]=256.00, c[10]=283.50, c[1023]=3069.25)`,退出码 0。
+
+### 6.3 Render Pass + CoreImage `CIGaussianBlur` 冒烟测试(`bash scripts/test-render-ci.sh arm64|arm64e`)
+1. **Render Pass(清蓝屏 + 画橙红三角形到 64×64 `RGBA8Unorm` 纹理 + Blit 读回校验)**:
+ - `arm64` 与 `arm64e` **均 PASS**:
+ `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`
+2. **CoreImage `CIContext(mtlDevice:)` + `CIGaussianBlur`**:
+ - 进展:`CIContext` 成功创建并加载 CoreImage 预编译 metallib,通过 DAG 图优化(`CIBlurProcessor-4.000`),进入 Apple `Metal.framework` 的 stitched function graph 编译器(`MTLCompilerStitchingRequest::serializedRequest`)。
+ - **本次过程中先补掉的 2 个阻塞点**:`XcmLibrary externFunctionNames`/`type`/`installName`,以及 `_MTLDevice` 基础限制(`recommendedMaxWorkingSetSize` 强制覆盖 + `maxTextureWidth2D`/`maxTextureHeight2D`/`maxThreadgroupMemoryLength`/`minimumLinearTextureAlignmentForPixelFormat:` 等,原默认返回 0 导致 CoreImage 报 `memory requirement of -1 too big`)。
+ - **落到 `stubbed` 的完整调用清单(下一步待补清单)**:
+ 1. `XcmQueue setBackgroundGPUPriority:`(低优先级,可沿用 `XnuCpuMetalShim.h` 里的 `kBackgroundPriorityKey` 存值)
+ 2. `XcmTexture isDrawable`(返回 `NO` 即可)
+ 3. `XcmBackendDevice newHeapWithDescriptor:`(MPS 探测时调用,目前返回 `nil` 使 CoreImage 跳过 MPS 走自有 shader;如需 MPS 支持需接入 `metal2vulkan_runtime::Heap`)
+ 4. `XcmCommandBuffer protectionOptions`(返回 `0` 即可)
+ 5. **`XcmFunction libraryData` / `bitCodeOffset` / `bitCodeFileSize`**(**当前阻断点**:`MTLCompilerStitchingRequest::serializedRequest` 读取这 3 个私有属性构造 stitched library XPC 请求,`libraryData` 返回 NULL 导致崩溃;需参考 `AdrenoMetal/NativeBridgeMetalFrontend.mm:4804` 覆盖 `newLibraryWithStitchedDescriptor:error:`,同时在 `libxnu_m2v` 暴露 `extern_function_names()` + `new_extern_function_with_name()` 供 CoreImage 链接 `ci_stdlib` extern 函数)
+ 6. **`newTextureWithDescriptor:iosurface:plane:`**(CoreImage 的 `imageWithBitmapData:` / `render:toBitmap:` 路径依赖 IOSurface 纹理读写,后续需补 IOSurface 映射/同步)
+
+## 7. Round 3:CoreImage `CIGaussianBlur` 端到端打通(`arm64` + `arm64e`)
+
+### 7.1 实现改动
+1. **Stitched library + `libxnu_m2v` extern/specialized function 接口**:
+ - `src/xnu-m2v-bridge/include/xnu_m2v.h` 与 `src/xnu-m2v-bridge/src/lib.rs`:新增 `xm2v_library_extern_function_count`、`xm2v_library_extern_function_name_at`、`xm2v_library_new_extern_function`、`xm2v_library_new_function_specialized`,并重编 `arm64` + `arm64e` 双架构 `libxnu_m2v.dylib`。
+ - `src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm`:实现 `newLibraryWithStitchedDescriptor:error:`(及 archive/async 重载),通过 `MTLCompiler.framework` 的 request 14(在 16 MiB 栈独立 pthread 上执行 `xcmCodeGenRequest`)把 CoreImage stitch graph 编译为 metallib,并实现 `externFunctionNames`、`newFunctionWithName:constantValues:error:`、`newFunctionWithDescriptor:error:` 与 `xcmExtractFunctionBitcode` / `xcmLookupCIKernelFunction`。
+2. **IOSurface 纹理双向同步**:
+ - `newTextureWithDescriptor:iosurface:plane:`(及 `slice:`):内部强制 `MTLStorageModeShared` 创建纹理,`syncFromIOSurfaceIfNeeded` 按 `IOSurfaceGetSeed` 懒同步 CPU/IOSurface 写入到纹理;`XcmCommandBuffer` 记录 `_dirtyIOSurfaceTextures`,在命令提交完成后调用 `syncToIOSurface` 回写 IOSurface 内存。
+ - 补齐 `_MTLDevice` 的内部 `limits` 结构体填充(`fillBaseLimits`)与 `iosurfaceTextureAlignmentBytes` / `linearTextureAlignmentBytes` / `readWriteTextureSupport` / `supportsSharedStorageTextures`。
+3. **消除剩余桩调用**:
+ - `XcmHeap`(`newHeapWithDescriptor:`,实现 `<MTLHeap>` 并代理分配到设备)
+ - `setBackgroundGPUPriority:`、`isDrawable`、`protectionOptions`(command buffer 与 heap)、`GPUStartTime` / `GPUEndTime`、`globalTraceObjectID`。
+4. **Mesa 26.3.1 `arm64e` gallivm JIT→C PAC 边界修复**:
+ - Round 2 修复了 C→JIT 方向(`gallivm_jit_function` 对返回指针签名);Round 3 跑 CoreImage 时发现 JIT→C 与 JIT→JIT 间接调用方向仍存在 PAC 签名未剥离问题(LLVM MCJIT 生成无 PAC 的 `blr`,跳转至 `arm64e` 签名指针触发 `SIGSEGV`,首次落点 `lp_texture_handle.c` 的 `get_size_function`)。
+ - 修复(均受 `#if defined(__has_feature) && __has_feature(ptrauth_calls)` 保护,不影响 `arm64`):
+ - `src/gallium/drivers/llvmpipe/lp_texture_handle.c`:`compile_function` 返回的 JIT 纹理/图像采样函数表指针以及 `matrix->compile_{sample,fetch,size}_function` 均剥离 PAC。
+ - `src/gallium/auxiliary/gallivm/lp_bld_const.c`(`lp_build_const_func_pointer_from_type`)、`lp_bld_format_aos.c`(`fetch_rgba_8unorm`)、`lp_bld_conv.c`(`_mesa_float_to_half`)、`lp_bld_init.c` & `lp_bld_init_orc.cpp`(`gallivm_add_global_mapping`)对传入 JIT 的 C 函数指针剥离 PAC。
+
+### 7.2 验收实测结果(`arm64` + `arm64e`)
+- `bash scripts/test-bundle.sh arm64`:`bad=0`,退出码 0。
+- `bash scripts/test-bundle.sh arm64e`:`bad=0`,退出码 0。
+- `bash scripts/test-render-ci.sh arm64`:
+ - `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`(PASS)
+ - `CPU Metal (XnuCpuMetal (llvmpipe (LLVM 22.1.8, 128 bits))): center=(243,243,243,255) edge_2px_out=(148,148,148,255) corner=(0,0,0,120)`
+ - `Native GPU (Apple M5 Max): center=(244,244,244,255) edge_2px_out=(157,157,157,255) corner=(0,0,0,137)`
+ - `Pixel diff (64x64x4=16384 channels): maxErr=17, meanErr=2.4154, nonZeroDiff=6749`(PASS)
+ - stderr `stubbed` 计数:**0**(除 `metal2vulkan` 精度说明外无任何其他输出)。
+- `bash scripts/test-render-ci.sh arm64e`:
+ - `Render pass status=4: center=(255,51,0,255) corner=(0,0,255,255) triPx=1352 bluePx=2744 otherPx=0`(PASS)
+ - `CPU Metal (XnuCpuMetal (llvmpipe (LLVM 22.1.8, 128 bits))): center=(243,243,243,255) edge_2px_out=(148,148,148,255) corner=(0,0,0,120)`
+ - `Native GPU (Apple M5 Max): center=(244,244,244,255) edge_2px_out=(157,157,157,255) corner=(0,0,0,137)`
+ - `Pixel diff (64x64x4=16384 channels): maxErr=17, meanErr=2.4154, nonZeroDiff=6749`(PASS)
+ - stderr `stubbed` 计数:**0**(除 `metal2vulkan` 精度说明外无任何其他输出)。
+
+## 8. Round 4:macOS 27 设备发现机制静态分析与内核侧需求清单
+
+### 8.1 macOS 27 `MTLCreateSystemDefaultDevice()` / `MTLCopyAllDevices()` 完整调用链(实机静态分析)
+通过对宿主 macOS 27.0.1(26A434)的 `Metal.framework`、`IOGPU.framework`、`libsystem_sandbox.dylib` 反汇编与符号解析,确认设备发现完整路径如下:
+1. **IORegistry 匹配**:`-[MTLIOAccelServiceGlobalContext init]` 调用 `IOServiceAddMatchingNotification(notifyPort, "IOServicePublish", IOServiceMatching("IOAccelerator"), ...)`,按 **IOKit 类名 `IOAccelerator`** 匹配(不是 `IOAcceleratorES`,后者为 iOS 专用)。
+2. **读取的 IORegistry 属性**:
+ - `getMetalPluginClassForService`(`Metal.framework`)与 `+[IOGPUMetalDevice registerAcceleratorService:]`(`IOGPU.framework`)均只读 2 个核心属性:
+ - `MetalPluginName`(`CFString`,必填;若内部构建且设置了 `MTL_INTERNAL_BUNDLE`,会尝试 `%sInternal`)
+ - `MetalPluginClassName`(`CFString`,可选;若缺失或未找到类,自动回退到 bundle 的 `NSPrincipalClass`)
+ - `-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 额外检查:
+ - `IOObjectConformsTo(port, "IOServiceCompatibility")` — **必须为 false**(若为 true 直接丢弃返回 `nil`)
+ - `IORegistryEntryGetRegistryEntryID(port, &rid)` + `IOServiceAddInterestNotification(notifyPort, port, "IOGeneralInterest", ...)`(普通 `IOService` 自带)
+ - `"Removable"`(若 `_mtlAvoidRemovable()` 为真且属性为 true 则跳过)与 `"SafeEjectRequested"`
+ - **`MetalStatisticsName`、`IOGLBundleName`、`IOGLESBundleName` 在 `MTLCreateSystemDefaultDevice()` / `MTLCopyAllDevices()` 路径中完全不读取**。
+3. **Bundle 搜索目录与信任检查**(`libsystem_sandbox.dylib` `gpu_bundle_find_trusted`):
+ - 按顺序搜索 3 个目录(格式化为 `%s/%s.bundle`,须为目录 `S_IFDIR`):
+ 1. `/Library/GPUBundles/<MetalPluginName>.bundle`(所有图形沙箱如 `system.sb` 均放行只读,推荐放此处)
+ 2. `/System/Library/Extensions/<MetalPluginName>.bundle`
+ 3. `/AppleInternal/Library/Extensions/<MetalPluginName>.bundle`(仅 internal build 允许非受信任路径)
+ - 信任检查:`gpu_bundle_is_path_trusted(path)` 调用 `rootless_check_trusted_class(path, "KernelExtensionManagement")`,若返回 1 再回退 `_dyld_shared_cache_contains_path(path)`。托管环境关闭 SIP(`CSR_ALLOW_UNRESTRICTED_FS`)时 `rootless_check_trusted_class` 直接返回 0(受信任)。
+4. **类校验与实例化**:
+ - `Metal.framework` `getMetalPluginClassForService` 要求类 `[cls isSubclassOfClass:[_MTLDevice class]]`。
+ - `IOGPU.framework` `+[IOGPUMetalDevice registerAcceleratorService:]` 要求类 `[cls isSubclassOfClass:[IOGPUMetalDevice class]]`(`IOGPUMetalDevice` 本身继承 `_MTLDevice`,我们的 `XnuCpuMetalDevice` 继承 `IOGPUMetalDevice`,两边同时满足)。
+ - `-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 调用 `[[cls alloc] initWithAcceleratorPort:port]` -> `[dev _setAcceleratorService:self]` -> `MTLAddDevice(dev)`。
+5. **`IOServiceOpen` / User Client**:
+ - `MTLCopyAllDevices` / `MTLIOAccelService` / `getMetalPluginClassForService` **全程不调用 `IOServiceOpen`**。
+ - `IOServiceOpen(service, mach_task_self(), 5 | (options << 16), &connect)` 以及 `IOConnectCallStructMethod`(selector `2` 输出 536 字节、selector `0` 输出 64 字节)仅在 `IOGPU.framework` 的 `IOGPUDeviceCreateWithOptions` 中调用(由 `-[IOGPUMetalDevice initWithAcceleratorPort:options:]` 触发)。
+
+### 8.2 插件无 User Client 验证
+- `XnuCpuMetalDevice` 覆盖了 `-initWithAcceleratorPort:` 与 `-initWithAcceleratorPort:options:`,不调用 `super`,内部全部由进程内 Mesa lavapipe 完成;`port == 0` 时仅跳过 `IORegistryEntryGetRegistryEntryID` 使用默认 `registryID`。
+- `nm -u dist/XnuCpuMetal.bundle/Contents/MacOS/XnuCpuMetal` 确认 **0 个 `IOServiceOpen` / `IOConnect*` / `IOGPUDevice*` 符号引用**;`test-bundle.sh arm64e` 以 `port=0` 实测 `bad=0`。
+
+### 8.3 内核侧需求清单与最小 kext 草稿
+- **父类与依赖 kext**:继承 `IOAccelerator`,来自 **`com.apple.iokit.IOGraphicsFamily`**(macOS 27.0.1 宿主 `kextstat` 已确认内置于 boot kernel collection,版本 `600`,`IOGPUFamily` 本身即依赖它;Apple Silicon 上未加载 `IOAcceleratorFamily2.kext`)。
+- **必须发布的属性**:`MetalPluginName = "XnuCpuMetal"`、`MetalPluginClassName = "XnuCpuMetalDevice"`、`IOMatchCategory = "IOAccelerator"`(可选 `model`、`gpu-core-count`)。**绝不可**发布 `Removable` 或 `SafeEjectRequested`(哪怕设为 `false`,`-[MTLIOAccelService initWithAcceleratorPort:deviceClass:]` 仅检查属性存在即跳过设备),且不可继承 `IOServiceCompatibility`。
+- **User Client**:**不需要**(默认 `IOService::newUserClient` 返回 `kIOReturnUnsupported` 即可)。
+- **最小 kext 源码草稿**(全新编写,不依赖 PCI/DT 硬件节点,挂在 `IOResources` 上):
+ - `src/xnu-cpu-metal-kext/XnuCpuMetalAccelerator.hpp`
+ - `src/xnu-cpu-metal-kext/XnuCpuMetalAccelerator.cpp`
+ - `src/xnu-cpu-metal-kext/Info.plist`
+
+## 9. Round 5:`ictool Stats.icon` 端到端出图打通(RenderBox + QuartzCore)
+
+基于宿主 `gpub/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm` 新基线,定位并修复了阻断 `ictool` → `icrtool`(RenderBox + QuartzCore)的全部问题:
+
+### 9.1 根因与修复清单
+1. **函数常量 UAF 与 `std::vector` 重分配悬垂指针(解决 `FunctionConstantType { index: 0 }` 与 `ColorAttachment { index: 1/2 }` / `VertexAttribute { attribute: 4 }`)**:
+ - 原 `newFunctionWithName:constantValues:error:` 中 `std::vector<std::string> nameStorage` 在 `push_back` 时可能扩容导致已存入的 `c.name` 悬垂(60 个命名常量下触发 `FunctionConstantType { index: 0 }`);且提取函数返回后 ARC 释放 `[constantValues copy]` 与 `named`/`indexed` 数组导致 `c.bytes` 成为 UAF 脏内存,使 QuartzCore 的 `fc_has_attachment_1/2 = false` 被读成 `true`。
+ - 修复:改用 `std::deque<std::string>` + `std::deque<std::vector<uint8_t>>` 持久化拷贝常量名与字节,同时补齐 `xm2v_library_new_function_specialized_zero_rest`(`zeroRest` 重试)与缺失 `VertexAttribute`/`ColorAttachment` 的安全回退。修复后 `Stats.icon` 全部 11 条 RenderPSO 一次编译通过(0 次重试)。
+2. **Linked Functions + 默认库/源码库覆盖(解决 `NeedsInput(LinkedFunction { symbol: "custom_fn" })`)**:
+ - 补齐 `newDefaultLibrary`、`newDefaultLibraryWithBundle:error:`、`newLibraryWithSource:options:error:`(经 `MTLCompiler.framework` request 13)及异步重载(均加 `NS_RETURNS_RETAINED`),防止 `_MTLDevice` 默认实现返回 `_MTLFunctionInternal`。
+ - `libxnu_m2v` 新增 `xm2v_library_new_function_with_descriptor`(传递 `specializedName`、`constantValues`、`options`)、`xm2v_compute_pipeline_new_with_linked` 以及 `Xm2vRenderPipelineDesc` 的 `vertex/fragment` public+private linked functions。
+3. **VertexDescriptor、DepthStencil(前/背面 Stencil)、StencilRef 与 BlendColor**:
+ - `Xm2vRenderPipelineDesc` 新增 `vertex_attributes` / `vertex_layouts` 透传到 `metal2vulkan::pipeline::VertexDescriptor`。
+ - `Xm2vDepthStencilDesc` 新增 `front_face_stencil` / `back_face_stencil`,`XcmRenderEncoder` 接入 `xm2v_render_encoder_set_stencil_reference_values` 与 `xm2v_render_encoder_set_blend_color`。
+4. **无有效 Pipeline 时安全空操作 + 异步 `commit` + 跨 `XcmTexture` 的 IOSurface 写后读同步**:
+ - `XcmRenderEncoder` 跟踪 `_hasPipeline`,无有效 pipeline 时 `drawPrimitives*` / `drawIndexedPrimitives*` 安全空操作,不再崩溃。
+ - `XcmCommandBuffer commit` 改为异步等待完成并触发 handlers 与 `syncToIOSurface`(消除多命令缓冲区事件等待 5s 死锁),并记录 `IOSurfaceID -> lastWriter`,在 `syncFromIOSurfaceIfNeeded` 中先等待已提交的写命令缓冲区完成再读 IOSurface(解决 RenderBox 跨 pass 复用同一 `IOSurface` 读到空白的问题)。
+5. **消除剩余 stubbed 调用**:
+ - 补齐 `XcmTexture` `protectionOptions` / `allocatedSize`、`XcmRenderEncoder` `memoryBarrierWithScope:afterStages:beforeStages:` / `memoryBarrierWithResources:...`、`XcmQueue` `setSubmissionQueue:` / `setCompletionQueue:`、`XcmCommandBuffer` `setProtectionOptions:` / `commitAndWaitUntilSubmitted`。
+
+### 9.2 宿主复现与全量回归验收
+- **宿主 `ictool Stats.icon` 复现**(`DYLD_INSERT_LIBRARIES=build/ic-repro/libforce_xcm.dylib` 强制走 `dist/XnuCpuMetal.bundle`,执行 `ictool Stats.icon --export-image --output-file build/ic-repro/test.png --platform macOS --rendition Default --width 16 --height 16 --scale 2`):
+ - 退出码 **`0`**,stderr 除 `metal2vulkan` 精度说明外 **0 行错误、0 行 `stubbed`**。
+ - 与真 Mac 原生 GPU(Apple M5 Max)导出图 `build/stats_native.png` 逐像素比对(`32×32×4 = 4096` 通道):
+ - 原生 GPU:`nonZero=3944/4096, max=255, center=(64,144,255,255)`
+ - CPU Metal:`nonZero=3944/4096, max=255, center=(50,123,237,255)`
+ - 误差:**`meanErr=3.7783, maxErr=51`**(轮廓与红/蓝波形条完全一致)。
+- **双架构回归全通过**:
+ - `bash scripts/test-bundle.sh arm64` / `arm64e`:`bad=0`,退出码 0。
+ - `bash scripts/test-render-ci.sh arm64` / `arm64e`:Render Pass PASS,CoreImage `CIGaussianBlur` 误差随常量 UAF 修复进一步降至 **`maxErr=1, meanErr=0.0161`**(`nonZeroDiff=264/16384`)!
diff --git a/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh
new file mode 100755
index 0000000..7d467c4
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-bundle-universal.sh
@@ -0,0 +1,77 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SDK="$(xcrun --show-sdk-path)"
+BUNDLE="$ROOT/dist/XnuCpuMetal.bundle"
+TMP="$ROOT/build/bundle-universal"
+
+rm -rf "$BUNDLE" "$TMP"
+mkdir -p "$BUNDLE/Contents/MacOS" "$BUNDLE/Contents/Frameworks" "$BUNDLE/Contents/Resources" "$TMP"
+
+cp -f "$ROOT/src/xnu-cpu-metal-bundle/Info.plist" "$BUNDLE/Contents/Info.plist"
+
+# 1. Create universal (arm64 + arm64e) Frameworks dylibs
+lipo -create \
+ "$ROOT/dist/m2v/lib/libxnu_m2v.dylib" \
+ "$ROOT/dist/m2v-arm64e/lib/libxnu_m2v.dylib" \
+ -output "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib"
+
+lipo -create \
+ "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib" \
+ "$ROOT/build/vkloader-arm64e-install/lib/libvulkan.1.dylib" \
+ -output "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib"
+
+lipo -create \
+ "$ROOT/dist/lavapipe/lib/libvulkan_lvp.dylib" \
+ "$ROOT/dist/lavapipe-arm64e/lib/libvulkan_lvp.dylib" \
+ -output "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"
+
+# 2. Relocatable ICD JSON
+cat > "$BUNDLE/Contents/Resources/lvp_icd.aarch64.json" <<'EOF'
+{
+ "ICD": {
+ "api_version": "1.4.363",
+ "library_arch": "64",
+ "library_path": "../Frameworks/libvulkan_lvp.dylib"
+ },
+ "file_format_version": "1.0.1"
+}
+EOF
+
+# 3. Compile XnuCpuMetal MH_BUNDLE for both arm64 and arm64e, then lipo
+for ARCH in arm64 arm64e; do
+ /usr/bin/clang++ -arch "$ARCH" -bundle -O2 -std=c++20 -fobjc-arc \
+ -isysroot "$SDK" \
+ -F"$SDK/System/Library/PrivateFrameworks" \
+ -I"$ROOT/dist/m2v/include" \
+ -I"$ROOT/src/xnu-cpu-metal-bundle" \
+ "$ROOT/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm" \
+ -L"$BUNDLE/Contents/Frameworks" -lxnu_m2v \
+ -Wl,-rpath,@loader_path/../Frameworks \
+ -framework Foundation \
+ -framework Metal \
+ -framework IOKit \
+ -framework IOSurface \
+ -framework IOGPU \
+ -o "$TMP/XnuCpuMetal.${ARCH}"
+done
+
+lipo -create "$TMP/XnuCpuMetal.arm64" "$TMP/XnuCpuMetal.arm64e" \
+ -output "$BUNDLE/Contents/MacOS/XnuCpuMetal"
+
+# 4. Ad-hoc sign all universal binaries
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib"
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib"
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"
+codesign -s - --force "$BUNDLE/Contents/MacOS/XnuCpuMetal"
+
+echo "=== Built universal (arm64 + arm64e) $BUNDLE ==="
+for f in \
+ "$BUNDLE/Contents/MacOS/XnuCpuMetal" \
+ "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib" \
+ "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib" \
+ "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"; do
+ lipo -info "$f"
+done
+ls -lh "$BUNDLE/Contents/MacOS/" "$BUNDLE/Contents/Frameworks/"
diff --git a/gpu/xnu-cpu-metal/scripts/build-bundle.sh b/gpu/xnu-cpu-metal/scripts/build-bundle.sh
new file mode 100755
index 0000000..ca7c22b
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-bundle.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SDK="$(xcrun --show-sdk-path)"
+BUNDLE="$ROOT/dist/XnuCpuMetal.bundle"
+
+rm -rf "$BUNDLE"
+mkdir -p "$BUNDLE/Contents/MacOS" "$BUNDLE/Contents/Frameworks" "$BUNDLE/Contents/Resources"
+
+cp -f "$ROOT/src/xnu-cpu-metal-bundle/Info.plist" "$BUNDLE/Contents/Info.plist"
+
+# Stage self-contained dylibs inside Contents/Frameworks
+cp -f "$ROOT/dist/m2v/lib/libxnu_m2v.dylib" "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib"
+cp -f "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib" "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib"
+cp -f "$ROOT/dist/lavapipe/lib/libvulkan_lvp.dylib" "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib"
+
+# Relocatable ICD JSON (relative to Contents/Resources/ -> ../Frameworks/libvulkan_lvp.dylib)
+cat > "$BUNDLE/Contents/Resources/lvp_icd.aarch64.json" <<'EOF'
+{
+ "ICD": {
+ "api_version": "1.4.363",
+ "library_arch": "64",
+ "library_path": "../Frameworks/libvulkan_lvp.dylib"
+ },
+ "file_format_version": "1.0.1"
+}
+EOF
+
+# Compile XnuCpuMetal MH_BUNDLE (arm64)
+/usr/bin/clang++ -arch arm64 -bundle -O2 -std=c++20 -fobjc-arc \
+ -isysroot "$SDK" \
+ -F"$SDK/System/Library/PrivateFrameworks" \
+ -I"$ROOT/dist/m2v/include" \
+ -I"$ROOT/src/xnu-cpu-metal-bundle" \
+ "$ROOT/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm" \
+ -L"$BUNDLE/Contents/Frameworks" -lxnu_m2v \
+ -Wl,-rpath,@loader_path/../Frameworks \
+ -framework Foundation \
+ -framework Metal \
+ -framework IOKit \
+ -framework IOSurface \
+ -framework IOGPU \
+ -o "$BUNDLE/Contents/MacOS/XnuCpuMetal"
+
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libxnu_m2v.dylib" 2>/dev/null || true
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libvulkan.1.dylib" 2>/dev/null || true
+codesign -s - --force "$BUNDLE/Contents/Frameworks/libvulkan_lvp.dylib" 2>/dev/null || true
+codesign -s - --force "$BUNDLE/Contents/MacOS/XnuCpuMetal" 2>/dev/null || true
+
+echo "=== Built $BUNDLE ==="
+ls -lh "$BUNDLE/Contents/MacOS/" "$BUNDLE/Contents/Frameworks/" "$BUNDLE/Contents/Resources/"
+file "$BUNDLE/Contents/MacOS/XnuCpuMetal"
+otool -L "$BUNDLE/Contents/MacOS/XnuCpuMetal"
diff --git a/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh
new file mode 100755
index 0000000..0e38dcb
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-lavapipe-arm64e.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+MESA_SRC="$ROOT/src/mesa"
+BUILD_DIR="$ROOT/build/mesa-lvp-arm64e"
+PREFIX="$ROOT/dist/lavapipe-arm64e"
+LLVM_BIN="$ROOT/build/llvm-arm64e-install/bin"
+
+export CC=/usr/bin/clang
+export CXX=/usr/bin/clang++
+export OBJC=/usr/bin/clang
+export OBJCXX=/usr/bin/clang++
+export PATH="$ROOT/build/pyvenv/bin:$ROOT/build/vk-deps/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin:$LLVM_BIN"
+export PKG_CONFIG_PATH="/opt/homebrew/lib/pkgconfig:/opt/homebrew/share/pkgconfig"
+
+if [ ! -f "$BUILD_DIR/build.ninja" ]; then
+ meson setup "$BUILD_DIR" "$MESA_SRC" \
+ --prefix="$PREFIX" \
+ --buildtype=release \
+ -Dc_args="-arch arm64e" \
+ -Dcpp_args="-arch arm64e" \
+ -Dobjc_args="-arch arm64e" \
+ -Dobjcpp_args="-arch arm64e" \
+ -Dc_link_args="-arch arm64e" \
+ -Dcpp_link_args="-arch arm64e" \
+ -Dobjc_link_args="-arch arm64e" \
+ -Dobjcpp_link_args="-arch arm64e" \
+ -Dplatforms= \
+ -Dgallium-drivers=llvmpipe \
+ -Dvulkan-drivers=swrast \
+ -Dglx=disabled \
+ -Degl=disabled \
+ -Dopengl=false \
+ -Dgles1=disabled \
+ -Dgles2=disabled \
+ -Dllvm=enabled \
+ -Dshared-llvm=disabled \
+ -Dzstd=disabled \
+ -Dxmlconfig=disabled \
+ -Dshader-cache=disabled \
+ -Dvideo-codecs= \
+ -Dvalgrind=disabled \
+ -Dlibunwind=disabled \
+ -Dbuild-tests=false
+fi
+
+ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
+ninja -C "$BUILD_DIR" install
+
+echo "=== lavapipe arm64e installed to $PREFIX ==="
+file "$PREFIX/lib/libvulkan_lvp.dylib"
+otool -L "$PREFIX/lib/libvulkan_lvp.dylib"
diff --git a/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh b/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh
new file mode 100755
index 0000000..2aede07
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-lavapipe.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+MESA_SRC="$ROOT/src/mesa"
+BUILD_DIR="$ROOT/build/mesa-lvp"
+PREFIX="$ROOT/dist/lavapipe"
+
+export CC=/usr/bin/clang
+export CXX=/usr/bin/clang++
+export OBJC=/usr/bin/clang
+export OBJCXX=/usr/bin/clang++
+export PATH="$ROOT/build/pyvenv/bin:$ROOT/build/vk-deps/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/homebrew/opt/llvm@22/bin"
+export PKG_CONFIG_PATH="/opt/homebrew/lib/pkgconfig:/opt/homebrew/share/pkgconfig"
+
+mkdir -p "$ROOT/build/static-libs"
+ln -sf /opt/homebrew/opt/zstd/lib/libzstd.a "$ROOT/build/static-libs/libzstd.a"
+
+if [ ! -f "$BUILD_DIR/build.ninja" ]; then
+ meson setup "$BUILD_DIR" "$MESA_SRC" \
+ --prefix="$PREFIX" \
+ --buildtype=release \
+ -Dc_link_args="-L$ROOT/build/static-libs" \
+ -Dcpp_link_args="-L$ROOT/build/static-libs" \
+ -Dplatforms= \
+ -Dgallium-drivers=llvmpipe \
+ -Dvulkan-drivers=swrast \
+ -Dglx=disabled \
+ -Degl=disabled \
+ -Dopengl=false \
+ -Dgles1=disabled \
+ -Dgles2=disabled \
+ -Dllvm=enabled \
+ -Dshared-llvm=disabled \
+ -Dzstd=disabled \
+ -Dxmlconfig=disabled \
+ -Dshader-cache=disabled \
+ -Dvideo-codecs= \
+ -Dvalgrind=disabled \
+ -Dlibunwind=disabled \
+ -Dbuild-tests=false
+fi
+
+ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
+ninja -C "$BUILD_DIR" install
+
+echo "=== lavapipe installed to $PREFIX ==="
+ls -lh "$PREFIX/lib/" "$PREFIX/share/vulkan/icd.d/"
+otool -L "$PREFIX/lib/libvulkan_lvp.dylib"
diff --git a/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh
new file mode 100755
index 0000000..c0ac9d0
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-llvm-arm64e.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BUILD_DIR="$ROOT/build/llvm-arm64e"
+PREFIX="$ROOT/build/llvm-arm64e-install"
+
+export PATH="$ROOT/build/pyvenv/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+
+cmake -G Ninja -S "$ROOT/src/llvm-project/llvm" -B "$BUILD_DIR" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_C_COMPILER=/usr/bin/clang \
+ -DCMAKE_CXX_COMPILER=/usr/bin/clang++ \
+ -DCMAKE_OSX_ARCHITECTURES=arm64e \
+ -DCMAKE_INSTALL_PREFIX="$PREFIX" \
+ -DLLVM_TARGETS_TO_BUILD=AArch64 \
+ -DLLVM_INCLUDE_TESTS=OFF \
+ -DLLVM_INCLUDE_EXAMPLES=OFF \
+ -DLLVM_INCLUDE_BENCHMARKS=OFF \
+ -DLLVM_INCLUDE_DOCS=OFF \
+ -DLLVM_BUILD_UTILS=OFF \
+ -DLLVM_BUILD_TOOLS=OFF \
+ -DLLVM_TOOL_LLVM_CONFIG_BUILD=ON \
+ -DLLVM_ENABLE_ZSTD=OFF \
+ -DLLVM_ENABLE_ZLIB=ON \
+ -DLLVM_ENABLE_LIBXML2=OFF \
+ -DLLVM_ENABLE_TERMINFO=OFF \
+ -DLLVM_ENABLE_RTTI=ON \
+ -DLLVM_BUILD_LLVM_DYLIB=OFF
+
+ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
+ninja -C "$BUILD_DIR" llvm-config
+ninja -C "$BUILD_DIR" install
+mkdir -p "$PREFIX/bin"
+cp -f "$BUILD_DIR/bin/llvm-config" "$PREFIX/bin/llvm-config"
+file "$PREFIX/bin/llvm-config"
+"$PREFIX/bin/llvm-config" --version --targets-built --system-libs
diff --git a/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh
new file mode 100755
index 0000000..c3e87a6
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-m2v-arm64e.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BRIDGE_DIR="$ROOT/src/xnu-m2v-bridge"
+DIST_DIR="$ROOT/dist/m2v-arm64e"
+WORK="$ROOT/build/m2v-arm64e-link"
+VK_HDR="$ROOT/build/vk-deps/vulkan-headers/1.4.363.0/include"
+OBJCOPY="/opt/homebrew/opt/llvm@22/bin/llvm-objcopy"
+
+mkdir -p "$DIST_DIR/lib" "$DIST_DIR/include"
+rm -rf "$WORK" && mkdir -p "$WORK/objs"
+
+# 1. Build Rust staticlib for arm64e-apple-darwin with -Zbuild-std
+export RUSTUP_TOOLCHAIN=nightly-aarch64-apple-darwin
+cargo build --manifest-path "$BRIDGE_DIR/Cargo.toml" \
+ -Zbuild-std=std,panic_unwind \
+ --target arm64e-apple-darwin \
+ --release
+
+# 2. Compile AdrenoMetal's RustPacBoundary.c as arm64e
+/usr/bin/clang -arch arm64e -O2 -I"$VK_HDR" \
+ -c "$ROOT/src/AdrenoMetal/bridge/RustPacBoundary.c" \
+ -o "$WORK/RustPacBoundary.o"
+
+# 3. Extract Rust staticlib objects and rename C-callback-taking imports to nmb_pac_*
+(cd "$WORK/objs" && ar x "$BRIDGE_DIR/target/arm64e-apple-darwin/release/libxnu_m2v.a")
+for obj in "$WORK/objs"/*.o; do
+ "$OBJCOPY" \
+ --redefine-sym _pthread_create=_nmb_pac_pthread_create \
+ --redefine-sym __tlv_atexit=_nmb_pac_tlv_atexit \
+ --redefine-sym _atexit=_nmb_pac_atexit \
+ --redefine-sym ___cxa_atexit=_nmb_pac_cxa_atexit \
+ --redefine-sym __dyld_register_func_for_add_image=_nmb_pac_dyld_register_func_for_add_image \
+ --redefine-sym __Unwind_Backtrace=_nmb_pac_Unwind_Backtrace \
+ --redefine-sym _dlsym=_nmb_pac_dlsym \
+ "$obj" "$obj.tmp"
+ mv "$obj.tmp" "$obj"
+done
+ar rcs "$WORK/libxnu_m2v_pac.a" "$WORK/objs"/*.o
+
+# 4. Link arm64e dylib with RustPacBoundary.o + renamed Rust archive
+/usr/bin/clang -arch arm64e -dynamiclib \
+ -Wl,-force_load,"$WORK/libxnu_m2v_pac.a" \
+ "$WORK/RustPacBoundary.o" \
+ -liconv -lSystem \
+ -install_name "@rpath/libxnu_m2v.dylib" \
+ -o "$DIST_DIR/lib/libxnu_m2v.dylib"
+
+# 5. Rewrite plain Rust `blr`/`br` into `bl`/`b _nmb_pac_call_xN` trampolines
+python3 "$ROOT/scripts/rust-pac-rewrite.py" "$DIST_DIR/lib/libxnu_m2v.dylib"
+
+# 6. Ad-hoc sign after binary rewrite
+codesign -s - --force "$DIST_DIR/lib/libxnu_m2v.dylib"
+cp -f "$BRIDGE_DIR/include/xnu_m2v.h" "$DIST_DIR/include/xnu_m2v.h"
+
+echo "=== arm64e PAC-safe libxnu_m2v.dylib installed to $DIST_DIR ==="
+file "$DIST_DIR/lib/libxnu_m2v.dylib"
+otool -L "$DIST_DIR/lib/libxnu_m2v.dylib"
diff --git a/gpu/xnu-cpu-metal/scripts/build-m2v.sh b/gpu/xnu-cpu-metal/scripts/build-m2v.sh
new file mode 100755
index 0000000..50d4b2f
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-m2v.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BRIDGE_DIR="$ROOT/src/xnu-m2v-bridge"
+DIST_DIR="$ROOT/dist/m2v"
+mkdir -p "$DIST_DIR/lib" "$DIST_DIR/include"
+
+export RUSTUP_TOOLCHAIN=1.100.0
+cargo build --manifest-path "$BRIDGE_DIR/Cargo.toml" --release --target aarch64-apple-darwin
+
+cp -f "$BRIDGE_DIR/target/aarch64-apple-darwin/release/libxnu_m2v.dylib" "$DIST_DIR/lib/libxnu_m2v.dylib"
+cp -f "$BRIDGE_DIR/include/xnu_m2v.h" "$DIST_DIR/include/xnu_m2v.h"
+install_name_tool -id "@rpath/libxnu_m2v.dylib" "$DIST_DIR/lib/libxnu_m2v.dylib"
+codesign -s - --force "$DIST_DIR/lib/libxnu_m2v.dylib" 2>/dev/null || true
+
+# Also stage libvulkan.1.dylib beside libvulkan_lvp.dylib for self-contained distribution
+cp -f "$ROOT/build/vk-deps/vulkan-loader/1.4.363.0/lib/libvulkan.1.4.363.dylib" "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib"
+chmod u+w "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib"
+install_name_tool -id "@rpath/libvulkan.1.dylib" "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib"
+codesign -s - --force "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib" 2>/dev/null || true
+
+echo "=== libxnu_m2v.dylib installed to $DIST_DIR ==="
+ls -lh "$DIST_DIR/lib/libxnu_m2v.dylib"
+otool -L "$DIST_DIR/lib/libxnu_m2v.dylib"
diff --git a/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh
new file mode 100755
index 0000000..f40dd88
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/build-vkloader-arm64e.sh
@@ -0,0 +1,25 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BUILD_DIR="$ROOT/build/vkloader-arm64e"
+PREFIX="$ROOT/build/vkloader-arm64e-install"
+VK_HDR_DIR="$ROOT/build/vk-deps/vulkan-headers/1.4.363.0"
+
+export PATH="$ROOT/build/pyvenv/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
+
+cmake -G Ninja -S "$ROOT/src/Vulkan-Loader" -B "$BUILD_DIR" \
+ -DCMAKE_BUILD_TYPE=Release \
+ -DCMAKE_C_COMPILER=/usr/bin/clang \
+ -DCMAKE_CXX_COMPILER=/usr/bin/clang++ \
+ -DCMAKE_OSX_ARCHITECTURES=arm64e \
+ -DCMAKE_INSTALL_PREFIX="$PREFIX" \
+ -DVULKAN_HEADERS_INSTALL_DIR="$VK_HDR_DIR" \
+ -DBUILD_TESTS=OFF
+
+ninja -C "$BUILD_DIR" -j"$(sysctl -n hw.ncpu)"
+ninja -C "$BUILD_DIR" install
+install_name_tool -id "@rpath/libvulkan.1.dylib" "$PREFIX/lib/libvulkan.1.dylib"
+codesign -s - --force "$PREFIX/lib/libvulkan.1.dylib" 2>/dev/null || true
+file "$PREFIX/lib/libvulkan.1.dylib"
+otool -L "$PREFIX/lib/libvulkan.1.dylib"
diff --git a/gpu/xnu-cpu-metal/scripts/fetch-sources.sh b/gpu/xnu-cpu-metal/scripts/fetch-sources.sh
new file mode 100755
index 0000000..6614ac0
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/fetch-sources.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+# Fetch the upstream sources the plugin builds against into src/ (never committed: see ../README.md).
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT/src"
+git_at() { # git_at DIR URL REV
+ [ -d "$1/.git" ] || git clone -q "$2" "$1"
+ git -C "$1" fetch -q --depth 1 origin "$3" 2>/dev/null || git -C "$1" fetch -q origin
+ git -C "$1" checkout -q "$3"
+}
+git_at metal2vulkan https://github.com/steelbrain/metal2vulkan.git d9236a8a11d3b90a1aa27b54e2d74d3891c4d2e5 # v0.2.0, GPL-2.0-or-later / LGPL-3.0-or-later
+git_at Vulkan-Loader https://github.com/KhronosGroup/Vulkan-Loader.git fa218055ff4948b159f31d43f800c808a13d51df # vulkan-sdk-1.4.363.0, Apache-2.0
+git_at llvm-project https://github.com/llvm/llvm-project.git ca7933e47d3a3451d81e72ac174dcb5aa28b59d1 # llvmorg-22.1.8 (arm64e llvmpipe JIT)
+mkdir -p "$ROOT/build"
+[ -f "$ROOT/build/mesa-26.3.1.tar.xz" ] || curl -sSLo "$ROOT/build/mesa-26.3.1.tar.xz" https://archive.mesa3d.org/mesa-26.3.1.tar.xz
+[ -d mesa ] || { mkdir mesa && tar -C mesa --strip-components=1 -xf "$ROOT/build/mesa-26.3.1.tar.xz"; } # MIT (lavapipe)
+echo "sources ready in $ROOT/src"
diff --git a/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note b/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note
new file mode 100644
index 0000000..0fccbd6
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/mesa-arm64e-jit-pac.note
@@ -0,0 +1,16 @@
+# Patches applied to Mesa 26.3.1 for arm64e macOS PAC compatibility in gallivm JIT:
+#
+# 1. C -> JIT indirect calls (sign unsigned JIT code pointer for arm64e blraaz):
+# - src/gallium/auxiliary/gallivm/lp_bld_init.c (gallivm_jit_function)
+# - src/gallium/auxiliary/gallivm/lp_bld_init_orc.cpp (gallivm_jit_function)
+#
+# 2. JIT -> C / JIT -> JIT table indirect calls (strip PAC since LLVM MCJIT emits plain blr):
+# - src/gallium/drivers/llvmpipe/lp_texture_handle.c (compile_function, matrix->compile_{sample,fetch,size}_function)
+# - src/gallium/auxiliary/gallivm/lp_bld_const.c (lp_build_const_func_pointer_from_type)
+# - src/gallium/auxiliary/gallivm/lp_bld_format_aos.c (fetch_rgba_8unorm)
+# - src/gallium/auxiliary/gallivm/lp_bld_conv.c (_mesa_float_to_half)
+# - src/gallium/auxiliary/gallivm/lp_bld_init.c (gallivm_add_global_mapping)
+# - src/gallium/auxiliary/gallivm/lp_bld_init_orc.cpp (gallivm_add_global_mapping)
+#
+# All patches are guarded by `#if defined(__has_feature) && __has_feature(ptrauth_calls)`
+# so arm64 builds are unaffected.
diff --git a/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py b/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py
new file mode 100755
index 0000000..5d34cab
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/rust-pac-rewrite.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Rewrite plain ARM64 `blr Xn` / `br Xn` (n=0..29) in a linked arm64e Rust Mach-O dylib
+into `bl _nmb_pac_call_xN` / `b _nmb_pac_call_xN` trampolines (from RustPacBoundary.c),
+skipping the trampolines themselves and RustPacBoundary's own C functions."""
+import struct
+import subprocess
+import sys
+
+
+def get_symbols(path):
+ out = subprocess.check_output(["nm", "-n", path], text=True)
+ syms = []
+ by_name = {}
+ for line in out.splitlines():
+ parts = line.split()
+ if len(parts) == 3 and parts[1] in ("T", "t"):
+ addr = int(parts[0], 16)
+ name = parts[2]
+ syms.append((addr, name))
+ by_name[name] = addr
+ return syms, by_name
+
+
+def parse_text_section(data):
+ magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags, reserved = struct.unpack_from("<IIIIIIII", data, 0)
+ if magic != 0xFEEDFACF:
+ raise RuntimeError(f"Expected 64-bit Mach-O, got magic {magic:#x}")
+ off = 32
+ for _ in range(ncmds):
+ cmd, cmdsize = struct.unpack_from("<II", data, off)
+ if cmd == 0x19: # LC_SEGMENT_64
+ segname = data[off + 8 : off + 24].split(b"\x00", 1)[0].decode()
+ nsects = struct.unpack_from("<I", data, off + 64)[0]
+ if segname == "__TEXT":
+ sect_off = off + 72
+ for _ in range(nsects):
+ sectname = data[sect_off : sect_off + 16].split(b"\x00", 1)[0].decode()
+ addr, size, fileoff = struct.unpack_from("<QQI", data, sect_off + 32)
+ if sectname == "__text":
+ return addr, size, fileoff
+ sect_off += 80
+ off += cmdsize
+ raise RuntimeError("__TEXT,__text section not found")
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit(f"Usage: {sys.argv[0]} <arm64e-mach-o>")
+ path = sys.argv[1]
+ syms, by_name = get_symbols(path)
+
+ tramp = {}
+ for r in range(30):
+ name = f"_nmb_pac_call_x{r}"
+ if name not in by_name:
+ raise RuntimeError(f"Missing trampoline symbol {name}")
+ tramp[r] = by_name[name]
+
+ # Build exclusion ranges for RustPacBoundary.c functions (nmb_pac_*, wrap*, signChain, restoreChain)
+ skip_prefixes = ("_nmb_pac_", "_wrapCreateInstance", "_wrapCreateMessenger", "_wrapGetInstanceProcAddr", "_signChain", "_restoreChain")
+ skip_ranges = []
+ for i, (addr, name) in enumerate(syms):
+ if name.startswith(skip_prefixes):
+ end = syms[i + 1][0] if i + 1 < len(syms) else addr + 4096
+ skip_ranges.append((addr, end))
+
+ def is_skipped(pc):
+ for s, e in skip_ranges:
+ if s <= pc < e:
+ return True
+ return False
+
+ with open(path, "rb") as f:
+ data = bytearray(f.read())
+
+ text_addr, text_size, text_fileoff = parse_text_section(data)
+ blr_count = 0
+ br_count = 0
+
+ for off in range(0, text_size, 4):
+ pc = text_addr + off
+ if is_skipped(pc):
+ continue
+ word = struct.unpack_from("<I", data, text_fileoff + off)[0]
+ is_blr = (word & 0xFFFFFC1F) == 0xD63F0000
+ is_br = (word & 0xFFFFFC1F) == 0xD61F0000
+ if not (is_blr or is_br):
+ continue
+ reg = (word >> 5) & 31
+ if reg >= 30:
+ continue
+ target = tramp[reg]
+ delta = (target - pc) >> 2
+ if delta < -(1 << 25) or delta >= (1 << 25):
+ raise RuntimeError(f"Branch out of ±128MB range at {pc:#x} -> {target:#x}")
+ op = 0x94000000 if is_blr else 0x14000000
+ new_word = op | (delta & 0x03FFFFFF)
+ struct.pack_into("<I", data, text_fileoff + off, new_word)
+ if is_blr:
+ blr_count += 1
+ else:
+ br_count += 1
+
+ with open(path, "wb") as f:
+ f.write(data)
+ print(f"rust-pac-rewrite: {path}: rewrote {blr_count} blr + {br_count} br (skipped {len(skip_ranges)} PAC boundary fns)")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/gpu/xnu-cpu-metal/scripts/test-bundle.sh b/gpu/xnu-cpu-metal/scripts/test-bundle.sh
new file mode 100755
index 0000000..f7ed986
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/test-bundle.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SDK="$(xcrun --show-sdk-path)"
+ARCH="${1:-arm64}"
+
+/usr/bin/clang++ -arch "$ARCH" -O2 -fobjc-arc -isysroot "$SDK" \
+ "$ROOT/test/test_bundle.mm" \
+ -framework Foundation -framework Metal \
+ -o "$ROOT/build/test_bundle_${ARCH}"
+
+file "$ROOT/build/test_bundle_${ARCH}"
+"$ROOT/build/test_bundle_${ARCH}" "$ROOT/dist/XnuCpuMetal.bundle" "$ROOT/build/vecadd.metallib"
diff --git a/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh b/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh
new file mode 100755
index 0000000..3e5a2fa
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/test-lavapipe.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VK_HDR="$ROOT/build/vk-deps/vulkan-headers/1.4.363.0/include"
+VK_LIB="$ROOT/build/vk-deps/vulkan-loader/1.4.363.0/lib"
+
+# Fix @@HOMEBREW_PREFIX@@ install_name on our local copy of libvulkan.1.dylib if needed
+if otool -D "$VK_LIB/libvulkan.1.dylib" | grep -q '@@HOMEBREW_PREFIX@@'; then
+ chmod u+w "$VK_LIB/libvulkan.1.4.363.dylib" 2>/dev/null || true
+ install_name_tool -id "@rpath/libvulkan.1.dylib" "$VK_LIB/libvulkan.1.4.363.dylib"
+ codesign -s - --force "$VK_LIB/libvulkan.1.4.363.dylib" 2>/dev/null || true
+fi
+
+"$ROOT/build/vk-deps/bin/glslangValidator" -V "$ROOT/test/vecadd.comp" -o "$ROOT/build/vecadd.spv"
+
+/usr/bin/clang -O2 -I"$VK_HDR" "$ROOT/test/test_lavapipe_compute.c" \
+ -L"$VK_LIB" -lvulkan -Wl,-rpath,"$VK_LIB" \
+ -o "$ROOT/build/test_lavapipe_compute"
+
+ICD_JSON="$(ls "$ROOT/dist/lavapipe/share/vulkan/icd.d/"lvp_icd*.json | head -n 1)"
+echo "Using ICD JSON: $ICD_JSON"
+cat "$ICD_JSON"
+echo ""
+
+VK_ICD_FILENAMES="$ICD_JSON" "$ROOT/build/test_lavapipe_compute" "$ROOT/build/vecadd.spv"
diff --git a/gpu/xnu-cpu-metal/scripts/test-m2v.sh b/gpu/xnu-cpu-metal/scripts/test-m2v.sh
new file mode 100755
index 0000000..1fb1bcc
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/test-m2v.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+
+# 1. Compile vecadd.metal -> vecadd.air -> vecadd.metallib via Xcode Metal toolchain
+xcrun -sdk macosx metal -c "$ROOT/test/vecadd.metal" -o "$ROOT/build/vecadd.air"
+xcrun -sdk macosx metallib "$ROOT/build/vecadd.air" -o "$ROOT/build/vecadd.metallib"
+
+# 2. Build C test binary linked against libxnu_m2v.dylib
+/usr/bin/clang -O2 -I"$ROOT/dist/m2v/include" "$ROOT/test/test_m2v_compute.c" \
+ -L"$ROOT/dist/m2v/lib" -lxnu_m2v -Wl,-rpath,"$ROOT/dist/m2v/lib" \
+ -o "$ROOT/build/test_m2v_compute"
+
+# 3. Run Metal -> metal2vulkan -> lavapipe!
+mkdir -p "$ROOT/build/m2v-cache"
+"$ROOT/build/test_m2v_compute" \
+ "$ROOT/dist/lavapipe/lib/libvulkan.1.dylib" \
+ "$ROOT/dist/lavapipe/share/vulkan/icd.d/lvp_icd.aarch64.json" \
+ "$ROOT/build/vecadd.metallib" \
+ "$ROOT/build/m2v-cache"
diff --git a/gpu/xnu-cpu-metal/scripts/test-render-ci.sh b/gpu/xnu-cpu-metal/scripts/test-render-ci.sh
new file mode 100755
index 0000000..0781040
--- /dev/null
+++ b/gpu/xnu-cpu-metal/scripts/test-render-ci.sh
@@ -0,0 +1,16 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SDK="$(xcrun --show-sdk-path)"
+ARCH="${1:-arm64}"
+
+xcrun -sdk macosx metal -c "$ROOT/test/tri.metal" -o "$ROOT/build/tri.air"
+xcrun -sdk macosx metallib "$ROOT/build/tri.air" -o "$ROOT/build/tri.metallib"
+
+/usr/bin/clang++ -arch "$ARCH" -O2 -fobjc-arc -isysroot "$SDK" \
+ "$ROOT/test/test_render_ci.mm" \
+ -framework Foundation -framework Metal -framework CoreImage -framework CoreGraphics \
+ -o "$ROOT/build/test_render_ci_${ARCH}"
+
+"$ROOT/build/test_render_ci_${ARCH}" "$ROOT/dist/XnuCpuMetal.bundle" "$ROOT/build/tri.metallib"
diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/Info.plist b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/Info.plist
new file mode 100644
index 0000000..09a3169
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/Info.plist
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleExecutable</key>
+ <string>XnuCpuMetal</string>
+ <key>CFBundleIdentifier</key>
+ <string>org.xnulinux.XnuCpuMetal</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>XnuCpuMetal</string>
+ <key>CFBundlePackageType</key>
+ <string>BNDL</string>
+ <key>NSPrincipalClass</key>
+ <string>XnuCpuMetalDevice</string>
+ <key>CFBundlePrincipalClass</key>
+ <string>XnuCpuMetalDevice</string>
+ <key>CFBundleShortVersionString</key>
+ <string>0.1.0</string>
+ <key>CFBundleVersion</key>
+ <string>1</string>
+</dict>
+</plist>
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
new file mode 100644
index 0000000..e08b465
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalPlugin.mm
@@ -0,0 +1,2458 @@
+#include <objc/message.h>
+// XnuCpuMetal.bundle — Pure-CPU Metal plugin for xnulinux (macOS 27).
+// Principal class: XnuCpuMetalDevice (subclass of IOGPUMetalDevice).
+// Backend: libxnu_m2v.dylib (steelbrain/metal2vulkan) -> libvulkan.1.dylib -> Mesa lavapipe (libvulkan_lvp.dylib).
+
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+#import <IOSurface/IOSurfaceRef.h>
+#import <IOKit/IOKitLib.h>
+#import <objc/runtime.h>
+#import <objc/message.h>
+#include <dlfcn.h>
+#include <mach-o/dyld.h>
+#include <mach-o/getsect.h>
+#include <mach-o/loader.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <deque>
+#include <functional>
+#include <mutex>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "xnu_m2v.h"
+#include "XnuCpuMetalShim.h"
+
+@interface IOGPUMetalDevice : NSObject
+@end
+
+@protocol XcmOriginalStitching
+- (NSString *)newDagStringWithGraphs:(NSArray<MTLFunctionStitchingGraph *> *)graphs;
+@end
+
+@interface MTLFunctionConstantValues (XcmPrivateAccess)
+- (NSArray *)newIndexedConstantArray;
+- (NSArray *)newNamedConstantArray;
+@end
+
+@protocol XcmPrivateConstantValue
+- (NSUInteger)dataType;
+- (void *)data;
+- (NSUInteger)index;
+- (NSString *)name;
+@end
+
+static bool xcmTraceOn() { static bool on = getenv("XNU_CPU_METAL_TRACE") != nullptr; return on; }
+
+static NSError *xcmError(NSString *domain, NSInteger code, const char *fallback) {
+ const char *msg = xm2v_last_error();
+ NSString *desc = (msg && msg[0]) ? [NSString stringWithUTF8String:msg]
+ : [NSString stringWithUTF8String:(fallback ?: "XnuCpuMetal error")];
+ return [NSError errorWithDomain:domain code:code userInfo:@{NSLocalizedDescriptionKey: desc}];
+}
+
+static uint64_t xcmConstantBytes(uint64_t type) {
+ switch (type) {
+ case 3: case 29: case 33: return 4;
+ case 4: case 30: case 34: return 8;
+ case 5: case 31: case 35: return 12;
+ case 6: case 32: case 36: return 16;
+ case 16: case 37: case 41: case 121: return 2;
+ case 17: case 38: case 42: case 122: return 4;
+ case 18: case 39: case 43: case 123: return 6;
+ case 19: case 40: case 44: case 124: return 8;
+ case 45: case 49: case 53: return 1;
+ case 46: case 50: case 54: return 2;
+ case 47: case 51: case 55: return 3;
+ case 48: case 52: case 56: return 4;
+ case 81: case 85: return 8;
+ case 82: case 86: return 16;
+ case 83: case 87: return 24;
+ case 84: case 88: return 32;
+ default: return 0;
+ }
+}
+
+/* ======================== MTLCompiler CodeGen (Stitched Libraries) ======================== */
+
+typedef void (^XcmCodeGenReply)(int32_t status, const void *reply, size_t length, const char *message);
+
+static void *xcmRunBlock(void *block) {
+ @autoreleasepool { ((__bridge void (^)(void))block)(); }
+ return nullptr;
+}
+
+static void xcmOnLargeStack(void (^body)(void)) {
+ pthread_attr_t attr;
+ pthread_t thread;
+ if (pthread_attr_init(&attr)) { body(); return; }
+ bool made = !pthread_attr_setstacksize(&attr, 16u << 20) &&
+ !pthread_create(&thread, &attr, xcmRunBlock, (__bridge void *)body);
+ pthread_attr_destroy(&attr);
+ if (made) pthread_join(thread, nullptr);
+ else body();
+}
+
+static NSData *xcmCodeGenRequest(uint32_t type, const std::vector<uint8_t> &request,
+ NSString **warnings, NSString **failure) {
+ static void *service = nullptr;
+ static void (*build)(void *, void *, uint32_t, const void *, size_t, XcmCodeGenReply) = nullptr;
+ static dispatch_once_t once;
+ static std::mutex lock;
+ dispatch_once(&once, ^{
+ static const char kFramework[] = "/System/Library/PrivateFrameworks/MTLCompiler.framework";
+ std::string path = std::string(kFramework) + "/MTLCompiler";
+ void *lib = dlopen(path.c_str(), RTLD_NOW);
+ if (!lib) {
+ static const char kPrefix[] = "/System/Library/PrivateFrameworks/MTLCompiler.framework/Versions/";
+ for (uint32_t i = 0, n = _dyld_image_count(); i < n && !lib; i++) {
+ const char *name = _dyld_get_image_name(i);
+ if (!name || !strstr(name, "/Metal.framework/") || strcmp(strrchr(name, '/'), "/Metal")) continue;
+ unsigned long size = 0;
+ const char *strings = (const char *)getsectiondata(
+ (const struct mach_header_64 *)_dyld_get_image_header(i), "__TEXT", "__cstring", &size);
+ for (unsigned long at = 0; strings && at + sizeof(kPrefix) < size;) {
+ const char *text = strings + at;
+ size_t len = strnlen(text, size - at);
+ if (!strncmp(text, kPrefix, sizeof(kPrefix) - 1) && len > sizeof(kPrefix) &&
+ !strcmp(text + len - 12, "/MTLCompiler")) {
+ path.assign(text, len);
+ lib = dlopen(path.c_str(), RTLD_NOW);
+ break;
+ }
+ at += len + 1;
+ }
+ }
+ }
+ if (!lib) {
+ path = std::string(kFramework) + "/Versions/Current/MTLCompiler";
+ lib = dlopen(path.c_str(), RTLD_NOW);
+ }
+ if (!lib) {
+ unsigned long highest = 0;
+ for (NSString *entry in [[NSFileManager defaultManager]
+ contentsOfDirectoryAtPath:[@(kFramework) stringByAppendingString:@"/Versions"] error:nil]) {
+ unsigned long ver = strtoul(entry.UTF8String, nullptr, 10);
+ if (ver > highest && [entry isEqualToString:[NSString stringWithFormat:@"%lu", ver]]) highest = ver;
+ }
+ if (highest) {
+ path = std::string(kFramework) + "/Versions/" + std::to_string(highest) + "/MTLCompiler";
+ lib = dlopen(path.c_str(), RTLD_NOW);
+ }
+ }
+ auto create = lib ? (void *(*)(const char *))dlsym(lib, "MTLCodeGenServiceCreate") : nullptr;
+ build = lib ? (void (*)(void *, void *, uint32_t, const void *, size_t, XcmCodeGenReply))
+ dlsym(lib, "MTLCodeGenServiceBuildRequest")
+ : nullptr;
+ service = (create && build) ? create("xnu-cpu-metal") : nullptr;
+ });
+ if (!service) {
+ if (failure) *failure = @"MTLCompiler.framework not available";
+ return nil;
+ }
+ __block NSData *metallib = nil;
+ __block NSString *warned = nil, *message = nil;
+ __block bool called = false;
+ {
+ std::lock_guard<std::mutex> guard(lock);
+ xcmOnLargeStack(^{
+ build(service, nullptr, type, request.data(), request.size(),
+ ^(int32_t status, const void *reply, size_t length, const char *why) {
+ called = true;
+ uint32_t hdr = 0, warn = 0;
+ if (reply && length >= 16) {
+ memcpy(&hdr, (const uint8_t *)reply + 8, 4);
+ memcpy(&warn, (const uint8_t *)reply + 12, 4);
+ }
+ if (status || !reply || length < 16 || (uint64_t)hdr + warn > length) {
+ message = (why && *why) ? @(why)
+ : [NSString stringWithFormat:@"MTLCompiler failed (status %d)", status];
+ return;
+ }
+ if (warn) {
+ warned = [[NSString alloc] initWithBytes:(const uint8_t *)reply + hdr
+ length:warn
+ encoding:NSUTF8StringEncoding];
+ }
+ metallib = [NSData dataWithBytes:(const uint8_t *)reply + hdr + warn
+ length:length - hdr - warn];
+ });
+ });
+ }
+ if (!called) message = @"MTLCompiler did not respond";
+ if (warnings) *warnings = warned;
+ if (failure) *failure = message;
+ return metallib;
+}
+
+/* ======================== Base Object ======================== */
+
+@interface XcmObject : NSObject
+@property (nonatomic, copy) NSString *label;
+@end
+@implementation XcmObject
+- (uint64_t)globalTraceObjectID { return 0; }
+@end
+
+/* ======================== Buffer ======================== */
+
+@interface XcmBuffer : XcmObject {
+@public
+ Xm2vBuffer *_handle;
+ id _device;
+ MTLResourceOptions _options;
+ uint64_t _length;
+ MTLPurgeableState _purgeable;
+}
+- (instancetype)initWithHandle:(Xm2vBuffer *)h device:(id)dev options:(MTLResourceOptions)opts;
+@end
+
+@implementation XcmBuffer
+- (instancetype)initWithHandle:(Xm2vBuffer *)h device:(id)dev options:(MTLResourceOptions)opts {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _options = opts;
+ _length = xm2v_buffer_length(h);
+ _purgeable = MTLPurgeableStateNonVolatile;
+ }
+ return self;
+}
+- (void)dealloc {
+ if (_handle) { xm2v_buffer_release(_handle); _handle = nullptr; }
+}
+- (id<MTLDevice>)device { return _device; }
+- (void *)contents { return _handle ? xm2v_buffer_contents(_handle) : nullptr; }
+- (NSUInteger)length { return (NSUInteger)_length; }
+- (uint64_t)gpuAddress { return _handle ? xm2v_buffer_gpu_address(_handle) : 0; }
+- (void)didModifyRange:(NSRange)range {
+ if (_handle) xm2v_buffer_did_modify_range(_handle, range.location, range.length);
+}
+- (MTLResourceOptions)resourceOptions { return _options; }
+- (MTLStorageMode)storageMode { return (MTLStorageMode)((_options & MTLResourceStorageModeMask) >> MTLResourceStorageModeShift); }
+- (MTLCPUCacheMode)cpuCacheMode { return (MTLCPUCacheMode)((_options & MTLResourceCPUCacheModeMask) >> MTLResourceCPUCacheModeShift); }
+- (MTLHazardTrackingMode)hazardTrackingMode { return (MTLHazardTrackingMode)((_options & MTLResourceHazardTrackingModeMask) >> MTLResourceHazardTrackingModeShift); }
+- (NSUInteger)allocatedSize { return (NSUInteger)_length; }
+- (MTLPurgeableState)setPurgeableState:(MTLPurgeableState)state {
+ MTLPurgeableState prev = _purgeable;
+ if (state != MTLPurgeableStateKeepCurrent) _purgeable = state;
+ return prev;
+}
+- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)desc offset:(NSUInteger)offset bytesPerRow:(NSUInteger)bytesPerRow {
+ (void)offset; (void)bytesPerRow;
+ return [_device newTextureWithDescriptor:desc];
+}
+@end
+
+/* ======================== Texture (with IOSurface bidirectional sync) ======================== */
+
+@interface XcmTexture : XcmObject {
+@public
+ Xm2vTexture *_handle;
+ id _device;
+ MTLTextureType _textureType;
+ MTLPixelFormat _pixelFormat;
+ NSUInteger _width, _height, _depth, _mipLevels, _sampleCount, _arrayLength;
+ MTLTextureUsage _usage;
+ MTLResourceOptions _options;
+ MTLPurgeableState _purgeable;
+ IOSurfaceRef _iosurface;
+ NSUInteger _iosurfacePlane;
+ uint32_t _iosurfaceSeed;
+ BOOL _iosurfaceSyncedIn;
+}
+- (instancetype)initWithHandle:(Xm2vTexture *)h device:(id)dev descriptor:(MTLTextureDescriptor *)desc;
+- (void)syncFromIOSurfaceIfNeeded;
+- (void)syncToIOSurface;
+@end
+
+@implementation XcmTexture
+- (instancetype)initWithHandle:(Xm2vTexture *)h device:(id)dev descriptor:(MTLTextureDescriptor *)desc {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _textureType = desc.textureType;
+ _pixelFormat = desc.pixelFormat;
+ _width = desc.width;
+ _height = desc.height;
+ _depth = desc.depth;
+ _mipLevels = desc.mipmapLevelCount;
+ _sampleCount = desc.sampleCount;
+ _arrayLength = desc.arrayLength;
+ _usage = desc.usage;
+ _options = desc.resourceOptions;
+ _purgeable = MTLPurgeableStateNonVolatile;
+ }
+ return self;
+}
+- (void)dealloc {
+ if (_handle) { xm2v_texture_release(_handle); _handle = nullptr; }
+ if (_iosurface) { CFRelease(_iosurface); _iosurface = nullptr; }
+}
+static std::mutex gIOSurfaceWriterLock;
+static std::unordered_map<uint32_t, __weak id> gIOSurfaceLastWriter;
+
+static void xcmRecordIOSurfaceWriter(IOSurfaceRef surf, id cmdBuf) {
+ if (!surf || !cmdBuf) return;
+ uint32_t sid = IOSurfaceGetID(surf);
+ if (!sid) return;
+ std::lock_guard<std::mutex> lk(gIOSurfaceWriterLock);
+ gIOSurfaceLastWriter[sid] = cmdBuf;
+}
+
+static void xcmFlushIOSurfaceWriter(IOSurfaceRef surf) {
+ if (!surf) return;
+ uint32_t sid = IOSurfaceGetID(surf);
+ if (!sid) return;
+ id writer = nil;
+ {
+ std::lock_guard<std::mutex> lk(gIOSurfaceWriterLock);
+ auto it = gIOSurfaceLastWriter.find(sid);
+ if (it != gIOSurfaceLastWriter.end()) writer = it->second;
+ }
+ if (writer && [writer respondsToSelector:@selector(waitUntilCompleted)] &&
+ [(id<MTLCommandBuffer>)writer status] >= MTLCommandBufferStatusCommitted) {
+ [(id<MTLCommandBuffer>)writer waitUntilCompleted];
+ }
+}
+
+- (void)syncFromIOSurfaceIfNeeded {
+ if (!_iosurface || !_handle) return;
+ xcmFlushIOSurfaceWriter(_iosurface);
+ uint32_t seed = IOSurfaceGetSeed(_iosurface);
+ if (_iosurfaceSyncedIn && seed == _iosurfaceSeed) return;
+ if (IOSurfaceLock(_iosurface, kIOSurfaceLockReadOnly, nullptr) == kIOReturnSuccess) {
+ size_t planeCount = IOSurfaceGetPlaneCount(_iosurface);
+ void *base = (planeCount > 0) ? IOSurfaceGetBaseAddressOfPlane(_iosurface, _iosurfacePlane)
+ : IOSurfaceGetBaseAddress(_iosurface);
+ size_t bpr = (planeCount > 0) ? IOSurfaceGetBytesPerRowOfPlane(_iosurface, _iosurfacePlane)
+ : IOSurfaceGetBytesPerRow(_iosurface);
+ if (base && bpr > 0) {
+ xm2v_texture_replace_region(_handle, 0, 0, 0, _width, _height, 1, 0, 0, base, bpr, 0);
+ }
+ IOSurfaceUnlock(_iosurface, kIOSurfaceLockReadOnly, nullptr);
+ _iosurfaceSeed = seed;
+ _iosurfaceSyncedIn = YES;
+ }
+}
+- (void)syncToIOSurface {
+ if (!_iosurface || !_handle) return;
+ if (IOSurfaceLock(_iosurface, 0, nullptr) == kIOReturnSuccess) {
+ size_t planeCount = IOSurfaceGetPlaneCount(_iosurface);
+ void *base = (planeCount > 0) ? IOSurfaceGetBaseAddressOfPlane(_iosurface, _iosurfacePlane)
+ : IOSurfaceGetBaseAddress(_iosurface);
+ size_t bpr = (planeCount > 0) ? IOSurfaceGetBytesPerRowOfPlane(_iosurface, _iosurfacePlane)
+ : IOSurfaceGetBytesPerRow(_iosurface);
+ if (base && bpr > 0) {
+ bool ok = xm2v_texture_get_bytes(_handle, base, bpr, 0, 0, 0, 0, _width, _height, 1, 0, 0);
+ if (xcmTraceOn() || !ok) {
+ const uint8_t *p = (const uint8_t *)base;
+ size_t nz = 0;
+ for (size_t i = 0; i < bpr * _height; i++) if (p[i]) nz++;
+ fprintf(stderr, "XCM syncToIOSurface(%p surf=%p fmt=%lu %lux%lu bpr=%zu) ok=%d nz=%zu/%zu err=%s\n",
+ (__bridge void *)self, _iosurface, (unsigned long)_pixelFormat,
+ (unsigned long)_width, (unsigned long)_height, bpr, ok, nz, bpr * _height,
+ ok ? "ok" : xm2v_last_error());
+ }
+ }
+ IOSurfaceUnlock(_iosurface, 0, nullptr);
+ _iosurfaceSeed = IOSurfaceGetSeed(_iosurface);
+ _iosurfaceSyncedIn = YES;
+ }
+}
+- (id<MTLDevice>)device { return _device; }
+- (MTLTextureType)textureType { return _textureType; }
+- (MTLPixelFormat)pixelFormat { return _pixelFormat; }
+- (NSUInteger)width { return _width; }
+- (NSUInteger)height { return _height; }
+- (NSUInteger)depth { return _depth; }
+- (NSUInteger)mipmapLevelCount { return _mipLevels; }
+- (NSUInteger)sampleCount { return _sampleCount; }
+- (NSUInteger)arrayLength { return _arrayLength; }
+- (MTLTextureUsage)usage { return _usage; }
+- (MTLResourceOptions)resourceOptions { return _options; }
+- (MTLStorageMode)storageMode { return (MTLStorageMode)((_options & MTLResourceStorageModeMask) >> MTLResourceStorageModeShift); }
+- (MTLCPUCacheMode)cpuCacheMode { return (MTLCPUCacheMode)((_options & MTLResourceCPUCacheModeMask) >> MTLResourceCPUCacheModeShift); }
+- (MTLHazardTrackingMode)hazardTrackingMode { return (MTLHazardTrackingMode)((_options & MTLResourceHazardTrackingModeMask) >> MTLResourceHazardTrackingModeShift); }
+- (BOOL)isFramebufferOnly { return NO; }
+- (BOOL)allowGPUOptimizedContents { return YES; }
+- (BOOL)isDrawable { return NO; }
+- (NSUInteger)protectionOptions { return 0; }
+- (NSUInteger)allocatedSize {
+ NSUInteger bpp = 4;
+ switch (_pixelFormat) {
+ case MTLPixelFormatA8Unorm: case MTLPixelFormatR8Unorm: case MTLPixelFormatR8Snorm:
+ case MTLPixelFormatR8Uint: case MTLPixelFormatR8Sint: case MTLPixelFormatStencil8:
+ bpp = 1; break;
+ case MTLPixelFormatR16Unorm: case MTLPixelFormatR16Snorm: case MTLPixelFormatR16Uint:
+ case MTLPixelFormatR16Sint: case MTLPixelFormatR16Float: case MTLPixelFormatRG8Unorm:
+ case MTLPixelFormatRG8Snorm: case MTLPixelFormatRG8Uint: case MTLPixelFormatRG8Sint:
+ case MTLPixelFormatDepth16Unorm:
+ bpp = 2; break;
+ case MTLPixelFormatRGBA16Unorm: case MTLPixelFormatRGBA16Snorm: case MTLPixelFormatRGBA16Uint:
+ case MTLPixelFormatRGBA16Sint: case MTLPixelFormatRGBA16Float:
+ case MTLPixelFormatRG32Uint: case MTLPixelFormatRG32Sint: case MTLPixelFormatRG32Float:
+ case MTLPixelFormatDepth32Float_Stencil8:
+ bpp = 8; break;
+ case MTLPixelFormatRGBA32Uint: case MTLPixelFormatRGBA32Sint: case MTLPixelFormatRGBA32Float:
+ bpp = 16; break;
+ default: bpp = 4; break;
+ }
+ NSUInteger sz = MAX(1ul, _width) * MAX(1ul, _height) * MAX(1ul, _depth) * MAX(1ul, _arrayLength) * MAX(1ul, _sampleCount) * bpp;
+ return (sz + 255ul) & ~255ul;
+}
+- (id<MTLTexture>)parentTexture { return nil; }
+- (id<MTLBuffer>)buffer { return nil; }
+- (IOSurfaceRef)iosurface { return _iosurface; }
+- (NSUInteger)iosurfacePlane { return _iosurfacePlane; }
+- (MTLPurgeableState)setPurgeableState:(MTLPurgeableState)state {
+ MTLPurgeableState prev = _purgeable;
+ if (state != MTLPurgeableStateKeepCurrent) _purgeable = state;
+ return prev;
+}
+- (void)replaceRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level slice:(NSUInteger)slice
+ withBytes:(const void *)pixelBytes bytesPerRow:(NSUInteger)bytesPerRow bytesPerImage:(NSUInteger)bytesPerImage {
+ if (_handle) {
+ xm2v_texture_replace_region(_handle,
+ region.origin.x, region.origin.y, region.origin.z,
+ region.size.width, region.size.height, region.size.depth,
+ level, slice, pixelBytes, bytesPerRow, bytesPerImage);
+ }
+}
+- (void)replaceRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level
+ withBytes:(const void *)pixelBytes bytesPerRow:(NSUInteger)bytesPerRow {
+ [self replaceRegion:region mipmapLevel:level slice:0 withBytes:pixelBytes bytesPerRow:bytesPerRow bytesPerImage:0];
+}
+- (void)getBytes:(void *)pixelBytes bytesPerRow:(NSUInteger)bytesPerRow bytesPerImage:(NSUInteger)bytesPerImage
+ fromRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level slice:(NSUInteger)slice {
+ if (_handle) {
+ xm2v_texture_get_bytes(_handle, pixelBytes, bytesPerRow, bytesPerImage,
+ region.origin.x, region.origin.y, region.origin.z,
+ region.size.width, region.size.height, region.size.depth,
+ level, slice);
+ }
+}
+- (void)getBytes:(void *)pixelBytes bytesPerRow:(NSUInteger)bytesPerRow
+ fromRegion:(MTLRegion)region mipmapLevel:(NSUInteger)level {
+ [self getBytes:pixelBytes bytesPerRow:bytesPerRow bytesPerImage:0 fromRegion:region mipmapLevel:level slice:0];
+}
+- (id<MTLTexture>)newTextureViewWithPixelFormat:(MTLPixelFormat)pixelFormat
+ textureType:(MTLTextureType)textureType
+ levels:(NSRange)levelRange
+ slices:(NSRange)sliceRange {
+ if (!_handle) return nil;
+ Xm2vTexture *vh = xm2v_texture_new_view(_handle, (uint64_t)pixelFormat, (uint64_t)textureType,
+ levelRange.location, levelRange.length,
+ sliceRange.location, sliceRange.length);
+ if (!vh) return nil;
+ MTLTextureDescriptor *desc = [[MTLTextureDescriptor alloc] init];
+ desc.textureType = textureType;
+ desc.pixelFormat = pixelFormat;
+ desc.width = MAX(1ul, _width >> levelRange.location);
+ desc.height = MAX(1ul, _height >> levelRange.location);
+ desc.depth = MAX(1ul, _depth >> levelRange.location);
+ desc.mipmapLevelCount = levelRange.length;
+ desc.sampleCount = _sampleCount;
+ desc.arrayLength = sliceRange.length;
+ desc.usage = _usage;
+ desc.resourceOptions = _options;
+ return (id<MTLTexture>)[[XcmTexture alloc] initWithHandle:vh device:_device descriptor:desc];
+}
+- (id<MTLTexture>)newTextureViewWithPixelFormat:(MTLPixelFormat)pixelFormat {
+ return [self newTextureViewWithPixelFormat:pixelFormat textureType:_textureType
+ levels:NSMakeRange(0, _mipLevels)
+ slices:NSMakeRange(0, _arrayLength)];
+}
+- (id<MTLTexture>)newTextureViewWithPixelFormat:(MTLPixelFormat)pixelFormat
+ textureType:(MTLTextureType)textureType
+ levels:(NSRange)levelRange
+ slices:(NSRange)sliceRange
+ swizzle:(MTLTextureSwizzleChannels)swizzle {
+ (void)swizzle;
+ return [self newTextureViewWithPixelFormat:pixelFormat textureType:textureType levels:levelRange slices:sliceRange];
+}
+- (id<MTLHeap>)heap { return nil; }
+- (NSUInteger)heapOffset { return 0; }
+- (BOOL)isAliasable { return NO; }
+- (MTLTextureSwizzleChannels)swizzle {
+ return MTLTextureSwizzleChannelsMake(MTLTextureSwizzleRed, MTLTextureSwizzleGreen, MTLTextureSwizzleBlue, MTLTextureSwizzleAlpha);
+}
+@end
+
+/* ======================== Function & Library ======================== */
+
+@class XcmLibrary;
+
+@interface XcmFunction : XcmObject {
+@public
+ Xm2vFunction *_handle;
+ id _device;
+ XcmLibrary *_library;
+ NSString *_name;
+ NSString *_sourceName;
+ MTLFunctionType _functionType;
+ MTLFunctionConstantValues *_constantValues;
+}
+- (instancetype)initWithHandle:(Xm2vFunction *)h device:(id)dev library:(XcmLibrary *)lib name:(NSString *)name type:(MTLFunctionType)type;
+@end
+
+@implementation XcmFunction
+- (instancetype)initWithHandle:(Xm2vFunction *)h device:(id)dev library:(XcmLibrary *)lib name:(NSString *)name type:(MTLFunctionType)type {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _library = lib;
+ _name = [name copy];
+ _sourceName = [name copy];
+ _functionType = h ? (MTLFunctionType)xm2v_function_type(h) : type;
+ }
+ return self;
+}
+- (void)dealloc {
+ if (_handle) { xm2v_function_release(_handle); _handle = nullptr; }
+}
+- (id<MTLDevice>)device { return _device; }
+- (NSString *)name { return _name; }
+- (MTLFunctionType)functionType { return _functionType; }
+- (NSArray *)vertexAttributes { return @[]; }
+- (NSArray *)stageInputAttributes { return @[]; }
+- (NSDictionary *)functionConstantsDictionary { return @{}; }
+@end
+
+@interface XcmLibrary : XcmObject {
+@public
+ Xm2vLibrary *_handle;
+ id _device;
+ NSData *_metallibData;
+}
+- (instancetype)initWithHandle:(Xm2vLibrary *)h device:(id)dev data:(NSData *)data;
+@end
+
+static bool xcmForEachMetallibEntry(NSData *data, const std::function<bool(const std::string &, int)> &visit) {
+ if (!data || data.length < 88) return false;
+ const uint8_t *file = (const uint8_t *)data.bytes;
+ size_t length = data.length;
+ if (memcmp(file, "MTLB", 4) != 0) return false;
+ uint64_t listAt = 0;
+ memcpy(&listAt, file + 24, 8);
+ if (listAt > length - 4) return false;
+ uint32_t count = 0;
+ memcpy(&count, file + listAt, 4);
+ size_t at = listAt + 4;
+ for (uint32_t i = 0; i < count; i++) {
+ uint32_t size = 0;
+ if (at > length - 4) return false;
+ memcpy(&size, file + at, 4);
+ if (size < 8 || size > length - at) return false;
+ size_t end = at + size;
+ std::string entry;
+ int type = -1;
+ for (size_t t = at + 4; t + 4 <= end && memcmp(file + t, "ENDT", 4) != 0;) {
+ if (t + 6 > end) return false;
+ uint16_t n = 0;
+ memcpy(&n, file + t + 4, 2);
+ const uint8_t *v = file + t + 6;
+ if (n > end - (t + 6)) return false;
+ if (!memcmp(file + t, "NAME", 4)) entry.assign((const char *)v, strnlen((const char *)v, n));
+ else if (!memcmp(file + t, "TYPE", 4) && n >= 1) type = v[0];
+ t += 6 + n;
+ }
+ if (!visit(entry, type)) return true;
+ at = end;
+ }
+ return true;
+}
+
+static NSData *xcmExtractFunctionBitcode(XcmFunction *fn) {
+ if (!fn || !fn->_library || !fn->_library->_metallibData) return nil;
+ NSData *data = fn->_library->_metallibData;
+ const uint8_t *file = (const uint8_t *)data.bytes;
+ size_t length = data.length;
+ const char *wanted = (fn->_sourceName ?: fn->_name).UTF8String;
+ if (!file || !wanted || length < 88 || memcmp(file, "MTLB", 4) != 0) return nil;
+ uint64_t listAt = 0, bitcodeAt = 0, bitcodeSize = 0;
+ memcpy(&listAt, file + 24, 8);
+ memcpy(&bitcodeAt, file + 72, 8);
+ memcpy(&bitcodeSize, file + 80, 8);
+ if (listAt > length - 4 || bitcodeAt > length || bitcodeSize > length - bitcodeAt) return nil;
+ uint32_t count = 0;
+ memcpy(&count, file + listAt, 4);
+ size_t at = listAt + 4;
+ for (uint32_t i = 0; i < count; i++) {
+ uint32_t size = 0;
+ if (at > length - 4) return nil;
+ memcpy(&size, file + at, 4);
+ if (size < 8 || size > length - at) return nil;
+ size_t end = at + size;
+ std::string name;
+ uint64_t bytes = 0, offset = 0;
+ bool sized = false, placed = false;
+ for (size_t t = at + 4; t + 4 <= end && memcmp(file + t, "ENDT", 4) != 0;) {
+ if (t + 6 > end) return nil;
+ uint16_t n = 0;
+ memcpy(&n, file + t + 4, 2);
+ const uint8_t *v = file + t + 6;
+ if (n > end - (t + 6)) return nil;
+ if (!memcmp(file + t, "NAME", 4)) name.assign((const char *)v, strnlen((const char *)v, n));
+ else if (!memcmp(file + t, "MDSZ", 4) && n >= 8) { memcpy(&bytes, v, 8); sized = true; }
+ else if (!memcmp(file + t, "OFFT", 4) && n >= 24) { memcpy(&offset, v + 16, 8); placed = true; }
+ t += 6 + n;
+ }
+ if (name == wanted) {
+ if (!sized || !placed || offset > bitcodeSize || bytes > bitcodeSize - offset) return nil;
+ return [NSData dataWithBytes:file + bitcodeAt + offset length:(NSUInteger)bytes];
+ }
+ at = end;
+ }
+ return nil;
+}
+
+static XcmFunction *xcmLookupCIKernelFunction(XcmLibrary *lib, NSString *name) {
+ if (!lib || !lib->_metallibData || !name || lib->_metallibData.length < 88) return nil;
+ const uint8_t *file = (const uint8_t *)lib->_metallibData.bytes;
+ if (file[10] != 1) return nil; // file_type 1 = CoreImage / dynamic kernel library
+ const char *wanted = name.UTF8String;
+ if (!wanted) return nil;
+ XcmFunction *found = nil;
+ xcmForEachMetallibEntry(lib->_metallibData, [&](const std::string &entry, int type) {
+ if (entry != wanted) return true;
+ if (type == 5) {
+ found = [[XcmFunction alloc] initWithHandle:nullptr device:lib->_device library:lib name:name type:(MTLFunctionType)4];
+ }
+ return false;
+ });
+ return found;
+}
+
+@implementation XcmLibrary
+- (instancetype)initWithHandle:(Xm2vLibrary *)h device:(id)dev data:(NSData *)data {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _metallibData = data;
+ }
+ return self;
+}
+- (void)dealloc {
+ if (_handle) { xm2v_library_release(_handle); _handle = nullptr; }
+}
+- (id<MTLDevice>)device { return _device; }
+- (MTLLibraryType)type { return MTLLibraryTypeExecutable; }
+- (NSString *)installName { return nil; }
+- (NSArray<NSString *> *)functionNames {
+ NSMutableArray<NSString *> *arr = [NSMutableArray array];
+ if (!_handle) return arr;
+ size_t count = xm2v_library_function_count(_handle);
+ char buf[512];
+ for (size_t i = 0; i < count; i++) {
+ size_t len = xm2v_library_function_name_at(_handle, i, buf, sizeof(buf));
+ if (len > 0) [arr addObject:[NSString stringWithUTF8String:buf]];
+ }
+ return arr;
+}
+- (NSArray<NSString *> *)externFunctionNames {
+ NSMutableArray<NSString *> *arr = [NSMutableArray array];
+ if (_handle) {
+ size_t count = xm2v_library_extern_function_count(_handle);
+ char buf[512];
+ for (size_t i = 0; i < count; i++) {
+ size_t len = xm2v_library_extern_function_name_at(_handle, i, buf, sizeof(buf));
+ if (len > 0) [arr addObject:[NSString stringWithUTF8String:buf]];
+ }
+ }
+ if (arr.count == 0 && _metallibData) {
+ xcmForEachMetallibEntry(_metallibData, [&](const std::string &entry, int type) {
+ if (type == 5 && !entry.empty()) [arr addObject:@(entry.c_str())];
+ return true;
+ });
+ }
+ return arr;
+}
+- (id<MTLFunction>)newFunctionWithName:(NSString *)functionName {
+ if (!functionName) return nil;
+ if (XcmFunction *ciFn = xcmLookupCIKernelFunction(self, functionName))
+ return (id<MTLFunction>)ciFn;
+ if (!_handle) return nil;
+ Xm2vFunction *fn = xm2v_library_new_function(_handle, functionName.UTF8String);
+ if (!fn) fn = xm2v_library_new_extern_function(_handle, functionName.UTF8String);
+ if (!fn) return nil;
+ return (id<MTLFunction>)[[XcmFunction alloc] initWithHandle:fn device:_device library:self name:functionName type:MTLFunctionTypeKernel];
+}
+static void xcmExtractConstants(MTLFunctionConstantValues *constantValues,
+ std::vector<Xm2vConstant> &constants,
+ std::deque<std::string> &nameStorage,
+ std::deque<std::vector<uint8_t>> &byteStorage) {
+ if (!constantValues) return;
+ MTLFunctionConstantValues *snap = [constantValues copy];
+ NSArray *indexed = [snap respondsToSelector:@selector(newIndexedConstantArray)] ? [snap newIndexedConstantArray] : nil;
+ NSArray *named = [snap respondsToSelector:@selector(newNamedConstantArray)] ? [snap newNamedConstantArray] : nil;
+ for (int grp = 0; grp < 2; grp++) {
+ for (id<XcmPrivateConstantValue> v in (grp ? named : indexed)) {
+ uint64_t dt = v.dataType;
+ uint64_t sz = xcmConstantBytes(dt);
+ void *ptr = v.data;
+ if (!sz || !ptr) continue;
+ byteStorage.emplace_back((const uint8_t *)ptr, (const uint8_t *)ptr + (size_t)sz);
+ Xm2vConstant c = {};
+ c.data_type = dt;
+ if (grp == 0) {
+ c.index = (uint32_t)v.index;
+ c.name = nullptr;
+ } else {
+ nameStorage.emplace_back(v.name.UTF8String ?: "");
+ c.name = nameStorage.back().c_str();
+ }
+ c.bytes = byteStorage.back().data();
+ c.length = (size_t)sz;
+ constants.push_back(c);
+ }
+ }
+}
+
+- (id<MTLFunction>)newFunctionWithName:(NSString *)name
+ constantValues:(MTLFunctionConstantValues *)constantValues
+ error:(NSError **)error {
+ if (!name) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFunctionNotFound, "Nil function name");
+ return nil;
+ }
+ if (XcmFunction *ciFn = xcmLookupCIKernelFunction(self, name)) {
+ if (error) *error = nil;
+ return (id<MTLFunction>)ciFn;
+ }
+ if (!_handle) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Null library");
+ return nil;
+ }
+ std::vector<Xm2vConstant> constants;
+ std::deque<std::string> nameStorage;
+ std::deque<std::vector<uint8_t>> byteStorage;
+ xcmExtractConstants(constantValues, constants, nameStorage, byteStorage);
+ Xm2vFunction *fn = constants.empty()
+ ? xm2v_library_new_function(_handle, name.UTF8String)
+ : xm2v_library_new_function_specialized(_handle, name.UTF8String, constants.data(), (uint32_t)constants.size());
+ if (!fn) fn = xm2v_library_new_extern_function(_handle, name.UTF8String);
+ if (!fn) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFunctionNotFound, "Function not found");
+ return nil;
+ }
+ if (error) *error = nil;
+ XcmFunction *out = [[XcmFunction alloc] initWithHandle:fn device:_device library:self name:name type:MTLFunctionTypeKernel];
+ if (constantValues) out->_constantValues = [constantValues copy];
+ return (id<MTLFunction>)out;
+}
+- (void)newFunctionWithName:(NSString *)name
+ constantValues:(MTLFunctionConstantValues *)constantValues
+ completionHandler:(void (^)(id<MTLFunction>, NSError *))completionHandler {
+ NSError *err = nil;
+ id<MTLFunction> fn = [self newFunctionWithName:name constantValues:constantValues error:&err];
+ if (completionHandler) completionHandler(fn, err);
+}
+- (id<MTLFunction>)newFunctionWithDescriptor:(MTLFunctionDescriptor *)d error:(NSError **)error {
+ if (!d || !d.name) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFunctionNotFound, "Missing function name");
+ return nil;
+ }
+ if (XcmFunction *ciFn = xcmLookupCIKernelFunction(self, d.name)) {
+ if (d.specializedName) ciFn->_name = [d.specializedName copy];
+ if (error) *error = nil;
+ return (id<MTLFunction>)ciFn;
+ }
+ if (!_handle) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Null library");
+ return nil;
+ }
+ std::vector<Xm2vConstant> constants;
+ std::deque<std::string> nameStorage;
+ std::deque<std::vector<uint8_t>> byteStorage;
+ xcmExtractConstants(d.constantValues, constants, nameStorage, byteStorage);
+ Xm2vFunction *fn = xm2v_library_new_function_with_descriptor(
+ _handle,
+ d.name.UTF8String,
+ d.specializedName ? d.specializedName.UTF8String : nullptr,
+ constants.empty() ? nullptr : constants.data(),
+ (uint32_t)constants.size(),
+ (uint64_t)d.options);
+ if (!fn) fn = xm2v_library_new_extern_function(_handle, d.name.UTF8String);
+ if (!fn) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFunctionNotFound, "Function not found");
+ return nil;
+ }
+ if (error) *error = nil;
+ XcmFunction *out = [[XcmFunction alloc] initWithHandle:fn device:_device library:self name:d.name type:MTLFunctionTypeKernel];
+ if (d.specializedName) out->_name = [d.specializedName copy];
+ if (d.constantValues) out->_constantValues = [d.constantValues copy];
+ return (id<MTLFunction>)out;
+}
+- (void)newFunctionWithDescriptor:(MTLFunctionDescriptor *)d
+ completionHandler:(void (^)(id<MTLFunction>, NSError *))completionHandler {
+ NSError *err = nil;
+ id<MTLFunction> fn = [self newFunctionWithDescriptor:d error:&err];
+ if (completionHandler) completionHandler(fn, err);
+}
+@end
+
+/* ======================== Pipelines & States ======================== */
+
+@interface XcmComputePipeline : XcmObject {
+@public
+ Xm2vComputePipeline *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vComputePipeline *)h device:(id)dev;
+@end
+
+@implementation XcmComputePipeline
+- (instancetype)initWithHandle:(Xm2vComputePipeline *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_compute_pipeline_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+- (NSUInteger)maxTotalThreadsPerThreadgroup { return _handle ? (NSUInteger)xm2v_compute_pipeline_max_threads(_handle) : 64; }
+- (NSUInteger)threadExecutionWidth { return _handle ? (NSUInteger)xm2v_compute_pipeline_thread_width(_handle) : 4; }
+- (NSUInteger)staticThreadgroupMemoryLength { return _handle ? (NSUInteger)xm2v_compute_pipeline_static_tg_mem(_handle) : 0; }
+- (BOOL)supportIndirectCommandBuffers { return NO; }
+@end
+
+@interface XcmRenderPipeline : XcmObject {
+@public
+ Xm2vRenderPipeline *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vRenderPipeline *)h device:(id)dev;
+@end
+
+@implementation XcmRenderPipeline
+- (instancetype)initWithHandle:(Xm2vRenderPipeline *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_render_pipeline_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+- (BOOL)supportIndirectCommandBuffers { return NO; }
+@end
+
+@interface XcmSampler : XcmObject {
+@public
+ Xm2vSampler *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vSampler *)h device:(id)dev;
+@end
+@implementation XcmSampler
+- (instancetype)initWithHandle:(Xm2vSampler *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_sampler_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+@end
+
+@interface XcmDepthStencil : XcmObject {
+@public
+ Xm2vDepthStencil *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vDepthStencil *)h device:(id)dev;
+@end
+@implementation XcmDepthStencil
+- (instancetype)initWithHandle:(Xm2vDepthStencil *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_depth_stencil_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+@end
+
+@interface XcmEvent : XcmObject {
+@public
+ Xm2vEvent *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vEvent *)h device:(id)dev;
+@end
+@implementation XcmEvent
+- (instancetype)initWithHandle:(Xm2vEvent *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_event_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+@end
+
+@interface XcmFence : XcmObject {
+@public
+ Xm2vFence *_handle;
+ id _device;
+}
+- (instancetype)initWithHandle:(Xm2vFence *)h device:(id)dev;
+@end
+@implementation XcmFence
+- (instancetype)initWithHandle:(Xm2vFence *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_fence_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+@end
+
+@interface XcmHeap : XcmObject {
+@public
+ id _device;
+ NSUInteger _size;
+ MTLStorageMode _storageMode;
+ MTLCPUCacheMode _cpuCacheMode;
+ MTLHazardTrackingMode _hazardTrackingMode;
+ MTLHeapType _type;
+ MTLPurgeableState _purgeable;
+}
+- (instancetype)initWithDevice:(id)dev descriptor:(MTLHeapDescriptor *)desc;
+@end
+
+@implementation XcmHeap
+- (instancetype)initWithDevice:(id)dev descriptor:(MTLHeapDescriptor *)desc {
+ if ((self = [super init])) {
+ _device = dev;
+ _size = desc.size;
+ _storageMode = desc.storageMode;
+ _cpuCacheMode = desc.cpuCacheMode;
+ _hazardTrackingMode = desc.hazardTrackingMode;
+ _type = desc.type;
+ _purgeable = MTLPurgeableStateNonVolatile;
+ }
+ return self;
+}
+- (id<MTLDevice>)device { return _device; }
+- (NSUInteger)size { return _size; }
+- (NSUInteger)usedSize { return 0; }
+- (NSUInteger)currentAllocatedSize { return _size; }
+- (MTLStorageMode)storageMode { return _storageMode; }
+- (MTLCPUCacheMode)cpuCacheMode { return _cpuCacheMode; }
+- (MTLHazardTrackingMode)hazardTrackingMode { return _hazardTrackingMode; }
+- (MTLResourceOptions)resourceOptions {
+ return ((MTLResourceOptions)_storageMode << MTLResourceStorageModeShift) |
+ ((MTLResourceOptions)_cpuCacheMode << MTLResourceCPUCacheModeShift) |
+ ((MTLResourceOptions)_hazardTrackingMode << MTLResourceHazardTrackingModeShift);
+}
+- (MTLHeapType)type { return _type; }
+- (NSUInteger)protectionOptions { return 0; }
+- (NSUInteger)maxAvailableSizeWithAlignment:(NSUInteger)alignment { (void)alignment; return _size; }
+- (MTLPurgeableState)setPurgeableState:(MTLPurgeableState)state {
+ MTLPurgeableState prev = _purgeable;
+ if (state != MTLPurgeableStateKeepCurrent) _purgeable = state;
+ return prev;
+}
+- (id<MTLBuffer>)newBufferWithLength:(NSUInteger)length options:(MTLResourceOptions)options {
+ return [_device newBufferWithLength:length options:options];
+}
+- (id<MTLBuffer>)newBufferWithLength:(NSUInteger)length options:(MTLResourceOptions)options offset:(NSUInteger)offset {
+ (void)offset;
+ return [_device newBufferWithLength:length options:options];
+}
+- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)desc {
+ return [_device newTextureWithDescriptor:desc];
+}
+- (id<MTLTexture>)newTextureWithDescriptor:(MTLTextureDescriptor *)desc offset:(NSUInteger)offset {
+ (void)offset;
+ return [_device newTextureWithDescriptor:desc];
+}
+@end
+
+/* ======================== Forward declaration for CommandBuffer ======================== */
+
+@interface XcmCommandBuffer : XcmObject {
+@public
+ Xm2vCommandBuffer *_handle;
+ id _device;
+ id _queue;
+ NSMutableArray<MTLCommandBufferHandler> *_scheduledHandlers;
+ NSMutableArray<MTLCommandBufferHandler> *_completedHandlers;
+ NSMutableArray<XcmTexture *> *_dirtyIOSurfaceTextures;
+ BOOL _handlersFired;
+ BOOL _iosurfaceFlushed;
+ NSUInteger _protectionOptions;
+}
+- (instancetype)initWithHandle:(Xm2vCommandBuffer *)h device:(id)dev queue:(id)q;
+- (void)markDirtyIOSurfaceTexture:(XcmTexture *)tex;
+@end
+
+/* ======================== Encoders ======================== */
+
+@interface XcmComputeEncoder : XcmObject {
+@public
+ Xm2vComputeEncoder *_handle;
+ id _device;
+ XcmCommandBuffer *_cmdBuf;
+ NSMutableArray *_retained;
+ id _boundBuffers[31];
+}
+- (instancetype)initWithHandle:(Xm2vComputeEncoder *)h device:(id)dev commandBuffer:(XcmCommandBuffer *)cb;
+@end
+
+@implementation XcmComputeEncoder
+- (instancetype)initWithHandle:(Xm2vComputeEncoder *)h device:(id)dev commandBuffer:(XcmCommandBuffer *)cb {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _cmdBuf = cb;
+ _retained = [NSMutableArray array];
+ }
+ return self;
+}
+- (void)dealloc {
+ if (_handle) { xm2v_compute_encoder_end(_handle); _handle = nullptr; }
+}
+- (id<MTLDevice>)device { return _device; }
+- (void)setComputePipelineState:(id<MTLComputePipelineState>)state {
+ if (!_handle || !state) return;
+ [_retained addObject:state];
+ xm2v_compute_encoder_set_pipeline(_handle, ((XcmComputePipeline *)state)->_handle);
+}
+- (void)setBuffer:(id<MTLBuffer>)buffer offset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (index < 31) _boundBuffers[index] = buffer;
+ if (buffer) [_retained addObject:buffer];
+ Xm2vBuffer *bh = buffer ? ((XcmBuffer *)buffer)->_handle : nullptr;
+ xm2v_compute_encoder_set_buffer(_handle, bh, offset, (uint32_t)index);
+}
+- (void)setBuffers:(const id<MTLBuffer> *)buffers offsets:(const NSUInteger *)offsets withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++)
+ [self setBuffer:buffers[i] offset:offsets[i] atIndex:range.location + i];
+}
+- (void)setBufferOffset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ if (index < 31 && _boundBuffers[index])
+ [self setBuffer:_boundBuffers[index] offset:offset atIndex:index];
+}
+- (void)setBytes:(const void *)bytes length:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (_handle) xm2v_compute_encoder_set_bytes(_handle, bytes, length, (uint32_t)index);
+}
+- (void)setTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (texture && [texture isKindOfClass:[XcmTexture class]]) {
+ XcmTexture *xt = (XcmTexture *)texture;
+ [_retained addObject:xt];
+ [xt syncFromIOSurfaceIfNeeded];
+ if (xt->_iosurface && (xt->_usage & MTLTextureUsageShaderWrite))
+ [_cmdBuf markDirtyIOSurfaceTexture:xt];
+ }
+ Xm2vTexture *th = texture ? ((XcmTexture *)texture)->_handle : nullptr;
+ xm2v_compute_encoder_set_texture(_handle, th, (uint32_t)index);
+}
+- (void)setTextures:(const id<MTLTexture> *)textures withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++)
+ [self setTexture:textures[i] atIndex:range.location + i];
+}
+- (void)setSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (sampler) [_retained addObject:sampler];
+ Xm2vSampler *sh = sampler ? ((XcmSampler *)sampler)->_handle : nullptr;
+ xm2v_compute_encoder_set_sampler(_handle, sh, (uint32_t)index);
+}
+- (void)setSamplerStates:(const id<MTLSamplerState> *)samplers withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++)
+ [self setSamplerState:samplers[i] atIndex:range.location + i];
+}
+- (void)setThreadgroupMemoryLength:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (_handle) xm2v_compute_encoder_set_threadgroup_memory_length(_handle, (uint32_t)length, (uint32_t)index);
+}
+- (void)dispatchThreadgroups:(MTLSize)threadgroupsPerGrid threadsPerThreadgroup:(MTLSize)threadsPerThreadgroup {
+ if (_handle) {
+ xm2v_compute_encoder_dispatch_threadgroups(_handle,
+ threadgroupsPerGrid.width, threadgroupsPerGrid.height, threadgroupsPerGrid.depth,
+ threadsPerThreadgroup.width, threadsPerThreadgroup.height, threadsPerThreadgroup.depth);
+ }
+}
+- (void)dispatchThreads:(MTLSize)threadsPerGrid threadsPerThreadgroup:(MTLSize)threadsPerThreadgroup {
+ if (_handle) {
+ xm2v_compute_encoder_dispatch_threads(_handle,
+ threadsPerGrid.width, threadsPerGrid.height, threadsPerGrid.depth,
+ threadsPerThreadgroup.width, threadsPerThreadgroup.height, threadsPerThreadgroup.depth);
+ }
+}
+- (void)endEncoding {
+ if (_handle) { xm2v_compute_encoder_end(_handle); _handle = nullptr; }
+ [_retained removeAllObjects];
+}
+- (void)pushDebugGroup:(NSString *)string { (void)string; }
+- (void)popDebugGroup {}
+- (void)insertDebugSignpost:(NSString *)string { (void)string; }
+@end
+
+@interface XcmRenderEncoder : XcmObject {
+@public
+ Xm2vRenderEncoder *_handle;
+ id _device;
+ NSMutableArray *_retained;
+ NSMutableDictionary *_vbufs, *_fbufs; // slot -> bound buffer (for set*BufferOffset:atIndex:)
+ BOOL _hasPipeline;
+}
+- (instancetype)initWithHandle:(Xm2vRenderEncoder *)h device:(id)dev;
+@end
+
+@implementation XcmRenderEncoder
+- (instancetype)initWithHandle:(Xm2vRenderEncoder *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; _retained = [NSMutableArray array]; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_render_encoder_end(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+- (void)setRenderPipelineState:(id<MTLRenderPipelineState>)pipelineState {
+ if (!_handle) return;
+ if (!pipelineState || ![pipelineState isKindOfClass:[XcmRenderPipeline class]] || !((XcmRenderPipeline *)pipelineState)->_handle) {
+ _hasPipeline = NO;
+ return;
+ }
+ _hasPipeline = YES;
+ [_retained addObject:pipelineState];
+ bool ok = xm2v_render_encoder_set_pipeline(_handle, ((XcmRenderPipeline *)pipelineState)->_handle);
+ if (!ok) fprintf(stderr, "XCM setRenderPipelineState FAILED: %s\n", xm2v_last_error());
+}
+- (void)setDepthStencilState:(id<MTLDepthStencilState>)depthStencilState {
+ if (!_handle) return;
+ if (depthStencilState) [_retained addObject:depthStencilState];
+ Xm2vDepthStencil *h = depthStencilState ? ((XcmDepthStencil *)depthStencilState)->_handle : nullptr;
+ xm2v_render_encoder_set_depth_stencil(_handle, h);
+}
+- (void)setViewport:(MTLViewport)vp {
+ if (_handle) xm2v_render_encoder_set_viewport(_handle, vp.originX, vp.originY, vp.width, vp.height, vp.znear, vp.zfar);
+}
+- (void)setScissorRect:(MTLScissorRect)r {
+ if (_handle) xm2v_render_encoder_set_scissor(_handle, r.x, r.y, r.width, r.height);
+}
+- (void)setCullMode:(MTLCullMode)cullMode {
+ if (_handle) xm2v_render_encoder_set_cull_mode(_handle, (uint64_t)cullMode);
+}
+- (void)setFrontFacingWinding:(MTLWinding)winding {
+ if (_handle) xm2v_render_encoder_set_front_facing_winding(_handle, (uint64_t)winding);
+}
+- (void)setVertexBuffer:(id<MTLBuffer>)buffer offset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (!_vbufs) _vbufs = [NSMutableDictionary dictionary];
+ if (buffer) _vbufs[@(index)] = buffer; else [_vbufs removeObjectForKey:@(index)];
+ if (buffer) [_retained addObject:buffer];
+ xm2v_render_encoder_set_vertex_buffer(_handle, buffer ? ((XcmBuffer *)buffer)->_handle : nullptr, offset, (uint32_t)index);
+}
+- (void)setVertexBytes:(const void *)bytes length:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (_handle) xm2v_render_encoder_set_vertex_bytes(_handle, bytes, length, (uint32_t)index);
+}
+- (void)setVertexTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (texture && [texture isKindOfClass:[XcmTexture class]]) {
+ [_retained addObject:texture];
+ [(XcmTexture *)texture syncFromIOSurfaceIfNeeded];
+ }
+ xm2v_render_encoder_set_vertex_texture(_handle, texture ? ((XcmTexture *)texture)->_handle : nullptr, (uint32_t)index);
+}
+- (void)setVertexSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (sampler) [_retained addObject:sampler];
+ xm2v_render_encoder_set_vertex_sampler(_handle, sampler ? ((XcmSampler *)sampler)->_handle : nullptr, (uint32_t)index);
+}
+- (void)setFragmentBuffer:(id<MTLBuffer>)buffer offset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (!_fbufs) _fbufs = [NSMutableDictionary dictionary];
+ if (buffer) _fbufs[@(index)] = buffer; else [_fbufs removeObjectForKey:@(index)];
+ if (buffer) [_retained addObject:buffer];
+ xm2v_render_encoder_set_fragment_buffer(_handle, buffer ? ((XcmBuffer *)buffer)->_handle : nullptr, offset, (uint32_t)index);
+}
+- (void)setFragmentBytes:(const void *)bytes length:(NSUInteger)length atIndex:(NSUInteger)index {
+ if (_handle) xm2v_render_encoder_set_fragment_bytes(_handle, bytes, length, (uint32_t)index);
+}
+- (void)setFragmentTexture:(id<MTLTexture>)texture atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (texture && [texture isKindOfClass:[XcmTexture class]]) {
+ [_retained addObject:texture];
+ [(XcmTexture *)texture syncFromIOSurfaceIfNeeded];
+ }
+ xm2v_render_encoder_set_fragment_texture(_handle, texture ? ((XcmTexture *)texture)->_handle : nullptr, (uint32_t)index);
+}
+- (void)setFragmentTextures:(const id<MTLTexture> *)textures withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++)
+ [self setFragmentTexture:textures[i] atIndex:range.location + i];
+}
+- (void)setFragmentSamplerState:(id<MTLSamplerState>)sampler atIndex:(NSUInteger)index {
+ if (!_handle) return;
+ if (sampler) [_retained addObject:sampler];
+ xm2v_render_encoder_set_fragment_sampler(_handle, sampler ? ((XcmSampler *)sampler)->_handle : nullptr, (uint32_t)index);
+}
+- (void)setFragmentSamplerStates:(const id<MTLSamplerState> *)samplers withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++)
+ [self setFragmentSamplerState:samplers[i] atIndex:range.location + i];
+}
+- (void)setVertexBufferOffset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ id b = _vbufs[@(index)]; if (b) [self setVertexBuffer:b offset:offset atIndex:index];
+}
+- (void)setFragmentBufferOffset:(NSUInteger)offset atIndex:(NSUInteger)index {
+ id b = _fbufs[@(index)]; if (b) [self setFragmentBuffer:b offset:offset atIndex:index];
+}
+- (void)setVertexBuffers:(const id<MTLBuffer> *)buffers offsets:(const NSUInteger *)offsets withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++) [self setVertexBuffer:buffers[i] offset:offsets[i] atIndex:range.location + i];
+}
+- (void)setFragmentBuffers:(const id<MTLBuffer> *)buffers offsets:(const NSUInteger *)offsets withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++) [self setFragmentBuffer:buffers[i] offset:offsets[i] atIndex:range.location + i];
+}
+- (void)setVertexTextures:(const id<MTLTexture> *)textures withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++) [self setVertexTexture:textures[i] atIndex:range.location + i];
+}
+- (void)setVertexSamplerStates:(const id<MTLSamplerState> *)samplers withRange:(NSRange)range {
+ for (NSUInteger i = 0; i < range.length; i++) [self setVertexSamplerState:samplers[i] atIndex:range.location + i];
+}
+- (void)setViewports:(const MTLViewport *)viewports count:(NSUInteger)count { if (count) [self setViewport:viewports[0]]; }
+- (void)setScissorRects:(const MTLScissorRect *)rects count:(NSUInteger)count { if (count) [self setScissorRect:rects[0]]; }
+// State the CPU backend keeps at its defaults (fill, clip, bias, blend constant, stencil reference) and residency hints.
+- (void)setTriangleFillMode:(MTLTriangleFillMode)mode { (void)mode; }
+- (void)setDepthClipMode:(MTLDepthClipMode)mode { (void)mode; }
+- (void)setDepthBias:(float)b slopeScale:(float)s clamp:(float)c { (void)b; (void)s; (void)c; }
+- (void)setBlendColorRed:(float)r green:(float)g blue:(float)b alpha:(float)a {
+ if (_handle) xm2v_render_encoder_set_blend_color(_handle, r, g, b, a);
+}
+- (void)setStencilReferenceValue:(uint32_t)v {
+ if (_handle) xm2v_render_encoder_set_stencil_reference_values(_handle, v, v);
+}
+- (void)setStencilFrontReferenceValue:(uint32_t)f backReferenceValue:(uint32_t)b {
+ if (_handle) xm2v_render_encoder_set_stencil_reference_values(_handle, f, b);
+}
+- (void)setVisibilityResultMode:(MTLVisibilityResultMode)mode offset:(NSUInteger)offset { (void)mode; (void)offset; }
+- (void)useResource:(id<MTLResource>)r usage:(MTLResourceUsage)u { (void)r; (void)u; }
+- (void)useResource:(id<MTLResource>)r usage:(MTLResourceUsage)u stages:(MTLRenderStages)st { (void)r; (void)u; (void)st; }
+- (void)useResources:(const id<MTLResource> *)r count:(NSUInteger)n usage:(MTLResourceUsage)u { (void)r; (void)n; (void)u; }
+- (void)useHeap:(id<MTLHeap>)h { (void)h; }
+- (void)textureBarrier {}
+- (void)memoryBarrierWithScope:(MTLBarrierScope)scope afterStages:(MTLRenderStages)after beforeStages:(MTLRenderStages)before {
+ (void)scope; (void)after; (void)before;
+}
+- (void)memoryBarrierWithResources:(const id<MTLResource> *)resources count:(NSUInteger)count afterStages:(MTLRenderStages)after beforeStages:(MTLRenderStages)before {
+ (void)resources; (void)count; (void)after; (void)before;
+}
+- (void)drawPrimitives:(MTLPrimitiveType)primitiveType vertexStart:(NSUInteger)vertexStart
+ vertexCount:(NSUInteger)vertexCount instanceCount:(NSUInteger)instanceCount
+ baseInstance:(NSUInteger)baseInstance {
+ if (_handle && _hasPipeline) {
+ bool ok = xm2v_render_encoder_draw_primitives(_handle, (uint64_t)primitiveType, vertexStart, vertexCount, instanceCount, baseInstance);
+ if (!ok) fprintf(stderr, "XCM drawPrimitives FAILED: %s\n", xm2v_last_error());
+ }
+}
+- (void)drawPrimitives:(MTLPrimitiveType)primitiveType vertexStart:(NSUInteger)vertexStart vertexCount:(NSUInteger)vertexCount {
+ [self drawPrimitives:primitiveType vertexStart:vertexStart vertexCount:vertexCount instanceCount:1 baseInstance:0];
+}
+- (void)drawIndexedPrimitives:(MTLPrimitiveType)primitiveType indexCount:(NSUInteger)indexCount
+ indexType:(MTLIndexType)indexType indexBuffer:(id<MTLBuffer>)indexBuffer
+ indexBufferOffset:(NSUInteger)indexBufferOffset instanceCount:(NSUInteger)instanceCount
+ baseVertex:(NSInteger)baseVertex baseInstance:(NSUInteger)baseInstance {
+ if (!_handle || !_hasPipeline || !indexBuffer) return;
+ [_retained addObject:indexBuffer];
+ bool ok = xm2v_render_encoder_draw_indexed_primitives(_handle, (uint64_t)primitiveType, indexCount, (uint64_t)indexType,
+ ((XcmBuffer *)indexBuffer)->_handle, indexBufferOffset, instanceCount, baseVertex, baseInstance);
+ if (!ok) fprintf(stderr, "XCM drawIndexedPrimitives FAILED: %s\n", xm2v_last_error());
+}
+- (void)drawIndexedPrimitives:(MTLPrimitiveType)primitiveType indexCount:(NSUInteger)indexCount
+ indexType:(MTLIndexType)indexType indexBuffer:(id<MTLBuffer>)indexBuffer
+ indexBufferOffset:(NSUInteger)indexBufferOffset {
+ [self drawIndexedPrimitives:primitiveType indexCount:indexCount indexType:indexType
+ indexBuffer:indexBuffer indexBufferOffset:indexBufferOffset
+ instanceCount:1 baseVertex:0 baseInstance:0];
+}
+- (void)drawIndexedPrimitives:(MTLPrimitiveType)primitiveType indexCount:(NSUInteger)indexCount
+ indexType:(MTLIndexType)indexType indexBuffer:(id<MTLBuffer>)indexBuffer
+ indexBufferOffset:(NSUInteger)indexBufferOffset instanceCount:(NSUInteger)instanceCount {
+ [self drawIndexedPrimitives:primitiveType indexCount:indexCount indexType:indexType
+ indexBuffer:indexBuffer indexBufferOffset:indexBufferOffset
+ instanceCount:instanceCount baseVertex:0 baseInstance:0];
+}
+- (void)drawPrimitives:(MTLPrimitiveType)primitiveType vertexStart:(NSUInteger)vertexStart
+ vertexCount:(NSUInteger)vertexCount instanceCount:(NSUInteger)instanceCount {
+ [self drawPrimitives:primitiveType vertexStart:vertexStart vertexCount:vertexCount instanceCount:instanceCount baseInstance:0];
+}
+- (void)endEncoding {
+ if (_handle) { xm2v_render_encoder_end(_handle); _handle = nullptr; }
+ [_retained removeAllObjects];
+}
+- (void)pushDebugGroup:(NSString *)string { (void)string; }
+- (void)popDebugGroup {}
+- (void)insertDebugSignpost:(NSString *)string { (void)string; }
+@end
+
+@interface XcmBlitEncoder : XcmObject {
+@public
+ Xm2vBlitEncoder *_handle;
+ id _device;
+ XcmCommandBuffer *_cmdBuf;
+ NSMutableArray *_retained;
+}
+- (instancetype)initWithHandle:(Xm2vBlitEncoder *)h device:(id)dev commandBuffer:(XcmCommandBuffer *)cb;
+@end
+
+@implementation XcmBlitEncoder
+- (instancetype)initWithHandle:(Xm2vBlitEncoder *)h device:(id)dev commandBuffer:(XcmCommandBuffer *)cb {
+ if ((self = [super init])) { _handle = h; _device = dev; _cmdBuf = cb; _retained = [NSMutableArray array]; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_blit_encoder_end(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+- (void)copyFromBuffer:(id<MTLBuffer>)src sourceOffset:(NSUInteger)srcOff
+ toBuffer:(id<MTLBuffer>)dst destinationOffset:(NSUInteger)dstOff size:(NSUInteger)size {
+ if (!_handle || !src || !dst) return;
+ [_retained addObject:src]; [_retained addObject:dst];
+ xm2v_blit_encoder_copy_buffer_to_buffer(_handle, ((XcmBuffer *)src)->_handle, srcOff, ((XcmBuffer *)dst)->_handle, dstOff, size);
+}
+- (void)copyFromBuffer:(id<MTLBuffer>)src sourceOffset:(NSUInteger)srcOff
+ sourceBytesPerRow:(NSUInteger)bpr sourceBytesPerImage:(NSUInteger)bpi
+ sourceSize:(MTLSize)sz toTexture:(id<MTLTexture>)dst
+ destinationSlice:(NSUInteger)slice destinationLevel:(NSUInteger)level destinationOrigin:(MTLOrigin)origin {
+ if (!_handle || !src || !dst) return;
+ [_retained addObject:src]; [_retained addObject:dst];
+ if ([dst isKindOfClass:[XcmTexture class]] && ((XcmTexture *)dst)->_iosurface)
+ [_cmdBuf markDirtyIOSurfaceTexture:(XcmTexture *)dst];
+ xm2v_blit_encoder_copy_buffer_to_texture(_handle, ((XcmBuffer *)src)->_handle, srcOff, bpr, bpi,
+ sz.width, sz.height, sz.depth, ((XcmTexture *)dst)->_handle, slice, level, origin.x, origin.y, origin.z);
+}
+- (void)copyFromTexture:(id<MTLTexture>)src sourceSlice:(NSUInteger)slice sourceLevel:(NSUInteger)level
+ sourceOrigin:(MTLOrigin)origin sourceSize:(MTLSize)sz toBuffer:(id<MTLBuffer>)dst
+ destinationOffset:(NSUInteger)dstOff destinationBytesPerRow:(NSUInteger)bpr destinationBytesPerImage:(NSUInteger)bpi {
+ if (!_handle || !src || !dst) return;
+ [_retained addObject:src]; [_retained addObject:dst];
+ if ([src isKindOfClass:[XcmTexture class]]) [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
+ xm2v_blit_encoder_copy_texture_to_buffer(_handle, ((XcmTexture *)src)->_handle, slice, level,
+ origin.x, origin.y, origin.z, sz.width, sz.height, sz.depth, ((XcmBuffer *)dst)->_handle, dstOff, bpr, bpi);
+}
+- (void)copyFromTexture:(id<MTLTexture>)src sourceSlice:(NSUInteger)ss sourceLevel:(NSUInteger)sl
+ sourceOrigin:(MTLOrigin)so sourceSize:(MTLSize)sz toTexture:(id<MTLTexture>)dst
+ destinationSlice:(NSUInteger)ds destinationLevel:(NSUInteger)dl destinationOrigin:(MTLOrigin)do_ {
+ if (!_handle || !src || !dst) return;
+ [_retained addObject:src]; [_retained addObject:dst];
+ if ([src isKindOfClass:[XcmTexture class]]) [(XcmTexture *)src syncFromIOSurfaceIfNeeded];
+ if ([dst isKindOfClass:[XcmTexture class]] && ((XcmTexture *)dst)->_iosurface)
+ [_cmdBuf markDirtyIOSurfaceTexture:(XcmTexture *)dst];
+ xm2v_blit_encoder_copy_texture_to_texture(_handle, ((XcmTexture *)src)->_handle, ss, sl,
+ so.x, so.y, so.z, sz.width, sz.height, sz.depth, ((XcmTexture *)dst)->_handle, ds, dl, do_.x, do_.y, do_.z);
+}
+- (void)fillBuffer:(id<MTLBuffer>)buffer range:(NSRange)range value:(uint8_t)value {
+ if (!_handle || !buffer) return;
+ [_retained addObject:buffer];
+ xm2v_blit_encoder_fill_buffer(_handle, ((XcmBuffer *)buffer)->_handle, range.location, range.length, value);
+}
+- (void)generateMipmapsForTexture:(id<MTLTexture>)texture {
+ if (!_handle || !texture) return;
+ [_retained addObject:texture];
+ xm2v_blit_encoder_generate_mipmaps(_handle, ((XcmTexture *)texture)->_handle);
+}
+- (void)synchronizeResource:(id<MTLResource>)resource {
+ if (!_handle || !resource) return;
+ [_retained addObject:resource];
+ if ([resource isKindOfClass:[XcmBuffer class]])
+ xm2v_blit_encoder_synchronize_buffer(_handle, ((XcmBuffer *)resource)->_handle);
+ else if ([resource isKindOfClass:[XcmTexture class]])
+ xm2v_blit_encoder_synchronize_texture(_handle, ((XcmTexture *)resource)->_handle);
+}
+- (void)endEncoding {
+ if (_handle) { xm2v_blit_encoder_end(_handle); _handle = nullptr; }
+ [_retained removeAllObjects];
+}
+- (void)pushDebugGroup:(NSString *)string { (void)string; }
+- (void)popDebugGroup {}
+- (void)insertDebugSignpost:(NSString *)string { (void)string; }
+@end
+
+/* ======================== CommandBuffer & Queue ======================== */
+
+@implementation XcmCommandBuffer
+- (instancetype)initWithHandle:(Xm2vCommandBuffer *)h device:(id)dev queue:(id)q {
+ if ((self = [super init])) {
+ _handle = h;
+ _device = dev;
+ _queue = q;
+ _scheduledHandlers = [NSMutableArray array];
+ _completedHandlers = [NSMutableArray array];
+ _dirtyIOSurfaceTextures = [NSMutableArray array];
+ }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_command_buffer_release(_handle); _handle = nullptr; } }
+- (void)markDirtyIOSurfaceTexture:(XcmTexture *)tex {
+ if (tex && tex->_iosurface && ![_dirtyIOSurfaceTextures containsObject:tex]) {
+ [_dirtyIOSurfaceTextures addObject:tex];
+ xcmRecordIOSurfaceWriter(tex->_iosurface, self);
+ }
+}
+- (id<MTLDevice>)device { return _device; }
+- (id<MTLCommandQueue>)commandQueue { return _queue; }
+- (BOOL)retainedReferences { return YES; }
+- (NSUInteger)protectionOptions { return _protectionOptions; }
+- (void)setProtectionOptions:(NSUInteger)opts { _protectionOptions = opts; }
+- (CFTimeInterval)GPUStartTime { return 0.0; }
+- (CFTimeInterval)GPUEndTime { return 0.0; }
+- (CFTimeInterval)kernelStartTime { return 0.0; }
+- (CFTimeInterval)kernelEndTime { return 0.0; }
+- (MTLCommandBufferStatus)status {
+ return _handle ? (MTLCommandBufferStatus)xm2v_command_buffer_status(_handle) : MTLCommandBufferStatusError;
+}
+- (NSError *)error {
+ if (self.status == MTLCommandBufferStatusError)
+ return xcmError(MTLCommandBufferErrorDomain, MTLCommandBufferErrorInternal, "Command buffer failed");
+ return nil;
+}
+- (void)enqueue {}
+- (void)addScheduledHandler:(MTLCommandBufferHandler)block {
+ if (block) [_scheduledHandlers addObject:[block copy]];
+}
+- (void)addCompletedHandler:(MTLCommandBufferHandler)block {
+ if (block) [_completedHandlers addObject:[block copy]];
+}
+- (void)_flushIOSurfacesOnce {
+ @synchronized(self) {
+ if (_iosurfaceFlushed) return;
+ _iosurfaceFlushed = YES;
+ for (XcmTexture *tex in _dirtyIOSurfaceTextures) [tex syncToIOSurface];
+ [_dirtyIOSurfaceTextures removeAllObjects];
+ }
+}
+- (void)_fireHandlersOnce {
+ NSArray<MTLCommandBufferHandler> *sched = nil;
+ NSArray<MTLCommandBufferHandler> *comp = nil;
+ @synchronized(self) {
+ if (_handlersFired) return;
+ _handlersFired = YES;
+ sched = [_scheduledHandlers copy];
+ comp = [_completedHandlers copy];
+ [_scheduledHandlers removeAllObjects];
+ [_completedHandlers removeAllObjects];
+ }
+ for (MTLCommandBufferHandler h in sched) h((id<MTLCommandBuffer>)self);
+ for (MTLCommandBufferHandler h in comp) h((id<MTLCommandBuffer>)self);
+}
+- (void)commit {
+ if (xcmTraceOn()) fprintf(stderr, "XCM commit cb=%p sched=%lu comp=%lu dirty=%lu\n",
+ (__bridge void *)self, (unsigned long)_scheduledHandlers.count,
+ (unsigned long)_completedHandlers.count, (unsigned long)_dirtyIOSurfaceTextures.count);
+ if (_handle) {
+ bool ok = xm2v_command_buffer_commit(_handle);
+ if (!ok) fprintf(stderr, "XCM commit FAILED cb=%p err=%s\n", (__bridge void *)self, xm2v_last_error());
+ }
+ if (_scheduledHandlers.count || _completedHandlers.count || _dirtyIOSurfaceTextures.count) {
+ static dispatch_queue_t waitQ;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ waitQ = dispatch_queue_create("xcm.cb.wait", DISPATCH_QUEUE_CONCURRENT); });
+ dispatch_async(waitQ, ^{
+ if (_handle) {
+ bool wok = xm2v_command_buffer_wait_until_completed(_handle, 60000);
+ if (!wok) fprintf(stderr, "XCM wait FAILED cb=%p status=%u err=%s\n",
+ (__bridge void *)self, xm2v_command_buffer_status(_handle), xm2v_last_error());
+ }
+ [self _flushIOSurfacesOnce];
+ [self _fireHandlersOnce];
+ });
+ }
+}
+- (void)commitAndWaitUntilSubmitted {
+ [self commit];
+}
+- (void)waitUntilScheduled {
+ [self waitUntilCompleted];
+}
+- (void)waitUntilCompleted {
+ if (_handle) xm2v_command_buffer_wait_until_completed(_handle, 60000);
+ [self _flushIOSurfacesOnce];
+ [self _fireHandlersOnce];
+}
+- (id<MTLComputeCommandEncoder>)computeCommandEncoder {
+ if (!_handle) return nil;
+ Xm2vComputeEncoder *eh = xm2v_compute_encoder_new(_handle);
+ if (xcmTraceOn()) fprintf(stderr, "XCM computeCommandEncoder -> %p\n", (void *)eh);
+ return eh ? (id<MTLComputeCommandEncoder>)[[XcmComputeEncoder alloc] initWithHandle:eh device:_device commandBuffer:self] : nil;
+}
+- (id<MTLComputeCommandEncoder>)computeCommandEncoderWithDispatchType:(MTLDispatchType)dispatchType {
+ (void)dispatchType;
+ return [self computeCommandEncoder];
+}
+- (id<MTLRenderCommandEncoder>)renderCommandEncoderWithDescriptor:(MTLRenderPassDescriptor *)desc {
+ if (!_handle || !desc) return nil;
+ Xm2vRenderPassDesc rd = {};
+ rd.color_attachment_count = 8;
+ for (int i = 0; i < 8; i++) {
+ MTLRenderPassColorAttachmentDescriptor *ca = desc.colorAttachments[i];
+ if (ca && ca.texture && [ca.texture isKindOfClass:[XcmTexture class]]) {
+ XcmTexture *xt = (XcmTexture *)ca.texture;
+ if (ca.loadAction == MTLLoadActionLoad) [xt syncFromIOSurfaceIfNeeded];
+ if (xt->_iosurface && ca.storeAction != MTLStoreActionDontCare)
+ [self markDirtyIOSurfaceTexture:xt];
+ rd.color_attachments[i].texture = xt->_handle;
+ rd.color_attachments[i].level = ca.level;
+ rd.color_attachments[i].slice = ca.slice;
+ rd.color_attachments[i].load_action = (uint64_t)ca.loadAction;
+ rd.color_attachments[i].store_action = (uint64_t)ca.storeAction;
+ rd.color_attachments[i].clear_r = ca.clearColor.red;
+ rd.color_attachments[i].clear_g = ca.clearColor.green;
+ rd.color_attachments[i].clear_b = ca.clearColor.blue;
+ rd.color_attachments[i].clear_a = ca.clearColor.alpha;
+ }
+ }
+ if (desc.depthAttachment.texture && [desc.depthAttachment.texture isKindOfClass:[XcmTexture class]]) {
+ rd.depth_texture = ((XcmTexture *)desc.depthAttachment.texture)->_handle;
+ rd.depth_load_action = (uint64_t)desc.depthAttachment.loadAction;
+ rd.depth_store_action = (uint64_t)desc.depthAttachment.storeAction;
+ rd.clear_depth = desc.depthAttachment.clearDepth;
+ }
+ if (desc.stencilAttachment.texture && [desc.stencilAttachment.texture isKindOfClass:[XcmTexture class]]) {
+ rd.stencil_texture = ((XcmTexture *)desc.stencilAttachment.texture)->_handle;
+ rd.stencil_load_action = (uint64_t)desc.stencilAttachment.loadAction;
+ rd.stencil_store_action = (uint64_t)desc.stencilAttachment.storeAction;
+ rd.clear_stencil = desc.stencilAttachment.clearStencil;
+ }
+ Xm2vRenderEncoder *eh = xm2v_render_encoder_new(_handle, &rd);
+ if (xcmTraceOn()) fprintf(stderr, "XCM renderEncoder -> %p\n", (void *)eh);
+ return eh ? (id<MTLRenderCommandEncoder>)[[XcmRenderEncoder alloc] initWithHandle:eh device:_device] : nil;
+}
+- (id<MTLBlitCommandEncoder>)blitCommandEncoder {
+ if (!_handle) return nil;
+ Xm2vBlitEncoder *eh = xm2v_blit_encoder_new(_handle);
+ return eh ? (id<MTLBlitCommandEncoder>)[[XcmBlitEncoder alloc] initWithHandle:eh device:_device commandBuffer:self] : nil;
+}
+- (void)encodeSignalEvent:(id<MTLEvent>)event value:(uint64_t)value {
+ if (_handle && [event isKindOfClass:[XcmEvent class]])
+ xm2v_command_buffer_encode_signal_event(_handle, ((XcmEvent *)event)->_handle, value);
+}
+- (void)encodeWaitForEvent:(id<MTLEvent>)event value:(uint64_t)value {
+ if (_handle && [event isKindOfClass:[XcmEvent class]])
+ xm2v_command_buffer_encode_wait_event(_handle, ((XcmEvent *)event)->_handle, value);
+}
+- (void)pushDebugGroup:(NSString *)string { (void)string; }
+- (void)popDebugGroup {}
+@end
+
+@interface XcmQueue : XcmObject {
+@public
+ Xm2vQueue *_handle;
+ id _device;
+ NSUInteger _gpuPriority;
+ NSUInteger _bgGpuPriority;
+ dispatch_queue_t _submissionQueue;
+ dispatch_queue_t _completionQueue;
+}
+- (instancetype)initWithHandle:(Xm2vQueue *)h device:(id)dev;
+@end
+
+@implementation XcmQueue
+- (instancetype)initWithHandle:(Xm2vQueue *)h device:(id)dev {
+ if ((self = [super init])) { _handle = h; _device = dev; _gpuPriority = 1; _bgGpuPriority = 2; }
+ return self;
+}
+- (void)dealloc { if (_handle) { xm2v_queue_release(_handle); _handle = nullptr; } }
+- (id<MTLDevice>)device { return _device; }
+- (void)setSubmissionQueue:(dispatch_queue_t)q { _submissionQueue = q; }
+- (void)setCompletionQueue:(dispatch_queue_t)q { _completionQueue = q; }
+- (NSUInteger)getGPUPriority { return _gpuPriority; }
+- (NSUInteger)getBackgroundGPUPriority { return _bgGpuPriority; }
+- (BOOL)setGPUPriority:(NSUInteger)p { _gpuPriority = p; return YES; }
+- (BOOL)setGPUPriority:(NSUInteger)p offset:(unsigned short)o { (void)o; _gpuPriority = p; return YES; }
+- (BOOL)setBackgroundGPUPriority:(NSUInteger)p { _bgGpuPriority = p; return YES; }
+- (BOOL)setBackgroundGPUPriority:(NSUInteger)p offset:(unsigned short)o { (void)o; _bgGpuPriority = p; return YES; }
+- (BOOL)_setGPUPriority:(NSUInteger)p backgroundPriority:(NSUInteger)b { _gpuPriority = p; _bgGpuPriority = b; return YES; }
+- (id<MTLCommandBuffer>)commandBuffer {
+ if (!_handle) return nil;
+ Xm2vCommandBuffer *cb = xm2v_command_buffer_new(_handle);
+ return cb ? (id<MTLCommandBuffer>)[[XcmCommandBuffer alloc] initWithHandle:cb device:_device queue:self] : nil;
+}
+- (id<MTLCommandBuffer>)commandBufferWithUnretainedReferences { return [self commandBuffer]; }
+- (id<MTLCommandBuffer>)commandBufferWithDescriptor:(MTLCommandBufferDescriptor *)desc {
+ (void)desc;
+ return [self commandBuffer];
+}
+@end
+
+/* ======================== Dynamic _MTLDevice Subclass ======================== */
+
+static Xm2vDevice *gXm2vDevice = nullptr;
+static uint64_t gRegistryID = 0x584e554350550001ULL;
+static id gSingletonDevice = nil;
+
+static NSString *xcmDev_name(id, SEL) {
+ char buf[256] = {};
+ if (gXm2vDevice && xm2v_device_name(gXm2vDevice, buf, sizeof(buf)) > 0)
+ return [NSString stringWithFormat:@"XnuCpuMetal (%s)", buf];
+ return @"XnuCpuMetal (lavapipe)";
+}
+static uint64_t xcmDev_registryID(id, SEL) { return gRegistryID; }
+static BOOL xcmDev_isLowPower(id, SEL) { return YES; }
+static BOOL xcmDev_isHeadless(id, SEL) { return YES; }
+static BOOL xcmDev_isRemovable(id, SEL) { return NO; }
+static BOOL xcmDev_hasUnifiedMemory(id, SEL) { return YES; }
+static NSUInteger xcmDev_maxBufferLength(id, SEL) {
+ return gXm2vDevice ? (NSUInteger)xm2v_device_max_buffer_length(gXm2vDevice) : (256 * 1024 * 1024);
+}
+static MTLSize xcmDev_maxThreadsPerThreadgroup(id, SEL) {
+ uint64_t v[3] = {256, 256, 256};
+ if (gXm2vDevice) xm2v_device_max_threads_per_threadgroup(gXm2vDevice, v);
+ return MTLSizeMake((NSUInteger)v[0], (NSUInteger)v[1], (NSUInteger)v[2]);
+}
+static NSUInteger xcmDev_maxTex2D(id, SEL) { return 16384; }
+static NSUInteger xcmDev_maxTex3D(id, SEL) { return 2048; }
+static NSUInteger xcmDev_maxTexLayers(id, SEL) { return 2048; }
+static NSUInteger xcmDev_maxColorAtt(id, SEL) { return 8; }
+static NSUInteger xcmDev_maxTGMem(id, SEL) { return 32768; }
+static NSUInteger xcmDev_minLinearAlign(id, SEL, MTLPixelFormat) { return 64; }
+static NSUInteger xcmDev_minTileAlign(id, SEL, MTLPixelFormat) { return 64; }
+static NSUInteger xcmDev_align64(id, SEL) { return 64; }
+static NSUInteger xcmDev_rwTexTier(id, SEL) { return MTLReadWriteTextureTier2; }
+static BOOL xcmDev_yes(id, SEL) { return YES; }
+static BOOL xcmDev_supportsSampleCount(id, SEL, NSUInteger c) { return c == 1; }
+static BOOL xcmDev_supportsFeatureSet(id, SEL, NSUInteger) { return YES; }
+static BOOL xcmDev_supportsFamily(id, SEL, MTLGPUFamily family) {
+ return gXm2vDevice ? xm2v_device_supports_family(gXm2vDevice, (int64_t)family) : NO;
+}
+
+static id xcmDev_newCommandQueue(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newCommandQueueMax(id self, SEL, NSUInteger) NS_RETURNS_RETAINED;
+static id xcmDev_newBufferLen(id self, SEL, NSUInteger, MTLResourceOptions) NS_RETURNS_RETAINED;
+static id xcmDev_newBufferBytes(id self, SEL, const void *, NSUInteger, MTLResourceOptions) NS_RETURNS_RETAINED;
+static id xcmDev_newBufferNoCopy(id self, SEL, void *, NSUInteger, MTLResourceOptions, void (^)(void *, NSUInteger)) NS_RETURNS_RETAINED;
+static id xcmDev_newTexture(id self, SEL, MTLTextureDescriptor *) NS_RETURNS_RETAINED;
+static id xcmDev_newTextureIOSurface(id self, SEL, MTLTextureDescriptor *, IOSurfaceRef, NSUInteger) NS_RETURNS_RETAINED;
+static id xcmDev_newTextureIOSurfaceSlice(id self, SEL, MTLTextureDescriptor *, IOSurfaceRef, NSUInteger, NSUInteger) NS_RETURNS_RETAINED;
+static id xcmDev_newDefaultLibrary(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newDefaultLibraryWithBundle(id self, SEL, NSBundle *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithSource(id self, SEL, NSString *, MTLCompileOptions *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithData(id self, SEL, dispatch_data_t, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithURL(id self, SEL, NSURL *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithFile(id self, SEL, NSString *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithStitched(id self, SEL, MTLStitchedLibraryDescriptor *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newLibraryWithStitchedArchive(id self, SEL, MTLStitchedLibraryDescriptor *, id, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newComputePSO(id self, SEL, id<MTLFunction>, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newComputePSOOpts(id self, SEL, id<MTLFunction>, MTLPipelineOption, MTLComputePipelineReflection **, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newComputePSODesc(id self, SEL, MTLComputePipelineDescriptor *, MTLPipelineOption, MTLComputePipelineReflection **, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newRenderPSO(id self, SEL, MTLRenderPipelineDescriptor *, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newRenderPSOOpts(id self, SEL, MTLRenderPipelineDescriptor *, MTLPipelineOption, MTLRenderPipelineReflection **, NSError **) NS_RETURNS_RETAINED;
+static id xcmDev_newSampler(id self, SEL, MTLSamplerDescriptor *) NS_RETURNS_RETAINED;
+static id xcmDev_newDepthStencil(id self, SEL, MTLDepthStencilDescriptor *) NS_RETURNS_RETAINED;
+static id xcmDev_newEvent(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newFence(id self, SEL) NS_RETURNS_RETAINED;
+static id xcmDev_newHeap(id self, SEL, MTLHeapDescriptor *) NS_RETURNS_RETAINED;
+
+static id xcmDev_newCommandQueue(id self, SEL) {
+ if (!gXm2vDevice) return nil;
+ Xm2vQueue *q = xm2v_queue_new(gXm2vDevice);
+ return q ? [[XcmQueue alloc] initWithHandle:q device:self] : nil;
+}
+static id xcmDev_newCommandQueueMax(id self, SEL, NSUInteger) {
+ return xcmDev_newCommandQueue(self, nullptr);
+}
+static id xcmDev_newBufferLen(id self, SEL, NSUInteger length, MTLResourceOptions opts) {
+ if (!gXm2vDevice) return nil;
+ Xm2vBuffer *b = xm2v_buffer_new(gXm2vDevice, length, opts, nullptr);
+ if (xcmTraceOn()) fprintf(stderr, "XCM newBufferLen(%lu, 0x%lx) -> %p\n", (unsigned long)length, (unsigned long)opts, (void *)b);
+ return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
+}
+static id xcmDev_newBufferBytes(id self, SEL, const void *pointer, NSUInteger length, MTLResourceOptions opts) {
+ if (!gXm2vDevice) return nil;
+ Xm2vBuffer *b = xm2v_buffer_new(gXm2vDevice, length, opts, pointer);
+ return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
+}
+static id xcmDev_newBufferNoCopy(id self, SEL, void *pointer, NSUInteger length, MTLResourceOptions opts, void (^deallocator)(void *, NSUInteger)) {
+ (void)deallocator;
+ if (!gXm2vDevice) return nil;
+ Xm2vBuffer *b = xm2v_buffer_new_no_copy(gXm2vDevice, pointer, length, opts);
+ if (!b) b = xm2v_buffer_new(gXm2vDevice, length, opts, pointer);
+ return b ? [[XcmBuffer alloc] initWithHandle:b device:self options:opts] : nil;
+}
+static id xcmDev_newTexture(id self, SEL, MTLTextureDescriptor *desc) {
+ if (!gXm2vDevice || !desc) return nil;
+ Xm2vTextureDesc td = {};
+ td.texture_type = (uint64_t)desc.textureType;
+ td.pixel_format = (uint64_t)desc.pixelFormat;
+ td.width = desc.width;
+ td.height = desc.height;
+ td.depth = desc.depth;
+ td.mipmap_level_count = desc.mipmapLevelCount;
+ td.sample_count = desc.sampleCount;
+ td.array_length = desc.arrayLength;
+ td.resource_options = (uint64_t)desc.resourceOptions;
+ td.usage = (uint64_t)desc.usage;
+ Xm2vTexture *t = xm2v_texture_new(gXm2vDevice, &td);
+ if (!t || xcmTraceOn()) {
+ fprintf(stderr, "XCM newTexture -> %p fmt=%lu type=%lu %lux%lux%lu mip=%lu usage=0x%lx opts=0x%lx err=%s\n",
+ (void *)t, (unsigned long)desc.pixelFormat, (unsigned long)desc.textureType,
+ (unsigned long)desc.width, (unsigned long)desc.height, (unsigned long)desc.depth,
+ (unsigned long)desc.mipmapLevelCount, (unsigned long)desc.usage, (unsigned long)desc.resourceOptions,
+ t ? "ok" : xm2v_last_error());
+ }
+ return t ? [[XcmTexture alloc] initWithHandle:t device:self descriptor:desc] : nil;
+}
+static id xcmDev_newTextureIOSurface(id self, SEL, MTLTextureDescriptor *desc, IOSurfaceRef surface, NSUInteger plane) {
+ if (xcmTraceOn()) fprintf(stderr, "XCM enter newTextureIOSurface desc=%p surf=%p plane=%lu\n", (__bridge void *)desc, surface, (unsigned long)plane);
+ if (!gXm2vDevice || !desc) return nil;
+ // Force Shared storage internally so replaceRegion/getBytes sync with IOSurface directly.
+ MTLTextureDescriptor *copy = [desc copy];
+ copy.storageMode = MTLStorageModeShared;
+ XcmTexture *tex = xcmDev_newTexture(self, nullptr, copy);
+ if (xcmTraceOn()) fprintf(stderr, "XCM newTextureIOSurface -> %p surf=%p plane=%lu\n", (__bridge void *)tex, surface, (unsigned long)plane);
+ if (tex && surface) {
+ CFRetain(surface);
+ tex->_iosurface = surface;
+ tex->_iosurfacePlane = plane;
+ [tex syncFromIOSurfaceIfNeeded];
+ }
+ return tex;
+}
+static id xcmDev_newTextureIOSurfaceSlice(id self, SEL, MTLTextureDescriptor *desc, IOSurfaceRef surface, NSUInteger plane, NSUInteger slice) {
+ (void)slice;
+ return xcmDev_newTextureIOSurface(self, nullptr, desc, surface, plane);
+}
+static id xcmDev_newLibraryWithData(id self, SEL, dispatch_data_t data, NSError **error) {
+ if (!gXm2vDevice || !data) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Null library data");
+ return nil;
+ }
+ const void *buf = nullptr;
+ size_t len = 0;
+ dispatch_data_t contig = dispatch_data_create_map(data, &buf, &len);
+ NSData *nsCopy = (buf && len) ? [NSData dataWithBytes:buf length:len] : nil;
+ Xm2vLibrary *lib = xm2v_library_new_with_data(gXm2vDevice, buf, len);
+ (void)contig;
+ if (!lib) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Library load failed");
+ return nil;
+ }
+ return [[XcmLibrary alloc] initWithHandle:lib device:self data:nsCopy];
+}
+static id xcmDev_newLibraryWithURL(id self, SEL, NSURL *url, NSError **error) {
+ NSData *nsdata = [NSData dataWithContentsOfURL:url options:0 error:error];
+ if (!nsdata) return nil;
+ dispatch_data_t d = dispatch_data_create(nsdata.bytes, nsdata.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
+ return xcmDev_newLibraryWithData(self, nullptr, d, error);
+}
+static id xcmDev_newLibraryWithFile(id self, SEL, NSString *filepath, NSError **error) {
+ return xcmDev_newLibraryWithURL(self, nullptr, [NSURL fileURLWithPath:filepath], error);
+}
+static NSString *xcmQuoteArg(NSString *text) {
+ if ([text rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@" \t\"\\'"]].location == NSNotFound)
+ return text;
+ NSString *escaped = [[text stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]
+ stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
+ return [NSString stringWithFormat:@"\"%@\"", escaped];
+}
+
+static NSString *xcmCompileArguments(MTLCompileOptions *options) {
+ NSMutableArray<NSString *> *args = [NSMutableArray arrayWithObjects:@"--driver-mode=metal", @"-x", @"metal", nil];
+ NSUInteger version = (options && options.languageVersion) ? (NSUInteger)options.languageVersion : (NSUInteger)MTLLanguageVersion3_1;
+ unsigned major = (unsigned)(version >> 16), minor = (unsigned)(version & 0xffff);
+ [args addObject:[NSString stringWithFormat:(major >= 3 ? @"-std=metal%u.%u" : @"-std=macos-metal%u.%u"), major, minor]];
+ SEL modeSel = sel_registerName("mathMode"), fnSel = sel_registerName("mathFloatingPointFunctions");
+ NSString *modeName = nil, *fnName = nil;
+ if (options && [options respondsToSelector:modeSel] && [options respondsToSelector:fnSel]) {
+ switch (((NSInteger (*)(id, SEL))objc_msgSend)(options, modeSel)) {
+ case MTLMathModeSafe: modeName = @"safe"; break;
+ case MTLMathModeRelaxed: modeName = @"relaxed"; break;
+ case MTLMathModeFast: modeName = @"fast"; break;
+ }
+ switch (((NSInteger (*)(id, SEL))objc_msgSend)(options, fnSel)) {
+ case MTLMathFloatingPointFunctionsFast: fnName = @"fast"; break;
+ case MTLMathFloatingPointFunctionsPrecise: fnName = @"precise"; break;
+ }
+ }
+ if (modeName && fnName) {
+ [args addObject:[@"-fmetal-math-mode=" stringByAppendingString:modeName]];
+ [args addObject:[@"-fmetal-math-fp32-functions=" stringByAppendingString:fnName]];
+ } else {
+ BOOL fast = options ? ((BOOL (*)(id, SEL))objc_msgSend)(options, sel_registerName("fastMathEnabled")) : YES;
+ [args addObject:fast ? @"-ffast-math" : @"-fno-fast-math"];
+ }
+ if (options.preserveInvariance) [args addObject:@"-fpreserve-invariance"];
+ if (options.optimizationLevel == MTLLibraryOptimizationLevelSize) [args addObject:@"-Os"];
+ [options.preprocessorMacros enumerateKeysAndObjectsUsingBlock:^(NSString *name, NSObject *value, BOOL *) {
+ [args addObject:xcmQuoteArg([NSString stringWithFormat:@"-D%@=%@", name, value])];
+ }];
+ [args addObject:xcmQuoteArg([@"-fmodules-cache-path=" stringByAppendingString:[NSTemporaryDirectory() stringByAppendingPathComponent:@"xcm-msl"]])];
+ return [args componentsJoinedByString:@" "];
+}
+
+static id xcmDev_newDefaultLibraryWithBundle(id self, SEL, NSBundle *bundle, NSError **error) {
+ NSURL *url = [bundle URLForResource:@"default" withExtension:@"metallib"];
+ if (!url) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorFileNotFound, "Bundle has no default.metallib");
+ return nil;
+ }
+ return xcmDev_newLibraryWithURL(self, nullptr, url, error);
+}
+static id xcmDev_newDefaultLibrary(id self, SEL) {
+ return xcmDev_newDefaultLibraryWithBundle(self, nullptr, [NSBundle mainBundle], nil);
+}
+static id xcmDev_newLibraryWithSource(id self, SEL, NSString *source, MTLCompileOptions *options, NSError **error) {
+ if (!source) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Nil source");
+ return nil;
+ }
+ NSData *text = [source dataUsingEncoding:NSUTF8StringEncoding];
+ NSString *argStr = xcmCompileArguments(options);
+ const char *argC = argStr.UTF8String ?: "";
+ uint64_t sourceBytes = (text.length + 1 + 3) & ~uint64_t(3);
+ uint64_t optionBytes = strlen(argC) + 1;
+ std::vector<uint8_t> req(16 + sourceBytes + optionBytes, 0);
+ memcpy(req.data(), &sourceBytes, 8);
+ memcpy(req.data() + 8, &optionBytes, 8);
+ memcpy(req.data() + 16, text.bytes, text.length);
+ memcpy(req.data() + 16 + sourceBytes, argC, optionBytes);
+ NSString *warnings = nil, *failure = nil;
+ NSData *metallib = xcmCodeGenRequest(13, req, &warnings, &failure);
+ if (!metallib) {
+ if (xcmTraceOn()) fprintf(stderr, "XCM newLibraryWithSource failed: %s\n", failure.UTF8String ?: "?");
+ if (error) *error = [NSError errorWithDomain:MTLLibraryErrorDomain code:MTLLibraryErrorCompileFailure
+ userInfo:@{NSLocalizedDescriptionKey: failure ?: @"Metal source compilation failed"}];
+ return nil;
+ }
+ dispatch_data_t data = dispatch_data_create(metallib.bytes, metallib.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
+ id<MTLLibrary> lib = xcmDev_newLibraryWithData(self, nullptr, data, error);
+ if (lib && warnings.length && error)
+ *error = [NSError errorWithDomain:MTLLibraryErrorDomain code:MTLLibraryErrorCompileWarning
+ userInfo:@{NSLocalizedDescriptionKey: warnings}];
+ return lib;
+}
+static void xcmDev_newLibraryWithSourceAsync(id self, SEL, NSString *source, MTLCompileOptions *options, MTLNewLibraryCompletionHandler handler) {
+ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ NSError *err = nil;
+ id<MTLLibrary> lib = xcmDev_newLibraryWithSource(self, nullptr, source, options, &err);
+ if (handler) handler(lib, err);
+ });
+}
+static id xcmDev_newLibraryWithStitched(id self, SEL, MTLStitchedLibraryDescriptor *d, NSError **error) {
+ NSArray<MTLFunctionStitchingGraph *> *graphs = d.functionGraphs;
+ NSArray<id<MTLFunction>> *functions = d.functions;
+ if (!graphs.count || !functions.count) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Stitched library needs graphs and functions");
+ return nil;
+ }
+ NSString *dag = [(id<XcmOriginalStitching>)self newDagStringWithGraphs:graphs];
+ if (!dag.length) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Empty stitching DAG text");
+ return nil;
+ }
+ std::vector<uint8_t> req;
+ auto pushWord = [&](uint32_t v) {
+ const uint8_t *b = (const uint8_t *)&v;
+ req.insert(req.end(), b, b + 4);
+ };
+ const char *text = dag.UTF8String;
+ pushWord(0x64616720); // 'dag '
+ req.insert(req.end(), text, text + strlen(text) + 1);
+ pushWord(0x6e756d66); // 'numf'
+ pushWord((uint32_t)functions.count);
+ for (id fn in functions) {
+ NSData *bc = [fn isKindOfClass:[XcmFunction class]] ? xcmExtractFunctionBitcode((XcmFunction *)fn) : nil;
+ if (!bc) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Missing bitcode for stitched function");
+ return nil;
+ }
+ pushWord(0x62697463); // 'bitc'
+ pushWord((uint32_t)bc.length);
+ const uint8_t *b = (const uint8_t *)bc.bytes;
+ req.insert(req.end(), b, b + bc.length);
+ }
+ // macOS 27 MTLCompilerObject::stitchFunctionDag trailing slots
+ pushWord(0x6e756d73); pushWord(0); // 'nums'
+ pushWord(0x7074666d); pushWord(0); // 'ptfm'
+ pushWord(0x61726964); pushWord(0); // 'arid'
+
+ NSString *warnings = nil, *failure = nil;
+ NSData *metallib = xcmCodeGenRequest(14, req, &warnings, &failure);
+ if (!metallib) {
+ if (error) *error = [NSError errorWithDomain:MTLLibraryErrorDomain
+ code:MTLLibraryErrorCompileFailure
+ userInfo:@{NSLocalizedDescriptionKey: failure ?: @"Stitched library compilation failed"}];
+ return nil;
+ }
+ dispatch_data_t data = dispatch_data_create(metallib.bytes, metallib.length, nullptr, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
+ return xcmDev_newLibraryWithData(self, nullptr, data, error);
+}
+static id xcmDev_newLibraryWithStitchedArchive(id self, SEL, MTLStitchedLibraryDescriptor *d, id, NSError **error) {
+ return xcmDev_newLibraryWithStitched(self, nullptr, d, error);
+}
+static void xcmDev_newLibraryWithStitchedAsync(id self, SEL, MTLStitchedLibraryDescriptor *d, MTLNewLibraryCompletionHandler handler) {
+ NSError *err = nil;
+ id<MTLLibrary> lib = xcmDev_newLibraryWithStitched(self, nullptr, d, &err);
+ if (handler) handler(lib, err);
+}
+static id xcmDev_newComputePSO(id self, SEL, id<MTLFunction> fn, NSError **error) {
+ if (!gXm2vDevice || ![fn isKindOfClass:[XcmFunction class]] || !((XcmFunction *)fn)->_handle) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Invalid function");
+ return nil;
+ }
+ Xm2vComputePipeline *pso = xm2v_compute_pipeline_new(gXm2vDevice, ((XcmFunction *)fn)->_handle);
+ if (xcmTraceOn() || !pso) {
+ fprintf(stderr, "XCM newComputePSO(%s) -> %p err=%s\n",
+ fn.name.UTF8String ?: "?", (void *)pso, pso ? "ok" : xm2v_last_error());
+ }
+ if (!pso) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Compute PSO failed");
+ return nil;
+ }
+ return [[XcmComputePipeline alloc] initWithHandle:pso device:self];
+}
+static id xcmDev_newComputePSOOpts(id self, SEL, id<MTLFunction> fn, MTLPipelineOption, MTLComputePipelineReflection **refl, NSError **error) {
+ if (refl) *refl = nil;
+ return xcmDev_newComputePSO(self, nullptr, fn, error);
+}
+static void xcmCollectLinkedFunctions(MTLLinkedFunctions *linked,
+ std::vector<Xm2vFunction *> &pubOut,
+ std::vector<Xm2vFunction *> &privOut) {
+ if (!linked) return;
+ auto push = [](NSArray<id<MTLFunction>> *arr, std::vector<Xm2vFunction *> &dst) {
+ for (id fn in arr) {
+ if ([fn isKindOfClass:[XcmFunction class]] && ((XcmFunction *)fn)->_handle)
+ dst.push_back(((XcmFunction *)fn)->_handle);
+ }
+ };
+ push(linked.functions, pubOut);
+ push(linked.binaryFunctions, pubOut);
+ push(linked.privateFunctions, privOut);
+}
+
+static id xcmDev_newComputePSODesc(id self, SEL, MTLComputePipelineDescriptor *desc, MTLPipelineOption opts, MTLComputePipelineReflection **refl, NSError **error) {
+ (void)opts;
+ if (refl) *refl = nil;
+ if (!gXm2vDevice || !desc || ![desc.computeFunction isKindOfClass:[XcmFunction class]] || !((XcmFunction *)desc.computeFunction)->_handle) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Invalid compute pipeline descriptor");
+ return nil;
+ }
+ std::vector<Xm2vFunction *> pubLinked, privLinked;
+ xcmCollectLinkedFunctions(desc.linkedFunctions, pubLinked, privLinked);
+ Xm2vComputePipeline *pso = (pubLinked.empty() && privLinked.empty())
+ ? xm2v_compute_pipeline_new(gXm2vDevice, ((XcmFunction *)desc.computeFunction)->_handle)
+ : xm2v_compute_pipeline_new_with_linked(
+ gXm2vDevice, ((XcmFunction *)desc.computeFunction)->_handle,
+ pubLinked.empty() ? nullptr : pubLinked.data(), (uint32_t)pubLinked.size(),
+ privLinked.empty() ? nullptr : privLinked.data(), (uint32_t)privLinked.size());
+ if (xcmTraceOn() || !pso) {
+ fprintf(stderr, "XCM newComputePSODesc(%s, linked=%zu+%zu) -> %p err=%s\n",
+ desc.computeFunction.name.UTF8String ?: "?", pubLinked.size(), privLinked.size(),
+ (void *)pso, pso ? "ok" : xm2v_last_error());
+ }
+ if (!pso) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Compute PSO failed");
+ return nil;
+ }
+ return [[XcmComputePipeline alloc] initWithHandle:pso device:self];
+}
+static void xcmDev_newComputePSOAsync(id self, SEL, id<MTLFunction> fn, void (^handler)(id<MTLComputePipelineState>, NSError *)) {
+ NSError *err = nil;
+ id pso = xcmDev_newComputePSO(self, nullptr, fn, &err);
+ if (handler) handler(pso, err);
+}
+static id xcmDev_newRenderPSO(id self, SEL, MTLRenderPipelineDescriptor *desc, NSError **error) {
+ if (!gXm2vDevice || !desc || ![desc.vertexFunction isKindOfClass:[XcmFunction class]] || !((XcmFunction *)desc.vertexFunction)->_handle) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorInternal, "Invalid render pipeline descriptor");
+ return nil;
+ }
+ Xm2vRenderPipelineDesc rd = {};
+ rd.vertex_function = ((XcmFunction *)desc.vertexFunction)->_handle;
+ if (desc.fragmentFunction && [desc.fragmentFunction isKindOfClass:[XcmFunction class]])
+ rd.fragment_function = ((XcmFunction *)desc.fragmentFunction)->_handle;
+ std::vector<Xm2vFunction *> vPub, vPriv, fPub, fPriv;
+ xcmCollectLinkedFunctions(desc.vertexLinkedFunctions, vPub, vPriv);
+ xcmCollectLinkedFunctions(desc.fragmentLinkedFunctions, fPub, fPriv);
+ rd.vertex_linked_functions = vPub.empty() ? nullptr : vPub.data();
+ rd.vertex_linked_function_count = (uint32_t)vPub.size();
+ rd.vertex_private_linked_functions = vPriv.empty() ? nullptr : vPriv.data();
+ rd.vertex_private_linked_function_count = (uint32_t)vPriv.size();
+ rd.fragment_linked_functions = fPub.empty() ? nullptr : fPub.data();
+ rd.fragment_linked_function_count = (uint32_t)fPub.size();
+ rd.fragment_private_linked_functions = fPriv.empty() ? nullptr : fPriv.data();
+ rd.fragment_private_linked_function_count = (uint32_t)fPriv.size();
+ rd.color_attachment_count = 8;
+ for (int i = 0; i < 8; i++) {
+ MTLRenderPipelineColorAttachmentDescriptor *ca = desc.colorAttachments[i];
+ if (ca && ca.pixelFormat != MTLPixelFormatInvalid) {
+ rd.color_attachments[i].pixel_format = (uint64_t)ca.pixelFormat;
+ rd.color_attachments[i].blending_enabled = ca.isBlendingEnabled;
+ rd.color_attachments[i].rgb_blend_op = (uint64_t)ca.rgbBlendOperation;
+ rd.color_attachments[i].alpha_blend_op = (uint64_t)ca.alphaBlendOperation;
+ rd.color_attachments[i].src_rgb_blend = (uint64_t)ca.sourceRGBBlendFactor;
+ rd.color_attachments[i].dst_rgb_blend = (uint64_t)ca.destinationRGBBlendFactor;
+ rd.color_attachments[i].src_alpha_blend = (uint64_t)ca.sourceAlphaBlendFactor;
+ rd.color_attachments[i].dst_alpha_blend = (uint64_t)ca.destinationAlphaBlendFactor;
+ rd.color_attachments[i].write_mask = (uint64_t)ca.writeMask;
+ }
+ }
+ rd.depth_attachment_pixel_format = (uint64_t)desc.depthAttachmentPixelFormat;
+ rd.stencil_attachment_pixel_format = (uint64_t)desc.stencilAttachmentPixelFormat;
+ rd.sample_count = desc.rasterSampleCount;
+ std::vector<Xm2vVertexAttribute> vattrs;
+ std::vector<Xm2vVertexLayout> vlayouts;
+ if (MTLVertexDescriptor *vd = desc.vertexDescriptor) {
+ for (NSUInteger i = 0; i < 31; i++) {
+ MTLVertexAttributeDescriptor *a = vd.attributes[i];
+ if (a && a.format != MTLVertexFormatInvalid) {
+ Xm2vVertexAttribute xa = {};
+ xa.index = (uint32_t)i;
+ xa.format = (uint64_t)a.format;
+ xa.offset = (uint32_t)a.offset;
+ xa.buffer_index = (uint32_t)a.bufferIndex;
+ vattrs.push_back(xa);
+ }
+ MTLVertexBufferLayoutDescriptor *l = vd.layouts[i];
+ if (l && (l.stride != 0 || l.stride == MTLBufferLayoutStrideDynamic)) {
+ Xm2vVertexLayout xl = {};
+ xl.index = (uint32_t)i;
+ xl.dynamic_stride = (l.stride == MTLBufferLayoutStrideDynamic);
+ xl.stride = xl.dynamic_stride ? 0 : (uint64_t)l.stride;
+ xl.step_function = (uint64_t)l.stepFunction;
+ xl.step_rate = (uint32_t)l.stepRate;
+ vlayouts.push_back(xl);
+ }
+ }
+ }
+ rd.vertex_attributes = vattrs.empty() ? nullptr : vattrs.data();
+ rd.vertex_attribute_count = (uint32_t)vattrs.size();
+ rd.vertex_layouts = vlayouts.empty() ? nullptr : vlayouts.data();
+ rd.vertex_layout_count = (uint32_t)vlayouts.size();
+ Xm2vRenderPipeline *pso = xm2v_render_pipeline_new(gXm2vDevice, &rd);
+ if (!pso) {
+ // Retry once with unspecified declared function constants defaulted to zero
+ // (QuartzCore/RenderBox omit default-false constants that gate stage_in attributes / color inputs).
+ auto rebuildZeroRest = [](id fnObj) -> Xm2vFunction * {
+ if (!fnObj || ![fnObj isKindOfClass:[XcmFunction class]]) return nullptr;
+ XcmFunction *xf = (XcmFunction *)fnObj;
+ if (!xf->_library || !xf->_library->_handle) return nullptr;
+ NSString *srcName = xf->_sourceName ?: xf->_name;
+ if (!srcName) return nullptr;
+ std::vector<Xm2vConstant> constants;
+ std::deque<std::string> nameStorage;
+ std::deque<std::vector<uint8_t>> byteStorage;
+ xcmExtractConstants(xf->_constantValues, constants, nameStorage, byteStorage);
+ return xm2v_library_new_function_specialized_zero_rest(
+ xf->_library->_handle, srcName.UTF8String,
+ constants.empty() ? nullptr : constants.data(), (uint32_t)constants.size());
+ };
+ Xm2vFunction *zv = rebuildZeroRest(desc.vertexFunction);
+ Xm2vFunction *zf = desc.fragmentFunction ? rebuildZeroRest(desc.fragmentFunction) : nullptr;
+ if (zv || zf) {
+ Xm2vRenderPipelineDesc rd2 = rd;
+ if (zv) rd2.vertex_function = zv;
+ if (zf) rd2.fragment_function = zf;
+ pso = xm2v_render_pipeline_new(gXm2vDevice, &rd2);
+ if (xcmTraceOn()) {
+ fprintf(stderr, "XCM newRenderPSO zeroRest retry(v=%s,f=%s) -> %p err=%s\n",
+ desc.vertexFunction.name.UTF8String ?: "?",
+ desc.fragmentFunction.name.UTF8String ?: "-",
+ (void *)pso, pso ? "ok" : xm2v_last_error());
+ }
+ if (zv) xm2v_function_release(zv);
+ if (zf) xm2v_function_release(zf);
+ }
+ }
+ // If Metal's vertex/fragment shader declares a stage_in attribute or color input attachment
+ // that the descriptor omitted (e.g. QuartzCore Vfx unused attribute 4, or sparse RenderBox
+ // color attachments), fill the missing slot with a safe default and retry.
+ for (int attempt = 0; !pso && attempt < 8; attempt++) {
+ const char *err = xm2v_last_error();
+ if (!err) break;
+ unsigned missingIdx = 0;
+ if (const char *va = strstr(err, "InvalidDescriptor(VertexAttribute { attribute: ")) {
+ if (sscanf(va, "InvalidDescriptor(VertexAttribute { attribute: %u", &missingIdx) == 1 && missingIdx < 31) {
+ bool exists = false;
+ for (const auto &a : vattrs) if (a.index == missingIdx) { exists = true; break; }
+ if (exists) break;
+ uint32_t bufIdx = vlayouts.empty() ? 0 : vlayouts[0].index;
+ if (vlayouts.empty()) {
+ Xm2vVertexLayout xl = {};
+ xl.index = 0; xl.stride = 16; xl.step_function = (uint64_t)MTLVertexStepFunctionConstant; xl.step_rate = 0;
+ vlayouts.push_back(xl);
+ }
+ Xm2vVertexAttribute xa = {};
+ xa.index = missingIdx;
+ xa.format = (uint64_t)MTLVertexFormatFloat4;
+ xa.offset = 0;
+ xa.buffer_index = bufIdx;
+ vattrs.push_back(xa);
+ rd.vertex_attributes = vattrs.data();
+ rd.vertex_attribute_count = (uint32_t)vattrs.size();
+ rd.vertex_layouts = vlayouts.data();
+ rd.vertex_layout_count = (uint32_t)vlayouts.size();
+ pso = xm2v_render_pipeline_new(gXm2vDevice, &rd);
+ if (xcmTraceOn()) fprintf(stderr, "XCM newRenderPSO missing-vattr(%u) retry -> %p err=%s\n", missingIdx, (void *)pso, pso ? "ok" : xm2v_last_error());
+ continue;
+ }
+ }
+ if (const char *ca = strstr(err, "InvalidDescriptor(ColorAttachment { index: ")) {
+ if (sscanf(ca, "InvalidDescriptor(ColorAttachment { index: %u", &missingIdx) == 1 && missingIdx < 8) {
+ if (rd.color_attachments[missingIdx].pixel_format != 0) break;
+ uint64_t fallbackFmt = rd.color_attachments[0].pixel_format ? rd.color_attachments[0].pixel_format : (uint64_t)MTLPixelFormatRGBA16Float;
+ rd.color_attachments[missingIdx].pixel_format = fallbackFmt;
+ rd.color_attachments[missingIdx].write_mask = (uint64_t)MTLColorWriteMaskAll;
+ pso = xm2v_render_pipeline_new(gXm2vDevice, &rd);
+ if (xcmTraceOn()) fprintf(stderr, "XCM newRenderPSO missing-color(%u) retry -> %p err=%s\n", missingIdx, (void *)pso, pso ? "ok" : xm2v_last_error());
+ continue;
+ }
+ }
+ break;
+ }
+ if (xcmTraceOn() || !pso) {
+ fprintf(stderr, "XCM newRenderPSO(v=%s,f=%s, vl=%zu+%zu, fl=%zu+%zu, fLinkedObj=%p) -> %p err=%s\n",
+ desc.vertexFunction.name.UTF8String ?: "?",
+ desc.fragmentFunction.name.UTF8String ?: "-",
+ vPub.size(), vPriv.size(), fPub.size(), fPriv.size(),
+ (__bridge void *)desc.fragmentLinkedFunctions,
+ (void *)pso, pso ? "ok" : xm2v_last_error());
+ if (!pso && !vattrs.empty()) {
+ fprintf(stderr, " vattrs(%zu):", vattrs.size());
+ for (const auto &a : vattrs) fprintf(stderr, " [idx=%u fmt=%llu off=%u buf=%u]", a.index, a.format, a.offset, a.buffer_index);
+ fprintf(stderr, "\n vlayouts(%zu):", vlayouts.size());
+ for (const auto &l : vlayouts) fprintf(stderr, " [idx=%u stride=%llu dyn=%d step=%llu rate=%u]", l.index, l.stride, l.dynamic_stride, l.step_function, l.step_rate);
+ fprintf(stderr, "\n");
+ }
+ if (!pso && desc.fragmentLinkedFunctions) {
+ MTLLinkedFunctions *fl = desc.fragmentLinkedFunctions;
+ fprintf(stderr, " fl.functions=%lu binary=%lu private=%lu groups=%lu\n",
+ (unsigned long)fl.functions.count, (unsigned long)fl.binaryFunctions.count,
+ (unsigned long)fl.privateFunctions.count, (unsigned long)fl.groups.count);
+ for (id fn in fl.functions)
+ fprintf(stderr, " fn: %s (%s)\n", object_getClassName(fn), [fn respondsToSelector:@selector(name)] ? [[fn name] UTF8String] : "?");
+ for (id fn in fl.privateFunctions)
+ fprintf(stderr, " priv: %s (%s)\n", object_getClassName(fn), [fn respondsToSelector:@selector(name)] ? [[fn name] UTF8String] : "?");
+ for (id fn in fl.binaryFunctions)
+ fprintf(stderr, " bin: %s (%s)\n", object_getClassName(fn), [fn respondsToSelector:@selector(name)] ? [[fn name] UTF8String] : "?");
+ }
+ }
+ if (!pso) {
+ if (error) *error = xcmError(MTLLibraryErrorDomain, MTLLibraryErrorCompileFailure, "Render PSO failed");
+ return nil;
+ }
+ return [[XcmRenderPipeline alloc] initWithHandle:pso device:self];
+}
+static id xcmDev_newRenderPSOOpts(id self, SEL, MTLRenderPipelineDescriptor *desc, MTLPipelineOption, MTLRenderPipelineReflection **refl, NSError **error) {
+ if (refl) *refl = nil;
+ return xcmDev_newRenderPSO(self, nullptr, desc, error);
+}
+static id xcmDev_newSampler(id self, SEL, MTLSamplerDescriptor *desc) {
+ if (!gXm2vDevice || !desc) return nil;
+ Xm2vSamplerDesc sd = {};
+ sd.min_filter = (uint64_t)desc.minFilter;
+ sd.mag_filter = (uint64_t)desc.magFilter;
+ sd.mip_filter = (uint64_t)desc.mipFilter;
+ sd.s_address_mode = (uint64_t)desc.sAddressMode;
+ sd.t_address_mode = (uint64_t)desc.tAddressMode;
+ sd.r_address_mode = (uint64_t)desc.rAddressMode;
+ sd.max_anisotropy = desc.maxAnisotropy;
+ sd.compare_function = (uint64_t)desc.compareFunction;
+ sd.lod_min_clamp = desc.lodMinClamp;
+ sd.lod_max_clamp = desc.lodMaxClamp;
+ sd.normalized_coordinates = desc.normalizedCoordinates;
+ Xm2vSampler *s = xm2v_sampler_new(gXm2vDevice, &sd);
+ return s ? [[XcmSampler alloc] initWithHandle:s device:self] : nil;
+}
+static id xcmDev_newDepthStencil(id self, SEL, MTLDepthStencilDescriptor *desc) {
+ if (!gXm2vDevice || !desc) return nil;
+ Xm2vDepthStencilDesc dsd = {};
+ dsd.depth_compare_function = (uint64_t)desc.depthCompareFunction;
+ dsd.depth_write_enabled = desc.isDepthWriteEnabled;
+ auto fillStencil = [](MTLStencilDescriptor *s, Xm2vStencilDesc &dst) {
+ if (!s) return;
+ dst.enabled = true;
+ dst.stencil_compare_function = (uint64_t)s.stencilCompareFunction;
+ dst.stencil_failure_operation = (uint64_t)s.stencilFailureOperation;
+ dst.depth_failure_operation = (uint64_t)s.depthFailureOperation;
+ dst.depth_stencil_pass_operation = (uint64_t)s.depthStencilPassOperation;
+ dst.read_mask = s.readMask;
+ dst.write_mask = s.writeMask;
+ };
+ fillStencil(desc.frontFaceStencil, dsd.front_face_stencil);
+ fillStencil(desc.backFaceStencil, dsd.back_face_stencil);
+ Xm2vDepthStencil *ds = xm2v_depth_stencil_new(gXm2vDevice, &dsd);
+ return ds ? [[XcmDepthStencil alloc] initWithHandle:ds device:self] : nil;
+}
+static id xcmDev_newEvent(id self, SEL) {
+ if (!gXm2vDevice) return nil;
+ Xm2vEvent *ev = xm2v_event_new(gXm2vDevice);
+ return ev ? [[XcmEvent alloc] initWithHandle:ev device:self] : nil;
+}
+static id xcmDev_newFence(id self, SEL) {
+ if (!gXm2vDevice) return nil;
+ Xm2vFence *f = xm2v_fence_new(gXm2vDevice);
+ return f ? [[XcmFence alloc] initWithHandle:f device:self] : nil;
+}
+static id xcmDev_newHeap(id self, SEL, MTLHeapDescriptor *desc) {
+ if (xcmTraceOn()) fprintf(stderr, "XCM newHeap(size=%lu storage=%lu)\n", (unsigned long)(desc ? desc.size : 0), (unsigned long)(desc ? desc.storageMode : 0));
+ if (!desc) return nil;
+ return [[XcmHeap alloc] initWithDevice:self descriptor:desc];
+}
+static MTLSizeAndAlign xcmDev_heapTexSizeAndAlign(id, SEL, MTLTextureDescriptor *desc) {
+ NSUInteger w = desc ? MAX(1ul, desc.width) : 1;
+ NSUInteger h = desc ? MAX(1ul, desc.height) : 1;
+ NSUInteger d = desc ? MAX(1ul, desc.depth) : 1;
+ NSUInteger sz = ((w * h * d * 16 + 255) & ~255ul);
+ return MTLSizeAndAlign{sz, 256};
+}
+static MTLSizeAndAlign xcmDev_heapBufSizeAndAlign(id, SEL, NSUInteger len, MTLResourceOptions) { return MTLSizeAndAlign{len, 256}; }
+
+// Metal's loader picks a slice of a binary archive / fat metallib by [device targetDeviceArchitecture] (cpuType, cpuSubtype);
+// nil asserts in +[MTLLoader sliceIDForDevice:...]. This device runs AIR (through metal2vulkan), so it names the AIR type.
+static id xcmDev_targetDeviceArchitecture(id, SEL) {
+ static id arch;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ int type = 0x01000017, subtype = 0;
+ if (const char *e = getenv("XNU_CPU_METAL_ARCH_TYPE")) type = (int)strtol(e, nullptr, 0);
+ if (const char *e = getenv("XNU_CPU_METAL_ARCH_SUBTYPE")) subtype = (int)strtol(e, nullptr, 0);
+ // Metal's internal MTLTargetDeviceArchitecture (cpuType, subType, driverVersion), not the public MTLArchitecture.
+ Class c = objc_getClass("MTLTargetDeviceArchitecture");
+ if (c) {
+ arch = [[c alloc] init];
+ ((void (*)(id, SEL, unsigned))objc_msgSend)(arch, sel_registerName("setCpuType:"), (unsigned)type);
+ ((void (*)(id, SEL, unsigned))objc_msgSend)(arch, sel_registerName("setSubType:"), (unsigned)subtype);
+ unsigned long long dv = 0;
+ if (const char *e = getenv("XNU_CPU_METAL_DRIVER_VERSION")) dv = strtoull(e, nullptr, 0);
+ ((void (*)(id, SEL, unsigned long long))objc_msgSend)(arch, sel_registerName("setDriverVersion:"), dv);
+ }
+ if (xcmTraceOn()) fprintf(stderr, "XCM targetDeviceArchitecture -> %p (0x%x/%d)\n", (__bridge void *)arch, type, subtype);
+ });
+ return arch;
+}
+
+static Class createBackendDeviceClass(void) {
+ static Class cls = nil;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{
+ Class base = objc_getClass("_MTLDevice");
+ if (!base) base = [NSObject class];
+ cls = objc_allocateClassPair(base, "XcmBackendDevice", 0);
+ if (!cls) { cls = objc_getClass("XcmBackendDevice"); return; }
+
+ struct Entry { const char *sel; IMP imp; const char *types; };
+ static const Entry entries[] = {
+ {"name", (IMP)xcmDev_name, "@16@0:8"},
+ {"targetDeviceArchitecture", (IMP)xcmDev_targetDeviceArchitecture, "@16@0:8"},
+ {"registryID", (IMP)xcmDev_registryID, "Q16@0:8"},
+ {"isLowPower", (IMP)xcmDev_isLowPower, "B16@0:8"},
+ {"isHeadless", (IMP)xcmDev_isHeadless, "B16@0:8"},
+ {"isRemovable", (IMP)xcmDev_isRemovable, "B16@0:8"},
+ {"hasUnifiedMemory", (IMP)xcmDev_hasUnifiedMemory, "B16@0:8"},
+ {"maxBufferLength", (IMP)xcmDev_maxBufferLength, "Q16@0:8"},
+ {"maxThreadsPerThreadgroup", (IMP)xcmDev_maxThreadsPerThreadgroup, "{?=QQQ}16@0:8"},
+ {"maxTextureWidth2D", (IMP)xcmDev_maxTex2D, "Q16@0:8"},
+ {"maxTextureHeight2D", (IMP)xcmDev_maxTex2D, "Q16@0:8"},
+ {"maxTextureWidth1D", (IMP)xcmDev_maxTex2D, "Q16@0:8"},
+ {"maxTextureWidth3D", (IMP)xcmDev_maxTex3D, "Q16@0:8"},
+ {"maxTextureHeight3D", (IMP)xcmDev_maxTex3D, "Q16@0:8"},
+ {"maxTextureDepth3D", (IMP)xcmDev_maxTex3D, "Q16@0:8"},
+ {"maxTextureLayers", (IMP)xcmDev_maxTexLayers, "Q16@0:8"},
+ {"maxColorAttachments", (IMP)xcmDev_maxColorAtt, "Q16@0:8"},
+ {"maxThreadgroupMemoryLength", (IMP)xcmDev_maxTGMem, "Q16@0:8"},
+ {"minimumLinearTextureAlignmentForPixelFormat:", (IMP)xcmDev_minLinearAlign, "Q24@0:8Q16"},
+ {"minimumTextureBufferAlignmentForPixelFormat:", (IMP)xcmDev_minTileAlign, "Q24@0:8Q16"},
+ {"linearTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"iosurfaceTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"iosurfaceReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"deviceLinearTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"deviceLinearReadOnlyTextureAlignmentBytes", (IMP)xcmDev_align64, "Q16@0:8"},
+ {"readWriteTextureSupport", (IMP)xcmDev_rwTexTier, "Q16@0:8"},
+ {"supportsSharedStorageTextures", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsRenderToLinearTextures", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsLinearTextureFromSharedBuffer", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsTextureSwizzle", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsNonPrivateDepthStencilTextures", (IMP)xcmDev_yes, "B16@0:8"},
+ {"supportsTextureSampleCount:", (IMP)xcmDev_supportsSampleCount, "B24@0:8Q16"},
+ {"supportsFeatureSet:", (IMP)xcmDev_supportsFeatureSet, "B24@0:8Q16"},
+ {"supportsFamily:", (IMP)xcmDev_supportsFamily, "B24@0:8q16"},
+ {"newCommandQueue", (IMP)xcmDev_newCommandQueue, "@16@0:8"},
+ {"newCommandQueueWithMaxCommandBufferCount:", (IMP)xcmDev_newCommandQueueMax, "@24@0:8Q16"},
+ {"newBufferWithLength:options:", (IMP)xcmDev_newBufferLen, "@32@0:8Q16Q24"},
+ {"newBufferWithBytes:length:options:", (IMP)xcmDev_newBufferBytes, "@40@0:8^v16Q24Q32"},
+ {"newBufferWithBytesNoCopy:length:options:deallocator:", (IMP)xcmDev_newBufferNoCopy, "@48@0:8^v16Q24Q32@?40"},
+ {"newTextureWithDescriptor:", (IMP)xcmDev_newTexture, "@24@0:8@16"},
+ {"newTextureWithDescriptor:iosurface:plane:", (IMP)xcmDev_newTextureIOSurface, "@40@0:8@16^{__IOSurface=}24Q32"},
+ {"newTextureWithDescriptor:iosurface:plane:slice:", (IMP)xcmDev_newTextureIOSurfaceSlice, "@48@0:8@16^{__IOSurface=}24Q32Q40"},
+ {"newDefaultLibrary", (IMP)xcmDev_newDefaultLibrary, "@16@0:8"},
+ {"newDefaultLibraryWithBundle:error:", (IMP)xcmDev_newDefaultLibraryWithBundle, "@32@0:8@16^@24"},
+ {"newLibraryWithSource:options:error:", (IMP)xcmDev_newLibraryWithSource, "@40@0:8@16@24^@32"},
+ {"newLibraryWithSource:options:completionHandler:", (IMP)xcmDev_newLibraryWithSourceAsync, "v40@0:8@16@24@?32"},
+ {"newLibraryWithData:error:", (IMP)xcmDev_newLibraryWithData, "@32@0:8@16^@24"},
+ {"newLibraryWithURL:error:", (IMP)xcmDev_newLibraryWithURL, "@32@0:8@16^@24"},
+ {"newLibraryWithFile:error:", (IMP)xcmDev_newLibraryWithFile, "@32@0:8@16^@24"},
+ {"newLibraryWithStitchedDescriptor:error:", (IMP)xcmDev_newLibraryWithStitched, "@32@0:8@16^@24"},
+ {"newLibraryWithStitchedDescriptor:destinationBinaryArchive:error:", (IMP)xcmDev_newLibraryWithStitchedArchive, "@40@0:8@16@24^@32"},
+ {"newLibraryWithStitchedDescriptor:completionHandler:", (IMP)xcmDev_newLibraryWithStitchedAsync, "v32@0:8@16@?24"},
+ {"newComputePipelineStateWithFunction:error:", (IMP)xcmDev_newComputePSO, "@32@0:8@16^@24"},
+ {"newComputePipelineStateWithFunction:options:reflection:error:", (IMP)xcmDev_newComputePSOOpts, "@48@0:8@16Q24^@32^@40"},
+ {"newComputePipelineStateWithDescriptor:options:reflection:error:", (IMP)xcmDev_newComputePSODesc, "@48@0:8@16Q24^@32^@40"},
+ {"newComputePipelineStateWithFunction:completionHandler:", (IMP)xcmDev_newComputePSOAsync, "v32@0:8@16@?24"},
+ {"newRenderPipelineStateWithDescriptor:error:", (IMP)xcmDev_newRenderPSO, "@32@0:8@16^@24"},
+ {"newRenderPipelineStateWithDescriptor:options:reflection:error:", (IMP)xcmDev_newRenderPSOOpts, "@48@0:8@16Q24^@32^@40"},
+ {"newSamplerStateWithDescriptor:", (IMP)xcmDev_newSampler, "@24@0:8@16"},
+ {"newDepthStencilStateWithDescriptor:", (IMP)xcmDev_newDepthStencil, "@24@0:8@16"},
+ {"newEvent", (IMP)xcmDev_newEvent, "@16@0:8"},
+ {"newFence", (IMP)xcmDev_newFence, "@16@0:8"},
+ {"newHeapWithDescriptor:", (IMP)xcmDev_newHeap, "@24@0:8@16"},
+ {"heapTextureSizeAndAlignWithDescriptor:", (IMP)xcmDev_heapTexSizeAndAlign, "{?=QQ}24@0:8@16"},
+ {"heapBufferSizeAndAlignWithLength:options:", (IMP)xcmDev_heapBufSizeAndAlign, "{?=QQ}32@0:8Q16Q24"},
+ };
+ for (const auto &e : entries)
+ class_addMethod(cls, sel_registerName(e.sel), e.imp, e.types);
+ Protocol *mtlDevProto = objc_getProtocol("MTLDevice");
+ if (mtlDevProto) class_addProtocol(cls, mtlDevProto);
+ // MTLAddDevice asserts [newDevice conformsToProtocol:@protocol(MTLDeviceSPI)] (Metal's own device list).
+ Protocol *mtlDevSPI = objc_getProtocol("MTLDeviceSPI");
+ if (!mtlDevSPI) fprintf(stderr, "XnuCpuMetal: no MTLDeviceSPI protocol in the runtime\n");
+ if (mtlDevSPI) class_addProtocol(cls, mtlDevSPI);
+ objc_registerClassPair(cls);
+ });
+ return cls;
+}
+
+static void fillBaseLimits(id device) {
+ Class base = objc_getClass("_MTLDevice");
+ SEL limitsSel = sel_registerName("limits");
+ if (!base || !device || ![device isKindOfClass:base] || !class_getInstanceMethod(base, limitsSel)) return;
+ uint8_t *limits = ((uint8_t *(*)(id, SEL))objc_msgSend)(device, limitsSel);
+ ptrdiff_t at = limits - (uint8_t *)(__bridge void *)device;
+ ptrdiff_t instance = (ptrdiff_t)class_getInstanceSize(base);
+ if (!limits || at <= 0 || at >= instance) return;
+ ptrdiff_t end = instance;
+ bool found = false;
+ unsigned count = 0;
+ Ivar *ivars = class_copyIvarList(base, &count);
+ for (unsigned i = 0; i < count; i++) {
+ ptrdiff_t off = ivar_getOffset(ivars[i]);
+ if (off == at) found = true;
+ else if (off > at && off < end) end = off;
+ }
+ free(ivars);
+ if (!found || end - at < 8) return;
+ size_t size = (size_t)(end - at);
+ struct LimitVal { const char *sel; uint64_t val; };
+ const LimitVal kLimits[] = {
+ {"maxTextureWidth1D", 16384},
+ {"maxTextureWidth2D", 16384},
+ {"maxTextureHeight2D", 16384},
+ {"maxTextureWidth3D", 2048},
+ {"maxTextureHeight3D", 2048},
+ {"maxTextureDepth3D", 2048},
+ {"maxTextureLayers", 2048},
+ {"maxColorAttachments", 8},
+ {"maxThreadgroupMemoryLength", 32768},
+ {"maxBufferLength", xcmDev_maxBufferLength(device, nullptr)},
+ {"maxFramebufferStorageBits", 512},
+ {"maxTotalComputeThreadsPerThreadgroup", 1024},
+ {"maxComputeSamplers", 16},
+ {"maxFragmentSamplers", 16},
+ {"maxVertexSamplers", 16},
+ {"maxComputeTextures", 128},
+ {"maxFragmentTextures", 128},
+ {"maxVertexTextures", 128},
+ {"maxComputeBuffers", 31},
+ {"maxFragmentBuffers", 31},
+ {"maxVertexBuffers", 31},
+ {"maxVertexAttributes", 31},
+ {"maxInterpolants", 32},
+ {"maxViewports", 16},
+ {"maxCustomSamplePositions", 0},
+ {"linearTextureAlignmentBytes", 256},
+ };
+ for (const auto &lv : kLimits) {
+ SEL s = sel_registerName(lv.sel);
+ Method orig = class_getInstanceMethod(base, s);
+ if (!orig || method_getNumberOfArguments(orig) != 2) continue;
+ char ret = method_getTypeEncoding(orig)[0];
+ if (ret != 'Q' && ret != 'I') continue;
+ auto getter = (NSUInteger (*)(id, SEL))method_getImplementation(orig);
+ for (size_t off = 0; off + 4 <= size; off += 4) {
+ uint32_t saved;
+ memcpy(&saved, limits + off, 4);
+ uint32_t marker = 0x5a17c000u | (uint32_t)(off & 0xfff);
+ memcpy(limits + off, &marker, 4);
+ NSUInteger seen = getter(device, s);
+ memcpy(limits + off, &saved, 4);
+ if ((uint32_t)seen != marker || (seen >> 32) != 0) continue;
+ bool wide = false;
+ if (off + 8 <= size) {
+ uint32_t next, one = 1;
+ memcpy(&next, limits + off + 4, 4);
+ memcpy(limits + off, &marker, 4);
+ memcpy(limits + off + 4, &one, 4);
+ wide = (getter(device, s) >> 32) == 1;
+ memcpy(limits + off, &saved, 4);
+ memcpy(limits + off + 4, &next, 4);
+ }
+ if (wide) {
+ memcpy(limits + off, &lv.val, 8);
+ } else {
+ uint32_t narrow = lv.val > UINT32_MAX ? UINT32_MAX : (uint32_t)lv.val;
+ memcpy(limits + off, &narrow, 4);
+ }
+ break;
+ }
+ }
+}
+
+extern "C" id xnu_cpu_metal_open_device(const char *loader, const char *icd_json, const char *cache_dir, unsigned port) {
+ if (gSingletonDevice) return gSingletonDevice;
+ gXm2vDevice = xm2v_device_open(loader, icd_json, cache_dir);
+ if (!gXm2vDevice) {
+ fprintf(stderr, "XnuCpuMetal: xm2v_device_open failed: %s\n", xm2v_last_error());
+ return nil;
+ }
+ if (port) {
+ uint64_t rid = 0;
+ if (IORegistryEntryGetRegistryEntryID(port, &rid) == KERN_SUCCESS && rid != 0)
+ gRegistryID = rid;
+ }
+ Class cls = createBackendDeviceClass();
+ id dev = [[cls alloc] init];
+ fillBaseLimits(dev);
+ xcm_iogpu::install(dev, port);
+ gSingletonDevice = dev;
+ return dev;
+}
+
+/* ======================== Bundle Principal Class ======================== */
+
+@interface XnuCpuMetalDevice : IOGPUMetalDevice
+- (id)initWithAcceleratorPort:(unsigned)port;
+- (id)initWithAcceleratorPort:(unsigned)port options:(unsigned long long)options;
+@end
+
+@implementation XnuCpuMetalDevice
+
+- (id)initWithAcceleratorPort:(unsigned)port options:(unsigned long long)options {
+ (void)options;
+ return [self initWithAcceleratorPort:port];
+}
+
+- (id)initWithAcceleratorPort:(unsigned)port {
+ static NSMutableArray *kept;
+ static dispatch_once_t once;
+ dispatch_once(&once, ^{ kept = [NSMutableArray array]; });
+ @synchronized(kept) { [kept addObject:self]; }
+
+ Dl_info info = {};
+ std::string contentsDir;
+ if (dladdr((const void *)&xnu_cpu_metal_open_device, &info) && info.dli_fname) {
+ std::string execPath(info.dli_fname);
+ size_t pos = execPath.rfind("/MacOS/");
+ if (pos != std::string::npos) contentsDir = execPath.substr(0, pos);
+ }
+
+ std::string loader = contentsDir.empty() ? "libvulkan.1.dylib" : (contentsDir + "/Frameworks/libvulkan.1.dylib");
+ std::string icdJson = contentsDir.empty() ? "" : (contentsDir + "/Resources/lvp_icd.aarch64.json");
+
+ const char *envLoader = getenv("XNU_CPU_METAL_LOADER");
+ if (envLoader && envLoader[0]) loader = envLoader;
+ const char *envIcd = getenv("XNU_CPU_METAL_ICD");
+ if (envIcd && envIcd[0]) icdJson = envIcd;
+
+ char cacheDir[512] = {};
+ if (confstr(_CS_DARWIN_USER_CACHE_DIR, cacheDir, sizeof(cacheDir) - 32) > 0) {
+ strlcat(cacheDir, "xnu-cpu-metal-m2v", sizeof(cacheDir));
+ mkdir(cacheDir, 0700);
+ } else {
+ strlcpy(cacheDir, "/tmp/xnu-cpu-metal-m2v", sizeof(cacheDir));
+ mkdir(cacheDir, 0777);
+ }
+
+ return xnu_cpu_metal_open_device(loader.c_str(), icdJson.c_str(), cacheDir, port);
+}
+
+@end
diff --git a/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h
new file mode 100644
index 0000000..06ce6c8
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-cpu-metal-bundle/XnuCpuMetalShim.h
@@ -0,0 +1,217 @@
+// Adapted from UniXNU/AdrenoMetal's IOGPUMetalDeviceShim.h (BSD-2-Clause-Patent).
+// Installs macOS IOGPUMetalDevice compatibility selectors and Metal protocol conformances
+// on the dynamically created _MTLDevice subclass and Xcm* frontend classes.
+#pragma once
+#import <Foundation/Foundation.h>
+#include <CommonCrypto/CommonDigest.h>
+#include <IOKit/IOKitLib.h>
+#include <atomic>
+#include <objc/runtime.h>
+#include <stdio.h>
+#include <string.h>
+
+namespace xcm_iogpu {
+
+inline io_service_t gAcceleratorPort;
+inline id gAcceleratorService;
+inline __weak id gDeviceWrapper;
+
+static void setAcceleratorService(id, SEL, id service) { gAcceleratorService = service; }
+static io_service_t acceleratorPort(id, SEL) { return gAcceleratorPort; }
+static void setDeviceWrapper(id, SEL, id wrapper) { gDeviceWrapper = wrapper; }
+static id deviceWrapper(id self, SEL) { id w = gDeviceWrapper; return w ? w : self; }
+static BOOL isBuiltIn(id, SEL) { return YES; }
+static BOOL no(id, SEL) { return NO; }
+static uint64_t zero(id, SEL) { return 0; }
+static uint32_t one(id, SEL) { return 1; }
+static void nothing(id, SEL) {}
+static void nothingWith(id, SEL, uint64_t) {}
+static BOOL amplificationCount(id, SEL, NSUInteger count) { return count == 1; }
+static uint64_t commandBufferArgumentsSize(id, SEL) { return 48; }
+static uint64_t workingSetSize(id, SEL) { return NSProcessInfo.processInfo.physicalMemory / 3 * 2; }
+static NSUInteger gpuCoreCount(id, SEL) { return 4; }
+static uint64_t stub(id, SEL) { return 0; }
+
+static Class referenceClass(Class cls) {
+ static const struct { const char *frontend, *iogpu; } classes[] = {
+ {"XcmBuffer", "IOGPUMetalBuffer"},
+ {"XcmTexture", "IOGPUMetalTexture"},
+ {"XcmQueue", "IOGPUMetalCommandQueue"},
+ {"XcmCommandBuffer", "IOGPUMetalCommandBuffer"},
+ {"XcmComputeEncoder", "IOGPUMetalComputeCommandEncoder"},
+ {"XcmRenderEncoder", "IOGPUMetalRenderCommandEncoder"},
+ {"XcmBlitEncoder", "IOGPUMetalBlitCommandEncoder"},
+ {"XcmFence", "IOGPUMetalFence"},
+ {"XcmEvent", "IOGPUMetalEvent"},
+ {"XcmHeap", "IOGPUMetalHeap"},
+ {"XcmLibrary", "_MTLLibrary"},
+ {"XcmFunction", "_MTLFunction"},
+ {"XcmComputePipeline", "_MTLComputePipelineState"},
+ {"XcmRenderPipeline", "_MTLRenderPipelineState"},
+ {"XcmObject", nullptr},
+ };
+ for (Class c = cls; c; c = class_getSuperclass(c))
+ for (const auto &entry : classes)
+ if (!strcmp(class_getName(c), entry.frontend))
+ return entry.iogpu ? objc_getClass(entry.iogpu) : nil;
+ return objc_getClass("IOGPUMetalDevice");
+}
+
+static BOOL resolveStub(id cls, SEL, SEL selector) {
+ Class ref = referenceClass((Class)cls);
+ Method method = ref ? class_getInstanceMethod(ref, selector) : nullptr;
+ if (!method) return NO;
+ fprintf(stderr, "XnuCpuMetal: %s: stubbed %s %s\n", getprogname(), class_getName((Class)cls), sel_getName(selector));
+ return class_addMethod((Class)cls, selector, (IMP)stub, method_getTypeEncoding(method));
+}
+
+static char kPriorityKey, kBackgroundPriorityKey;
+static NSUInteger priorityOf(id queue, const void *key, NSUInteger initial) {
+ NSNumber *v = objc_getAssociatedObject(queue, key);
+ return v ? v.unsignedIntegerValue : initial;
+}
+static NSUInteger getGPUPriority(id self, SEL) { return priorityOf(self, &kPriorityKey, 1); }
+static NSUInteger getBackgroundGPUPriority(id self, SEL) { return priorityOf(self, &kBackgroundPriorityKey, 2); }
+static void setPriorities(id self, NSUInteger priority, NSUInteger background) {
+ objc_setAssociatedObject(self, &kPriorityKey, @(priority), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ objc_setAssociatedObject(self, &kBackgroundPriorityKey, @(background), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+}
+static BOOL setGPUPriority(id self, SEL, NSUInteger priority) {
+ setPriorities(self, priority, getBackgroundGPUPriority(self, nullptr));
+ return YES;
+}
+static BOOL setGPUPriorityOffset(id self, SEL, NSUInteger priority, NSUInteger) { return setGPUPriority(self, nullptr, priority); }
+static BOOL setBothGPUPriorities(id self, SEL, NSUInteger priority, NSUInteger background) {
+ setPriorities(self, priority, background);
+ return YES;
+}
+
+static char kUserDictionaryKey;
+static id userDictionary(id self, SEL) {
+ @synchronized(self) {
+ NSMutableDictionary *d = objc_getAssociatedObject(self, &kUserDictionaryKey);
+ if (!d) {
+ d = [NSMutableDictionary dictionary];
+ objc_setAssociatedObject(self, &kUserDictionaryKey, d, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ return d;
+ }
+}
+
+static char kBitCodeHashKey;
+static const void *bitCodeHash(id self, SEL) {
+ @synchronized(self) {
+ NSData *hash = objc_getAssociatedObject(self, &kBitCodeHashKey);
+ if (!hash) {
+ static std::atomic<uint64_t> serial;
+ NSString *text = [NSString stringWithFormat:@"%@#%llu", [self valueForKey:@"name"], (unsigned long long)++serial];
+ NSData *bytes = [text dataUsingEncoding:NSUTF8StringEncoding];
+ NSMutableData *digest = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
+ CC_SHA256(bytes.bytes, (CC_LONG)bytes.length, (unsigned char *)digest.mutableBytes);
+ hash = digest;
+ objc_setAssociatedObject(self, &kBitCodeHashKey, hash, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
+ }
+ return hash.bytes;
+ }
+}
+
+struct MethodSpec {
+ const char *name;
+ IMP imp;
+ const char *types;
+ bool overrideExisting;
+};
+
+static void addMethods(Class cls, const MethodSpec *methods, size_t count) {
+ for (size_t i = 0; i < count; i++) {
+ SEL sel = sel_registerName(methods[i].name);
+ if (methods[i].overrideExisting || ![cls instancesRespondToSelector:sel])
+ class_addMethod(cls, sel, methods[i].imp, methods[i].types);
+ }
+}
+
+static void install(id device, io_service_t port) {
+ if (port) IOObjectRetain(port);
+ gAcceleratorPort = port;
+ static const MethodSpec deviceMethods[] = {
+ {"_setAcceleratorService:", (IMP)setAcceleratorService, "v24@0:8@16", false},
+ {"acceleratorPort", (IMP)acceleratorPort, "I16@0:8", true},
+ {"_setDeviceWrapper:", (IMP)setDeviceWrapper, "v24@0:8@16", true},
+ {"_deviceWrapper", (IMP)deviceWrapper, "@16@0:8", true},
+ {"isBuiltIn", (IMP)isBuiltIn, "B16@0:8", false},
+ {"supportPriorityBand", (IMP)no, "B16@0:8", false},
+ {"supportsBackgroundAppRole", (IMP)no, "B16@0:8", false},
+ {"isSlotted", (IMP)no, "B16@0:8", false},
+ {"supportsResourceDetachBacking", (IMP)no, "B16@0:8", false},
+ {"supportsVertexAmplification", (IMP)no, "B16@0:8", false},
+ {"supportsVertexAmplificationCount:", (IMP)amplificationCount, "B24@0:8Q16", false},
+ {"maxTransferRate", (IMP)zero, "Q16@0:8", false},
+ {"location", (IMP)zero, "Q16@0:8", false},
+ {"locationNumber", (IMP)zero, "Q16@0:8", false},
+ {"peerGroupID", (IMP)zero, "Q16@0:8", false},
+ {"peerIndex", (IMP)zero, "I16@0:8", false},
+ {"peerCount", (IMP)one, "I16@0:8", false},
+ {"dedicatedMemorySize", (IMP)zero, "Q16@0:8", false},
+ {"hwResourcePoolCount", (IMP)zero, "I16@0:8", false},
+ {"cmdBufArgsSize", (IMP)commandBufferArgumentsSize, "Q16@0:8", false},
+ {"kickCleanupQueue", (IMP)nothing, "v16@0:8", false},
+ {"updateGPUSelectionProperties", (IMP)nothing, "v16@0:8", false},
+ {"updateResourcePoolPurgeability", (IMP)nothing, "v16@0:8", false},
+ {"periodicUpdateResourcePoolPurgeability", (IMP)nothing, "v16@0:8", false},
+ {"cancelPeriodicUpdateResourcePoolPurgeability", (IMP)nothing, "v16@0:8", false},
+ {"recommendedMaxWorkingSetSize", (IMP)workingSetSize, "Q16@0:8", true},
+ {"sharedMemorySize", (IMP)workingSetSize, "Q16@0:8", true},
+ {"currentAllocatedSize", (IMP)zero, "Q16@0:8", false},
+ {"gpuCoreCount", (IMP)gpuCoreCount, "Q16@0:8", false},
+ {"featureProfile", (IMP)zero, "Q16@0:8", false},
+ };
+ Class cls = object_getClass(device);
+ addMethods(cls, deviceMethods, sizeof deviceMethods / sizeof *deviceMethods);
+ class_addMethod(object_getClass(cls), @selector(resolveInstanceMethod:), (IMP)resolveStub, "B24@0:8:16");
+
+ static const MethodSpec queueMethods[] = {
+ {"getGPUPriority", (IMP)getGPUPriority, "Q16@0:8", false},
+ {"getBackgroundGPUPriority", (IMP)getBackgroundGPUPriority, "Q16@0:8", false},
+ {"setGPUPriority:", (IMP)setGPUPriority, "B24@0:8Q16", false},
+ {"setGPUPriority:offset:", (IMP)setGPUPriorityOffset, "B32@0:8Q16Q24", false},
+ {"_setGPUPriority:backgroundPriority:", (IMP)setBothGPUPriorities, "B32@0:8Q16Q24", false},
+ };
+ if (Class q = objc_getClass("XcmQueue"))
+ addMethods(q, queueMethods, sizeof queueMethods / sizeof *queueMethods);
+
+ static const MethodSpec resMethods[] = {
+ {"setResponsibleProcess:", (IMP)nothingWith, "v20@0:8i16", false},
+ {"makeAliasable", (IMP)nothing, "v16@0:8", false},
+ };
+ for (const char *name : {"XcmBuffer", "XcmTexture"})
+ if (Class r = objc_getClass(name))
+ addMethods(r, resMethods, sizeof resMethods / sizeof *resMethods);
+
+ static const MethodSpec cbMethods[] = {{"userDictionary", (IMP)userDictionary, "@16@0:8", true}};
+ static const MethodSpec fnMethods[] = {{"bitCodeHash", (IMP)bitCodeHash, "^v16@0:8", false}};
+ if (Class fn = objc_getClass("XcmFunction")) addMethods(fn, fnMethods, 1);
+ if (Class cb = objc_getClass("XcmCommandBuffer")) addMethods(cb, cbMethods, 1);
+
+ static const char *const conformances[][2] = {
+ {"XcmBuffer", "MTLBuffer"}, {"XcmTexture", "MTLTexture"},
+ {"XcmLibrary", "MTLLibrary"}, {"XcmFunction", "MTLFunction"},
+ {"XcmComputePipeline", "MTLComputePipelineState"},
+ {"XcmRenderPipeline", "MTLRenderPipelineState"},
+ {"XcmSampler", "MTLSamplerState"}, {"XcmDepthStencil", "MTLDepthStencilState"},
+ {"XcmEvent", "MTLEvent"}, {"XcmFence", "MTLFence"},
+ {"XcmHeap", "MTLHeap"},
+ {"XcmQueue", "MTLCommandQueue"}, {"XcmCommandBuffer", "MTLCommandBuffer"},
+ {"XcmComputeEncoder", "MTLComputeCommandEncoder"},
+ {"XcmRenderEncoder", "MTLRenderCommandEncoder"},
+ {"XcmBlitEncoder", "MTLBlitCommandEncoder"},
+ };
+ for (const auto &c : conformances) {
+ Class frontend = objc_getClass(c[0]);
+ Protocol *proto = objc_getProtocol(c[1]);
+ if (frontend && proto) class_addProtocol(frontend, proto);
+ }
+ if (Class obj = objc_getClass("XcmObject"))
+ class_addMethod(object_getClass(obj), @selector(resolveInstanceMethod:), (IMP)resolveStub, "B24@0:8:16");
+}
+
+} // namespace xcm_iogpu
diff --git a/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml
new file mode 100644
index 0000000..5eb2127
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "xnu-m2v-bridge"
+version = "0.1.0"
+edition = "2021"
+
+[lib]
+name = "xnu_m2v"
+crate-type = ["cdylib", "staticlib"]
+
+[dependencies]
+metal2vulkan = { path = "../metal2vulkan/crates/metal2vulkan", features = ["ash"] }
+metal2vulkan-runtime = { path = "../metal2vulkan/crates/metal2vulkan-runtime" }
+libc = "0.2"
+
+[profile.release]
+opt-level = 3
+lto = "thin"
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
new file mode 100644
index 0000000..cf3d419
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/include/xnu_m2v.h
@@ -0,0 +1,316 @@
+#ifndef XNU_M2V_H
+#define XNU_M2V_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct Xm2vDevice Xm2vDevice;
+typedef struct Xm2vBuffer Xm2vBuffer;
+typedef struct Xm2vTexture Xm2vTexture;
+typedef struct Xm2vLibrary Xm2vLibrary;
+typedef struct Xm2vFunction Xm2vFunction;
+typedef struct Xm2vComputePipeline Xm2vComputePipeline;
+typedef struct Xm2vRenderPipeline Xm2vRenderPipeline;
+typedef struct Xm2vSampler Xm2vSampler;
+typedef struct Xm2vDepthStencil Xm2vDepthStencil;
+typedef struct Xm2vQueue Xm2vQueue;
+typedef struct Xm2vCommandBuffer Xm2vCommandBuffer;
+typedef struct Xm2vComputeEncoder Xm2vComputeEncoder;
+typedef struct Xm2vRenderEncoder Xm2vRenderEncoder;
+typedef struct Xm2vBlitEncoder Xm2vBlitEncoder;
+typedef struct Xm2vEvent Xm2vEvent;
+typedef struct Xm2vFence Xm2vFence;
+
+typedef struct Xm2vTextureDesc {
+ uint64_t texture_type;
+ uint64_t pixel_format;
+ uint64_t width;
+ uint64_t height;
+ uint64_t depth;
+ uint64_t mipmap_level_count;
+ uint64_t sample_count;
+ uint64_t array_length;
+ uint64_t resource_options;
+ uint64_t usage;
+} Xm2vTextureDesc;
+
+typedef struct Xm2vColorAttachmentDesc {
+ uint64_t pixel_format;
+ bool blending_enabled;
+ uint64_t rgb_blend_op;
+ uint64_t alpha_blend_op;
+ uint64_t src_rgb_blend;
+ uint64_t dst_rgb_blend;
+ uint64_t src_alpha_blend;
+ uint64_t dst_alpha_blend;
+ uint64_t write_mask;
+} Xm2vColorAttachmentDesc;
+
+typedef struct Xm2vVertexAttribute {
+ uint32_t index;
+ uint64_t format;
+ uint32_t offset;
+ uint32_t buffer_index;
+} Xm2vVertexAttribute;
+
+typedef struct Xm2vVertexLayout {
+ uint32_t index;
+ uint64_t stride;
+ uint64_t step_function;
+ uint32_t step_rate;
+ bool dynamic_stride;
+} Xm2vVertexLayout;
+
+typedef struct Xm2vRenderPipelineDesc {
+ Xm2vFunction *vertex_function;
+ Xm2vFunction *fragment_function;
+ uint32_t color_attachment_count;
+ Xm2vColorAttachmentDesc color_attachments[8];
+ uint64_t depth_attachment_pixel_format;
+ uint64_t stencil_attachment_pixel_format;
+ uint64_t sample_count;
+ Xm2vFunction *const *vertex_linked_functions;
+ uint32_t vertex_linked_function_count;
+ Xm2vFunction *const *vertex_private_linked_functions;
+ uint32_t vertex_private_linked_function_count;
+ Xm2vFunction *const *fragment_linked_functions;
+ uint32_t fragment_linked_function_count;
+ Xm2vFunction *const *fragment_private_linked_functions;
+ uint32_t fragment_private_linked_function_count;
+ const Xm2vVertexAttribute *vertex_attributes;
+ uint32_t vertex_attribute_count;
+ const Xm2vVertexLayout *vertex_layouts;
+ uint32_t vertex_layout_count;
+} Xm2vRenderPipelineDesc;
+
+typedef struct Xm2vRenderPassColorAttachment {
+ Xm2vTexture *texture;
+ uint64_t level;
+ uint64_t slice;
+ uint64_t load_action;
+ uint64_t store_action;
+ double clear_r, clear_g, clear_b, clear_a;
+} Xm2vRenderPassColorAttachment;
+
+typedef struct Xm2vRenderPassDesc {
+ uint32_t color_attachment_count;
+ Xm2vRenderPassColorAttachment color_attachments[8];
+ Xm2vTexture *depth_texture;
+ uint64_t depth_load_action;
+ uint64_t depth_store_action;
+ double clear_depth;
+ Xm2vTexture *stencil_texture;
+ uint64_t stencil_load_action;
+ uint64_t stencil_store_action;
+ uint32_t clear_stencil;
+} Xm2vRenderPassDesc;
+
+typedef struct Xm2vSamplerDesc {
+ uint64_t min_filter;
+ uint64_t mag_filter;
+ uint64_t mip_filter;
+ uint64_t s_address_mode;
+ uint64_t t_address_mode;
+ uint64_t r_address_mode;
+ uint64_t max_anisotropy;
+ uint64_t compare_function;
+ float lod_min_clamp;
+ float lod_max_clamp;
+ bool normalized_coordinates;
+} Xm2vSamplerDesc;
+
+typedef struct Xm2vStencilDesc {
+ bool enabled;
+ uint64_t stencil_compare_function;
+ uint64_t stencil_failure_operation;
+ uint64_t depth_failure_operation;
+ uint64_t depth_stencil_pass_operation;
+ uint32_t read_mask;
+ uint32_t write_mask;
+} Xm2vStencilDesc;
+
+typedef struct Xm2vDepthStencilDesc {
+ uint64_t depth_compare_function;
+ bool depth_write_enabled;
+ Xm2vStencilDesc front_face_stencil;
+ Xm2vStencilDesc back_face_stencil;
+} Xm2vDepthStencilDesc;
+
+/* Error reporting */
+const char *xm2v_last_error(void);
+
+/* Device */
+Xm2vDevice *xm2v_device_open(const char *loader_path, 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);
+bool xm2v_device_max_threads_per_threadgroup(const Xm2vDevice *dev, uint64_t out[3]);
+bool xm2v_device_supports_family(const Xm2vDevice *dev, int64_t family);
+
+/* Buffers */
+Xm2vBuffer *xm2v_buffer_new(Xm2vDevice *dev, uint64_t length, uint64_t resource_options, const void *bytes);
+Xm2vBuffer *xm2v_buffer_new_no_copy(Xm2vDevice *dev, void *ptr, uint64_t length, uint64_t resource_options);
+void xm2v_buffer_release(Xm2vBuffer *buf);
+void *xm2v_buffer_contents(const Xm2vBuffer *buf);
+uint64_t xm2v_buffer_length(const Xm2vBuffer *buf);
+uint64_t xm2v_buffer_gpu_address(const Xm2vBuffer *buf);
+void xm2v_buffer_did_modify_range(const Xm2vBuffer *buf, uint64_t location, uint64_t length);
+
+/* Textures */
+Xm2vTexture *xm2v_texture_new(Xm2vDevice *dev, const Xm2vTextureDesc *desc);
+Xm2vTexture *xm2v_texture_new_view(Xm2vTexture *tex, uint64_t pixel_format, uint64_t texture_type,
+ uint64_t level_start, uint64_t level_len,
+ uint64_t slice_start, uint64_t slice_len);
+void xm2v_texture_release(Xm2vTexture *tex);
+bool xm2v_texture_replace_region(const Xm2vTexture *tex,
+ uint64_t x, uint64_t y, uint64_t z,
+ uint64_t w, uint64_t h, uint64_t d,
+ uint64_t mip_level, uint64_t slice,
+ const void *bytes, uint64_t bytes_per_row, uint64_t bytes_per_image);
+bool xm2v_texture_get_bytes(const Xm2vTexture *tex,
+ void *out_bytes, uint64_t bytes_per_row, uint64_t bytes_per_image,
+ uint64_t x, uint64_t y, uint64_t z,
+ uint64_t w, uint64_t h, uint64_t d,
+ uint64_t mip_level, uint64_t slice);
+
+/* Libraries & Functions */
+typedef struct Xm2vConstant {
+ uint64_t data_type;
+ uint32_t index;
+ const char *name; /* NULL => indexed constant */
+ const void *bytes;
+ size_t length;
+} Xm2vConstant;
+
+Xm2vLibrary *xm2v_library_new_with_data(Xm2vDevice *dev, const void *bytes, size_t len);
+void xm2v_library_release(Xm2vLibrary *lib);
+size_t xm2v_library_function_count(const Xm2vLibrary *lib);
+size_t xm2v_library_function_name_at(const Xm2vLibrary *lib, size_t index, char *out, size_t size);
+size_t xm2v_library_extern_function_count(const Xm2vLibrary *lib);
+size_t xm2v_library_extern_function_name_at(const Xm2vLibrary *lib, size_t index, char *out, size_t size);
+Xm2vFunction *xm2v_library_new_function(Xm2vLibrary *lib, const char *name);
+Xm2vFunction *xm2v_library_new_extern_function(Xm2vLibrary *lib, const char *name);
+Xm2vFunction *xm2v_library_new_function_specialized(Xm2vLibrary *lib, const char *name,
+ const Xm2vConstant *constants, uint32_t count);
+Xm2vFunction *xm2v_library_new_function_specialized_zero_rest(Xm2vLibrary *lib, const char *name,
+ const Xm2vConstant *constants, uint32_t count);
+Xm2vFunction *xm2v_library_new_function_with_descriptor(Xm2vLibrary *lib, const char *name,
+ const char *specialized_name,
+ const Xm2vConstant *constants, uint32_t count,
+ uint64_t options);
+void xm2v_function_release(Xm2vFunction *fn);
+uint32_t xm2v_function_type(const Xm2vFunction *fn);
+
+/* Pipelines & States */
+Xm2vComputePipeline *xm2v_compute_pipeline_new(Xm2vDevice *dev, Xm2vFunction *fn);
+Xm2vComputePipeline *xm2v_compute_pipeline_new_with_linked(Xm2vDevice *dev, Xm2vFunction *fn,
+ Xm2vFunction *const *linked_fns, uint32_t linked_count,
+ Xm2vFunction *const *private_fns, uint32_t private_count);
+void xm2v_compute_pipeline_release(Xm2vComputePipeline *pso);
+uint64_t xm2v_compute_pipeline_max_threads(const Xm2vComputePipeline *pso);
+uint64_t xm2v_compute_pipeline_thread_width(const Xm2vComputePipeline *pso);
+uint64_t xm2v_compute_pipeline_static_tg_mem(const Xm2vComputePipeline *pso);
+
+Xm2vRenderPipeline *xm2v_render_pipeline_new(Xm2vDevice *dev, const Xm2vRenderPipelineDesc *desc);
+void xm2v_render_pipeline_release(Xm2vRenderPipeline *pso);
+
+Xm2vSampler *xm2v_sampler_new(Xm2vDevice *dev, const Xm2vSamplerDesc *desc);
+void xm2v_sampler_release(Xm2vSampler *s);
+
+Xm2vDepthStencil *xm2v_depth_stencil_new(Xm2vDevice *dev, const Xm2vDepthStencilDesc *desc);
+void xm2v_depth_stencil_release(Xm2vDepthStencil *ds);
+
+/* Queue & CommandBuffer */
+Xm2vQueue *xm2v_queue_new(Xm2vDevice *dev);
+void xm2v_queue_release(Xm2vQueue *q);
+
+Xm2vCommandBuffer *xm2v_command_buffer_new(Xm2vQueue *q);
+void xm2v_command_buffer_release(Xm2vCommandBuffer *cb);
+bool xm2v_command_buffer_commit(Xm2vCommandBuffer *cb);
+bool xm2v_command_buffer_wait_until_completed(Xm2vCommandBuffer *cb, uint64_t timeout_ms);
+uint32_t xm2v_command_buffer_status(const Xm2vCommandBuffer *cb);
+bool xm2v_command_buffer_encode_signal_event(Xm2vCommandBuffer *cb, Xm2vEvent *ev, uint64_t value);
+bool xm2v_command_buffer_encode_wait_event(Xm2vCommandBuffer *cb, Xm2vEvent *ev, uint64_t value);
+
+/* Compute Encoder */
+Xm2vComputeEncoder *xm2v_compute_encoder_new(Xm2vCommandBuffer *cb);
+bool xm2v_compute_encoder_set_pipeline(Xm2vComputeEncoder *enc, Xm2vComputePipeline *pso);
+bool xm2v_compute_encoder_set_buffer(Xm2vComputeEncoder *enc, Xm2vBuffer *buf, uint64_t offset, uint32_t index);
+bool xm2v_compute_encoder_set_bytes(Xm2vComputeEncoder *enc, const void *bytes, size_t len, uint32_t index);
+bool xm2v_compute_encoder_set_texture(Xm2vComputeEncoder *enc, Xm2vTexture *tex, uint32_t index);
+bool xm2v_compute_encoder_set_sampler(Xm2vComputeEncoder *enc, Xm2vSampler *samp, uint32_t index);
+bool xm2v_compute_encoder_set_threadgroup_memory_length(Xm2vComputeEncoder *enc, uint32_t length, uint32_t index);
+bool xm2v_compute_encoder_dispatch_threadgroups(Xm2vComputeEncoder *enc,
+ uint64_t gx, uint64_t gy, uint64_t gz,
+ uint64_t tx, uint64_t ty, uint64_t tz);
+bool xm2v_compute_encoder_dispatch_threads(Xm2vComputeEncoder *enc,
+ uint64_t gx, uint64_t gy, uint64_t gz,
+ uint64_t tx, uint64_t ty, uint64_t tz);
+bool xm2v_compute_encoder_end(Xm2vComputeEncoder *enc);
+
+/* Render Encoder */
+Xm2vRenderEncoder *xm2v_render_encoder_new(Xm2vCommandBuffer *cb, const Xm2vRenderPassDesc *desc);
+bool xm2v_render_encoder_set_pipeline(Xm2vRenderEncoder *enc, Xm2vRenderPipeline *pso);
+bool xm2v_render_encoder_set_depth_stencil(Xm2vRenderEncoder *enc, Xm2vDepthStencil *ds);
+bool xm2v_render_encoder_set_viewport(Xm2vRenderEncoder *enc, double x, double y, double w, double h, double znear, double zfar);
+bool xm2v_render_encoder_set_scissor(Xm2vRenderEncoder *enc, uint64_t x, uint64_t y, uint64_t w, uint64_t h);
+bool xm2v_render_encoder_set_cull_mode(Xm2vRenderEncoder *enc, uint64_t mode);
+bool xm2v_render_encoder_set_front_facing_winding(Xm2vRenderEncoder *enc, uint64_t winding);
+bool xm2v_render_encoder_set_stencil_reference_values(Xm2vRenderEncoder *enc, uint32_t front, uint32_t back);
+bool xm2v_render_encoder_set_blend_color(Xm2vRenderEncoder *enc, float r, float g, float b, float a);
+bool xm2v_render_encoder_set_vertex_buffer(Xm2vRenderEncoder *enc, Xm2vBuffer *buf, uint64_t offset, uint32_t index);
+bool xm2v_render_encoder_set_vertex_bytes(Xm2vRenderEncoder *enc, const void *bytes, size_t len, uint32_t index);
+bool xm2v_render_encoder_set_vertex_texture(Xm2vRenderEncoder *enc, Xm2vTexture *tex, uint32_t index);
+bool xm2v_render_encoder_set_vertex_sampler(Xm2vRenderEncoder *enc, Xm2vSampler *samp, uint32_t index);
+bool xm2v_render_encoder_set_fragment_buffer(Xm2vRenderEncoder *enc, Xm2vBuffer *buf, uint64_t offset, uint32_t index);
+bool xm2v_render_encoder_set_fragment_bytes(Xm2vRenderEncoder *enc, const void *bytes, size_t len, uint32_t index);
+bool xm2v_render_encoder_set_fragment_texture(Xm2vRenderEncoder *enc, Xm2vTexture *tex, uint32_t index);
+bool xm2v_render_encoder_set_fragment_sampler(Xm2vRenderEncoder *enc, Xm2vSampler *samp, uint32_t index);
+bool xm2v_render_encoder_draw_primitives(Xm2vRenderEncoder *enc, uint64_t prim, uint64_t vertex_start, uint64_t vertex_count,
+ uint64_t instance_count, uint64_t base_instance);
+bool xm2v_render_encoder_draw_indexed_primitives(Xm2vRenderEncoder *enc, uint64_t prim, uint64_t index_count, uint64_t index_type,
+ Xm2vBuffer *index_buf, uint64_t index_offset, uint64_t instance_count,
+ int64_t base_vertex, uint64_t base_instance);
+bool xm2v_render_encoder_end(Xm2vRenderEncoder *enc);
+
+/* Blit Encoder */
+Xm2vBlitEncoder *xm2v_blit_encoder_new(Xm2vCommandBuffer *cb);
+bool xm2v_blit_encoder_copy_buffer_to_buffer(Xm2vBlitEncoder *enc, Xm2vBuffer *src, uint64_t src_off,
+ Xm2vBuffer *dst, uint64_t dst_off, uint64_t size);
+bool xm2v_blit_encoder_copy_buffer_to_texture(Xm2vBlitEncoder *enc, Xm2vBuffer *src, uint64_t src_off,
+ uint64_t src_bpr, uint64_t src_bpi,
+ uint64_t w, uint64_t h, uint64_t d,
+ Xm2vTexture *dst, uint64_t dst_slice, uint64_t dst_level,
+ uint64_t dx, uint64_t dy, uint64_t dz);
+bool xm2v_blit_encoder_copy_texture_to_buffer(Xm2vBlitEncoder *enc, Xm2vTexture *src, uint64_t src_slice, uint64_t src_level,
+ uint64_t sx, uint64_t sy, uint64_t sz,
+ uint64_t w, uint64_t h, uint64_t d,
+ Xm2vBuffer *dst, uint64_t dst_off, uint64_t dst_bpr, uint64_t dst_bpi);
+bool xm2v_blit_encoder_copy_texture_to_texture(Xm2vBlitEncoder *enc,
+ Xm2vTexture *src, uint64_t src_slice, uint64_t src_level,
+ uint64_t sx, uint64_t sy, uint64_t sz,
+ uint64_t w, uint64_t h, uint64_t d,
+ Xm2vTexture *dst, uint64_t dst_slice, uint64_t dst_level,
+ uint64_t dx, uint64_t dy, uint64_t dz);
+bool xm2v_blit_encoder_fill_buffer(Xm2vBlitEncoder *enc, Xm2vBuffer *buf, uint64_t location, uint64_t length, uint8_t value);
+bool xm2v_blit_encoder_generate_mipmaps(Xm2vBlitEncoder *enc, Xm2vTexture *tex);
+bool xm2v_blit_encoder_synchronize_buffer(Xm2vBlitEncoder *enc, Xm2vBuffer *buf);
+bool xm2v_blit_encoder_synchronize_texture(Xm2vBlitEncoder *enc, Xm2vTexture *tex);
+bool xm2v_blit_encoder_end(Xm2vBlitEncoder *enc);
+
+/* Events & Fences */
+Xm2vEvent *xm2v_event_new(Xm2vDevice *dev);
+void xm2v_event_release(Xm2vEvent *ev);
+Xm2vFence *xm2v_fence_new(Xm2vDevice *dev);
+void xm2v_fence_release(Xm2vFence *f);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* XNU_M2V_H */
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
new file mode 100644
index 0000000..df09383
--- /dev/null
+++ b/gpu/xnu-cpu-metal/src/xnu-m2v-bridge/src/lib.rs
@@ -0,0 +1,1929 @@
+//! C ABI bridge over `metal2vulkan` and `metal2vulkan-runtime` for xnulinux CPU Metal.
+
+use metal2vulkan::bind::SamplerDescriptor;
+use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
+use metal2vulkan::metal::state::{DepthStencilDescriptor, StencilDescriptor};
+use metal2vulkan::metal::{
+ BlendFactor, BlendOperation, ColorWriteMask, CompareFunction, CullMode, DataType,
+ FunctionOptions, IndexType, PixelFormat, PrimitiveType, SamplerAddressMode,
+ SamplerMinMagFilter, SamplerMipFilter, StencilOperation, TextureType, TextureUsage,
+ VertexFormat, VertexStepFunction, Winding,
+};
+use metal2vulkan::pipeline::{
+ ColorAttachmentDescriptor, ComputePipelineDescriptor, LinkedFunctions,
+ RenderPipelineDescriptor, StageSource, VertexAttributeDescriptor,
+ VertexBufferLayoutDescriptor, VertexDescriptor,
+};
+use metal2vulkan_runtime::{
+ BlitCommandEncoder, BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus,
+ CommandQueue, ComputeCommandEncoder, ComputePipelineState, DepthStencilState, Device,
+ DeviceOptions, Event, EventRef, Fence, Function, FunctionDescriptor, HostMemory, Library,
+ LoadAction, Origin, PipelineOptions, Region, RenderCommandEncoder, RenderPassDescriptor,
+ RenderPipelineState, ResourceOptions, ResourceRef, SamplerState, ScissorRect,
+ ShaderCacheOptions, Size, StoreAction, Texture, TextureDescriptor, Viewport,
+};
+use std::cell::RefCell;
+use std::ffi::{c_char, c_void, CStr};
+use std::path::PathBuf;
+use std::ptr::NonNull;
+use std::time::Duration;
+
+thread_local! {
+ static LAST_ERR: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
+}
+
+fn set_error(msg: impl Into<String>) {
+ let s = msg.into();
+ LAST_ERR.with(|cell| {
+ let mut buf = cell.borrow_mut();
+ buf.clear();
+ buf.extend(s.bytes().filter(|&b| b != 0));
+ buf.push(0);
+ });
+}
+
+fn guard<T>(fallback: T, f: impl FnOnce() -> Result<T, String>) -> T {
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
+ Ok(Ok(v)) => v,
+ Ok(Err(e)) => {
+ set_error(e);
+ fallback
+ }
+ Err(p) => {
+ let msg = p
+ .downcast_ref::<String>()
+ .map(String::as_str)
+ .or_else(|| p.downcast_ref::<&str>().copied())
+ .unwrap_or("unknown panic");
+ set_error(format!("panic: {msg}"));
+ fallback
+ }
+ }
+}
+
+fn boxed<T>(v: T) -> *mut T {
+ Box::into_raw(Box::new(v))
+}
+
+fn get<'a, T>(p: *const T) -> Result<&'a T, String> {
+ unsafe { p.as_ref() }.ok_or_else(|| "null handle".to_string())
+}
+
+fn get_mut<'a, T>(p: *mut T) -> Result<&'a mut T, String> {
+ unsafe { p.as_mut() }.ok_or_else(|| "null handle".to_string())
+}
+
+fn take_box<T>(p: *mut T) -> Result<Box<T>, String> {
+ if p.is_null() {
+ Err("null handle".to_string())
+ } else {
+ Ok(unsafe { Box::from_raw(p) })
+ }
+}
+
+fn release<T>(p: *mut T) {
+ if !p.is_null() {
+ drop(unsafe { Box::from_raw(p) });
+ }
+}
+
+fn copy_str(s: &str, out: *mut c_char, size: usize) -> usize {
+ if !out.is_null() && size > 0 {
+ let n = s.len().min(size - 1);
+ unsafe {
+ std::ptr::copy_nonoverlapping(s.as_ptr(), out.cast::<u8>(), n);
+ *out.add(n) = 0;
+ }
+ }
+ s.len()
+}
+
+fn cstr_opt(p: *const c_char) -> Option<String> {
+ if p.is_null() {
+ return None;
+ }
+ let s = unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned();
+ if s.is_empty() {
+ None
+ } else {
+ Some(s)
+ }
+}
+
+fn raw_enum<T: TryFrom<u32>>(v: u64, what: &str) -> Result<T, String>
+where
+ T::Error: std::fmt::Debug,
+{
+ u32::try_from(v)
+ .ok()
+ .and_then(|x| T::try_from(x).ok())
+ .ok_or_else(|| format!("invalid {what}: {v}"))
+}
+
+fn raw_opts(v: u64) -> Result<ResourceOptions, String> {
+ ResourceOptions::from_raw(v).map_err(|e| format!("resource options {v:#x}: {e:?}"))
+}
+
+fn raw_load(v: u64) -> Result<LoadAction, String> {
+ match v {
+ 0 => Ok(LoadAction::DontCare),
+ 1 => Ok(LoadAction::Load),
+ 2 => Ok(LoadAction::Clear),
+ _ => Err(format!("invalid load_action: {v}")),
+ }
+}
+
+fn raw_store(v: u64) -> Result<StoreAction, String> {
+ match v {
+ 0 => Ok(StoreAction::DontCare),
+ 1 => Ok(StoreAction::Store),
+ 2 => Ok(StoreAction::MultisampleResolve),
+ 3 => Ok(StoreAction::StoreAndMultisampleResolve),
+ _ => Err(format!("invalid store_action: {v}")),
+ }
+}
+
+/* ---- C descriptor structs ---- */
+
+#[repr(C)]
+pub struct Xm2vTextureDesc {
+ pub texture_type: u64,
+ pub pixel_format: u64,
+ pub width: u64,
+ pub height: u64,
+ pub depth: u64,
+ pub mipmap_level_count: u64,
+ pub sample_count: u64,
+ pub array_length: u64,
+ pub resource_options: u64,
+ pub usage: u64,
+}
+
+#[repr(C)]
+pub struct Xm2vColorAttachmentDesc {
+ pub pixel_format: u64,
+ pub blending_enabled: bool,
+ pub rgb_blend_op: u64,
+ pub alpha_blend_op: u64,
+ pub src_rgb_blend: u64,
+ pub dst_rgb_blend: u64,
+ pub src_alpha_blend: u64,
+ pub dst_alpha_blend: u64,
+ pub write_mask: u64,
+}
+
+#[repr(C)]
+pub struct Xm2vVertexAttribute {
+ pub index: u32,
+ pub format: u64,
+ pub offset: u32,
+ pub buffer_index: u32,
+}
+
+#[repr(C)]
+pub struct Xm2vVertexLayout {
+ pub index: u32,
+ pub stride: u64,
+ pub step_function: u64,
+ pub step_rate: u32,
+ pub dynamic_stride: bool,
+}
+
+#[repr(C)]
+pub struct Xm2vRenderPipelineDesc {
+ pub vertex_function: *mut Function,
+ pub fragment_function: *mut Function,
+ pub color_attachment_count: u32,
+ pub color_attachments: [Xm2vColorAttachmentDesc; 8],
+ pub depth_attachment_pixel_format: u64,
+ pub stencil_attachment_pixel_format: u64,
+ pub sample_count: u64,
+ pub vertex_linked_functions: *const *mut Function,
+ pub vertex_linked_function_count: u32,
+ pub vertex_private_linked_functions: *const *mut Function,
+ pub vertex_private_linked_function_count: u32,
+ pub fragment_linked_functions: *const *mut Function,
+ pub fragment_linked_function_count: u32,
+ pub fragment_private_linked_functions: *const *mut Function,
+ pub fragment_private_linked_function_count: u32,
+ pub vertex_attributes: *const Xm2vVertexAttribute,
+ pub vertex_attribute_count: u32,
+ pub vertex_layouts: *const Xm2vVertexLayout,
+ pub vertex_layout_count: u32,
+}
+
+#[repr(C)]
+pub struct Xm2vRenderPassColorAttachment {
+ pub texture: *mut Texture,
+ pub level: u64,
+ pub slice: u64,
+ pub load_action: u64,
+ pub store_action: u64,
+ pub clear_r: f64,
+ pub clear_g: f64,
+ pub clear_b: f64,
+ pub clear_a: f64,
+}
+
+#[repr(C)]
+pub struct Xm2vRenderPassDesc {
+ pub color_attachment_count: u32,
+ pub color_attachments: [Xm2vRenderPassColorAttachment; 8],
+ pub depth_texture: *mut Texture,
+ pub depth_load_action: u64,
+ pub depth_store_action: u64,
+ pub clear_depth: f64,
+ pub stencil_texture: *mut Texture,
+ pub stencil_load_action: u64,
+ pub stencil_store_action: u64,
+ pub clear_stencil: u32,
+}
+
+#[repr(C)]
+pub struct Xm2vSamplerDesc {
+ pub min_filter: u64,
+ pub mag_filter: u64,
+ pub mip_filter: u64,
+ pub s_address_mode: u64,
+ pub t_address_mode: u64,
+ pub r_address_mode: u64,
+ pub max_anisotropy: u64,
+ pub compare_function: u64,
+ pub lod_min_clamp: f32,
+ pub lod_max_clamp: f32,
+ pub normalized_coordinates: bool,
+}
+
+#[repr(C)]
+pub struct Xm2vStencilDesc {
+ pub enabled: bool,
+ pub stencil_compare_function: u64,
+ pub stencil_failure_operation: u64,
+ pub depth_failure_operation: u64,
+ pub depth_stencil_pass_operation: u64,
+ pub read_mask: u32,
+ pub write_mask: u32,
+}
+
+#[repr(C)]
+pub struct Xm2vDepthStencilDesc {
+ pub depth_compare_function: u64,
+ pub depth_write_enabled: bool,
+ pub front_face_stencil: Xm2vStencilDesc,
+ pub back_face_stencil: Xm2vStencilDesc,
+}
+
+/* ---- Error ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_last_error() -> *const c_char {
+ LAST_ERR.with(|cell| {
+ let buf = cell.borrow();
+ if buf.is_empty() {
+ c"".as_ptr()
+ } else {
+ buf.as_ptr().cast::<c_char>()
+ }
+ })
+}
+
+/* ---- Device ---- */
+
+#[no_mangle]
+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 {
+ guard(std::ptr::null_mut(), || {
+ if let Some(icd) = cstr_opt(icd_json_path) {
+ unsafe {
+ std::env::set_var("VK_ICD_FILENAMES", &icd);
+ std::env::set_var("VK_DRIVER_FILES", &icd);
+ }
+ }
+ let mut opts = DeviceOptions::default();
+ if let Some(loader) = cstr_opt(loader_path) {
+ opts.loader = Some(PathBuf::from(loader));
+ }
+ if let Some(cache) = cstr_opt(cache_dir) {
+ opts.shader_cache = ShaderCacheOptions::in_directory(cache);
+ }
+ let dev = Device::system_default_with(&opts).map_err(|e| format!("device open: {e:?}"))?;
+ Ok(boxed(dev))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_release(dev: *mut Device) {
+ release(dev);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_name(dev: *const Device, out: *mut c_char, size: usize) -> usize {
+ guard(0, || {
+ let dev = get(dev)?;
+ Ok(copy_str(&dev.name(), out, size))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_max_buffer_length(dev: *const Device) -> u64 {
+ guard(0, || Ok(get(dev)?.properties().max_buffer_length))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_max_threads_per_threadgroup(
+ dev: *const Device,
+ out: *mut u64,
+) -> bool {
+ guard(false, || {
+ let dev = get(dev)?;
+ if out.is_null() {
+ return Err("null out".to_string());
+ }
+ let s = dev.properties().max_threads_per_threadgroup;
+ unsafe {
+ *out.add(0) = s.width;
+ *out.add(1) = s.height;
+ *out.add(2) = s.depth;
+ }
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_device_supports_family(dev: *const Device, family: i64) -> bool {
+ guard(false, || Ok(get(dev)?.supports_family(family)))
+}
+
+/* ---- Buffers ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new(
+ dev: *mut Device,
+ length: u64,
+ resource_options: u64,
+ bytes: *const c_void,
+) -> *mut Buffer {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let opts = raw_opts(resource_options)?;
+ let buf = if bytes.is_null() {
+ dev.new_buffer(length, opts)
+ } else {
+ let slice = unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), length as usize) };
+ dev.new_buffer_with_bytes(slice, opts)
+ }
+ .map_err(|e| format!("new_buffer: {e:?}"))?;
+ Ok(boxed(buf))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_new_no_copy(
+ dev: *mut Device,
+ ptr: *mut c_void,
+ length: u64,
+ resource_options: u64,
+) -> *mut Buffer {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let opts = raw_opts(resource_options)?;
+ let nn = NonNull::new(ptr.cast::<u8>()).ok_or_else(|| "null ptr".to_string())?;
+ let hm = unsafe { HostMemory::new(nn) };
+ let buf = unsafe { dev.new_buffer_with_bytes_no_copy(hm, length, opts, None) }
+ .map_err(|e| format!("new_buffer_no_copy: {e:?}"))?;
+ Ok(boxed(buf))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_release(buf: *mut Buffer) {
+ release(buf);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_contents(buf: *const Buffer) -> *mut c_void {
+ guard(std::ptr::null_mut(), || {
+ Ok(get(buf)?
+ .contents()
+ .map(|p| p.as_ptr().cast::<c_void>())
+ .unwrap_or(std::ptr::null_mut()))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_length(buf: *const Buffer) -> u64 {
+ guard(0, || Ok(get(buf)?.length()))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_gpu_address(buf: *const Buffer) -> u64 {
+ guard(0, || Ok(get(buf)?.gpu_address().0))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_buffer_did_modify_range(buf: *const Buffer, location: u64, length: u64) {
+ let _ = guard((), || {
+ let _ = get(buf)?.did_modify_range(location..location.saturating_add(length));
+ Ok(())
+ });
+}
+
+/* ---- Textures ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_texture_new(
+ dev: *mut Device,
+ desc: *const Xm2vTextureDesc,
+) -> *mut Texture {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let d = get(desc)?;
+ let pixel_format: PixelFormat = raw_enum(d.pixel_format, "PixelFormat")?;
+ let texture_type: TextureType = raw_enum(d.texture_type, "TextureType")?;
+ let mut td = TextureDescriptor::texture_2d(
+ pixel_format,
+ d.width.max(1),
+ d.height.max(1),
+ d.mipmap_level_count > 1,
+ );
+ td.texture_type = texture_type;
+ td.depth = d.depth.max(1);
+ td.mipmap_level_count = d.mipmap_level_count.max(1);
+ td.sample_count = d.sample_count.max(1);
+ td.array_length = d.array_length.max(1);
+ td.resource_options = raw_opts(d.resource_options)?;
+ td.usage = raw_enum::<TextureUsage>(d.usage, "TextureUsage")?;
+ let tex = dev
+ .new_texture(&td)
+ .map_err(|e| format!("new_texture: {e:?}"))?;
+ Ok(boxed(tex))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_texture_new_view(
+ tex: *mut Texture,
+ pixel_format: u64,
+ texture_type: u64,
+ level_start: u64,
+ level_len: u64,
+ slice_start: u64,
+ slice_len: u64,
+) -> *mut Texture {
+ guard(std::ptr::null_mut(), || {
+ let tex = get(tex)?;
+ let pf: PixelFormat = raw_enum(pixel_format, "PixelFormat")?;
+ let tt: TextureType = raw_enum(texture_type, "TextureType")?;
+ let view = tex
+ .new_texture_view_with_levels_slices(
+ pf,
+ tt,
+ level_start..level_start.saturating_add(level_len),
+ slice_start..slice_start.saturating_add(slice_len),
+ )
+ .map_err(|e| format!("new_texture_view: {e:?}"))?;
+ Ok(boxed(view))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_texture_release(tex: *mut Texture) {
+ release(tex);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_texture_replace_region(
+ tex: *const Texture,
+ x: u64,
+ y: u64,
+ z: u64,
+ w: u64,
+ h: u64,
+ d: u64,
+ mip_level: u64,
+ slice: u64,
+ bytes: *const c_void,
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+) -> bool {
+ guard(false, || {
+ let tex = get(tex)?;
+ if bytes.is_null() {
+ return Err("null bytes".to_string());
+ }
+ let total = if bytes_per_image > 0 {
+ bytes_per_image * d.max(1)
+ } else {
+ bytes_per_row * h.max(1) * d.max(1)
+ };
+ let src = unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), total as usize) };
+ let region = Region::new_3d(x, y, z, w, h, d);
+ tex.replace_region(region, mip_level, slice, src, bytes_per_row, bytes_per_image)
+ .map_err(|e| format!("replace_region: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_texture_get_bytes(
+ tex: *const Texture,
+ out_bytes: *mut c_void,
+ bytes_per_row: u64,
+ bytes_per_image: u64,
+ x: u64,
+ y: u64,
+ z: u64,
+ w: u64,
+ h: u64,
+ d: u64,
+ mip_level: u64,
+ slice: u64,
+) -> bool {
+ guard(false, || {
+ let tex = get(tex)?;
+ if out_bytes.is_null() {
+ return Err("null out_bytes".to_string());
+ }
+ let total = if bytes_per_image > 0 {
+ bytes_per_image * d.max(1)
+ } else {
+ bytes_per_row * h.max(1) * d.max(1)
+ };
+ let dst = unsafe { std::slice::from_raw_parts_mut(out_bytes.cast::<u8>(), total as usize) };
+ let region = Region::new_3d(x, y, z, w, h, d);
+ tex.get_bytes(dst, bytes_per_row, bytes_per_image, region, mip_level, slice)
+ .map_err(|e| format!("get_bytes: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+/* ---- Libraries & Functions ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_with_data(
+ dev: *mut Device,
+ bytes: *const c_void,
+ len: usize,
+) -> *mut Library {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ if bytes.is_null() || len == 0 {
+ return Err("empty library data".to_string());
+ }
+ let slice = unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), len) };
+ let lib = dev
+ .new_library_with_data(slice)
+ .map_err(|e| format!("new_library_with_data: {e:?}"))?;
+ Ok(boxed(lib))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_release(lib: *mut Library) {
+ release(lib);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_function_count(lib: *const Library) -> usize {
+ guard(0, || Ok(get(lib)?.function_names().len()))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_function_name_at(
+ lib: *const Library,
+ index: usize,
+ out: *mut c_char,
+ size: usize,
+) -> usize {
+ guard(0, || {
+ let names = get(lib)?.function_names();
+ let name = names
+ .get(index)
+ .ok_or_else(|| format!("function index {index} out of bounds"))?;
+ Ok(copy_str(name, out, size))
+ })
+}
+
+#[repr(C)]
+pub struct Xm2vConstant {
+ pub data_type: u64,
+ pub index: u32,
+ pub name: *const c_char,
+ pub bytes: *const c_void,
+ pub length: usize,
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_extern_function_count(lib: *const Library) -> usize {
+ guard(0, || Ok(get(lib)?.extern_function_names().len()))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_extern_function_name_at(
+ lib: *const Library,
+ index: usize,
+ out: *mut c_char,
+ size: usize,
+) -> usize {
+ guard(0, || {
+ let names = get(lib)?.extern_function_names();
+ let name = names
+ .get(index)
+ .ok_or_else(|| format!("extern function index {index} out of bounds"))?;
+ Ok(copy_str(name, out, size))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_function(
+ lib: *mut Library,
+ name: *const c_char,
+) -> *mut Function {
+ guard(std::ptr::null_mut(), || {
+ let lib = get(lib)?;
+ let name = cstr_opt(name).ok_or_else(|| "empty function name".to_string())?;
+ let f = lib
+ .new_function_with_name(&name)
+ .map_err(|e| format!("new_function({name}): {e:?}"))?;
+ Ok(boxed(f))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_extern_function(
+ lib: *mut Library,
+ name: *const c_char,
+) -> *mut Function {
+ guard(std::ptr::null_mut(), || {
+ let lib = get(lib)?;
+ let name = cstr_opt(name).ok_or_else(|| "empty extern function name".to_string())?;
+ let f = lib
+ .new_extern_function_with_name(&name)
+ .map_err(|e| format!("new_extern_function({name}): {e:?}"))?;
+ Ok(boxed(f))
+ })
+}
+
+fn build_fcv(constants: *const Xm2vConstant, count: u32) -> Result<FunctionConstantValues, String> {
+ let mut fcv = FunctionConstantValues::defaults();
+ if count > 0 && !constants.is_null() {
+ let slice = unsafe { std::slice::from_raw_parts(constants, count as usize) };
+ for c in slice {
+ let ty: DataType = raw_enum(c.data_type, "DataType")?;
+ let bytes = if c.bytes.is_null() || c.length == 0 {
+ Vec::new()
+ } else {
+ unsafe { std::slice::from_raw_parts(c.bytes.cast::<u8>(), c.length) }.to_vec()
+ };
+ let val = FunctionConstantValue::new(ty, bytes);
+ if let Some(cname) = cstr_opt(c.name) {
+ fcv = fcv.with_name(cname, val);
+ } else {
+ fcv = fcv.with_index(c.index, val);
+ }
+ }
+ }
+ Ok(fcv)
+}
+
+fn build_linked(
+ public_fns: *const *mut Function,
+ public_count: u32,
+ private_fns: *const *mut Function,
+ private_count: u32,
+) -> Result<LinkedFunctions, String> {
+ let mut linked = LinkedFunctions::new();
+ if public_count > 0 && !public_fns.is_null() {
+ let slice = unsafe { std::slice::from_raw_parts(public_fns, public_count as usize) };
+ for &fp in slice {
+ if !fp.is_null() {
+ linked = linked.with_function(get(fp)?.linked_function());
+ }
+ }
+ }
+ if private_count > 0 && !private_fns.is_null() {
+ let slice = unsafe { std::slice::from_raw_parts(private_fns, private_count as usize) };
+ for &fp in slice {
+ if !fp.is_null() {
+ linked = linked.with_private_function(get(fp)?.linked_function());
+ }
+ }
+ }
+ Ok(linked)
+}
+
+fn constant_bytes(raw: u32) -> usize {
+ match raw {
+ 3..=6 => (raw as usize - 2) * 4,
+ 16..=19 => (raw as usize - 15) * 2,
+ 29..=32 => (raw as usize - 28) * 4,
+ 33..=36 => (raw as usize - 32) * 4,
+ 37..=40 => (raw as usize - 36) * 2,
+ 41..=44 => (raw as usize - 40) * 2,
+ 45..=48 => raw as usize - 44,
+ 49..=52 => raw as usize - 48,
+ 53..=56 => raw as usize - 52,
+ 81..=84 => (raw as usize - 80) * 8,
+ 85..=88 => (raw as usize - 84) * 8,
+ 121..=124 => (raw as usize - 120) * 2,
+ _ => 0,
+ }
+}
+
+fn fill_zero_rest(lib: &Library, name: &str, fcv: &mut FunctionConstantValues) -> Result<(), String> {
+ let generic = lib
+ .new_function_with_name(name)
+ .map_err(|e| format!("new_function({name}): {e:?}"))?;
+ let dict = generic
+ .function_constants_dictionary()
+ .map_err(|e| format!("function_constants_dictionary({name}): {e:?}"))?;
+ for (key, constant) in dict {
+ if fcv.by_name.contains_key(&key) || fcv.by_index.contains_key(&constant.index()) {
+ continue;
+ }
+ let ty = constant.data_type();
+ let sz = constant_bytes(ty.as_raw());
+ if sz > 0 {
+ fcv.by_index
+ .insert(constant.index(), FunctionConstantValue::new(ty, vec![0u8; sz]));
+ }
+ }
+ Ok(())
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_function_specialized(
+ lib: *mut Library,
+ name: *const c_char,
+ constants: *const Xm2vConstant,
+ count: u32,
+) -> *mut Function {
+ guard(std::ptr::null_mut(), || {
+ let lib = get(lib)?;
+ let name = cstr_opt(name).ok_or_else(|| "empty function name".to_string())?;
+ let fcv = build_fcv(constants, count)?;
+ let f = lib
+ .new_function_with_name_constant_values(&name, &fcv)
+ .map_err(|e| format!("new_function_specialized({name}): {e:?}"))?;
+ Ok(boxed(f))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_function_specialized_zero_rest(
+ lib: *mut Library,
+ name: *const c_char,
+ constants: *const Xm2vConstant,
+ count: u32,
+) -> *mut Function {
+ guard(std::ptr::null_mut(), || {
+ let lib = get(lib)?;
+ let name = cstr_opt(name).ok_or_else(|| "empty function name".to_string())?;
+ let mut fcv = build_fcv(constants, count)?;
+ fill_zero_rest(lib, &name, &mut fcv)?;
+ let f = lib
+ .new_function_with_name_constant_values(&name, &fcv)
+ .map_err(|e| format!("new_function_specialized_zero_rest({name}): {e:?}"))?;
+ Ok(boxed(f))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_library_new_function_with_descriptor(
+ lib: *mut Library,
+ name: *const c_char,
+ specialized_name: *const c_char,
+ constants: *const Xm2vConstant,
+ count: u32,
+ options: u64,
+) -> *mut Function {
+ guard(std::ptr::null_mut(), || {
+ let lib = get(lib)?;
+ let name = cstr_opt(name).ok_or_else(|| "empty function name".to_string())?;
+ let mut fd = FunctionDescriptor::new(&name);
+ if let Some(sname) = cstr_opt(specialized_name) {
+ fd = fd.with_specialized_name(sname);
+ }
+ if count > 0 && !constants.is_null() {
+ fd.constant_values = Some(build_fcv(constants, count)?);
+ }
+ fd.options = raw_enum::<FunctionOptions>(options, "FunctionOptions")?;
+ let f = lib
+ .new_function_with_descriptor(&fd)
+ .map_err(|e| format!("new_function_with_descriptor({name}): {e:?}"))?;
+ Ok(boxed(f))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_function_release(f: *mut Function) {
+ release(f);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_function_type(f: *const Function) -> u32 {
+ guard(0, || {
+ let ft = get(f)?
+ .function_type()
+ .map_err(|e| format!("function_type: {e:?}"))?;
+ Ok(ft as u32)
+ })
+}
+
+/* ---- Pipelines & States ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_new(
+ dev: *mut Device,
+ f: *mut Function,
+) -> *mut ComputePipelineState {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let f = get(f)?;
+ let pso = dev
+ .new_compute_pipeline_state_with_function(f, &PipelineOptions::default())
+ .map_err(|e| format!("compute pipeline: {e:?}"))?;
+ Ok(boxed(pso))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_new_with_linked(
+ dev: *mut Device,
+ f: *mut Function,
+ linked_fns: *const *mut Function,
+ linked_count: u32,
+ private_fns: *const *mut Function,
+ private_count: u32,
+) -> *mut ComputePipelineState {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let f = get(f)?;
+ let linked = build_linked(linked_fns, linked_count, private_fns, private_count)?;
+ let fd = if linked.is_empty() {
+ f.function_descriptor()
+ } else {
+ f.function_descriptor().with_linked(linked)
+ };
+ let cpd = ComputePipelineDescriptor::new(StageSource::Function(fd));
+ let pso = dev
+ .new_compute_pipeline_state(&cpd, &PipelineOptions::default())
+ .map_err(|e| format!("compute pipeline: {e:?}"))?;
+ Ok(boxed(pso))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_release(pso: *mut ComputePipelineState) {
+ release(pso);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_max_threads(pso: *const ComputePipelineState) -> u64 {
+ guard(0, || Ok(get(pso)?.max_total_threads_per_threadgroup() as u64))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_thread_width(pso: *const ComputePipelineState) -> u64 {
+ guard(0, || Ok(get(pso)?.thread_execution_width() as u64))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_pipeline_static_tg_mem(pso: *const ComputePipelineState) -> u64 {
+ guard(0, || Ok(get(pso)?.static_threadgroup_memory_length() as u64))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_pipeline_new(
+ dev: *mut Device,
+ desc: *const Xm2vRenderPipelineDesc,
+) -> *mut RenderPipelineState {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let d = get(desc)?;
+ let vfn = get(d.vertex_function)?;
+ let vlinked = build_linked(
+ d.vertex_linked_functions,
+ d.vertex_linked_function_count,
+ d.vertex_private_linked_functions,
+ d.vertex_private_linked_function_count,
+ )?;
+ let vfd = if vlinked.is_empty() {
+ vfn.function_descriptor()
+ } else {
+ vfn.function_descriptor().with_linked(vlinked)
+ };
+ let mut rpd = RenderPipelineDescriptor::new(StageSource::Function(vfd));
+ if !d.fragment_function.is_null() {
+ let ffn = get(d.fragment_function)?;
+ let flinked = build_linked(
+ d.fragment_linked_functions,
+ d.fragment_linked_function_count,
+ d.fragment_private_linked_functions,
+ d.fragment_private_linked_function_count,
+ )?;
+ let ffd = if flinked.is_empty() {
+ ffn.function_descriptor()
+ } else {
+ ffn.function_descriptor().with_linked(flinked)
+ };
+ rpd.fragment = Some(StageSource::Function(ffd));
+ }
+ let count = (d.color_attachment_count as usize).min(8);
+ for i in 0..count {
+ let ca = &d.color_attachments[i];
+ if ca.pixel_format == 0 {
+ continue;
+ }
+ let pf: PixelFormat = raw_enum(ca.pixel_format, "PixelFormat")?;
+ let mut cad = ColorAttachmentDescriptor::new(pf);
+ cad.blending_enabled = ca.blending_enabled;
+ if ca.blending_enabled {
+ cad.rgb_blend_operation = raw_enum::<BlendOperation>(ca.rgb_blend_op, "BlendOp")?;
+ cad.alpha_blend_operation = raw_enum::<BlendOperation>(ca.alpha_blend_op, "BlendOp")?;
+ cad.source_rgb_blend_factor = raw_enum::<BlendFactor>(ca.src_rgb_blend, "BlendFactor")?;
+ cad.destination_rgb_blend_factor = raw_enum::<BlendFactor>(ca.dst_rgb_blend, "BlendFactor")?;
+ cad.source_alpha_blend_factor = raw_enum::<BlendFactor>(ca.src_alpha_blend, "BlendFactor")?;
+ cad.destination_alpha_blend_factor = raw_enum::<BlendFactor>(ca.dst_alpha_blend, "BlendFactor")?;
+ }
+ cad.write_mask = raw_enum::<ColorWriteMask>(ca.write_mask, "ColorWriteMask")?;
+ rpd.color_attachments[i] = Some(cad);
+ }
+ if d.depth_attachment_pixel_format != 0 {
+ rpd.depth_format = Some(raw_enum(d.depth_attachment_pixel_format, "DepthFormat")?);
+ }
+ if d.stencil_attachment_pixel_format != 0 {
+ rpd.stencil_format = Some(raw_enum(d.stencil_attachment_pixel_format, "StencilFormat")?);
+ }
+ if d.sample_count > 1 {
+ rpd.raster_sample_count = d.sample_count as u32;
+ }
+ if (d.vertex_attribute_count > 0 && !d.vertex_attributes.is_null())
+ || (d.vertex_layout_count > 0 && !d.vertex_layouts.is_null())
+ {
+ let mut vd = VertexDescriptor::new();
+ if d.vertex_attribute_count > 0 && !d.vertex_attributes.is_null() {
+ let attrs = unsafe {
+ std::slice::from_raw_parts(d.vertex_attributes, d.vertex_attribute_count as usize)
+ };
+ for a in attrs {
+ let fmt: VertexFormat = raw_enum(a.format, "VertexFormat")?;
+ vd.attributes.insert(
+ a.index,
+ VertexAttributeDescriptor::new(fmt, a.offset, a.buffer_index),
+ );
+ }
+ }
+ if d.vertex_layout_count > 0 && !d.vertex_layouts.is_null() {
+ let layouts = unsafe {
+ std::slice::from_raw_parts(d.vertex_layouts, d.vertex_layout_count as usize)
+ };
+ for l in layouts {
+ let stride = if l.dynamic_stride {
+ None
+ } else {
+ Some(l.stride as u32)
+ };
+ let mut ld = VertexBufferLayoutDescriptor::new(stride);
+ ld.step_function = raw_enum::<VertexStepFunction>(l.step_function, "VertexStepFunction")?;
+ ld.step_rate = l.step_rate;
+ vd.layouts.insert(l.index, ld);
+ }
+ }
+ rpd.vertex_descriptor = Some(vd);
+ }
+ let pso = dev
+ .new_render_pipeline_state(&rpd, &PipelineOptions::default())
+ .map_err(|e| format!("render pipeline: {e:?}"))?;
+ Ok(boxed(pso))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_pipeline_release(pso: *mut RenderPipelineState) {
+ release(pso);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_sampler_new(
+ dev: *mut Device,
+ desc: *const Xm2vSamplerDesc,
+) -> *mut SamplerState {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let d = get(desc)?;
+ let mut sd = SamplerDescriptor::default();
+ sd.min_filter = raw_enum::<SamplerMinMagFilter>(d.min_filter, "MinFilter")?;
+ sd.mag_filter = raw_enum::<SamplerMinMagFilter>(d.mag_filter, "MagFilter")?;
+ sd.mip_filter = raw_enum::<SamplerMipFilter>(d.mip_filter, "MipFilter")?;
+ sd.s_address_mode = raw_enum::<SamplerAddressMode>(d.s_address_mode, "SAddressMode")?;
+ sd.t_address_mode = raw_enum::<SamplerAddressMode>(d.t_address_mode, "TAddressMode")?;
+ sd.r_address_mode = raw_enum::<SamplerAddressMode>(d.r_address_mode, "RAddressMode")?;
+ sd.max_anisotropy = (d.max_anisotropy.max(1)) as u32;
+ sd.compare_function = raw_enum::<CompareFunction>(d.compare_function, "CompareFunction")?;
+ sd.lod_min_clamp = d.lod_min_clamp;
+ sd.lod_max_clamp = d.lod_max_clamp;
+ sd.normalized_coordinates = d.normalized_coordinates;
+ let s = dev
+ .new_sampler_state(&sd)
+ .map_err(|e| format!("new_sampler_state: {e:?}"))?;
+ Ok(boxed(s))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_sampler_release(s: *mut SamplerState) {
+ release(s);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_depth_stencil_new(
+ dev: *mut Device,
+ desc: *const Xm2vDepthStencilDesc,
+) -> *mut DepthStencilState {
+ guard(std::ptr::null_mut(), || {
+ let dev = get(dev)?;
+ let d = get(desc)?;
+ let mut dsd = DepthStencilDescriptor::default();
+ dsd.depth_compare_function =
+ raw_enum::<CompareFunction>(d.depth_compare_function, "CompareFunction")?;
+ dsd.depth_write_enabled = d.depth_write_enabled;
+ let map_stencil = |s: &Xm2vStencilDesc| -> Result<StencilDescriptor, String> {
+ let mut sd = StencilDescriptor::default();
+ if !s.enabled {
+ return Ok(sd);
+ }
+ sd.stencil_compare_function =
+ raw_enum::<CompareFunction>(s.stencil_compare_function, "StencilCompareFunction")?;
+ sd.stencil_failure_operation =
+ raw_enum::<StencilOperation>(s.stencil_failure_operation, "StencilFailureOp")?;
+ sd.depth_failure_operation =
+ raw_enum::<StencilOperation>(s.depth_failure_operation, "DepthFailureOp")?;
+ sd.depth_stencil_pass_operation = raw_enum::<StencilOperation>(
+ s.depth_stencil_pass_operation,
+ "DepthStencilPassOp",
+ )?;
+ sd.read_mask = s.read_mask;
+ sd.write_mask = s.write_mask;
+ Ok(sd)
+ };
+ dsd.front_face_stencil = map_stencil(&d.front_face_stencil)?;
+ dsd.back_face_stencil = map_stencil(&d.back_face_stencil)?;
+ let ds = dev
+ .new_depth_stencil_state(&dsd)
+ .map_err(|e| format!("new_depth_stencil_state: {e:?}"))?;
+ Ok(boxed(ds))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_depth_stencil_release(ds: *mut DepthStencilState) {
+ release(ds);
+}
+
+/* ---- Queue & CommandBuffer ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_queue_new(dev: *mut Device) -> *mut CommandQueue {
+ guard(std::ptr::null_mut(), || {
+ let q = get(dev)?
+ .new_command_queue()
+ .map_err(|e| format!("new_command_queue: {e:?}"))?;
+ Ok(boxed(q))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_queue_release(q: *mut CommandQueue) {
+ release(q);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_new(q: *mut CommandQueue) -> *mut CommandBuffer {
+ guard(std::ptr::null_mut(), || {
+ let cb = get(q)?
+ .command_buffer()
+ .map_err(|e| format!("command_buffer: {e:?}"))?;
+ Ok(boxed(cb))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_release(cb: *mut CommandBuffer) {
+ release(cb);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_commit(cb: *mut CommandBuffer) -> bool {
+ guard(false, || {
+ get(cb)?
+ .commit()
+ .map_err(|e| format!("commit: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_wait_until_completed(
+ cb: *mut CommandBuffer,
+ timeout_ms: u64,
+) -> bool {
+ guard(false, || {
+ let cb = get(cb)?;
+ if timeout_ms == 0 {
+ let _ = cb.wait_until_completed();
+ } else {
+ cb.wait_until_completed_for(Duration::from_millis(timeout_ms))
+ .map_err(|e| format!("wait_until_completed: {e:?}"))?;
+ }
+ Ok(cb.status() == CommandBufferStatus::Completed)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_status(cb: *const CommandBuffer) -> u32 {
+ guard(5, || {
+ Ok(match get(cb)?.status() {
+ CommandBufferStatus::NotEnqueued => 0,
+ CommandBufferStatus::Enqueued => 1,
+ CommandBufferStatus::Committed => 2,
+ CommandBufferStatus::Scheduled => 3,
+ CommandBufferStatus::Completed => 4,
+ CommandBufferStatus::Error => 5,
+ _ => 5,
+ })
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_signal_event(
+ cb: *mut CommandBuffer,
+ ev: *mut Event,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_signal_event(EventRef::Event(get(ev)?), value)
+ .map_err(|e| format!("encode_signal_event: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_command_buffer_encode_wait_event(
+ cb: *mut CommandBuffer,
+ ev: *mut Event,
+ value: u64,
+) -> bool {
+ guard(false, || {
+ get(cb)?
+ .encode_wait_for_event(EventRef::Event(get(ev)?), value)
+ .map_err(|e| format!("encode_wait_for_event: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+/* ---- Compute Encoder ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_new(cb: *mut CommandBuffer) -> *mut ComputeCommandEncoder {
+ guard(std::ptr::null_mut(), || {
+ let enc = get(cb)?
+ .compute_command_encoder()
+ .map_err(|e| format!("compute_command_encoder: {e:?}"))?;
+ Ok(boxed(enc))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_pipeline(
+ enc: *mut ComputeCommandEncoder,
+ pso: *mut ComputePipelineState,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .set_compute_pipeline_state(get(pso)?)
+ .map_err(|e| format!("set_compute_pipeline_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_buffer(
+ enc: *mut ComputeCommandEncoder,
+ buf: *mut Buffer,
+ offset: u64,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let b = if buf.is_null() { None } else { Some(get(buf)?) };
+ get_mut(enc)?
+ .set_buffer(b, offset, index)
+ .map_err(|e| format!("set_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_bytes(
+ enc: *mut ComputeCommandEncoder,
+ bytes: *const c_void,
+ len: usize,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let slice = if bytes.is_null() || len == 0 {
+ &[]
+ } else {
+ unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), len) }
+ };
+ get_mut(enc)?
+ .set_bytes(slice, index)
+ .map_err(|e| format!("set_bytes: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_texture(
+ enc: *mut ComputeCommandEncoder,
+ tex: *mut Texture,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let t = if tex.is_null() { None } else { Some(get(tex)?) };
+ get_mut(enc)?
+ .set_texture(t, index)
+ .map_err(|e| format!("set_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_sampler(
+ enc: *mut ComputeCommandEncoder,
+ samp: *mut SamplerState,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let s = if samp.is_null() { None } else { Some(get(samp)?) };
+ get_mut(enc)?
+ .set_sampler_state(s, index)
+ .map_err(|e| format!("set_sampler_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_set_threadgroup_memory_length(
+ enc: *mut ComputeCommandEncoder,
+ length: u32,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .set_threadgroup_memory_length(length, index)
+ .map_err(|e| format!("set_threadgroup_memory_length: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_dispatch_threadgroups(
+ enc: *mut ComputeCommandEncoder,
+ gx: u64,
+ gy: u64,
+ gz: u64,
+ tx: u64,
+ ty: u64,
+ tz: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .dispatch_threadgroups(Size::new(gx, gy, gz), Size::new(tx, ty, tz))
+ .map_err(|e| format!("dispatch_threadgroups: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_dispatch_threads(
+ enc: *mut ComputeCommandEncoder,
+ gx: u64,
+ gy: u64,
+ gz: u64,
+ tx: u64,
+ ty: u64,
+ tz: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .dispatch_threads(Size::new(gx, gy, gz), Size::new(tx, ty, tz))
+ .map_err(|e| format!("dispatch_threads: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_compute_encoder_end(enc: *mut ComputeCommandEncoder) -> bool {
+ guard(false, || {
+ take_box(enc)?
+ .end_encoding()
+ .map_err(|e| format!("compute end_encoding: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+/* ---- Render Encoder ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_new(
+ cb: *mut CommandBuffer,
+ desc: *const Xm2vRenderPassDesc,
+) -> *mut RenderCommandEncoder {
+ guard(std::ptr::null_mut(), || {
+ let cb = get(cb)?;
+ let d = get(desc)?;
+ let mut rpd = RenderPassDescriptor::new();
+ let count = (d.color_attachment_count as usize).min(8);
+ for i in 0..count {
+ let ca = &d.color_attachments[i];
+ if !ca.texture.is_null() {
+ let att = &mut rpd.color_attachments[i];
+ att.texture = Some(get(ca.texture)?.clone());
+ att.level = ca.level;
+ att.slice = ca.slice;
+ att.load_action = raw_load(ca.load_action)?;
+ att.store_action = raw_store(ca.store_action)?;
+ att.clear_color = ClearColor::new(ca.clear_r, ca.clear_g, ca.clear_b, ca.clear_a);
+ }
+ }
+ if !d.depth_texture.is_null() {
+ rpd.depth_attachment.texture = Some(get(d.depth_texture)?.clone());
+ rpd.depth_attachment.load_action = raw_load(d.depth_load_action)?;
+ rpd.depth_attachment.store_action = raw_store(d.depth_store_action)?;
+ rpd.depth_attachment.clear_depth = d.clear_depth;
+ }
+ if !d.stencil_texture.is_null() {
+ rpd.stencil_attachment.texture = Some(get(d.stencil_texture)?.clone());
+ rpd.stencil_attachment.load_action = raw_load(d.stencil_load_action)?;
+ rpd.stencil_attachment.store_action = raw_store(d.stencil_store_action)?;
+ rpd.stencil_attachment.clear_stencil = d.clear_stencil;
+ }
+ let enc = cb
+ .render_command_encoder(&rpd)
+ .map_err(|e| format!("render_command_encoder: {e:?}"))?;
+ Ok(boxed(enc))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_pipeline(
+ enc: *mut RenderCommandEncoder,
+ pso: *mut RenderPipelineState,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .set_render_pipeline_state(get(pso)?)
+ .map_err(|e| format!("set_render_pipeline_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_depth_stencil(
+ enc: *mut RenderCommandEncoder,
+ ds: *mut DepthStencilState,
+) -> bool {
+ guard(false, || {
+ let s = if ds.is_null() { None } else { Some(get(ds)?) };
+ get_mut(enc)?
+ .set_depth_stencil_state(s)
+ .map_err(|e| format!("set_depth_stencil_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_stencil_reference_values(
+ enc: *mut RenderCommandEncoder,
+ front: u32,
+ back: u32,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?.set_stencil_reference_values(front, back);
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_blend_color(
+ enc: *mut RenderCommandEncoder,
+ r: f32,
+ g: f32,
+ b: f32,
+ a: f32,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?.set_blend_color(r, g, b, a);
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_viewport(
+ enc: *mut RenderCommandEncoder,
+ x: f64,
+ y: f64,
+ w: f64,
+ h: f64,
+ znear: f64,
+ zfar: f64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .set_viewport(Viewport {
+ origin_x: x,
+ origin_y: y,
+ width: w,
+ height: h,
+ znear,
+ zfar,
+ })
+ .map_err(|e| format!("set_viewport: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_scissor(
+ enc: *mut RenderCommandEncoder,
+ x: u64,
+ y: u64,
+ w: u64,
+ h: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .set_scissor_rect(ScissorRect {
+ x,
+ y,
+ width: w,
+ height: h,
+ })
+ .map_err(|e| format!("set_scissor_rect: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_cull_mode(
+ enc: *mut RenderCommandEncoder,
+ mode: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?.set_cull_mode(raw_enum::<CullMode>(mode, "CullMode")?);
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_front_facing_winding(
+ enc: *mut RenderCommandEncoder,
+ winding: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?.set_front_facing_winding(raw_enum::<Winding>(winding, "Winding")?);
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_vertex_buffer(
+ enc: *mut RenderCommandEncoder,
+ buf: *mut Buffer,
+ offset: u64,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let b = if buf.is_null() { None } else { Some(get(buf)?) };
+ get_mut(enc)?
+ .set_vertex_buffer(b, offset, index)
+ .map_err(|e| format!("set_vertex_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_vertex_bytes(
+ enc: *mut RenderCommandEncoder,
+ bytes: *const c_void,
+ len: usize,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let slice = if bytes.is_null() || len == 0 {
+ &[]
+ } else {
+ unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), len) }
+ };
+ get_mut(enc)?
+ .set_vertex_bytes(slice, index)
+ .map_err(|e| format!("set_vertex_bytes: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_vertex_texture(
+ enc: *mut RenderCommandEncoder,
+ tex: *mut Texture,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let t = if tex.is_null() { None } else { Some(get(tex)?) };
+ get_mut(enc)?
+ .set_vertex_texture(t, index)
+ .map_err(|e| format!("set_vertex_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_vertex_sampler(
+ enc: *mut RenderCommandEncoder,
+ samp: *mut SamplerState,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let s = if samp.is_null() { None } else { Some(get(samp)?) };
+ get_mut(enc)?
+ .set_vertex_sampler_state(s, index)
+ .map_err(|e| format!("set_vertex_sampler_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_fragment_buffer(
+ enc: *mut RenderCommandEncoder,
+ buf: *mut Buffer,
+ offset: u64,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let b = if buf.is_null() { None } else { Some(get(buf)?) };
+ get_mut(enc)?
+ .set_fragment_buffer(b, offset, index)
+ .map_err(|e| format!("set_fragment_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_fragment_bytes(
+ enc: *mut RenderCommandEncoder,
+ bytes: *const c_void,
+ len: usize,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let slice = if bytes.is_null() || len == 0 {
+ &[]
+ } else {
+ unsafe { std::slice::from_raw_parts(bytes.cast::<u8>(), len) }
+ };
+ get_mut(enc)?
+ .set_fragment_bytes(slice, index)
+ .map_err(|e| format!("set_fragment_bytes: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_fragment_texture(
+ enc: *mut RenderCommandEncoder,
+ tex: *mut Texture,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let t = if tex.is_null() { None } else { Some(get(tex)?) };
+ get_mut(enc)?
+ .set_fragment_texture(t, index)
+ .map_err(|e| format!("set_fragment_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_set_fragment_sampler(
+ enc: *mut RenderCommandEncoder,
+ samp: *mut SamplerState,
+ index: u32,
+) -> bool {
+ guard(false, || {
+ let s = if samp.is_null() { None } else { Some(get(samp)?) };
+ get_mut(enc)?
+ .set_fragment_sampler_state(s, index)
+ .map_err(|e| format!("set_fragment_sampler_state: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_draw_primitives(
+ enc: *mut RenderCommandEncoder,
+ prim: u64,
+ vertex_start: u64,
+ vertex_count: u64,
+ instance_count: u64,
+ base_instance: u64,
+) -> bool {
+ guard(false, || {
+ let p: PrimitiveType = raw_enum(prim, "PrimitiveType")?;
+ get_mut(enc)?
+ .draw_primitives(
+ p,
+ vertex_start as u32,
+ vertex_count as u32,
+ instance_count as u32,
+ base_instance as u32,
+ )
+ .map_err(|e| format!("draw_primitives: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_draw_indexed_primitives(
+ enc: *mut RenderCommandEncoder,
+ prim: u64,
+ index_count: u64,
+ index_type: u64,
+ index_buf: *mut Buffer,
+ index_offset: u64,
+ instance_count: u64,
+ base_vertex: i64,
+ base_instance: u64,
+) -> bool {
+ guard(false, || {
+ let p: PrimitiveType = raw_enum(prim, "PrimitiveType")?;
+ let it: IndexType = raw_enum(index_type, "IndexType")?;
+ get_mut(enc)?
+ .draw_indexed_primitives(
+ p,
+ index_count as u32,
+ it,
+ get(index_buf)?,
+ index_offset,
+ instance_count as u32,
+ base_vertex as i32,
+ base_instance as u32,
+ )
+ .map_err(|e| format!("draw_indexed_primitives: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_render_encoder_end(enc: *mut RenderCommandEncoder) -> bool {
+ guard(false, || {
+ take_box(enc)?
+ .end_encoding()
+ .map_err(|e| format!("render end_encoding: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+/* ---- Blit Encoder ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_new(cb: *mut CommandBuffer) -> *mut BlitCommandEncoder {
+ guard(std::ptr::null_mut(), || {
+ let enc = get(cb)?
+ .blit_command_encoder()
+ .map_err(|e| format!("blit_command_encoder: {e:?}"))?;
+ Ok(boxed(enc))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_copy_buffer_to_buffer(
+ enc: *mut BlitCommandEncoder,
+ src: *mut Buffer,
+ src_off: u64,
+ dst: *mut Buffer,
+ dst_off: u64,
+ size: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .copy_from_buffer_to_buffer(get(src)?, src_off, get(dst)?, dst_off, size)
+ .map_err(|e| format!("copy_from_buffer_to_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_copy_buffer_to_texture(
+ enc: *mut BlitCommandEncoder,
+ src: *mut Buffer,
+ src_off: u64,
+ src_bpr: u64,
+ src_bpi: u64,
+ w: u64,
+ h: u64,
+ d: u64,
+ dst: *mut Texture,
+ dst_slice: u64,
+ dst_level: u64,
+ dx: u64,
+ dy: u64,
+ dz: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .copy_from_buffer_to_texture(
+ get(src)?,
+ src_off,
+ src_bpr,
+ src_bpi,
+ Size::new(w, h, d),
+ get(dst)?,
+ dst_slice,
+ dst_level,
+ Origin::new(dx, dy, dz),
+ BlitOption::None,
+ )
+ .map_err(|e| format!("copy_from_buffer_to_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_copy_texture_to_buffer(
+ enc: *mut BlitCommandEncoder,
+ src: *mut Texture,
+ src_slice: u64,
+ src_level: u64,
+ sx: u64,
+ sy: u64,
+ sz: u64,
+ w: u64,
+ h: u64,
+ d: u64,
+ dst: *mut Buffer,
+ dst_off: u64,
+ dst_bpr: u64,
+ dst_bpi: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .copy_from_texture_to_buffer(
+ get(src)?,
+ src_slice,
+ src_level,
+ Origin::new(sx, sy, sz),
+ Size::new(w, h, d),
+ get(dst)?,
+ dst_off,
+ dst_bpr,
+ dst_bpi,
+ BlitOption::None,
+ )
+ .map_err(|e| format!("copy_from_texture_to_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_copy_texture_to_texture(
+ enc: *mut BlitCommandEncoder,
+ src: *mut Texture,
+ src_slice: u64,
+ src_level: u64,
+ sx: u64,
+ sy: u64,
+ sz: u64,
+ w: u64,
+ h: u64,
+ d: u64,
+ dst: *mut Texture,
+ dst_slice: u64,
+ dst_level: u64,
+ dx: u64,
+ dy: u64,
+ dz: u64,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .copy_from_texture_to_texture(
+ get(src)?,
+ src_slice,
+ src_level,
+ Origin::new(sx, sy, sz),
+ Size::new(w, h, d),
+ get(dst)?,
+ dst_slice,
+ dst_level,
+ Origin::new(dx, dy, dz),
+ )
+ .map_err(|e| format!("copy_from_texture_to_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_fill_buffer(
+ enc: *mut BlitCommandEncoder,
+ buf: *mut Buffer,
+ location: u64,
+ length: u64,
+ value: u8,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .fill_buffer(get(buf)?, location..location.saturating_add(length), value)
+ .map_err(|e| format!("fill_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_generate_mipmaps(
+ enc: *mut BlitCommandEncoder,
+ tex: *mut Texture,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .generate_mipmaps(get(tex)?)
+ .map_err(|e| format!("generate_mipmaps: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_synchronize_buffer(
+ enc: *mut BlitCommandEncoder,
+ buf: *mut Buffer,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .synchronize_resource(ResourceRef::Buffer(get(buf)?))
+ .map_err(|e| format!("synchronize_buffer: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_synchronize_texture(
+ enc: *mut BlitCommandEncoder,
+ tex: *mut Texture,
+) -> bool {
+ guard(false, || {
+ get_mut(enc)?
+ .synchronize_resource(ResourceRef::Texture(get(tex)?))
+ .map_err(|e| format!("synchronize_texture: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_blit_encoder_end(enc: *mut BlitCommandEncoder) -> bool {
+ guard(false, || {
+ take_box(enc)?
+ .end_encoding()
+ .map_err(|e| format!("blit end_encoding: {e:?}"))?;
+ Ok(true)
+ })
+}
+
+/* ---- Events & Fences ---- */
+
+#[no_mangle]
+pub extern "C" fn xm2v_event_new(dev: *mut Device) -> *mut Event {
+ guard(std::ptr::null_mut(), || {
+ let ev = get(dev)?
+ .new_event()
+ .map_err(|e| format!("new_event: {e:?}"))?;
+ Ok(boxed(ev))
+ })
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_event_release(ev: *mut Event) {
+ release(ev);
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_fence_new(dev: *mut Device) -> *mut Fence {
+ guard(std::ptr::null_mut(), || Ok(boxed(get(dev)?.new_fence())))
+}
+
+#[no_mangle]
+pub extern "C" fn xm2v_fence_release(f: *mut Fence) {
+ release(f);
+}