Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Render OpenGL ES in guests

Jacky39f6e672e02b
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 7ca1f49e..5879d697 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -1699,6 +1699,7 @@ Apple's ROM and this patch. See `Firmware/openavb_boot_rom.md`.
| JB-33 | B | `patchTproOff` (record `kernel-exp-frida_tpro_off`) | `_xprr_tpro_enabled` (`__DATA_CONST`), found via the `if (xprr_tpro_enabled)` guard of the VM_REGION_FLAG_TPRO_ENABLED store | **Frida spawn support (opt-in, Frida set; port of mowisec/frida_patches_srd `tpro-off`).** libdyld asserts on every API entry that TPRO pages are read-only and aborts (`TPRO regions should not be writable on entry to dyld`); Frida's spawn handshake re-enters libdyld inside dyld's own TPRO window, so `frida -f` and spawn-gated apps abort. Clearing the flag takes the kernel's existing no-TPRO path for every process (global). Anchor: unique `adrp/ldr/cbz/ldr/cmp/b.lo/ldrh/orr #2/strh` window, decoded with Capstone; the flag must resolve into `__DATA_CONST` and hold 1, else fail closed. 26.4 `c0ecdb4b`: flag at file-off `0x7526D4` (1 → 0). See `Research/KernelCustomFirmwarePatches/patch_tpro_off.md`. | Frida set |
| JB-34 | B | `patchSyscallFilterOff` (record `kernel-exp-frida_syscall_filter_off`) | `_task_get_mach_trap_filter_mask`, `_task_get_mach_kobj_filter_mask`, `_mac_proc_check_syscall_unix` | **Frida in syscall-filtered processes (opt-in, Frida set; port of mowisec/frida_patches_srd `syscall-filter-off`).** Sandbox syscall filters (`syscall-unix/-mach/-mig`) deny the agent's own calls inside the target: attaching to trustd, apsd, cfprefsd, backboardd or runningboardd kills them, and in locationd `thread_get_state` returns `KERN_DENIED` (no threads for Stalker). The two mask accessors return NULL ("no filter", XNU `bsd_arm64.c:249`, `ipc_kobject.c:563`) and the MACF BSD check returns 0 (`systemcalls.c:162`); the rest of the sandbox is untouched. JB-07 (`kernel-boot-syscallmask`, which rewrites the masks as they are installed) does not reach these processes; this is the NULL-mask alternative that row mentions. Anchors: the inlined `bitstr_test` of each check (kobject one behind `cmn #1 ; b.eq`), and `and w1,#0xffff ; mov x0 ; bl ; mov ; cbnz w0` in unix_syscall; each must match once and the three functions must open `pacibsp ; stp`, else fail closed. 26.4 `c0ecdb4b`: file-off `0x1D43090`, `0x1D43120`, `0x24CCAE8` (2 words each). See `Research/KernelCustomFirmwarePatches/patch_syscall_filter_off.md`. | Frida set |
| JB-35 | C | `patchAksUnlockBagCount5` (records `kernel-cfw-aks_unlock_bag.redirect` / `.cave`) | AppleSEPKeyStore keybag-unlock external-method handler (the one whose `IOExternalMethodArguments` count check is `cmp w8,#3 ; b.eq ; cmp w8,#4 ; b.ne BadArg`) | **Escrow-bag unlock / encrypted backups for an iOS 26.6-or-newer userland on the 26.4 kernel (`iOSBase: .atLeast(26, 6)`; pipeline `applyAksUnlockBag5`, not `applyIOS27`).** From iOS 26.6 on, the userland keybag unlock sends `inputScalarCount == 5` (scalars[3]=flags&1, scalars[4]=flags); the 26.4 AppleSEPKeyStore handler accepts only 3 or 4 and rejects 5 with `kIOReturnBadArgument`, so every escrow-bag unlock fails and `backup2 encryption` returns EscrowFailure. The count-4 path reads only scalars[3] (the same flag bit), so a count-5 call is handled correctly by it unchanged. Redirect the `cmp w8,#4` into a 6-word cave that accepts 4 or 5 (both → the original count-4 path) else takes the handler's own BadArgument branch. Anchor (structural): the 13-word count-dispatch block matched by its fixed words with the four branch words masked (opcode+condition kept, imm19/imm26 wildcarded); BadArgument/count-4 targets decoded from the anchor's own branches, no absolute offset. The `cset w25,ne` word is part of the fixed match and is what makes the block unique among the five keystore handlers that share this 3/4-count preamble — see caveat (2). **Self-guarding:** the anchor requires `cmp w8,#4 ; b.ne` (the 3/4-only reject shape), so on a kernel that already accepts 5 (Apple-native 26.6+, or this patch's own output) it finds no match and no-ops — hence no cloudOS bound is needed. Replacement bytes from the keystone-verified `ARM64Encoder.encodeCmpWImmediate`/`encodeBCond`/`encodeB`. Kernelcache is SPTM-content-measured, so apply at create time (not hot-swappable). **Version floor empirically pinned (2026-10-26)** by scanning native iPhone17,3 kernelcaches: the keybag handler is `cmp#3;b.eq ; cmp#4;b.ne` (3/4 only) on 18.6.2 / 26.1 / 26.4 / **26.5 (23F77)**, and becomes `cmp#3;b.eq ; cmp#4;b.eq ; cmp#5;b.ne` (accepts 5) on **26.6 (23G71)** / 26.6.1 / 27.0.1 — Apple's own 26.6+ handler is byte-identical to the shape this patch synthesizes. **Review caveats (not yet on-device validated):** (1) the dispatch-table index of the patched handler is 13, not the "selector 12" the introducing commit's comment states — cosmetic (the block, not the label, is patched), but the comment should be corrected; (2) uniqueness rests on the arbitrary `cset w25` register allocation, so a kernel rebuild that reallocates it would drop the match (fail-closed) — the robust key would be the IOExternalMethod dispatch-table entry for the real keybag-unlock selector, needing on-device confirmation of that selector number before retargeting. See `KernelCustomFirmwarePatchAksUnlockBag.swift`. | `26.6+` |
+| JB-36 | B | `patchParavirtGLESRenderer` (record `kernel-cfw-paravirt_gles_renderer`) | The `AppleParavirtGPUARM` IOKit personality (AppleParavirtGPUIOGPUFamily) in `__PRELINK_INFO` | **OpenGL ES over Metal (upstream issue #793, on in `standard`).** `gfxInitializeLibrary` (OpenGLES `libGFXShared`) takes the renderer only from the `IOAcceleratorES` service's `IOGLESBundleName` / `IOGLESMetalBundleName` registry properties and loads `/System/Library/Extensions/<name>.bundle`; with neither, every `-[EAGLContext initWithAPI:]` returns nil although Metal works. Real AGX personalities carry `IOGLESBundleName = AppleMetalGLRenderer` (j236c `AGXG14X`, cloudOS 26.4); the paravirtual one names only its Metal plugin. A personality's keys become the matched driver's property table, so the key is added after `IOClass` in the prelink XML, indented like that line; the bytes come from the leading tabs of the lines that follow, so the record is about a hundred bytes and nothing else moves. Anchor: the one personality whose `IOClass` is `AppleParavirtGPU` and `IOMatchCategory` is `IOAcceleratorES`, flat dict; already present → no-op. The patched XML is parsed back and must equal the original plus that key. No code, no instruction bytes. Gated by `applyParavirtGLES`, set from the plan; tvOS and HomePod presets block it. Draws also need the compiler plugin's GLES metadata completion and guest row 30; see "OpenGL ES in guests (2026-11-02)" and `Research/Guest/gpu_acceleration.md`. | Y |
### EXP-Only Kernel Methods (Reference List)
@@ -1745,6 +1746,7 @@ do NOT execute these).
| 27 | No binary change: both spawn hooks insert `libdevicename.dylib` into `configd` and `lockdownd` (after `libmisfix.dylib`, the first process to take two inserted libraries). In `configd` it interposes `SCDynamicStoreSetMultiple` and `SCDynamicStoreSetValue` and pins `Setup:/System`'s `ComputerName`; in `lockdownd` it interposes `SCPreferencesSetComputerName`, `SCPreferencesSetHostName` and `SCPreferencesSetLocalHostName` and refuses every rename with `kSCStatusAccessError`. Inert unless `/var/db/vphone/devicename.plist` holds a valid `DeviceName` — **all bases** | none (new guest dylib `VPhoneGuestComponents/DeviceName/libdevicename.c`, installed at `/usr/lib/libdevicename.dylib`; vphoned `device.name.get`/`device.name.set`) | **Pin the guest's device name to the VM's name.** The name is `System/System/ComputerName` in `preferences.plist`; configd's PreferencesMonitor (`updateConfiguration`, 24A435 `0x100062098`) flattens it into `Setup:/System` with one `SCDynamicStoreSetMultiple`, and every reader (`SCDynamicStoreCopyComputerName` in lockdownd's `copy_device_name`, MobileGestalt `UserAssignedDeviceName`, `UIDevice.name`) reads the store. The hook rewrites that publication, not the preferences read: the monitor's model-change path (`sub_10006155c`) writes the `kSCPrefSystem` value it reads back to disk, and the publication route leaves `preferences.plist` with the guest's own name. A publication that leaves `Setup:/System` out as unchanged gets the store's value pinned; one that removes it gets the pinned name instead. `vphone-vm` sends the VM's name to vphoned's `device.name.set` after every connect; vphoned writes the file (one rename, 0644) and applies the preferences unchanged, so configd publishes again and the new pin, or the guest's own name when the file is removed, is live within a second. The file outlives a reboot, so configd's first publication at boot carries it. The library re-reads the file when its inode, size or mtime change. lockdownd's `set_device_name` (`0x1000073b0`) is the only caller of the three setters; it logs their failure and still commits, and the `SetValue DeviceName` handler ignores the result, so a host rename reports success and the name stays. The pinned name itself is refused too: lockdownd runs `set_device_name(copy_device_name())` whenever it starts, and a lockdownd restarted after configd published would otherwise write the pinned name and derived host names into `preferences.plist` (seen once). An NVRAM variable was the first channel and never reached the guest: iBoot keeps only the variables it knows (even `vphone-vm`'s `boot-args` write is replaced). Interposing works because both daemons are standalone images. Ships with `system-launchdaemons-boot-environment` and the environment update; takes effect at the next boot. Verified on iOS 27.0 (24A435) on 2026-10-07: pin at boot and live, host rename refused, `vm rename` followed, preferences untouched. CoreDevice (`devicectl`, DeviceHub) reads the name when the device appears and can lag one boot after a rename. Details: `Research/Guest/device_name_pinning.md`. | Y | Y | Y |
| 28 | `cbz`/`cbnz` -> `b` at the four compact-command choices in `-[PGSerializerRenderCommandEncoder drawIndexedPrimitives:…]` (`0x140b0`, `0x1421c`, `0x143b4`, `0x143c4` in 23E5207q) — **cloudOS 26.4** | `AppleParavirtGPUMetalIOGPUFamily` (`/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle`) | **Heap index buffer fix.** The compact command stores `parentResourceOffset + indexBufferOffset` in 16 bits but is chosen by testing `indexBufferOffset` alone, so an index buffer 64 KiB or more into an `MTLHeap` is read from the wrong address and meshes (Unity games) draw with another mesh's indices. Every indexed draw takes the 64-bit command instead. `system-paravirt_gpu-cfw-heap_index_offset`; see "Heap index buffers reach the host whole (2026-10-14)" and `Research/Guest/gpu_acceleration.md` | Y | Y | Y |
| 29 | No binary change: SystemHook calls `setenv("FS_CACHE_REUSE_ON_REBOOT", "1", 0)` first thing in its constructor, in every process it is inserted into, while `/usr/lib/vphone-metal-cache-reuse` exists — **all bases** | none (`VPhoneGuestComponents/SystemHook/SystemHook-vphone.c`; marker written by `cfw install` / `cfw update-environment`) | **Keep the guest's Metal shader caches across a reboot.** `libCoreFSCache` stamps each cache with `kern.bootsessionuuid` and resets it at the next boot unless the variable is set; on the paravirtual GPU CoreAnimation's precompiled pipelines are disabled, so backboardd rebuilt every pipeline after every boot. `system-systemhook-cfw-metal_cache_reuse`; see "Guest Metal caches survive a reboot (2026-10-19)" | Y | Y | Y |
+| 30 | `pacibsp` -> `ret` at the entry of `-[PGSerializerRenderCommandEncoder setPrimitiveRestartEnabled:index:]` (`0x174b4` in 23E5207q) — **cloudOS 26.4** | `AppleParavirtGPUMetalIOGPUFamily` (`/System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle`) | **OpenGL ES draws reach the host.** AppleMetalGLRenderer sets `NO, 0xffffffff` before its draws; the driver sends it as command 0x91 and the host's GPU task checks the index against `maxViewportCount`, throws "Invalid viewport index" and fails the command buffer (guest: `kIOGPUCommandBufferCallbackErrorHang`, GPU restart). The command is no longer sent, so Metal's own restart (on, at the index type's maximum) applies. Found by command 0x91's unique `mov w2, #0x8 ; mov w3, #0x91` and the nearest `pacibsp` before it. `system-paravirt_gpu-cfw-primitive_restart`, verb `patch-paravirt-gpu-primitive-restart`, staged with the heap index patch on one copy; see "OpenGL ES in guests (2026-11-02)" | Y | Y | Y |
### Swift port status — the eight DSC patchers (2026-09-23)
@@ -5878,3 +5880,80 @@ AVFlashlight construction; no shared-cache code is modified for these hooks.
Selection restores SpringBoard and removes the library on opt-out; a restart
restores native methods.
No native iOS 17 kernel, Metal driver, camera or networking support is claimed.
+
+## OpenGL ES in guests (2026-11-02)
+
+Upstream issue Lakr233/vphone-cli#793: every `-[EAGLContext initWithAPI:]`
+returned nil in a guest while Metal worked, so apps that need OpenGL ES refused
+to start or aborted (WeChat's `OpenGLContextManager: root_ctx_ != nullptr`).
+Three pieces make OpenGL ES render, each needed by the next.
+
+**1. Kernel: the renderer name (JB-36, `kernel-cfw-paravirt_gles_renderer`).**
+`gfxInitializeLibrary` (`libGFXShared`) loads
+`/System/Library/Extensions/<name>.bundle` from the `IOAcceleratorES` service's
+`IOGLESBundleName` / `IOGLESMetalBundleName`; `AppleParavirtGPU` had neither.
+AGX personalities carry `IOGLESBundleName = AppleMetalGLRenderer`, and the
+patch adds that key after `IOClass` in the `AppleParavirtGPUARM` personality in
+`__PRELINK_INFO`. On 23E5207q the record is 609 bytes at file offset
+`0x256824C`: the key's two lines, and the next lines' indentation shortened by
+the same 76 bytes, so nothing else in the kernelcache moves. The patched XML must
+parse to the original plus that key. Contexts are created from here on, but every
+draw failed in the next two pieces.
+
+**2. Compiler plugin: GLES modules (no binary patch; `VPhoneGuestComponents/GraphicLoader`).**
+AppleMetalGLRenderer hands the backend AIR whose `air.language_version` is
+`"OpenGL ES GLSL" 1.0.0`, with no `air.version` and with the argument metadata
+the AGX backend reads: a buffer stops after `"air.read"`, most nodes have no
+`air.arg_type_name` or `air.arg_name`. `MTLDowngradeAIRModule`,
+`MetalModule::materialize` and `air::Reflection::create` index those
+operands without checks, so `MTLCompilerService` crashed (`NamedMDNode::getOperand`,
+then `MDString::getString`) on every GLES shader. The plugin now completes such a
+module before the downgrade: every node gets the fields the Metal front end
+writes after its own, in its order (`air.address_space`, `air.arg_type_size`,
+`air.arg_type_align_size` for a buffer; `air.arg_type_name`; `air.arg_name`
+except on a render target), derived from the entry point's parameter and return
+types, and the module gets `!air.version = !{i32 2, i32 7, i32 0}`, the version
+the guest's front end (metalfe-32023.921) writes and the plugin's target
+(the value MTLCompilerService passes the plugin as `targetTriple` is a packed
+version tuple, `0x700000002`). The guest's libLLVM C API cannot replace a
+node's operand, so the module is printed, its argument lines extended, and the
+text parsed back in the same context. `make -C VPhoneGuestComponents test-gles-air`
+runs three guest-captured modules through the plugin on the host (same
+GPUCompiler 32023) and into the host's Metal.
+
+The plugin comes from the bundle (`guest-resources`), and an installed guest
+used to keep the one it was restored with. `cfw update-environment` (and `cfw
+install` without a restore tree) now replaces it when the bundle's differs and
+reseals the GPU bundle (`[+] system-extensions-boot-gpu_bundle: compiler plugin
+updated from this bundle`); tvOS guests, whose plugin is retargeted, are left alone.
+
+**3. Driver: primitive restart (guest row 30, `system-paravirt_gpu-cfw-primitive_restart`).**
+With shaders compiling, the host's `ParavirtualizedGraphicsGPUTask` threw
+`NSGenericException: Invalid viewport index` replaying each GL command buffer
+(caught with lldb on the task; Debugging Restrictions are off on this host). The
+throwing handler is command 0x91, `setPrimitiveRestartEnabled:index:`, which
+checks the index against `[device maxViewportCount]`; GL sends the restart index
+itself, `0xffffffff`. The guest saw a GPU hang and restart. The serialiser method
+now returns at entry: `0x174b4` `7f2303d5` `pacibsp` -> `c0035fd6` `ret`. Patched
+alone, 23E5207q hashes to `1992ab68…24d3dc`; with the heap index patch, as the
+installer stages both, `870ba415…3996d8`.
+
+**Verified** on `glestest-iphone` (iPhone17,3 iOS 27.0.1, cloudOS 26.4, host
+macOS 27.2, bundle built from this branch; plugin and driver delivered by
+`vm set-bundle --update-environment`, kernel by the restore): EAGL APIs 1-3 OK,
+`GL_RENDERER` "Apple Paravirtual device GPU", `GL_VERSION` "OpenGL ES 3.0 Metal -
+105"; as root and as mobile, a shader draw reads back exactly; an ES 2 program
+with a 2x2 texture, `mat4`/`float`/`vec4` uniforms and varyings reads back all four
+texels; an ES 3 program with a uniform block, a flat `int` varying, `texelFetch`
+and a `GL_PRIMITIVE_RESTART_FIXED_INDEX` strip split at `0xFFFF` reads back right
+with the gap clear; an app drawing through `CAEAGLLayer` presented 1560 frames
+with a rotating triangle on screen. No `MTLCompilerService` crash and no GPU
+restart in those runs.
+
+**Not covered.** Real apps (WeChat, the #463 game) were not run. The metadata
+completion covers the argument kinds the probes produced (buffers, the vertex
+fetch buffer, vertex id, textures, samplers, fragment inputs, position and
+vertex outputs, render targets); an argument kind the reflection reads in a
+layout the completion does not produce could still crash the compiler
+service. With primitive restart no longer sent, an OpenGL ES 2 strip that draws
+vertex 65535 is cut there.
diff --git a/Research/Guest/gpu_acceleration.md b/Research/Guest/gpu_acceleration.md
index 259958d3..a68f9763 100644
--- a/Research/Guest/gpu_acceleration.md
+++ b/Research/Guest/gpu_acceleration.md
@@ -1026,6 +1026,93 @@ Verified on the iPad guest with the patched driver in place: every heap row
above covers 100%, the plain-buffer probe is unchanged, and Subway Surfers
draws its menu scene and gameplay correctly.
+## OpenGL ES
+
+Upstream issue Lakr233/vphone-cli#793: `[[EAGLContext alloc] initWithAPI:]`
+returned nil for every API in a guest while Metal worked. OpenGL ES on Apple
+GPUs is AppleMetalGLRenderer, a renderer over Metal, and on the paravirtual GPU
+it failed at three points in turn. Measured on 2026-11-02: host macOS 27.2,
+cloudOS 26.4 (23E5207q) kernel, iPhone17,3 iOS 27.0.1 userland, test VM
+`glestest-iphone`.
+
+### No renderer
+
+`gfxInitializeLibrary` in `OpenGLES.framework/libGFXShared.dylib` walks the
+`IOAcceleratorES` services and, for each, reads `IOGLESBundleName` and
+`IOGLESMetalBundleName` from the registry; the renderer it loads is
+`/System/Library/Extensions/<name>.bundle`. With neither key there is no
+renderer and no context. The AGX personalities carry
+`IOGLESBundleName = AppleMetalGLRenderer` (`AGXG14X` in the j236c kernelcache
+of the same cloudOS IPSW); `AppleParavirtGPUARM` names only its Metal plugin.
+A personality's keys become the driver's property table, so
+`kernel-cfw-paravirt_gles_renderer` adds the AGX key to the personality in
+`__PRELINK_INFO`. With it, all three APIs return a context, `GLEngine` and
+`AppleMetalGLRenderer` load, and `glClear` with a readback works.
+
+### Shaders crash the compiler service
+
+The first draw with a shader failed with
+`GPU Hang Error (00000003:kIOGPUCommandBufferCallbackErrorHang)` and an
+unchanged framebuffer, while `MTLCompilerService` crashed in the compiler
+plugin, `libAppleParavirtCompilerPluginIOGPUFamily.dylib`, which this project
+builds (`VPhoneGuestComponents/GraphicLoader`). A copy of the plugin that wrote
+each module it received to `/private/var/tmp` showed what OpenGL ES sends it:
+
+```
+target triple = "air64-apple-ios"
+!air.language_version = !{!0}
+!air.fragment = !{!4}
+!0 = !{!"OpenGL ES GLSL", i32 1, i32 0, i32 0}
+!10 = !{i32 2, !"air.buffer", !"air.buffer_size", i32 112, !"air.location_index", i32 12, i32 1, !"air.read"}
+!12 = !{i32 4, !"air.sampler", !"air.location_index", i32 0, i32 1}
+```
+
+A module from the Metal front end has `!air.version = !{i32 2, i32 7, i32 0}`,
+a versioned triple, and argument nodes that go on to `air.address_space`,
+`air.arg_type_size`, `air.arg_type_align_size`, `air.arg_type_name` and
+`air.arg_name`. GPUCompiler reads those without bounds or null checks:
+`MTLDowngradeAIRModule` and `MetalModule::materialize` dereference
+`getNamedMetadata("air.version")`, and `air::Reflection::create` reads
+`air.address_space` at a fixed index past the end of the GL buffer node. The
+plugin now completes an OpenGL ES module before compiling it, from the entry
+point's own types, and gives it the version the front end writes, 2.7.0 — also
+the plugin's target, which `MTLCompilerService` passes as a packed version tuple
+(`0x700000002`) in the field the plugin calls `targetTriple`.
+
+The host carries the same GPUCompiler (32023), so the plugin built for macOS
+runs the guest's modules on the host: `make -C VPhoneGuestComponents
+test-gles-air` turns three captured modules into metallibs, loads each in the
+host's Metal and links the vertex and fragment functions into a pipeline.
+
+### The host refuses the primitive restart command
+
+Shaders then compiled, and the guest kernel logged an `AppleParavirtGPU
+HardwareDiagnosisReport` and a GPU restart for every GL command buffer. The
+host task (`com.apple.gpusw.ParavirtualizedGraphicsGPUTask`) logged
+`Command buffer failed: NSGenericException <redacted reason>`. A task starts
+for each guest process that opens the GPU, so a probe that pauses after creating
+its context leaves time to attach lldb to the new one and break on
+`objc_exception_throw`: the reason is `Invalid viewport index`, thrown by the
+handler that replays `setPrimitiveRestartEnabled:index:` after checking `index`
+against `[device maxViewportCount]`. OpenGL ES sends the restart index there,
+`0xffffffff`. `system-paravirt_gpu-cfw-primitive_restart` makes the guest
+driver's serialiser for that call return at entry, so Metal's own restart
+behaviour applies (on, at the index type's largest value).
+
+### Measured
+
+| Probe | Result |
+| --- | --- |
+| EAGL API 1, 2, 3 | all OK; `GL_RENDERER` "Apple Paravirtual device GPU", `GL_VERSION` "OpenGL ES 3.0 Metal - 105" |
+| ES 2 shader draw, root and mobile launchd jobs | exact readback of draw and clear |
+| ES 2 textured quad, 2x2 nearest texture, `mat4`/`float`/`vec4` uniforms, varyings | all four texels exact |
+| ES 3 uniform block, flat `int` varying, `texelFetch`, fixed-index restart strip | both quads exact, the split gap clear |
+| App drawing through `CAEAGLLayer` at 1290x2796 | 1560 frames presented, a rotating triangle on screen |
+
+No `MTLCompilerService` crash and no GPU restart in any of these.
+`Research/0_binary_patch_comparison.md` ("OpenGL ES in guests (2026-11-02)") has
+the bytes and what is not covered.
+
## Settings That Do Nothing Here
Both are private properties of `VZMacGraphicsDeviceConfiguration`, tried on
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift
new file mode 100644
index 00000000..2067afb3
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift
@@ -0,0 +1,150 @@
+// CustomFirmwareParavirtGPUPrimitiveRestart.swift — stop sending the primitive
+// restart override the host refuses.
+//
+// What goes wrong. AppleMetalGLRenderer, OpenGL ES over Metal, calls
+// `-[MTLRenderCommandEncoder setPrimitiveRestartEnabled:index:]` before its
+// draws, with the restart index itself as `index`: `NO, 0xffffffff` for an
+// OpenGL ES 2 context. The guest driver serialises that as command 0x91, eight
+// bytes of (enabled, index):
+//
+// mov w2, #0x8 ; mov w3, #0x91
+// bl objc_msgSend$getCommandBytesRetry:forCommand:
+// stp w20, w19, [x0]
+//
+// The host's ParavirtualizedGraphicsGPUTask checks that `index` against
+// `[device maxViewportCount]` before replaying it, throws "Invalid viewport
+// index" for anything above 15, and fails the whole command buffer. The guest
+// sees `kIOGPUCommandBufferCallbackErrorHang` and a GPU restart, and nothing the
+// command buffer drew reaches the framebuffer. `Research/Guest/gpu_acceleration.md`
+// ("OpenGL ES") has the evidence.
+//
+// The patch. The serialiser method returns at its first instruction, so the
+// command is never sent and the host encoder keeps Metal's own behaviour:
+// primitive restart on, at the index type's largest value, which is what
+// OpenGL ES 3 asks for with its fixed restart index. An OpenGL ES 2 strip that
+// really draws vertex 65535 would be cut there; nothing else changes.
+//
+// Finding the site. The `mov w2, #0x8 ; mov w3, #0x91` pair is unique in
+// `__TEXT,__text`: it names the command. The method's `pacibsp` is the nearest
+// one before it, within a few instructions and with no return between. A
+// method that already starts with `ret` is this patch's own output and is left
+// alone. A driver laid out otherwise is refused unchanged.
+
+import Foundation
+import VPhonePatchKit
+
+public enum CustomFirmwareParavirtGPUPrimitiveRestart {
+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }
+
+ static let method = "-[PGSerializerRenderCommandEncoder setPrimitiveRestartEnabled:index:]"
+ static let commandSize: UInt32 = 0x08
+ static let command: UInt32 = 0x91
+ /// How far before the command setup the method may start.
+ static let maximumPrologue = 16
+
+ public enum State: Sendable, Equatable {
+ case patched
+ case alreadyPatched
+ }
+
+ public struct Report: Sendable, Equatable {
+ /// File offset of the method's first instruction.
+ public let fileOffset: Int
+ public let state: State
+ }
+
+ /// Patch the driver binary at `url` in place. The file is rewritten only
+ /// when the method changes.
+ @discardableResult
+ public static func patch(
+ fileAt url: URL,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> Report {
+ guard FileManager.default.fileExists(atPath: url.path) else {
+ throw PatcherError.fileNotFound(url.path)
+ }
+ var data = try Data(contentsOfFileToRewrite: url)
+ let report = try patch(&data, log: log)
+ if report.state == .patched {
+ try data.write(to: url)
+ }
+ return report
+ }
+
+ /// In-memory form. `data` is left untouched unless the site resolves.
+ @discardableResult
+ public static func patch(
+ _ data: inout Data,
+ log: ((String) -> Void)? = stdoutLog,
+ ) throws -> Report {
+ if data.startIndex != 0 {
+ data = Data(data)
+ }
+ let report = try resolve(in: data)
+ switch report.state {
+ case .patched:
+ data.replaceSubrange(report.fileOffset ..< report.fileOffset + 4, with: ARM64.ret)
+ log?(" [+] 0x\(hex(report.fileOffset)): \(method) — pacibsp -> ret, command 0x\(hex(command)) no longer sent")
+ case .alreadyPatched:
+ log?(" [·] 0x\(hex(report.fileOffset)): \(method) — already returns at entry")
+ }
+ return report
+ }
+
+ /// Resolve the method's first instruction, or throw without having changed anything.
+ public static func resolve(in data: Data) throws -> Report {
+ let sections = MachOParser.parseSections(from: data)
+ guard let text = sections["__TEXT,__text"] else {
+ throw PatcherError.invalidFormat("not a 64-bit Mach-O with a __TEXT,__text section")
+ }
+ let start = Int(text.fileOffset)
+ let end = start + Int(text.size)
+ guard start >= 0, end <= data.count, start < end else {
+ throw PatcherError.invalidFormat("__TEXT,__text lies outside the file")
+ }
+ let setup = CustomFirmwareParavirtGPUIndexOffset.setup(size: commandSize, command: command)
+ let setups = CustomFirmwareParavirtGPUIndexOffset.offsets(of: setup, in: data, range: start ..< end)
+ guard setups.count == 1, let setupOffset = setups.first else {
+ throw PatcherError.patchSiteNotFound(
+ "\(method) — expected one command 0x\(hex(command)) setup in __text, found \(setups.count); this is not the cloudOS 26.4 (23E5207q) driver",
+ )
+ }
+ let pacibsp = ARM64.pacibsp.loadLE(UInt32.self, at: 0)
+ let ret = ARM64.ret.loadLE(UInt32.self, at: 0)
+ let returns: Set<UInt32> = [ret, ARM64.retab.loadLE(UInt32.self, at: 0), ARM64.retaa.loadLE(UInt32.self, at: 0)]
+ for distance in 1 ... maximumPrologue {
+ let offset = setupOffset - 4 * distance
+ guard offset >= start else { break }
+ let word = data.loadLE(UInt32.self, at: offset)
+ if word == pacibsp {
+ return Report(fileOffset: offset, state: .patched)
+ }
+ if word == ret, offset == start || returnsBefore(offset, in: data, start: start, returns: returns) {
+ return Report(fileOffset: offset, state: .alreadyPatched)
+ }
+ if returns.contains(word) {
+ break
+ }
+ }
+ throw PatcherError.patchSiteNotFound(
+ "\(method) — no pacibsp within \(maximumPrologue) instructions before the command 0x\(hex(command)) setup at 0x\(hex(setupOffset))",
+ )
+ }
+
+ /// True when the word before `offset` ends a function, so `offset` starts one.
+ static func returnsBefore(_ offset: Int, in data: Data, start: Int, returns: Set<UInt32>) -> Bool {
+ offset - 4 >= start && returns.contains(data.loadLE(UInt32.self, at: offset - 4))
+ || branchBefore(offset, in: data, start: start)
+ }
+
+ /// True when the word before `offset` is an unconditional `b`, the tail of
+ /// the previous method.
+ static func branchBefore(_ offset: Int, in data: Data, start: Int) -> Bool {
+ offset - 4 >= start
+ && CustomFirmwareParavirtGPUIndexOffset.branchDisplacement(data.loadLE(UInt32.self, at: offset - 4)) != nil
+ }
+
+ static func hex(_ value: some BinaryInteger) -> String {
+ String(value, radix: 16)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtGLES.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtGLES.swift
new file mode 100644
index 00000000..7702b224
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchParavirtGLES.swift
@@ -0,0 +1,193 @@
+// KernelCustomFirmwarePatchParavirtGLES.swift — CFW kernel patch: give the
+// paravirtual GPU's IOKit personality the OpenGL ES renderer that AGX names.
+//
+// Background: OpenGLES finds its renderer through the `IOAcceleratorES`
+// service. `gfxInitializeLibrary` (libGFXShared) reads `IOGLESBundleName` or
+// `IOGLESMetalBundleName` from that service's registry properties and loads
+// `/System/Library/Extensions/<name>.bundle`. A service with neither gets no
+// renderer, so every `-[EAGLContext initWithAPI:]` returns nil. On real hardware
+// the AGX personality carries `IOGLESBundleName = AppleMetalGLRenderer`, GLES
+// over Metal. `AppleParavirtGPU`'s personality (AppleParavirtGPUIOGPUFamily)
+// names its Metal plugin and nothing for GLES, although the guest ships
+// AppleMetalGLRenderer.
+//
+// A personality's keys become the matched driver's property table, so the key
+// goes into the personality in `__PRELINK_INFO`, after `IOClass`, as in AGX's.
+// The plist is XML text; the room for the new key is taken from the indentation
+// of the lines that follow it, so the record stays small and every byte outside
+// it keeps its offset.
+//
+// Anchor (no offsets): the one personality whose `IOClass` is `AppleParavirtGPU`
+// and whose `IOMatchCategory` is `IOAcceleratorES`. The patched plist is parsed
+// back and must equal the original with that one key added.
+
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ static let paravirtGLESKey = "IOGLESBundleName"
+ static let paravirtGLESRenderer = "AppleMetalGLRenderer"
+
+ @discardableResult
+ func patchParavirtGLESRenderer() -> Bool {
+ log("\n[CFW]AppleParavirtGPU personality: \(Self.paravirtGLESKey) = \(Self.paravirtGLESRenderer)")
+
+ guard let segment = segments.first(where: { $0.name == "__PRELINK_INFO" }), segment.fileSize > 0 else {
+ log(" [-] no __PRELINK_INFO")
+ return false
+ }
+ let data = buffer.data
+ let segmentRange = Int(segment.fileOffset) ..< min(Int(segment.fileOffset + segment.fileSize), data.count)
+ guard let xmlStart = data.range(of: Data("<?xml".utf8), in: segmentRange),
+ let xmlEnd = data.range(of: Data("</plist>".utf8), in: xmlStart.lowerBound ..< segmentRange.upperBound)
+ else {
+ log(" [-] __PRELINK_INFO holds no XML plist")
+ return false
+ }
+ let xml = xmlStart.lowerBound ..< xmlEnd.upperBound
+
+ guard let personality = paravirtGPUPersonality(in: xml) else { return false }
+ if data.range(of: Data("<key>\(Self.paravirtGLESKey)</key>".utf8), in: personality.dict) != nil {
+ log(" [=] the personality already names a GLES renderer")
+ return true
+ }
+
+ // The new lines take the indentation of the IOClass key line.
+ let insertion = Data((personality.indent + "<key>\(Self.paravirtGLESKey)</key>\n" + personality.indent + "<string>\(Self.paravirtGLESRenderer)</string>\n").utf8)
+ guard let replaced = reclaimIndentation(insertion.count, from: personality.insertAt, before: xml.upperBound) else {
+ log(" [-] not enough indentation after the personality to make room for \(insertion.count) bytes")
+ return false
+ }
+ let region = personality.insertAt ..< replaced.end
+ let patch = insertion + replaced.lines
+ guard patch.count == region.count else {
+ log(" [-] replacement is \(patch.count) bytes for a \(region.count)-byte region")
+ return false
+ }
+
+ var patchedXML = Data(data[xml])
+ patchedXML.replaceSubrange((region.lowerBound - xml.lowerBound) ..< (region.upperBound - xml.lowerBound), with: patch)
+ guard patchedPrelinkInfoAddsOnlyGLESKey(original: Data(data[xml]), patched: patchedXML) else {
+ log(" [-] the patched plist does not parse to the original plus \(Self.paravirtGLESKey)")
+ return false
+ }
+
+ emit(
+ region.lowerBound,
+ patch,
+ patchID: FirmwarePatchSetCatalog.paravirtGLESPatch,
+ virtualAddress: fileOffsetToVA(region.lowerBound),
+ description: "AppleParavirtGPU personality + \(Self.paravirtGLESKey) = \(Self.paravirtGLESRenderer) [\(region.count) bytes]",
+ )
+ return true
+ }
+
+ /// The personality dict, the indentation of its `IOClass` key and the offset
+ /// of the line after that key's value.
+ private func paravirtGPUPersonality(in xml: Range<Int>) -> (dict: Range<Int>, indent: String, insertAt: Int)? {
+ let data = buffer.data
+ let classKey = Data("<key>IOClass</key>".utf8)
+ let classValue = Data("<string>AppleParavirtGPU</string>".utf8)
+
+ var hits: [(key: Range<Int>, value: Range<Int>)] = []
+ for valueOff in buffer.findAll(classValue, in: xml) {
+ var keyEnd = valueOff
+ while keyEnd > xml.lowerBound, Self.isXMLSpace(data[keyEnd - 1]) {
+ keyEnd -= 1
+ }
+ guard keyEnd - classKey.count >= xml.lowerBound,
+ data[(keyEnd - classKey.count) ..< keyEnd] == classKey
+ else { continue }
+ hits.append((keyEnd - classKey.count ..< keyEnd, valueOff ..< valueOff + classValue.count))
+ }
+ guard hits.count == 1, let hit = hits.first else {
+ log(" [-] expected one personality with IOClass AppleParavirtGPU, found \(hits.count)")
+ return nil
+ }
+
+ guard let open = data.range(of: Data("<dict>".utf8), options: .backwards, in: xml.lowerBound ..< hit.key.lowerBound),
+ let close = data.range(of: Data("</dict>".utf8), in: hit.value.upperBound ..< xml.upperBound)
+ else {
+ log(" [-] the IOClass key is not inside a dict")
+ return nil
+ }
+ let dict = open.lowerBound ..< close.upperBound
+ // A nested dict would make `open`/`close` the wrong pair; a personality
+ // here holds only strings and arrays.
+ guard data.range(of: Data("<dict>".utf8), in: open.upperBound ..< close.lowerBound) == nil else {
+ log(" [-] the AppleParavirtGPU personality holds a nested dict")
+ return nil
+ }
+ guard let category = data.range(of: Data("<key>IOMatchCategory</key>".utf8), in: dict),
+ let categoryValue = data.range(of: Data("<string>IOAcceleratorES</string>".utf8), in: category.upperBound ..< dict.upperBound),
+ data[category.upperBound ..< categoryValue.lowerBound].allSatisfy(Self.isXMLSpace)
+ else {
+ log(" [-] the AppleParavirtGPU personality does not match IOAcceleratorES")
+ return nil
+ }
+
+ var lineStart = hit.key.lowerBound
+ while lineStart > dict.lowerBound, data[lineStart - 1] == UInt8(ascii: "\t") || data[lineStart - 1] == UInt8(ascii: " ") {
+ lineStart -= 1
+ }
+ guard lineStart > dict.lowerBound, data[lineStart - 1] == UInt8(ascii: "\n"),
+ let newline = data[hit.value.upperBound ..< dict.upperBound].firstIndex(of: UInt8(ascii: "\n")),
+ data[hit.value.upperBound ..< newline].allSatisfy(Self.isXMLSpace)
+ else {
+ log(" [-] the IOClass key and value are not one line each")
+ return nil
+ }
+ let indent = String(decoding: data[lineStart ..< hit.key.lowerBound], as: UTF8.self)
+ return (dict, indent, newline + 1)
+ }
+
+ /// Lines from `start` with `count` bytes of leading indentation removed, and
+ /// where they end. Only whitespace between a tag that closes one line and a
+ /// tag that opens the next is removed, which the plist parser ignores.
+ private func reclaimIndentation(_ count: Int, from start: Int, before end: Int) -> (lines: Data, end: Int)? {
+ let data = buffer.data
+ var lines = Data()
+ var freed = 0
+ var lineStart = start
+ while freed < count, lineStart < end {
+ guard data[lineStart - 1] == UInt8(ascii: "\n"), lineStart - 2 >= 0, data[lineStart - 2] == UInt8(ascii: ">"),
+ let newline = data[lineStart ..< end].firstIndex(of: UInt8(ascii: "\n"))
+ else { return nil }
+ var tagStart = lineStart
+ while tagStart < newline, data[tagStart] == UInt8(ascii: "\t") || data[tagStart] == UInt8(ascii: " ") {
+ tagStart += 1
+ }
+ let removable = data[tagStart] == UInt8(ascii: "<") ? tagStart - lineStart : 0
+ let removed = min(removable, count - freed)
+ lines.append(data[(lineStart + removed) ... newline])
+ freed += removed
+ lineStart = newline + 1
+ }
+ return freed == count ? (lines, lineStart) : nil
+ }
+
+ /// True when `patched` parses to `original` with the GLES key added to the
+ /// AppleParavirtGPU personality and nothing else changed.
+ private func patchedPrelinkInfoAddsOnlyGLESKey(original: Data, patched: Data) -> Bool {
+ guard let expected = try? PropertyListSerialization.propertyList(from: original, options: .mutableContainersAndLeaves, format: nil) as? NSMutableDictionary,
+ let actual = try? PropertyListSerialization.propertyList(from: patched, format: nil) as? NSDictionary,
+ let items = expected["_PrelinkInfoDictionary"] as? [NSMutableDictionary]
+ else { return false }
+
+ var added = 0
+ for item in items {
+ guard let personalities = item["IOKitPersonalities"] as? NSMutableDictionary else { continue }
+ for case let personality as NSMutableDictionary in personalities.allValues
+ where personality["IOClass"] as? String == "AppleParavirtGPU"
+ {
+ personality[Self.paravirtGLESKey] = Self.paravirtGLESRenderer
+ added += 1
+ }
+ }
+ return added == 1 && actual.isEqual(expected)
+ }
+
+ private static func isXMLSpace(_ byte: UInt8) -> Bool {
+ byte == UInt8(ascii: " ") || byte == UInt8(ascii: "\t") || byte == UInt8(ascii: "\n") || byte == UInt8(ascii: "\r")
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index 95eab0a0..fa2943c6 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -58,6 +58,10 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
/// enables it. False here so direct patchers preserve the reference corpus.
public var applyParavirtTask3 = false
+ /// The paravirtual GPU's OpenGL ES renderer. Set from the plan; `standard`
+ /// enables it. False here so direct patchers preserve the reference corpus.
+ public var applyParavirtGLES = false
+
public func findAll() throws -> [PatchRecord] {
parseMachO()
buildADRPIndex()
@@ -154,6 +158,11 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
}
}
+ // Name the GLES renderer in the paravirtual GPU's personality.
+ if applyParavirtGLES {
+ patchParavirtGLESRenderer()
+ }
+
// Group C
patchCredLabelUpdateExecve()
patchHookCredLabelUpdateExecve()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
index a5b21b9e..42d7d0a7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift
@@ -46,6 +46,7 @@ public enum FirmwareGuestSystemPatchSet {
public static let ciBarcodeExecutablePath = ciBarcodeBundlePath + "/CIBarcode"
public static let paravirtGPUIndexOffset = "system-paravirt_gpu-cfw-heap_index_offset"
+ public static let paravirtGPUPrimitiveRestart = "system-paravirt_gpu-cfw-primitive_restart"
public static let paravirtGPUDriverPath =
"System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle/AppleParavirtGPUMetalIOGPUFamily"
@@ -464,6 +465,17 @@ public enum FirmwareGuestSystemPatchSet {
target: .guestExecutable(path: "/\(paravirtGPUDriverPath)"),
applicability: VPhonePatchApplicability(cloudOS: .release(major: 26, minor: 4)),
),
+ VPhonePatchDeclaration(
+ identifier: paravirtGPUPrimitiveRestart,
+ title: "GPU primitive restart",
+ summary: """
+ Stops the paravirtual GPU driver sending the primitive restart override OpenGL ES \
+ sets before its draws. The host checks its restart index as if it were a viewport \
+ index and fails the whole command buffer, so nothing an OpenGL ES app draws appears.
+ """,
+ target: .guestExecutable(path: "/\(paravirtGPUDriverPath)"),
+ applicability: VPhonePatchApplicability(cloudOS: .release(major: 26, minor: 4)),
+ ),
VPhonePatchDeclaration(
identifier: "system-vphoned-boot-install",
title: "vphoned",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index c0534ecf..8c0477ef 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -355,6 +355,17 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
// cloudOS 26.1–26.3 kernels; discovery fails there.
applicability: VPhonePatchApplicability(cloudOS: .release(major: 26, minor: 4)),
),
+
+ VPhonePatchDeclaration(
+ identifier: FirmwarePatchSetCatalog.paravirtGLESPatch,
+ title: "OpenGL ES",
+ summary: """
+ Names AppleMetalGLRenderer as the paravirtual GPU's OpenGL ES renderer, \
+ as Apple GPUs do, so apps that create an EAGLContext get OpenGL ES over \
+ Metal instead of nil.
+ """,
+ target: .firmware(.kernelcache),
+ ),
],
requires: ["vphone.kernel.base"],
provides: ["vphone.kernel.cfw"],
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index d668954a..964e7621 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -95,6 +95,11 @@ public enum FirmwarePatchSetCatalog {
/// `Research/Guest/gpu_acceleration.md`.
public static let paravirtTask3Patch = "kernel-cfw-paravirt_gpu_task3"
+ /// OpenGL ES: the paravirtual GPU's personality names AppleMetalGLRenderer
+ /// as AGX's does, so `EAGLContext` gets a renderer. On in `standard`. See
+ /// `Research/Guest/gpu_acceleration.md`.
+ public static let paravirtGLESPatch = "kernel-cfw-paravirt_gles_renderer"
+
/// Identifiers an installed bundle declared that a later one renamed, old to new.
///
/// A VM's `PatchSelection.plist` and `PatchReceipt.plist` outlive the bundle
@@ -237,6 +242,7 @@ public enum FirmwarePatchSetCatalog {
/// the iPhone 19 ARM64E_X1 boot path.
public static let tvOSBlockedPatches: Set<String> = [
paravirtTask3Patch,
+ paravirtGLESPatch,
FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,
FirmwareGuestSystemPatchSet.arm64eX1CacheRemaining,
FirmwareGuestSystemPatchSet.arm64eX1CIBarcode,
@@ -280,6 +286,7 @@ public enum FirmwarePatchSetCatalog {
"system-mobileactivationd-boot-should_hactivate",
FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,
"system-paravirt_gpu-cfw-heap_index_offset",
+ "system-paravirt_gpu-cfw-primitive_restart",
"system-systemhook-cfw-metal_cache_reuse",
"system-systemversion-cfw-build_version",
"system-virtiosound-cfw-hal_plugin",
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index 3bc7a801..fc720c5d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -340,6 +340,7 @@ extension FirmwarePipeline {
applyTVTPROPagers: isEnabled(FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers, fallback: false),
applyParavirtUserClients: applyParavirtUserClients,
applyParavirtTask3: isEnabled(FirmwarePatchSetCatalog.paravirtTask3Patch, fallback: false),
+ applyParavirtGLES: isEnabled(FirmwarePatchSetCatalog.paravirtGLESPatch, fallback: false),
includeBase: includeKernelBase,
includeCustomFirmware: includeKernelCustomFirmware,
includeHypervisor: includeHypervisor,
@@ -533,6 +534,7 @@ extension FirmwarePipeline {
applyTVTPROPagers: Bool,
applyParavirtUserClients: Bool,
applyParavirtTask3: Bool,
+ applyParavirtGLES: Bool,
includeBase: Bool,
includeCustomFirmware: Bool,
includeHypervisor: Bool,
@@ -556,6 +558,7 @@ extension FirmwarePipeline {
p.applyTVTPROPagers = applyTVTPROPagers
p.applyParavirtUserClients = applyParavirtUserClients
p.applyParavirtTask3 = applyParavirtTask3
+ p.applyParavirtGLES = applyParavirtGLES
p.gate = gate
return p
}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUPrimitiveRestartTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUPrimitiveRestartTests.swift
new file mode 100644
index 00000000..9e9bee0d
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUPrimitiveRestartTests.swift
@@ -0,0 +1,168 @@
+// CustomFirmwareParavirtGPUPrimitiveRestartTests.swift — the GPU driver's primitive restart override.
+//
+// Two halves. A synthetic Mach-O carries the serialiser method around command
+// 0x91's setup, so resolution, the written word, idempotence and the refusals
+// are checked anywhere. The real cloudOS 26.4 (23E5207q) driver is the
+// reference for the bytes: patched, it must hash to what was installed in a
+// guest where OpenGL ES draws reached the framebuffer.
+//
+// The real driver is looked up as in CustomFirmwareParavirtGPUIndexOffsetTests:
+// `VPHONE_MACHO_PRISTINE`, or `ipsws/ref_extract/macho_pristine/`, with
+// `VPHONE_MACHO_FIXTURE_OPTIONAL=1` to skip when it is absent.
+
+import CryptoKit
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+private typealias Patcher = CustomFirmwareParavirtGPUPrimitiveRestart
+
+private enum RealDriver {
+ static let repoRoot = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+ .deletingLastPathComponent()
+
+ static let pristineSHA256 = "29ba36c7bc87d82c40fa1cecdf357e7a383fa70eb46df0d75869f5ac562aedbc"
+ static let patchedSHA256 = "1992ab682b537ba084c32a6f0f1511b42f5f010f8e8912e8fa6a4ab8a224d3dc"
+ /// Both driver patches, in the installer's order: heap index offsets, then this.
+ static let bothSHA256 = "870ba415b82c13373e681ed7f7ee16c0d03d8072af2de68f67beaa0d133996d8"
+
+ static var pristine: URL? {
+ let directory = ProcessInfo.processInfo.environment["VPHONE_MACHO_PRISTINE"]
+ .map { URL(fileURLWithPath: $0) }
+ ?? repoRoot.appendingPathComponent("ipsws/ref_extract/macho_pristine")
+ let binary = directory.appendingPathComponent("AppleParavirtGPUMetalIOGPUFamily")
+ return FileManager.default.fileExists(atPath: binary.path) ? binary : nil
+ }
+
+ static var runs: Bool {
+ pristine != nil || ProcessInfo.processInfo.environment["VPHONE_MACHO_FIXTURE_OPTIONAL"] != "1"
+ }
+
+ static let missing: Comment = """
+ the cloudOS 26.4 (23E5207q) AppleParavirtGPUMetalIOGPUFamily is required — put it at \
+ ipsws/ref_extract/macho_pristine/, point VPHONE_MACHO_PRISTINE at its directory, or set \
+ VPHONE_MACHO_FIXTURE_OPTIONAL=1 to skip
+ """
+
+ static func sha256(_ data: Data) -> String {
+ SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+}
+
+/// A one-section Mach-O whose `__TEXT,__text` holds the end of a previous
+/// method, then the serialiser method: `pacibsp`, a few body words, and the
+/// command 0x91 setup.
+private struct SyntheticDriver {
+ static let textOffset = 0x100
+ static let textSize = 0x100
+ static let previousReturn = textOffset + 0x20
+ static let methodStart = previousReturn + 4
+ static let bodyWords = 11
+
+ var data: Data
+
+ init(setup: Bool = true, prologue: Bool = true, bodyWords: Int = Self.bodyWords) {
+ var file = Data(count: Self.textOffset + Self.textSize)
+ func put(_ value: UInt32, at offset: Int) {
+ file.replaceSubrange(offset ..< offset + 4, with: ARM64.encodeU32(value))
+ }
+ func put64(_ value: UInt64, at offset: Int) {
+ put(UInt32(truncatingIfNeeded: value), at: offset)
+ put(UInt32(truncatingIfNeeded: value >> 32), at: offset + 4)
+ }
+ func putName(_ name: String, at offset: Int) {
+ file.replaceSubrange(offset ..< offset + name.utf8.count, with: Data(name.utf8))
+ }
+ put(0xFEED_FACF, at: 0) // MH_MAGIC_64
+ put(0x0100_000C, at: 4) // CPU_TYPE_ARM64
+ put(1, at: 16) // ncmds
+ put(72 + 80, at: 20) // sizeofcmds
+ let segment = 32
+ put(0x19, at: segment) // LC_SEGMENT_64
+ put(72 + 80, at: segment + 4)
+ putName("__TEXT", at: segment + 8)
+ put64(UInt64(Self.textOffset + Self.textSize), at: segment + 32) // vmsize
+ put64(UInt64(Self.textOffset + Self.textSize), at: segment + 48) // filesize
+ put(1, at: segment + 64) // nsects
+ let section = segment + 72
+ putName("__text", at: section)
+ putName("__TEXT", at: section + 16)
+ put64(UInt64(Self.textOffset), at: section + 32) // addr
+ put64(UInt64(Self.textSize), at: section + 40) // size
+ put(UInt32(Self.textOffset), at: section + 48) // offset
+
+ for offset in stride(from: Self.textOffset, to: Self.textOffset + Self.textSize, by: 4) {
+ put(0xD503_201F, at: offset) // nop
+ }
+ file.replaceSubrange(Self.previousReturn ..< Self.previousReturn + 4, with: ARM64.retab)
+ if prologue {
+ file.replaceSubrange(Self.methodStart ..< Self.methodStart + 4, with: ARM64.pacibsp)
+ }
+ if setup {
+ let at = Self.methodStart + 4 * (bodyWords + 1)
+ file.replaceSubrange(at ..< at + 8, with: CustomFirmwareParavirtGPUIndexOffset.setup(size: 0x08, command: 0x91))
+ }
+ data = file
+ }
+}
+
+struct CustomFirmwareParavirtGPUPrimitiveRestartTests {
+ @Test func `The method's pacibsp becomes ret`() throws {
+ var driver = SyntheticDriver()
+ let report = try Patcher.patch(&driver.data, log: nil)
+ #expect(report == Patcher.Report(fileOffset: SyntheticDriver.methodStart, state: .patched))
+ #expect(driver.data[SyntheticDriver.methodStart ..< SyntheticDriver.methodStart + 4] == ARM64.ret)
+ }
+
+ @Test func `A second run recognises its own output and writes nothing`() throws {
+ var driver = SyntheticDriver()
+ try Patcher.patch(&driver.data, log: nil)
+ let once = driver.data
+ let report = try Patcher.patch(&driver.data, log: nil)
+ #expect(report.state == .alreadyPatched)
+ #expect(driver.data == once)
+ }
+
+ @Test func `A driver without command 0x91 refuses and changes nothing`() throws {
+ var driver = SyntheticDriver(setup: false)
+ let before = driver.data
+ #expect(throws: PatcherError.self) { try Patcher.patch(&driver.data, log: nil) }
+ #expect(driver.data == before)
+ }
+
+ @Test func `A method without a prologue before the setup refuses`() throws {
+ var driver = SyntheticDriver(prologue: false)
+ let before = driver.data
+ #expect(throws: PatcherError.self) { try Patcher.patch(&driver.data, log: nil) }
+ #expect(driver.data == before)
+ }
+
+ @Test func `A prologue further away than a method's head refuses`() throws {
+ var driver = SyntheticDriver(bodyWords: Patcher.maximumPrologue + 4)
+ #expect(throws: PatcherError.self) { try Patcher.patch(&driver.data, log: nil) }
+ }
+
+ // MARK: - Real driver
+
+ @Test(.enabled(if: RealDriver.runs))
+ func `The 23E5207q driver patches to the verified bytes, alone and with the heap index patch`() throws {
+ let url = try #require(RealDriver.pristine, RealDriver.missing)
+ let pristine = try Data(contentsOf: url)
+ #expect(RealDriver.sha256(pristine) == RealDriver.pristineSHA256)
+
+ var alone = pristine
+ #expect(try Patcher.patch(&alone, log: nil) == Patcher.Report(fileOffset: 0x174B4, state: .patched))
+ #expect(RealDriver.sha256(alone) == RealDriver.patchedSHA256)
+ #expect(try Patcher.patch(&alone, log: nil).state == .alreadyPatched)
+
+ var both = pristine
+ try CustomFirmwareParavirtGPUIndexOffset.patch(&both, log: nil)
+ try Patcher.patch(&both, log: nil)
+ #expect(RealDriver.sha256(both) == RealDriver.bothSHA256)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtGLESTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtGLESTests.swift
new file mode 100644
index 00000000..d24c440b
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Kernel/KernelParavirtGLESTests.swift
@@ -0,0 +1,161 @@
+@testable import FirmwarePatcher
+import Foundation
+import Testing
+import VPhonePatchKit
+
+@Suite("Paravirtual GPU OpenGL ES renderer")
+struct KernelParavirtGLESTests {
+ // The raw vphone600 research kernel is operator supplied, never redistributed.
+ static var fixture: String? { ProcessInfo.processInfo.environment["VPHONE_GLES_KERNEL"] }
+
+ /// A `__PRELINK_INFO` laid out as vphone600's: the paravirtual GPU kext and
+ /// an unrelated one after it, then NUL padding to the end of the segment.
+ static func prelinkInfo(gpuClass: String = "AppleParavirtGPU", category: String = "IOAcceleratorES", extraKeys: String = "") -> Data {
+ let xml = """
+ <?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>
+ \t<key>_PrelinkInfoDictionary</key>
+ \t<array>
+ \t\t<dict>
+ \t\t\t<key>CFBundleIdentifier</key>
+ \t\t\t<string>com.apple.driver.AppleParavirtGPUIOGPUFamily</string>
+ \t\t\t<key>IOKitPersonalities</key>
+ \t\t\t<dict>
+ \t\t\t\t<key>AppleParavirtGPUARM</key>
+ \t\t\t\t<dict>
+ \t\t\t\t\t<key>CFBundleIdentifier</key>
+ \t\t\t\t\t<string>com.apple.driver.AppleParavirtGPUIOGPUFamily</string>
+ \t\t\t\t\t<key>IOClass</key>
+ \t\t\t\t\t<string>\(gpuClass)</string>
+ \(extraKeys)\t\t\t\t\t<key>IOMatchCategory</key>
+ \t\t\t\t\t<string>\(category)</string>
+ \t\t\t\t\t<key>IONameMatch</key>
+ \t\t\t\t\t<string>paravirtualizedgraphics,gpu</string>
+ \t\t\t\t\t<key>IOProviderClass</key>
+ \t\t\t\t\t<string>AppleARMIODevice</string>
+ \t\t\t\t\t<key>MetalPluginClassName</key>
+ \t\t\t\t\t<string>AppleParavirtDevice</string>
+ \t\t\t\t\t<key>MetalPluginName</key>
+ \t\t\t\t\t<string>AppleParavirtGPUMetalIOGPUFamily</string>
+ \t\t\t\t</dict>
+ \t\t\t</dict>
+ \t\t\t<key>MinimumOSVersion</key>
+ \t\t\t<string>26.4</string>
+ \t\t</dict>
+ \t\t<dict>
+ \t\t\t<key>CFBundleIdentifier</key>
+ \t\t\t<string>com.apple.iokit.IOGPUFamily</string>
+ \t\t\t<key>MinimumOSVersion</key>
+ \t\t\t<string>26.4</string>
+ \t\t</dict>
+ \t</array>
+ </dict>
+ </plist>
+
+ """
+ var data = Data(xml.utf8)
+ data.append(Data(repeating: 0, count: 64))
+ return data
+ }
+
+ func patcher(_ data: Data, gate: VPhonePatchGate? = nil) -> KernelCustomFirmwarePatcher {
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.segments = [MachOSegmentInfo(name: "__PRELINK_INFO", vmAddr: 0x1000, vmSize: UInt64(data.count), fileOffset: 0, fileSize: UInt64(data.count))]
+ if let gate {
+ patcher.gate = gate
+ }
+ return patcher
+ }
+
+ func personalities(_ data: Data) throws -> [[String: Any]] {
+ let end = try #require(data.range(of: Data("</plist>".utf8)))
+ let plist = try #require(PropertyListSerialization.propertyList(from: data[..<end.upperBound], format: nil) as? [String: Any])
+ let items = try #require(plist["_PrelinkInfoDictionary"] as? [[String: Any]])
+ return items.compactMap { $0["IOKitPersonalities"] as? [String: [String: Any]] }.flatMap(\.values)
+ }
+
+ @Test
+ func `names the renderer in the paravirtual GPU personality only`() throws {
+ let data = Self.prelinkInfo()
+ let patcher = patcher(data)
+ #expect(patcher.patchParavirtGLESRenderer())
+ #expect(patcher.patches.count == 1)
+ let record = try #require(patcher.patches.first)
+ #expect(record.patchID == FirmwarePatchSetCatalog.paravirtGLESPatch)
+
+ // The plist keeps its size and every byte outside the record.
+ let patched = patcher.buffer.data
+ #expect(patched.count == data.count)
+ let region = record.fileOffset ..< record.fileOffset + record.patchedBytes.count
+ #expect(patched[..<region.lowerBound] == data[..<region.lowerBound])
+ #expect(patched[region.upperBound...] == data[region.upperBound...])
+ #expect(patched.suffix(64).allSatisfy { $0 == 0 })
+
+ let gpu = try #require(personalities(patched).first)
+ #expect(gpu["IOGLESBundleName"] as? String == "AppleMetalGLRenderer")
+ #expect(gpu["IOClass"] as? String == "AppleParavirtGPU")
+ #expect(gpu["MetalPluginName"] as? String == "AppleParavirtGPUMetalIOGPUFamily")
+ #expect(gpu.count == 8)
+
+ // The key lands after IOClass with the IOClass line's indentation.
+ let text = String(decoding: patched, as: UTF8.self)
+ #expect(text.contains("<string>AppleParavirtGPU</string>\n\t\t\t\t\t<key>IOGLESBundleName</key>\n\t\t\t\t\t<string>AppleMetalGLRenderer</string>\n"))
+
+ // A second run finds the key and writes nothing.
+ let second = self.patcher(patched)
+ #expect(second.patchParavirtGLESRenderer())
+ #expect(second.patches.isEmpty)
+ }
+
+ @Test
+ func `blocked patch leaves the plist unchanged`() {
+ let data = Self.prelinkInfo()
+ let patcher = patcher(data, gate: VPhonePatchGate(declared: [FirmwarePatchSetCatalog.paravirtGLESPatch], enabled: []))
+ #expect(patcher.patchParavirtGLESRenderer())
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.buffer.data == data)
+ }
+
+ @Test
+ func `refuses a personality that is not the paravirtual accelerator`() {
+ for data in [
+ Self.prelinkInfo(gpuClass: "AGXAcceleratorG14X"),
+ Self.prelinkInfo(category: "IOFramebuffer"),
+ // A nested dict would leave the personality's bounds unknown.
+ Self.prelinkInfo(extraKeys: "\t\t\t\t\t<key>IOPropertyMatch</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t</dict>\n"),
+ ] {
+ let patcher = patcher(data)
+ #expect(!patcher.patchParavirtGLESRenderer())
+ #expect(patcher.patches.isEmpty)
+ #expect(patcher.buffer.data == data)
+ }
+ }
+
+ @Test
+ func `refuses when the indentation after the key cannot make room`() {
+ // A compact plist has no indentation to give.
+ let compact = Self.prelinkInfo().filter { $0 != UInt8(ascii: "\t") }
+ let indented = Data(String(decoding: compact, as: UTF8.self)
+ .replacingOccurrences(of: "<key>IOClass</key>", with: "\t\t<key>IOClass</key>").utf8)
+ let patcher = patcher(indented)
+ #expect(!patcher.patchParavirtGLESRenderer())
+ #expect(patcher.patches.isEmpty)
+ }
+
+ @Test(.enabled(if: fixture != nil))
+ func `patches the supplied kernel`() throws {
+ let data = try Data(contentsOf: URL(fileURLWithPath: #require(Self.fixture)))
+ let patcher = KernelCustomFirmwarePatcher(data: data, verbose: false)
+ patcher.parseMachO()
+ #expect(patcher.patchParavirtGLESRenderer())
+ #expect(patcher.patches.count == 1)
+ #expect(patcher.buffer.data.count == data.count)
+
+ let second = KernelCustomFirmwarePatcher(data: patcher.patchedData, verbose: false)
+ second.parseMachO()
+ #expect(second.patchParavirtGLESRenderer())
+ #expect(second.patches.isEmpty)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
index 97bb15ab..97d59ad7 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift
@@ -281,6 +281,7 @@ struct FirmwareGuestPatchResolutionTests {
#expect(unvalidated.contains("system-launchdaemons-boot-environment"))
#expect(unvalidated.contains("system-extensions-boot-gpu_bundle"))
#expect(unvalidated.contains(FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset))
+ #expect(unvalidated.contains(FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart))
#expect(unvalidated.contains("dyld-cfw-camera"))
#expect(!unvalidated.contains("system-seputil-boot-gigalocker_uuid"))
#expect(!unvalidated.contains("system-gigalocker-boot-rename"))
@@ -352,6 +353,7 @@ struct FirmwareGuestPatchResolutionTests {
#expect(tv4K.isEnabled("system-vphoned-boot-install"))
// The upstream GPU heap index patch stays out, as for every TV guest.
#expect(!tv4K.isEnabled(FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset))
+ #expect(!tv4K.isEnabled(FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart))
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K.enabled, arm64eUserland: true).isEmpty)
#expect(FirmwareGuestPatchResolution.unvalidatedTVGuestPatches(enabled: tv4K.enabled) == [gpu, ota].sorted())
// The 27 shared-cache patches are on but meet only a 27 userland.
@@ -447,6 +449,7 @@ struct FirmwareGuestPatchResolutionTests {
FirmwareGuestSystemPatchSet.tvTPRO,
FirmwareKernelCustomFirmwarePatchSet.tvTPROPagers,
FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset,
+ FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart,
"system-launchdaemons-boot-environment",
"dyld-cfw-camera",
]
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
index 46d779f3..25e29d1b 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift
@@ -462,6 +462,29 @@ struct FirmwarePatchSetCatalogTests {
}
}
+ @Test
+ func `Standard names the GLES renderer on every base while tvOS stays off`() throws {
+ let patch = FirmwarePatchSetCatalog.paravirtGLESPatch
+ #expect(!FirmwarePatchSetCatalog.manualOnlyPatches.contains(patch))
+ for base in ["18.6.2", "26.4", "26.6.2", "27.0.1"] {
+ for cloud in ["26.1", "26.4"] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: FirmwarePatchSetCatalog.standardPreset,
+ patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion(cloud),
+ )
+ #expect(plan.isEnabled(patch), "\(patch) on \(base)/\(cloud)")
+ }
+ }
+ for preset in [FirmwarePatchSetCatalog.tvOSPreset, FirmwarePatchSetCatalog.tvOS4KPreset, FirmwarePatchSetCatalog.homePodMiniPreset] {
+ let plan = try VPhonePatchPlan.resolve(
+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,
+ iOSBase: VPhoneVersion("27.0"), cloudOS: VPhoneVersion("26.4"),
+ )
+ #expect(!plan.isEnabled(patch))
+ }
+ }
+
@Test
func `A renamed patch maps to one the catalogue declares`() {
let declared = Set(FirmwarePatchSetCatalog.allDeclarations.map(\.identifier))
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
index fd4875f3..15710bb1 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift
@@ -1901,7 +1901,9 @@ struct VPhoneCustomFirmwareInstaller {
// The paravirtual GPU bundle comes from the restore tree, so an
// environment update cannot (re)install it; an installed guest already
- // carries it, so record it live when on and skip with a note.
+ // carries it, so record it live when on and skip with a note. Its
+ // compiler plugin is this project's own build, so an update still
+ // brings that one up to date.
var gpuBundleReinstalled = false
if on("system-extensions-boot-gpu_bundle") {
isolate(["system-extensions-boot-gpu_bundle"]) {
@@ -1913,33 +1915,47 @@ struct VPhoneCustomFirmwareInstaller {
gpuBundleReinstalled = true
} else {
print(" [·] system-extensions-boot-gpu_bundle: no restore tree; GPU bundle left as installed")
+ if !guestDevice.usesTVOS, try refreshGPUCompilerPlugin(system: system) {
+ print(" [+] system-extensions-boot-gpu_bundle: compiler plugin updated from this bundle")
+ }
}
live.insert("system-extensions-boot-gpu_bundle")
}
}
// The driver's compact indexed-draw commands truncate a heap index
- // buffer's offset to 16 bits. After the bundle step on purpose:
+ // buffer's offset to 16 bits, and its primitive restart override is
+ // one the host refuses. After the bundle step on purpose:
// `installGPUBundle` replaces the whole bundle, `.bak` included, so the
// backup taken here is always the staged driver — and a bundle it just
- // reinstalled is already pristine, which is what "off" means.
- let gpuIndexOffset = FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset
+ // reinstalled is already pristine, which is what "off" means. Both ride
+ // one staged copy: `patchMachO` stages from the pristine backup, so two
+ // calls would not compose.
+ let gpuDriverPatches: [(id: String, verb: String)] = [
+ (FirmwareGuestSystemPatchSet.paravirtGPUIndexOffset, "patch-paravirt-gpu-index-offset"),
+ (FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart, "patch-paravirt-gpu-primitive-restart"),
+ ]
let gpuDriver = FirmwareGuestSystemPatchSet.paravirtGPUDriverPath
let gpuBundle = "System/Library/Extensions/\(VPhonePCCGPUDriver.name)"
- isolate([gpuIndexOffset]) {
- if on(gpuIndexOffset) {
+ let gpuDriverOn = gpuDriverPatches.filter { on($0.id) }
+ isolate(gpuDriverPatches.map(\.id)) {
+ if !gpuDriverOn.isEmpty {
try patchMachO(
system: system, work: work, path: gpuDriver,
- verbs: ["patch-paravirt-gpu-index-offset"],
+ verbs: gpuDriverOn.map(\.verb),
identifier: "com.apple.driver.AppleParavirtGPUMetalIOGPUFamily",
)
try sealGuestBundle(system: system, bundle: gpuBundle)
- live.insert(gpuIndexOffset)
+ for patch in gpuDriverOn {
+ live.insert(patch.id)
+ }
} else if try revertMachO(system: system, work: work, path: gpuDriver, bundle: gpuBundle) {
- print(" [+] \(gpuIndexOffset): restored \(gpuDriver) from backup")
- } else if priorGuest.contains(gpuIndexOffset), !gpuBundleReinstalled {
- print(" [!] \(gpuIndexOffset): off now but no backup to revert; leaving the patched driver (not revertible)")
- live.insert(gpuIndexOffset)
+ print(" [+] \(gpuDriver) restored from backup (heap index and primitive restart patches off)")
+ } else if !gpuBundleReinstalled {
+ for patch in gpuDriverPatches where priorGuest.contains(patch.id) {
+ print(" [!] \(patch.id): off now but no backup to revert; leaving the patched driver (not revertible)")
+ live.insert(patch.id)
+ }
}
}
@@ -2753,6 +2769,21 @@ struct VPhoneCustomFirmwareInstaller {
}
}
+ /// Replace an installed guest's compiler plugin with this bundle's when
+ /// they differ, and seal the GPU bundle again. True when it was replaced.
+ private func refreshGPUCompilerPlugin(system: VPhoneConfinedDirectory) throws -> Bool {
+ let gpu = "System/Library/Extensions/\(VPhonePCCGPUDriver.name)"
+ let plugin = "\(gpu)/libAppleParavirtCompilerPluginIOGPUFamily.dylib"
+ let source = resources.gpuCompilerPlugin
+ guard try system.isRegularFile(plugin),
+ FileManager.default.fileExists(atPath: source.path),
+ try system.readData(plugin) != Data(contentsOf: source)
+ else { return false }
+ try system.replaceFile(plugin, fromFileAt: source, mode: 0o755, owner: Self.guestOwner)
+ try sealGuestBundle(system: system, bundle: gpu)
+ return true
+ }
+
/// The staged OTA, the configured device and the patched target firmware
/// must all name the same 27.x build before System is replaced.
private func requireOTAUpdate(
diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
index 3c29346e..a1f09731 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift
@@ -640,6 +640,36 @@ struct VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand: ParsableCommand {
}
}
+// MARK: - patch-paravirt-gpu-primitive-restart
+
+struct VPhoneCustomFirmwarePatchParavirtGPUPrimitiveRestartCommand: ParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "patch-paravirt-gpu-primitive-restart",
+ abstract: "Stop the paravirtual GPU driver sending the primitive restart override",
+ discussion: """
+ OpenGL ES calls setPrimitiveRestartEnabled:index: with the restart
+ index itself, 0xffffffff. The cloudOS 26.4 driver sends it as command
+ 0x91, and the host checks the index against maxViewportCount, throws,
+ and fails the command buffer. The serialiser method's pacibsp becomes
+ ret, so the command is never sent and Metal's own restart behaviour
+ applies.
+
+ The method is found from the command's mov w2/mov w3 setup, which is
+ unique in __text. Idempotent: a method that already returns at entry is
+ reported and the file is not rewritten.
+ """,
+ )
+
+ @Argument(help: "Path to the AppleParavirtGPUMetalIOGPUFamily Mach-O, patched in place", transform: URL.init(fileURLWithPath:))
+ var binary: URL
+
+ func run() throws {
+ try requireUntruncatedMachO(at: binary)
+ // No re-attestation: the caller re-signs.
+ try CustomFirmwareParavirtGPUPrimitiveRestart.patch(fileAt: binary, log: machOVerbLog)
+ }
+}
+
enum VPhoneCustomFirmwareMachOVerbs {
/// Registered into `vphone-cli cfw` by `VPhoneCustomFirmwareCommand`.
///
@@ -661,6 +691,7 @@ enum VPhoneCustomFirmwareMachOVerbs {
VPhoneCustomFirmwarePatchVirtualAudioVolumeGateCommand.self,
VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand.self,
VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand.self,
+ VPhoneCustomFirmwarePatchParavirtGPUPrimitiveRestartCommand.self,
]
}
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
index 12f55cf2..d3297244 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist
@@ -82,6 +82,7 @@
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
+ <string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-hv_vmm</string>
<string>dyld-exp-hv_vmm</string>
@@ -141,6 +142,7 @@
<string>system-mobileactivationd-boot-should_hactivate</string>
<string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-paravirt_gpu-cfw-primitive_restart</string>
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtualaudio-cfw-microphone_graph_chains</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
index 250b48a8..9a880221 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist
@@ -91,6 +91,7 @@
<string>kernel-boot-arm64e_x1</string>
<string>kernel-boot-cssc_emulation</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
+ <string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_syscall_filter_off</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-exp-frida_tpro_off</string>
@@ -142,6 +143,7 @@
<string>system-mobileactivationd-exp-tv_activation</string>
<string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-paravirt_gpu-cfw-primitive_restart</string>
<string>system-preferences-cfw-followup_groups</string>
<string>system-preferences-exp-root_rows</string>
<string>system-setup-exp-deferred_focus</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
index caebe244..314ba2c3 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist
@@ -92,6 +92,7 @@
<string>system-exp-ota_userland</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
+ <string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
@@ -147,6 +148,7 @@
<string>system-mobileactivationd-boot-should_hactivate</string>
<string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-paravirt_gpu-cfw-primitive_restart</string>
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
index 2cfccf9f..60ced4b6 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist
@@ -90,6 +90,7 @@
<string>preboot-homepod-exp-audio_product</string>
<string>kernel-exp-frida_thread_set_state_entitlement_flag</string>
<string>kernel-cfw-paravirt_gpu_task3</string>
+ <string>kernel-cfw-paravirt_gles_renderer</string>
<string>kernel-exp-frida_vm_map_delete_immutable_code</string>
<string>kernel-exp-frida_tpro_off</string>
<string>kernel-exp-frida_syscall_filter_off</string>
@@ -151,6 +152,7 @@
<string>system-mobileactivationd-boot-should_hactivate</string>
<string>system-mount-boot-arm64e_x1_bootstrap</string>
<string>system-paravirt_gpu-cfw-heap_index_offset</string>
+ <string>system-paravirt_gpu-cfw-primitive_restart</string>
<string>system-systemhook-cfw-metal_cache_reuse</string>
<string>system-systemversion-cfw-build_version</string>
<string>system-virtiosound-cfw-hal_plugin</string>
diff --git a/VPhoneGuestComponents/GraphicLoader/GLESAIR.h b/VPhoneGuestComponents/GraphicLoader/GLESAIR.h
new file mode 100644
index 00000000..28eca30e
--- /dev/null
+++ b/VPhoneGuestComponents/GraphicLoader/GLESAIR.h
@@ -0,0 +1,13 @@
+// OpenGL ES shader modules from AppleMetalGLRenderer: see GLESAIR.mm.
+#pragma once
+
+typedef struct LLVMOpaqueModule *LLVMModuleRef;
+typedef struct LLVMOpaqueValue *LLVMValueRef;
+
+// True for a module whose air.language_version is "OpenGL ES GLSL".
+bool isGLESModule(LLVMModuleRef module);
+
+// A copy of the module, in its context, with the argument metadata fields
+// GPUCompiler needs added. Null when nothing was missing, or on failure with
+// *error set.
+LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error);
diff --git a/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm b/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm
new file mode 100644
index 00000000..09ef8b99
--- /dev/null
+++ b/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm
@@ -0,0 +1,332 @@
+// Complete the argument metadata of the AIR modules AppleMetalGLRenderer builds
+// for OpenGL ES shaders, so GPUCompiler can make a metallib of them.
+//
+// GLEngine writes the older AIR argument layout the AGX backend reads: a buffer
+// is `i32 index, "air.buffer", ["air.buffer_size", i32 size,]
+// "air.location_index", i32 slot, i32 count, "air.read"` and stops there, and
+// most nodes have no type or argument name. llvm::air::Reflection::create
+// (MTLMetalFunctionCreate) reads the layout the Metal front end writes, in
+// which a buffer goes on with "air.address_space", "air.arg_type_size" and
+// "air.arg_type_align_size", and every node ends with "air.arg_type_name" and
+// "air.arg_name". It indexes the missing operands without a bounds check and
+// crashes the compiler service. Each node gets the fields it lacks, in the
+// front end's order, derived from the entry point's own parameter and return
+// types; nothing the module already says is changed.
+//
+// The LLVM C API in the guest's libLLVM can read metadata but not replace a
+// node's operand, so the module is printed, its argument lines extended, and
+// the text parsed back into a new module in the same context.
+
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+
+#include "GLESAIR.h"
+
+extern "C" {
+ typedef struct LLVMOpaqueContext *LLVMContextRef;
+ typedef struct LLVMOpaqueType *LLVMTypeRef;
+ typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
+ typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;
+
+ LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M);
+ unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char *Name);
+ void LLVMGetNamedMetadataOperands(LLVMModuleRef M, const char *Name, LLVMValueRef *Dest);
+ unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V);
+ void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest);
+ const char *LLVMGetMDString(LLVMValueRef V, unsigned *Length);
+ LLVMValueRef LLVMIsAMDString(LLVMValueRef Val);
+ char *LLVMPrintModuleToString(LLVMModuleRef M);
+ void LLVMDisposeMessage(char *Message);
+ LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName);
+ int LLVMParseIRInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage);
+
+ LLVMTypeRef LLVMGlobalGetValueType(LLVMValueRef Global);
+ LLVMTypeRef LLVMGetReturnType(LLVMTypeRef FunctionTy);
+ unsigned LLVMCountParamTypes(LLVMTypeRef FunctionTy);
+ void LLVMGetParamTypes(LLVMTypeRef FunctionTy, LLVMTypeRef *Dest);
+ int LLVMGetTypeKind(LLVMTypeRef Ty);
+ unsigned LLVMGetIntTypeWidth(LLVMTypeRef IntegerTy);
+ unsigned LLVMGetVectorSize(LLVMTypeRef VectorTy);
+ LLVMTypeRef LLVMGetElementType(LLVMTypeRef Ty);
+ unsigned LLVMGetArrayLength(LLVMTypeRef ArrayTy);
+ unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy);
+ LLVMTypeRef LLVMStructGetTypeAtIndex(LLVMTypeRef StructTy, unsigned i);
+ const char *LLVMGetStructName(LLVMTypeRef Ty);
+ unsigned LLVMGetPointerAddressSpace(LLVMTypeRef PointerTy);
+ LLVMTargetDataRef LLVMGetModuleDataLayout(LLVMModuleRef M);
+ unsigned long long LLVMABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
+ unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);
+}
+
+namespace {
+
+// LLVMTypeKind values; stable across the releases that still have typed pointers.
+enum { kindHalf = 1, kindFloat = 2, kindDouble = 3, kindInteger = 8, kindStruct = 10, kindArray = 11, kindPointer = 12, kindVector = 13 };
+
+std::vector<LLVMValueRef> operands(LLVMValueRef node) {
+ std::vector<LLVMValueRef> ops(LLVMGetMDNodeNumOperands(node));
+ if (!ops.empty())
+ LLVMGetMDNodeOperands(node, ops.data());
+ return ops;
+}
+
+std::string stringOf(LLVMValueRef value) {
+ if (!value || !LLVMIsAMDString(value))
+ return {};
+ unsigned length = 0;
+ const char *s = LLVMGetMDString(value, &length);
+ return s ? std::string(s, length) : std::string();
+}
+
+// The Metal spelling of a type, as the front end writes it in air.arg_type_name.
+std::string typeName(LLVMTypeRef type) {
+ switch (LLVMGetTypeKind(type)) {
+ case kindHalf: return "half";
+ case kindFloat: return "float";
+ case kindDouble: return "double";
+ case kindInteger:
+ switch (LLVMGetIntTypeWidth(type)) {
+ case 1: return "bool";
+ case 8: return "char";
+ case 16: return "short";
+ case 64: return "long";
+ default: return "int";
+ }
+ case kindVector: return typeName(LLVMGetElementType(type)) + std::to_string(LLVMGetVectorSize(type));
+ case kindArray: return typeName(LLVMGetElementType(type)) + "[" + std::to_string(LLVMGetArrayLength(type)) + "]";
+ case kindPointer: return typeName(LLVMGetElementType(type));
+ case kindStruct: {
+ const char *name = LLVMGetStructName(type);
+ if (name && !strcmp(name, "struct._sampler_t"))
+ return "sampler";
+ return "struct";
+ }
+ default: return "void";
+ }
+}
+
+// The operands of a `!N = !{...}` line, split at top-level commas.
+std::vector<std::string> lineOperands(const std::string &line) {
+ std::vector<std::string> ops;
+ size_t open = line.find("!{");
+ size_t close = line.rfind('}');
+ if (open == std::string::npos || close == std::string::npos || close < open)
+ return ops;
+ std::string current;
+ int depth = 0;
+ bool quoted = false;
+ for (size_t i = open + 2; i < close; i++) {
+ char c = line[i];
+ if (c == '"' && (i == 0 || line[i - 1] != '\\'))
+ quoted = !quoted;
+ if (!quoted) {
+ if (c == '{' || c == '(' || c == '<' || c == '[')
+ depth++;
+ else if (c == '}' || c == ')' || c == '>' || c == ']')
+ depth--;
+ else if (c == ',' && depth == 0) {
+ ops.push_back(current);
+ current.clear();
+ continue;
+ }
+ }
+ if (!(current.empty() && c == ' '))
+ current += c;
+ }
+ if (!current.empty())
+ ops.push_back(current);
+ return ops;
+}
+
+bool hasKey(const std::vector<std::string> &ops, const char *key) {
+ std::string quoted = std::string("!\"") + key + "\"";
+ for (const std::string &op : ops)
+ if (op == quoted)
+ return true;
+ return false;
+}
+
+struct Entry {
+ std::vector<LLVMTypeRef> params;
+ LLVMTypeRef result = nullptr;
+};
+
+class Rewriter {
+public:
+ Rewriter(LLVMModuleRef module, std::string text) : module(module), layout(LLVMGetModuleDataLayout(module)) {
+ size_t start = 0;
+ while (start < text.size()) {
+ size_t end = text.find('\n', start);
+ if (end == std::string::npos)
+ end = text.size();
+ lines.push_back(text.substr(start, end - start));
+ start = end + 1;
+ }
+ for (size_t i = 0; i < lines.size(); i++) {
+ const std::string &line = lines[i];
+ if (line.size() > 1 && line[0] == '!') {
+ size_t eq = line.find(" = ");
+ if (eq != std::string::npos)
+ index[line.substr(0, eq)] = i;
+ }
+ }
+ }
+
+ void completeStage(const char *stage) {
+ unsigned count = LLVMGetNamedMetadataNumOperands(module, stage);
+ if (count == 0)
+ return;
+ std::vector<LLVMValueRef> nodes(count);
+ LLVMGetNamedMetadataOperands(module, stage, nodes.data());
+ auto named = index.find(std::string("!") + stage);
+ if (named == index.end())
+ return;
+ std::vector<std::string> ids = lineOperands(lines[named->second]);
+ for (size_t e = 0; e < ids.size() && e < nodes.size(); e++) {
+ std::vector<LLVMValueRef> ops = operands(nodes[e]);
+ if (ops.size() < 3 || !ops[0])
+ continue;
+ Entry entry;
+ LLVMTypeRef function = LLVMGlobalGetValueType(ops[0]);
+ entry.params.resize(LLVMCountParamTypes(function));
+ if (!entry.params.empty())
+ LLVMGetParamTypes(function, entry.params.data());
+ entry.result = LLVMGetReturnType(function);
+ auto line = index.find(ids[e]);
+ if (line == index.end())
+ continue;
+ std::vector<std::string> fields = lineOperands(lines[line->second]);
+ if (fields.size() < 3)
+ continue;
+ completeList(fields[fields.size() - 2], entry, true);
+ completeList(fields[fields.size() - 1], entry, false);
+ }
+ }
+
+ std::string text() const {
+ std::string out;
+ for (const std::string &line : lines)
+ out += line + "\n";
+ return out;
+ }
+
+ bool changed = false;
+
+private:
+ LLVMModuleRef module;
+ LLVMTargetDataRef layout;
+ std::vector<std::string> lines;
+ std::map<std::string, size_t> index;
+ std::set<std::string> done;
+
+ LLVMTypeRef outputType(const Entry &entry, size_t i) {
+ if (LLVMGetTypeKind(entry.result) == kindStruct)
+ return i < LLVMCountStructElementTypes(entry.result) ? LLVMStructGetTypeAtIndex(entry.result, (unsigned)i) : nullptr;
+ return i == 0 ? entry.result : nullptr;
+ }
+
+ void completeList(const std::string &id, const Entry &entry, bool outputs) {
+ auto list = index.find(id);
+ if (list == index.end())
+ return;
+ std::vector<std::string> nodes = lineOperands(lines[list->second]);
+ for (size_t i = 0; i < nodes.size(); i++) {
+ auto node = index.find(nodes[i]);
+ if (node == index.end() || done.count(nodes[i]))
+ continue;
+ done.insert(nodes[i]);
+ std::vector<std::string> ops = lineOperands(lines[node->second]);
+ if (ops.empty())
+ continue;
+ LLVMTypeRef type = nullptr;
+ std::string name;
+ if (outputs) {
+ type = outputType(entry, i);
+ name = "_gles_out" + std::to_string(i);
+ } else if (ops[0].rfind("i32 ", 0) == 0) {
+ unsigned long p = strtoul(ops[0].c_str() + 4, nullptr, 10);
+ type = p < entry.params.size() ? entry.params[p] : nullptr;
+ name = "_gles_arg" + std::to_string(p);
+ }
+ std::string extra = completion(ops, type, name, outputs);
+ if (extra.empty())
+ continue;
+ std::string &line = lines[node->second];
+ line.insert(line.rfind('}'), extra);
+ changed = true;
+ }
+ }
+
+ // The fields the front end would have written after the node's own, in
+ // its order, as text to insert before the node's closing brace.
+ std::string completion(const std::vector<std::string> &ops, LLVMTypeRef type, const std::string &name, bool output) {
+ std::string extra;
+ auto string = [&](const std::string &s) { extra += ", !\"" + s + "\""; };
+ auto integer = [&](unsigned long long n) { extra += ", i32 " + std::to_string(n); };
+ bool buffer = !output && ops.size() > 1 && ops[1] == "!\"air.buffer\"";
+ if (buffer && type && LLVMGetTypeKind(type) == kindPointer && !hasKey(ops, "air.address_space")) {
+ LLVMTypeRef pointee = LLVMGetElementType(type);
+ string("air.address_space");
+ integer(LLVMGetPointerAddressSpace(type));
+ string("air.arg_type_size");
+ integer(LLVMABISizeOfType(layout, pointee));
+ string("air.arg_type_align_size");
+ integer(LLVMABIAlignmentOfType(layout, pointee));
+ }
+ if (!hasKey(ops, "air.arg_type_name")) {
+ string("air.arg_type_name");
+ string(type ? typeName(type) : "void");
+ }
+ // The front end names no render target.
+ bool renderTarget = output && ops[0] == "!\"air.render_target\"";
+ if (!renderTarget && !hasKey(ops, "air.arg_name") && !name.empty()) {
+ string("air.arg_name");
+ string(name);
+ }
+ return extra;
+ }
+};
+
+} // namespace
+
+bool isGLESModule(LLVMModuleRef module) {
+ unsigned count = LLVMGetNamedMetadataNumOperands(module, "air.language_version");
+ if (count == 0)
+ return false;
+ std::vector<LLVMValueRef> versions(count);
+ LLVMGetNamedMetadataOperands(module, "air.language_version", versions.data());
+ std::vector<LLVMValueRef> ops = operands(versions[0]);
+ return !ops.empty() && stringOf(ops[0]) == "OpenGL ES GLSL";
+}
+
+LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error) {
+ char *printed = LLVMPrintModuleToString(module);
+ if (!printed) {
+ *error = "cannot print the OpenGL ES module";
+ return nullptr;
+ }
+ Rewriter rewriter(module, printed);
+ LLVMDisposeMessage(printed);
+ for (const char *stage : {"air.vertex", "air.fragment", "air.kernel"})
+ rewriter.completeStage(stage);
+ if (!rewriter.changed)
+ return nullptr;
+ std::string text = rewriter.text();
+ LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(text.data(), text.size(), "OpenGL ES shader");
+ LLVMModuleRef completed = nullptr;
+ char *message = nullptr;
+ if (LLVMParseIRInContext(LLVMGetModuleContext(module), buffer, &completed, &message)) {
+ static std::string reason;
+ reason = std::string("cannot parse the completed OpenGL ES module: ") + (message ? message : "");
+ if (message)
+ LLVMDisposeMessage(message);
+ *error = reason.c_str();
+ return nullptr;
+ }
+ return completed;
+}
diff --git a/VPhoneGuestComponents/GraphicLoader/README.md b/VPhoneGuestComponents/GraphicLoader/README.md
index 1cc8ed42..bd8c6d83 100644
--- a/VPhoneGuestComponents/GraphicLoader/README.md
+++ b/VPhoneGuestComponents/GraphicLoader/README.md
@@ -23,3 +23,13 @@ Metal compilation, leaving the host VM window black even while vphoned connects.
The Xcode bundle build stages it in `Contents/Resources/guest-resources`.
`fw prepare` copies that dylib alongside the
firmware-sourced GPU driver before exposing the complete restore tree.
+An installed guest without a restore tree gets a changed plugin from
+`cfw update-environment`, which replaces it when the bundle's differs.
+
+`GLESAIR.mm` completes the AIR modules AppleMetalGLRenderer builds for OpenGL
+ES shaders before they reach GPUCompiler: their argument metadata in the layout
+the Metal front end writes, and `air.version`. Without it every GLES shader
+crashed `MTLCompilerService`. `make -C VPhoneGuestComponents test-gles-air`
+runs the modules in `Tests/GLESAIRFixtures`, captured from an iOS 27.0.1 guest,
+through the plugin and into the host's Metal. See the "OpenGL ES" section of
+`Research/Guest/gpu_acceleration.md`.
diff --git a/VPhoneGuestComponents/GraphicLoader/main.mm b/VPhoneGuestComponents/GraphicLoader/main.mm
index 65764b24..5f54392c 100644
--- a/VPhoneGuestComponents/GraphicLoader/main.mm
+++ b/VPhoneGuestComponents/GraphicLoader/main.mm
@@ -8,6 +8,8 @@
#include <cstring>
#include <cstdint>
+#include "GLESAIR.h"
+
// --- LLVM C API (from libLLVM.dylib) ---
extern "C" {
// Opaque types
@@ -29,6 +31,15 @@ extern "C" {
unsigned LLVMGetMDNodeNumOperands(LLVMValueRef V);
void LLVMGetMDNodeOperands(LLVMValueRef V, LLVMValueRef *Dest);
const char *LLVMGetValueName2(LLVMValueRef Val, size_t *Length);
+
+ // LLVM metadata construction
+ typedef struct LLVMOpaqueContext *LLVMContextRef;
+ typedef struct LLVMOpaqueType *LLVMTypeRef;
+ LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M);
+ LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C);
+ LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N, int SignExtend);
+ LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals, unsigned Count);
+ void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name, LLVMValueRef Val);
}
// --- GPUCompiler API (from libGPUCompiler.dylib) ---
@@ -82,6 +93,27 @@ static const char *entryPointsMetadata[] = {
};
static const int numEntryPointsMetadata = 3;
+// The AIR version the guest's Metal front end writes into the modules it
+// compiles from MSL (iOS 27.0.1, metalfe-32023.921).
+static const unsigned long long glesAIRVersion[] = {2, 7, 0};
+
+// MTLDowngradeAIRModule and MTLMetalFunctionCreate both read
+// getNamedMetadata("air.version")->getOperand(0) without a null check. The
+// modules AppleMetalGLRenderer builds for OpenGL ES name only their language
+// ("OpenGL ES GLSL" 1.0) and carry no air.version, so the compiler service
+// crashed on every GLES shader. Give such a module the version the front end
+// would have written.
+static void addMissingAIRVersion(LLVMModuleRef module) {
+ if (LLVMGetNamedMetadataNumOperands(module, "air.version") > 0)
+ return;
+ LLVMContextRef context = LLVMGetModuleContext(module);
+ LLVMTypeRef i32 = LLVMInt32TypeInContext(context);
+ LLVMValueRef parts[3];
+ for (int i = 0; i < 3; i++)
+ parts[i] = LLVMConstInt(i32, glesAIRVersion[i], 0);
+ LLVMAddNamedMetadataOperand(module, "air.version", LLVMMDNodeInContext(context, parts, 3));
+}
+
// --- Implementation ---
AppleParavirtCompiler::~AppleParavirtCompiler() {
@@ -119,6 +151,17 @@ bool AppleParavirtCompiler::buildRequestWithOptions(
return true; // error
}
+ if (isGLESModule(module)) {
+ const char *error = nullptr;
+ if (LLVMModuleRef completed = completedGLESModule(module, &error))
+ module = completed;
+ else if (error) {
+ *outError = error;
+ return true;
+ }
+ }
+ addMissingAIRVersion(module);
+
// Downgrade the AIR module for this target
int result = MTLDowngradeAIRModule(module, _targetTriple, 0);
if (!result) {
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index e968155b..cf44d367 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -146,6 +146,33 @@ GPU_DYNAMIC_LOOKUP_SYMS := \
-Wl,-U,_LLVMGetMDNodeNumOperands \
-Wl,-U,_LLVMGetMDNodeOperands \
-Wl,-U,_LLVMGetValueName2 \
+ -Wl,-U,_LLVMGetModuleContext \
+ -Wl,-U,_LLVMInt32TypeInContext \
+ -Wl,-U,_LLVMConstInt \
+ -Wl,-U,_LLVMMDNodeInContext \
+ -Wl,-U,_LLVMAddNamedMetadataOperand \
+ -Wl,-U,_LLVMABIAlignmentOfType \
+ -Wl,-U,_LLVMABISizeOfType \
+ -Wl,-U,_LLVMCountParamTypes \
+ -Wl,-U,_LLVMCountStructElementTypes \
+ -Wl,-U,_LLVMCreateMemoryBufferWithMemoryRangeCopy \
+ -Wl,-U,_LLVMDisposeMessage \
+ -Wl,-U,_LLVMGetArrayLength \
+ -Wl,-U,_LLVMGetElementType \
+ -Wl,-U,_LLVMGetIntTypeWidth \
+ -Wl,-U,_LLVMGetMDString \
+ -Wl,-U,_LLVMGetModuleDataLayout \
+ -Wl,-U,_LLVMGetParamTypes \
+ -Wl,-U,_LLVMGetPointerAddressSpace \
+ -Wl,-U,_LLVMGetReturnType \
+ -Wl,-U,_LLVMGetStructName \
+ -Wl,-U,_LLVMGetTypeKind \
+ -Wl,-U,_LLVMGetVectorSize \
+ -Wl,-U,_LLVMGlobalGetValueType \
+ -Wl,-U,_LLVMIsAMDString \
+ -Wl,-U,_LLVMParseIRInContext \
+ -Wl,-U,_LLVMPrintModuleToString \
+ -Wl,-U,_LLVMStructGetTypeAtIndex \
-Wl,-U,_MTLGPUCompilerCreate \
-Wl,-U,_MTLGPUCompilerDestroy \
-Wl,-U,_MTLDowngradeAIRModule \
@@ -227,6 +254,18 @@ test-x1-lowering:
-o $(OUT)/X1LoweringTests Tests/X1LoweringTests.c LaunchHook/VPhoneX1Lowering.c
@$(OUT)/X1LoweringTests
+# Host proof harness for the compiler plugin's OpenGL ES path: the AIR modules
+# AppleMetalGLRenderer hands it, through the plugin and into the host's Metal.
+# The plugin resolves libLLVM and libGPUCompiler at load, so it and the tests
+# are one dylib the runner loads after them.
+.PHONY: test-gles-air
+test-gles-air:
+ @mkdir -p $(OUT)
+ xcrun --sdk macosx clang++ -std=c++17 -fobjc-arc -O1 -Wall -Wextra -IGraphicLoader -dynamiclib -Wl,-undefined,dynamic_lookup \
+ -o $(OUT)/GLESAIRTests.dylib Tests/GLESAIRTests.mm $(GPU_PLUGIN_SOURCES) -framework Foundation -framework Metal
+ xcrun --sdk macosx clang -Wall -Wextra -Werror -o $(OUT)/GLESAIRTestRunner Tests/GLESAIRTestRunner.c
+ @$(OUT)/GLESAIRTestRunner $(OUT)/GLESAIRTests.dylib Tests/GLESAIRFixtures
+
# Host proof harness for libdevicename's name decoding, configd publication
# rewrite and lockdownd rename decision.
test-devicename:
diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/constant-fragment.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/constant-fragment.ll
new file mode 100644
index 00000000..59335625
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/constant-fragment.ll
@@ -0,0 +1,39 @@
+; ModuleID = 'glsl shader'
+source_filename = "glsl shader"
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
+target triple = "air64-apple-ios"
+
+; Function Attrs: nounwind
+define { <4 x half> } @"#main"(<4 x float> addrspace(2)* %0) #0 {
+allocaBlock:
+ %1 = alloca <4 x half>, align 8
+ %2 = alloca <4 x half>, align 8
+ br label %globalBlock
+
+globalBlock: ; preds = %allocaBlock
+ br label %block
+
+block: ; preds = %globalBlock
+ store <4 x half> <half 0xH3C00, half 0xH0000, half 0xH3800, half 0xH3C00>, <4 x half>* %1, align 8
+ %3 = load <4 x half>, <4 x half>* %1, align 8
+ store <4 x half> %3, <4 x half>* %2, align 8
+ %4 = load <4 x half>, <4 x half>* %2, align 8
+ %5 = insertvalue { <4 x half> } undef, <4 x half> %4, 0
+ ret { <4 x half> } %5
+}
+
+attributes #0 = { nounwind }
+
+!air.language_version = !{!0}
+!air.compile_options = !{!1, !2, !3}
+!air.fragment = !{!4}
+
+!0 = !{!"OpenGL ES GLSL", i32 1, i32 0, i32 0}
+!1 = !{!"air.compile.fast_math_enable"}
+!2 = !{!"air.compile.denorms_disable"}
+!3 = !{!"air.compile.native_double_disable"}
+!4 = !{{ <4 x half> } (<4 x float> addrspace(2)*)* @"#main", !5, !7}
+!5 = !{!6}
+!6 = !{!"air.render_target", i32 0, i32 0}
+!7 = !{!8}
+!8 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 0, !"air.location_index", i32 12, i32 1, !"air.read"}
diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-fragment.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-fragment.ll
new file mode 100644
index 00000000..9ec92c0b
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-fragment.ll
@@ -0,0 +1,78 @@
+; ModuleID = 'glsl shader'
+source_filename = "glsl shader"
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
+target triple = "air64-apple-ios"
+
+%struct._texture_2d_t = type opaque
+%struct._sampler_t = type opaque
+
+; Function Attrs: nounwind
+define { <4 x half> } @"#main"(<2 x half> %0, half %1, <4 x float> addrspace(2)* %2, %struct._texture_2d_t addrspace(1)* %3, %struct._sampler_t addrspace(2)* %4) #0 {
+allocaBlock:
+ %5 = alloca <2 x half>, align 4
+ %6 = alloca half, align 2
+ %7 = alloca half, align 2
+ %8 = alloca <2 x half>, align 4
+ %9 = alloca <4 x half>, align 8
+ %10 = alloca <4 x half>, align 8
+ %11 = alloca <4 x half>, align 8
+ br label %globalBlock
+
+globalBlock: ; preds = %allocaBlock
+ %12 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 5
+ br label %block
+
+block: ; preds = %globalBlock
+ store <2 x half> %0, <2 x half>* %5, align 4
+ store half %1, half* %6, align 2
+ %13 = load half, half* %6, align 2
+ %14 = load half, half* %7, align 2
+ store half %13, half* %7, align 2
+ %15 = load <2 x half>, <2 x half>* %5, align 4
+ store <2 x half> %15, <2 x half>* %8, align 4
+ %16 = load <2 x half>, <2 x half>* %8, align 4
+ %17 = shufflevector <2 x half> %16, <2 x half> %16, <4 x i32> <i32 0, i32 1, i32 1, i32 1>
+ %18 = shufflevector <4 x half> %17, <4 x half> undef, <2 x i32> <i32 0, i32 1>
+ %19 = fpext <2 x half> %18 to <2 x float>
+ %20 = call { <4 x half>, i8 } @air.sample_texture_2d.v4f16(%struct._texture_2d_t addrspace(1)* %3, %struct._sampler_t addrspace(2)* %4, <2 x float> %19, i1 false, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)
+ %21 = extractvalue { <4 x half>, i8 } %20, 0
+ store <4 x half> %21, <4 x half>* %9, align 8
+ %22 = load <4 x half>, <4 x half>* %9, align 8
+ %23 = load <4 x float>, <4 x float> addrspace(2)* %12, align 16
+ %24 = fptrunc <4 x float> %23 to <4 x half>
+ %25 = fmul reassoc nsz arcp contract afn <4 x half> %22, %24
+ %26 = load half, half* %7, align 2
+ %27 = insertelement <4 x half> undef, half %26, i32 0
+ %28 = shufflevector <4 x half> %27, <4 x half> %27, <4 x i32> zeroinitializer
+ %29 = fmul reassoc nsz arcp contract afn <4 x half> %25, %28
+ store <4 x half> %29, <4 x half>* %10, align 8
+ %30 = load <4 x half>, <4 x half>* %10, align 8
+ store <4 x half> %30, <4 x half>* %11, align 8
+ %31 = load <4 x half>, <4 x half>* %11, align 8
+ %32 = insertvalue { <4 x half> } undef, <4 x half> %31, 0
+ ret { <4 x half> } %32
+}
+
+; Function Attrs: nounwind readonly
+declare { <4 x half>, i8 } @air.sample_texture_2d.v4f16(%struct._texture_2d_t addrspace(1)*, %struct._sampler_t addrspace(2)*, <2 x float>, i1, <2 x i32>, i1, float, float, i32) #1
+
+attributes #0 = { nounwind }
+attributes #1 = { nounwind readonly }
+
+!air.language_version = !{!0}
+!air.compile_options = !{!1, !2, !3}
+!air.fragment = !{!4}
+
+!0 = !{!"OpenGL ES GLSL", i32 1, i32 0, i32 0}
+!1 = !{!"air.compile.fast_math_enable"}
+!2 = !{!"air.compile.denorms_disable"}
+!3 = !{!"air.compile.native_double_disable"}
+!4 = !{{ <4 x half> } (<2 x half>, half, <4 x float> addrspace(2)*, %struct._texture_2d_t addrspace(1)*, %struct._sampler_t addrspace(2)*)* @"#main", !5, !7}
+!5 = !{!6}
+!6 = !{!"air.render_target", i32 0, i32 0}
+!7 = !{!8, !9, !10, !11, !12}
+!8 = !{i32 0, !"air.fragment_input", !"user(slot9)", !"air.perspective", !"air.center", !"air.arg_type_name", !"half2"}
+!9 = !{i32 1, !"air.fragment_input", !"user(slot8)", !"air.perspective", !"air.center", !"air.arg_type_name", !"half"}
+!10 = !{i32 2, !"air.buffer", !"air.buffer_size", i32 112, !"air.location_index", i32 12, i32 1, !"air.read"}
+!11 = !{i32 3, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>"}
+!12 = !{i32 4, !"air.sampler", !"air.location_index", i32 0, i32 1}
diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-vertex.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-vertex.ll
new file mode 100644
index 00000000..c4c8a80e
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/textured-vertex.ll
@@ -0,0 +1,137 @@
+; ModuleID = 'glsl shader'
+source_filename = "glsl shader"
+target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"
+target triple = "air64-apple-ios"
+
+; Function Attrs: nounwind
+define { <2 x half>, <4 x float>, half } @"#main"(<2 x float> %0, <2 x float> %1, <4 x float> addrspace(2)* %2) #0 {
+allocaBlock:
+ %3 = alloca <2 x float>, align 8
+ %4 = alloca <2 x float>, align 8
+ %5 = alloca <2 x float>, align 8
+ %6 = alloca <2 x float>, align 8
+ %7 = alloca <4 x float>, align 16
+ %8 = alloca <2 x float>, align 8
+ %9 = alloca <4 x float>, align 16
+ %10 = alloca <4 x float>, align 16
+ %11 = alloca <4 x float>, align 16
+ %12 = alloca <2 x float>, align 8
+ %13 = alloca float, align 4
+ %14 = alloca <4 x float>, align 16
+ %15 = alloca half, align 2
+ %16 = alloca <2 x half>, align 4
+ br label %globalBlock
+
+globalBlock: ; preds = %allocaBlock
+ %17 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 4
+ %18 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 3
+ %19 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 2
+ %20 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 1
+ %21 = getelementptr <4 x float>, <4 x float> addrspace(2)* %2, i32 0
+ br label %block
+
+block: ; preds = %globalBlock
+ store <2 x float> %0, <2 x float>* %3, align 8
+ store <2 x float> %1, <2 x float>* %4, align 8
+ %22 = load <2 x float>, <2 x float>* %3, align 8
+ store <2 x float> %22, <2 x float>* %5, align 8
+ %23 = load <2 x float>, <2 x float>* %4, align 8
+ store <2 x float> %23, <2 x float>* %6, align 8
+ %24 = load <2 x float>, <2 x float>* %6, align 8
+ %25 = bitcast <4 x float> addrspace(2)* %17 to float addrspace(2)*
+ %26 = load float, float addrspace(2)* %25, align 4
+ %27 = insertelement <2 x float> undef, float %26, i32 0
+ %28 = shufflevector <2 x float> %27, <2 x float> %27, <2 x i32> zeroinitializer
+ %29 = fmul reassoc nsz arcp contract afn <2 x float> %24, %28
+ store <2 x float> %29, <2 x float>* %8, align 8
+ %30 = load <2 x float>, <2 x float>* %8, align 8
+ %31 = shufflevector <2 x float> %30, <2 x float> <float 0.000000e+00, float 1.000000e+00>, <4 x i32> <i32 0, i32 1, i32 2, i32 3>
+ store <4 x float> %31, <4 x float>* %9, align 16
+ %32 = load <4 x float>, <4 x float>* %9, align 16
+ store <4 x float> %32, <4 x float>* %7, align 16
+ %33 = load <4 x float>, <4 x float> addrspace(2)* %18, align 16
+ %34 = load <4 x float>, <4 x float>* %7, align 16
+ %35 = shufflevector <4 x float> %34, <4 x float> %34, <4 x i32> <i32 3, i32 3, i32 3, i32 3>
+ %36 = load <4 x float>, <4 x float> addrspace(2)* %19, align 16
+ %37 = load <4 x float>, <4 x float>* %7, align 16
+ %38 = shufflevector <4 x float> %37, <4 x float> %37, <4 x i32> <i32 2, i32 2, i32 2, i32 2>
+ %39 = load <4 x float>, <4 x float> addrspace(2)* %20, align 16
+ %40 = load <4 x float>, <4 x float>* %7, align 16
+ %41 = shufflevector <4 x float> %40, <4 x float> %40, <4 x i32> <i32 1, i32 1, i32 1, i32 1>
+ %42 = load <4 x float>, <4 x float> addrspace(2)* %21, align 16
+ %43 = load <4 x float>, <4 x float>* %7, align 16
+ %44 = shufflevector <4 x float> %43, <4 x float> %43, <4 x i32> zeroinitializer
+ %45 = fmul reassoc nsz arcp contract afn <4 x float> %42, %44
+ %46 = call reassoc nsz arcp contract afn <4 x float> @air.mad.v4f32(<4 x float> %39, <4 x float> %41, <4 x float> %45)
+ %47 = call reassoc nsz arcp contract afn <4 x float> @air.mad.v4f32(<4 x float> %36, <4 x float> %38, <4 x float> %46)
+ %48 = call reassoc nsz arcp contract afn <4 x float> @air.mad.v4f32(<4 x float> %33, <4 x float> %35, <4 x float> %47)
+ store <4 x float> %48, <4 x float>* %10, align 16
+ %49 = load <4 x float>, <4 x float>* %10, align 16
+ store <4 x float> %49, <4 x float>* %11, align 16
+ %50 = load <2 x float>, <2 x float>* %5, align 8
+ store <2 x float> %50, <2 x float>* %12, align 8
+ store float 1.000000e+00, float* %13, align 4
+ %51 = load <4 x float>, <4 x float>* %11, align 16
+ store <4 x float> %51, <4 x float>* %14, align 16
+ %52 = load float, float* %13, align 4
+ %53 = fptrunc float %52 to half
+ %54 = load half, half* %15, align 2
+ store half %53, half* %15, align 2
+ %55 = load <2 x float>, <2 x float>* %12, align 8
+ %56 = extractelement <2 x float> %55, i32 0
+ %57 = fptrunc float %56 to half
+ %58 = load <2 x half>, <2 x half>* %16, align 4
+ %59 = insertelement <2 x half> %58, half %57, i32 0
+ store <2 x half> %59, <2 x half>* %16, align 4
+ %60 = load <2 x float>, <2 x float>* %12, align 8
+ %61 = extractelement <2 x float> %60, i32 1
+ %62 = fptrunc float %61 to half
+ %63 = load <2 x half>, <2 x half>* %16, align 4
+ %64 = insertelement <2 x half> %63, half %62, i32 1
+ store <2 x half> %64, <2 x half>* %16, align 4
+ %65 = load half, half* %15, align 2
+ %66 = insertvalue { <2 x half>, <4 x float>, half } undef, half %65, 2
+ %67 = load <4 x float>, <4 x float>* %14, align 16
+ %68 = insertvalue { <2 x half>, <4 x float>, half } %66, <4 x float> %67, 1
+ %69 = load <2 x half>, <2 x half>* %16, align 4
+ %70 = insertvalue { <2 x half>, <4 x float>, half } %68, <2 x half> %69, 0
+ ret { <2 x half>, <4 x float>, half } %70
+}
+
+; Function Attrs: nounwind readnone
+declare <4 x float> @air.mad.v4f32(<4 x float>, <4 x float>, <4 x float>) #1
+
+define { <2 x half>, <4 x float>, half } @air.vertexFetchFunction(<4 x float> addrspace(2)* %0, <{ [16 x i8] }> addrspace(1)* %1, i32 zeroext %2) {
+Body:
+ %3 = zext i32 %2 to i64
+ %4 = getelementptr <{ [16 x i8] }>, <{ [16 x i8] }> addrspace(1)* %1, i64 %3, i32 0, i64 0
+ %5 = bitcast i8 addrspace(1)* %4 to <2 x float> addrspace(1)*
+ %6 = load <2 x float>, <2 x float> addrspace(1)* %5, align 4
+ %7 = zext i32 %2 to i64
+ %8 = getelementptr <{ [16 x i8] }>, <{ [16 x i8] }> addrspace(1)* %1, i64 %7, i32 0, i64 8
+ %9 = bitcast i8 addrspace(1)* %8 to <2 x float> addrspace(1)*
+ %10 = load <2 x float>, <2 x float> addrspace(1)* %9, align 4
+ %11 = call { <2 x half>, <4 x float>, half } @"#main"(<2 x float> %6, <2 x float> %10, <4 x float> addrspace(2)* %0)
+ ret { <2 x half>, <4 x float>, half } %11
+}
+
+attributes #0 = { nounwind }
+attributes #1 = { nounwind readnone }
+
+!air.language_version = !{!0}
+!air.compile_options = !{!1, !2, !3}
+!air.vertex = !{!4}
+
+!0 = !{!"OpenGL ES GLSL", i32 1, i32 0, i32 0}
+!1 = !{!"air.compile.fast_math_enable"}
+!2 = !{!"air.compile.denorms_disable"}
+!3 = !{!"air.compile.native_double_disable"}
+!4 = !{{ <2 x half>, <4 x float>, half } (<4 x float> addrspace(2)*, <{ [16 x i8] }> addrspace(1)*, i32)* @air.vertexFetchFunction, !5, !9}
+!5 = !{!6, !7, !8}
+!6 = !{!"air.vertex_output", !"user(slot9)"}
+!7 = !{!"air.position"}
+!8 = !{!"air.vertex_output", !"user(slot8)"}
+!9 = !{!10, !11, !12}
+!10 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 112, !"air.location_index", i32 12, i32 1, !"air.read"}
+!11 = !{i32 1, !"air.buffer", !"air.location_index", i32 15, i32 1, !"air.read", !"air.arg_type_name", !"void", !"air.arg_name", !".hidden"}
+!12 = !{i32 2, !"air.vertex_id", !"air.arg_type_name", !"uint"}
diff --git a/VPhoneGuestComponents/Tests/GLESAIRTestRunner.c b/VPhoneGuestComponents/Tests/GLESAIRTestRunner.c
new file mode 100644
index 00000000..8c309d7e
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GLESAIRTestRunner.c
@@ -0,0 +1,30 @@
+// Loads the host's libLLVM and libGPUCompiler globally, then the GLES AIR test
+// dylib, whose plugin code resolves their symbols by flat lookup, as
+// MTLCompilerService provides them to the plugin in the guest.
+
+#include <dlfcn.h>
+#include <stdio.h>
+
+int main(int argc, char **argv) {
+ if (argc != 3) {
+ fprintf(stderr, "usage: %s <GLESAIRTests.dylib> <fixtures directory>\n", argv[0]);
+ return 2;
+ }
+ const char *libraries[] = {
+ "/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/32023/Libraries/libLLVM.dylib",
+ "/System/Library/PrivateFrameworks/GPUCompiler.framework/Versions/32023/Libraries/libGPUCompiler.dylib",
+ };
+ for (int i = 0; i < 2; i++) {
+ if (!dlopen(libraries[i], RTLD_NOW | RTLD_GLOBAL)) {
+ fprintf(stderr, "%s\n", dlerror());
+ return 1;
+ }
+ }
+ void *tests = dlopen(argv[1], RTLD_NOW);
+ if (!tests) {
+ fprintf(stderr, "%s\n", dlerror());
+ return 1;
+ }
+ int (*run)(const char *) = (int (*)(const char *))dlsym(tests, "GLESAIRRunTests");
+ return run ? run(argv[2]) : 1;
+}
diff --git a/VPhoneGuestComponents/Tests/GLESAIRTests.mm b/VPhoneGuestComponents/Tests/GLESAIRTests.mm
new file mode 100644
index 00000000..965f345b
--- /dev/null
+++ b/VPhoneGuestComponents/Tests/GLESAIRTests.mm
@@ -0,0 +1,142 @@
+// Host proof harness for the compiler plugin's OpenGL ES path (GraphicLoader).
+//
+// The fixtures are AIR modules AppleMetalGLRenderer handed the plugin in an
+// iOS 27.0.1 guest, dumped as text: a constant-colour fragment shader, and the
+// fragment and vertex shaders of a textured, uniform-driven program. The host
+// carries the same GPUCompiler (32023) as the guest, so each module is run
+// through the plugin as MTLCompilerService runs it, and the metallib must load
+// in the host's Metal as the right kind of function; the vertex and fragment
+// functions must link into a render pipeline. Built as a dylib and loaded by
+// GLESAIRTestRunner after libLLVM and libGPUCompiler, as the compiler service
+// loads the plugin.
+
+#import <Foundation/Foundation.h>
+#import <Metal/Metal.h>
+
+#include <cstdio>
+#include <cstring>
+#include <string>
+
+#include "GLESAIR.h"
+
+typedef struct LLVMOpaqueContext *LLVMContextRef;
+typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;
+
+extern "C" {
+LLVMContextRef LLVMContextCreate(void);
+LLVMMemoryBufferRef LLVMCreateMemoryBufferWithMemoryRangeCopy(const char *InputData, size_t InputDataLength, const char *BufferName);
+int LLVMParseIRInContext(LLVMContextRef ContextRef, LLVMMemoryBufferRef MemBuf, LLVMModuleRef *OutM, char **OutMessage);
+char *LLVMPrintModuleToString(LLVMModuleRef M);
+
+void *MTLCompilerCreate(void *targetInfo, uint64_t version);
+bool MTLCompilerBuildRequestWithOptions(void *compiler, const void *inputData, size_t inputSize, unsigned flags, LLVMModuleRef module,
+ const void **outCode, size_t *outCodeSize, const void **outReflection, size_t *outReflectionSize,
+ const void **outDebug, size_t *outDebugSize, const char **outError);
+}
+
+static int failures = 0;
+
+static void check(bool condition, const char *what) {
+ printf("%s %s\n", condition ? "ok " : "FAIL", what);
+ if (!condition)
+ failures++;
+}
+
+static LLVMModuleRef parse(const char *directory, const char *name) {
+ NSString *path = [NSString stringWithFormat:@"%s/%s", directory, name];
+ NSData *text = [NSData dataWithContentsOfFile:path];
+ if (!text)
+ return nullptr;
+ LLVMModuleRef module = nullptr;
+ char *error = nullptr;
+ if (LLVMParseIRInContext(LLVMContextCreate(), LLVMCreateMemoryBufferWithMemoryRangeCopy((const char *)text.bytes, text.length, name), &module, &error))
+ return nullptr;
+ return module;
+}
+
+static bool contains(const std::string &text, const char *needle) {
+ return text.find(needle) != std::string::npos;
+}
+
+// The rewritten metadata, checked line by line against what the Metal front end writes.
+static void testCompletion(const char *fixtures) {
+ LLVMModuleRef fragment = parse(fixtures, "textured-fragment.ll");
+ check(fragment && isGLESModule(fragment), "the textured fragment module is an OpenGL ES module");
+ const char *error = nullptr;
+ LLVMModuleRef completed = completedGLESModule(fragment, &error);
+ check(completed && !error, "the textured fragment module is completed");
+ if (!completed)
+ return;
+ std::string text = LLVMPrintModuleToString(completed);
+ check(contains(text, "!{i32 2, !\"air.buffer\", !\"air.buffer_size\", i32 112, !\"air.location_index\", i32 12, i32 1, !\"air.read\", "
+ "!\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 16, "
+ "!\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"_gles_arg2\"}"),
+ "the uniform buffer gains address space, size, alignment, type and name");
+ check(contains(text, "!{i32 4, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"_gles_arg4\"}"),
+ "the sampler gains its type and name");
+ check(contains(text, "!\"air.sample\", !\"air.arg_type_name\", !\"texture2d<float, sample>\", !\"air.arg_name\", !\"_gles_arg3\"}"),
+ "the texture keeps its own type name and gains a name");
+ check(contains(text, "!{!\"air.render_target\", i32 0, i32 0, !\"air.arg_type_name\", !\"half4\"}"),
+ "the render target gains a type and no name, as the front end writes it");
+
+ LLVMModuleRef vertex = parse(fixtures, "textured-vertex.ll");
+ completed = vertex ? completedGLESModule(vertex, &error) : nullptr;
+ text = completed ? LLVMPrintModuleToString(completed) : "";
+ check(contains(text, "!{i32 1, !\"air.buffer\", !\"air.location_index\", i32 15, i32 1, !\"air.read\", !\"air.arg_type_name\", !\"void\", "
+ "!\"air.arg_name\", !\".hidden\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 16, !\"air.arg_type_align_size\", i32 1}"),
+ "the vertex fetch buffer GLEngine already described is left as it is");
+ check(contains(text, "!{!\"air.position\", !\"air.arg_type_name\", !\"float4\", !\"air.arg_name\", !\"_gles_out1\"}"),
+ "the position output gains its type from the return struct");
+}
+
+// Each module through the plugin, then into the host's Metal.
+static void testMetallibs(const char *fixtures) {
+ struct { uint64_t target; } info = {0x700000002}; // AIR 2.7, as MTLCompilerService passes it
+ void *compiler = MTLCompilerCreate(&info, 8);
+ check(compiler != nullptr, "the plugin creates a compiler");
+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();
+ id<MTLFunction> vertexFunction = nil, fragmentFunction = nil;
+ struct { const char *file; MTLFunctionType type; } cases[] = {
+ {"constant-fragment.ll", MTLFunctionTypeFragment},
+ {"textured-fragment.ll", MTLFunctionTypeFragment},
+ {"textured-vertex.ll", MTLFunctionTypeVertex},
+ };
+ for (auto &c : cases) {
+ LLVMModuleRef module = parse(fixtures, c.file);
+ const void *code = nullptr, *reflection = nullptr, *debug = nullptr;
+ size_t codeSize = 0, reflectionSize = 0, debugSize = 0;
+ const char *error = nullptr;
+ bool failed = !module || MTLCompilerBuildRequestWithOptions(compiler, nullptr, 0, 0, module, &code, &codeSize, &reflection, &reflectionSize, &debug, &debugSize, &error);
+ std::string what = std::string(c.file) + " builds a metallib" + (error ? std::string(": ") + error : "");
+ check(!failed && code && codeSize > 0, what.c_str());
+ if (failed || !code)
+ continue;
+ NSError *libraryError = nil;
+ id<MTLLibrary> library = [device newLibraryWithData:dispatch_data_create(code, codeSize, nil, nil) error:&libraryError];
+ id<MTLFunction> function = library.functionNames.count == 1 ? [library newFunctionWithName:library.functionNames.firstObject] : nil;
+ what = std::string(c.file) + " loads in the host's Metal as one function of its stage";
+ check(function && function.functionType == c.type, what.c_str());
+ if (!strcmp(c.file, "textured-vertex.ll"))
+ vertexFunction = function;
+ if (!strcmp(c.file, "textured-fragment.ll"))
+ fragmentFunction = function;
+ }
+ if (vertexFunction && fragmentFunction) {
+ MTLRenderPipelineDescriptor *descriptor = [MTLRenderPipelineDescriptor new];
+ descriptor.vertexFunction = vertexFunction;
+ descriptor.fragmentFunction = fragmentFunction;
+ descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;
+ NSError *pipelineError = nil;
+ id<MTLRenderPipelineState> pipeline = [device newRenderPipelineStateWithDescriptor:descriptor error:&pipelineError];
+ check(pipeline != nil, "the textured program's vertex and fragment functions link into a render pipeline");
+ }
+}
+
+extern "C" int GLESAIRRunTests(const char *fixtures) {
+ @autoreleasepool {
+ testCompletion(fixtures);
+ testMetallibs(fixtures);
+ }
+ printf("%s\n", failures ? "GLES AIR tests FAILED" : "GLES AIR tests passed");
+ return failures ? 1 : 0;
+}