Run a virtual iPhone on an Apple Silicon Mac.
Swift
Fix native GLES rendering on paravirtual Metal
lijunliang.981903aa06a4623f
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex b8cf435b..c29020cf 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -1782,8 +1782,13 @@ 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 |-+| 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.** The observed restart-disabled renderer call passes `NO, 0xffffffff`; 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 |+| 31 | SystemHook selects `AGX_GL_VIEWPORT_INVERT_CONFIG=UPPER_LEFT` while `/usr/lib/vphone-gles-upper-left` exists — **iOS 26.6 / cloudOS 26.4** | No Apple binary change; project's SystemHook and installer marker | **Correct native GLES drawable orientation.** The renderer's existing viewport/scissor path avoids IOSurface attachment `yInvert`, whose effect the measured paravirtual path does not preserve. `system-systemhook-cfw-gles_upper_left`; selectable and revertible. See "Native GLES follow-up (2026-11-02)". | Y | Y | Y |+| 32 | Convert legacy vertex/instance ID attribute formats 43/44 to public UInt (36) at the descriptor wire write — **iOS 26.6 / cloudOS 26.4** | Metal framework's `PipelineLibrarySerializer::serializeVertexDescriptor`, guest dyld shared cache | **Let the host compile GLES builtin-ID pipelines.** Preserve guest descriptors and AIR; normalize only the serialized format through a 32-byte in-image trampoline. `dyld-cfw-metal_vertex_id_format`; symbol/operand discovery, page re-attestation and undo-log revert. See "Native GLES follow-up (2026-11-02)". | Y | Y | Y |+| 33 | Select GLEngine primitive expansion for indexed line/triangle strips with restart disabled — **iOS 26.6 / cloudOS 26.4** | AppleMetalGLRenderer's `gldRenderVertexArray`, guest dyld shared cache | **Preserve a valid maximum index while restart is disabled.** A checked 68-byte entry trampoline reads state fields derived from `updateRenderPrimitiveRestart`; other draws keep their normal path. `dyld-cfw-gles_primitive_restart` requires rows 30/32, adds CPU vertex copying and supports undo-log revert. Guest validation passes the seven restart cases, seven builtin controls and 36 matrix cases. See "Native GLES follow-up (2026-11-02)". | Y | Y | Y |+| 34 | Remove four point-size reflection guards that suppress valid `GL_POINTS` submissions — **iOS 26.6 / cloudOS 26.4** | AppleMetalGLRenderer's direct and primitive-buffer draw paths, guest dyld shared cache | **Submit points despite missing PV pipeline usage flags.** `dyld-cfw-gles_point_draw` replaces only the four bit-7 `TBZ` guards with NOPs, preserving other gates and the native shader/rasterizer. Semantic discovery and transactional DSC undo; cloned-cache apply/repeat/revert restores all 85 files exactly. Process-local diagnostics restore point footprints but expose a separate coordinate Y-flip transport gap. Development-build guest validation passes all 21 point cases on the restored old default cache and a warm repeat; see "Native GLES follow-up (2026-11-02)". | Y | Y | Y |+| 35 | Derive the paravirtual driver compiler cache identity from the installed plugin — **iOS 26.6 / cloudOS 26.4** | AppleParavirtGPUMetalIOGPUFamily | **Invalidate shader output after plugin updates.** `system-paravirt_gpu-cfw-compiler_cache` replaces only two eight-byte SHA-256 seed inputs with a 96-bit plugin content identity. Changes compose with the other driver patches on its pristine backup. Requires row 36 when cross-boot reuse is enabled; installer verifies it actually applied before refreshing the plugin. Private APFS clone and fatal identity-failure handling prevent inconsistent publication. Development-build guest validation rejects stale default-cache shaders and passes all 21 point cases. | Y | Y | Y |+| 36 | Retain cache-key validation when cross-boot reuse is enabled — **iOS 26.6 / cloudOS 26.4** | libCoreFSCache in the guest dyld shared cache | **Reject stale compiler output while retaining warm caches across boots.** The original `FS_CACHE_REUSE_ON_REBOOT=1` skips both the key and boot checks. `dyld-cfw-metal_cache_reuse_key` routes only that path through the key comparison; the no-reuse path remains intact. Development-build guest validation passes all 21 point cases on the restored old default cache and a warm repeat; actual-cache apply/repeat/undo restores all 85 files. | Y | Y | Y |### Swift port status — the eight DSC patchers (2026-09-23)@@ -5991,5 +5996,97 @@ completion covers the argument kinds the probes produced (buffers, the vertexfetch buffer, vertex id, textures, samplers, fragment inputs, position andvertex outputs, render targets); an argument kind the reflection reads in alayout 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.+service. With primitive restart no longer sent, a strip that draws vertex+65535 while restart is disabled is cut there. This includes ES2 and ES3's+initial or explicitly disabled state; row 33 addresses that gap.++## Native GLES follow-up (2026-11-02)++Rows 31–36 are selected by `standard` only for iOS 26.6/cloudOS 26.4,+including patch releases; TV, HomePod and HomeView presets exclude them.+A missing plan enables none, opt-in cannot widen the version gate, and current+guest selections can enable declarations absent from an older boot plan.++**Orientation, `system-systemhook-cfw-gles_upper_left` (row 31).** Reveal+AppleMetalGLRenderer's `AGX_GL_VIEWPORT_INVERT_CONFIG` / `UPPER_LEFT` strings+and `populateConfigData`, then follow `drawableInvert`, `drawablePBEInvert`,+`updateRenderViewport` and `updateRenderScissor`. SystemHook selects this+existing viewport/scissor path at constructor entry only while the installer+marker exists, preserving explicit environment values. It avoids the private+IOSurface attachment `yInvert` flag that had no effect in PV controls.+No Apple binary changes; opt-out removes the marker.++**Descriptor, `dyld-cfw-metal_vertex_id_format` (row 32).** Resolve Metal's+image-local `PipelineLibrarySerializer::serializeVertexDescriptor` and format+getter; prove the unique wire-property-1 write from decoded operands/control+flow. A 32-byte trampoline converts only private ID formats 43/44 to UInt+(36) at that write, after guest shader variant generation. Original descriptors,+AIR and other formats remain intact. Private format 43 reproduced the host+`CloneAttributeDescriptor` crash; the same AIR with UInt compiled successfully.++**Restart, `dyld-cfw-gles_primitive_restart` (row 33).** Resolve+`gldRenderVertexArray` and `updateRenderPrimitiveRestart`; derive state fields+from the decoded updater. A 68-byte entry trampoline returns zero only for+disabled indexed line/triangle strips, selecting GLEngine's existing primitive+expansion, which retains vertex/instance IDs in a nonindexed draw. Other draws+keep their normal path. All affected strips pay CPU copying cost. Dependencies+are command suppression (row 30) and ID-format repair (row 32); removing only+the unsupported command leaves Metal's maximum-index restart active.++**Points, `dyld-cfw-gles_point_draw` (row 34).** Recover full next-symbol+function bounds and context fields from `setRenderPipeline`. Replace three+point-size bit-7 `TBZ` guards in `gldRenderVertexArray` and one in+`gldEndPrimitiveBuffer` with NOPs; preserve point-mode, pipeline, buffer and+other gates. The indexed path must prove the exact NUL-terminated draw selector+in `beginRenderPass`, encoder/selector arguments to `methodForSelector:`,+returned IMP store and use of the recovered encoder/IMP slots. Validate all+four sites before writing. PV's inherited pipeline-flags method returns zero;+no global reflection flags are fabricated to compensate.++**Identity, `system-paravirt_gpu-cfw-compiler_cache` (row 35).** Reveal+`setupCompiler` through relative Objective-C metadata, then verify imported+SHA-256 Init/Update/Update/Final dataflow, both eight-byte date/time inputs and+use of the digest as `cacheUUID`. Decoded code references to both literals+must be exclusive to these inputs. Replace only their 16 bytes with base64 of+the installed plugin's first 12 SHA-256 bytes (96 identity bits), preserving+terminators; validate and read back both writes. The installer hashes the+actual plugin after refresh, composes selected driver patches from one pristine+backup and signs the result. Opt-out restores the original seed while retaining+other selected driver changes.++**Reuse, `dyld-cfw-metal_cache_reuse_key` (row 36).** Row 29's original+interpretation was incomplete: `FS_CACHE_REUSE_ON_REBOOT=1` skips the 32-byte+key check as well as the 64-byte boot/system-stamp check. In `libCoreFSCache`,+follow the environment branch and both comparisons; prove the recovered+skip-boot flag's complete lifetime, semantic uses and callee-save restoration.+Redirect only the reuse-enabled branch through an eight-byte trampoline that+sets the flag to one and resumes at the existing key comparison after its+normal assignment. A mismatched key rejects the cache; a matching key skips+only the boot comparison. The no-reuse path is unchanged. This and row 35+invalidate stale compiler output without deleting application caches.++All four DSC patches snapshot code/hash bytes, re-attest changed pages and+capture undo before publication. Trampolines require verified unused executable+header padding. Unsupported shapes and occupied space are refused. Failed+writes are restored and read back; failed restoration retains recovery records+and reports possible partial modification. Actual 23G90 point and cache-reuse+apply/repeat/undo checks each restore all 85 files exactly; repeats change+neither bytes nor undo records. Points change four instructions and one page+hash; reuse changes one branch, an eight-byte cave and two page hashes.++Selection preflight rejects compiler identity plus cross-boot reuse without+key validation, exiting 64 before disk attachment or mutation. Installation+also verifies that key validation actually applied before any plugin refresh,+requires a private APFS clone of `Disk.img`, and discards it if identity patching+fails. Host tests cover the applied-key dependency and failure handling;+clone-discard paths were not exercised through injected VM failures.++Retained tests cover malformed discovery, exact identity writes, same/different+plugin replay, rollback and selection/dependency guards. Generated ARM64 executes+192 restart draw/state combinations; cache tests validate the production+trampoline and semantic discovery in a `verify_list_file` fixture. AIR tests+cover ES1 metadata and GLES-only point-coordinate adaptation, preserving unrelated+inputs and rejecting malformed ones. Development builds were tested on iOS+26.6.2 (23G90)/cloudOS 26.4 (23E5207q), macOS 26.6.2 (25G83, Apple M5 Max).+See [GPU research](Guest/gpu_acceleration.md#native-gles-semantics) for the+failure controls, historical installed-VM results, replay procedure and limits.diff --git a/Research/Guest/gpu_acceleration.md b/Research/Guest/gpu_acceleration.mdindex a68f9763..15f3c2a0 100644--- a/Research/Guest/gpu_acceleration.md+++ b/Research/Guest/gpu_acceleration.md@@ -419,6 +419,14 @@ Why the guest compiles at all, and why it starts over at each boot:changes (19,148 bytes, foreign header kept) and backboardd compiles 2functions in the guest instead of 92.+ **2026-11-03 correction:** on the measured iOS 26.6.2 base the same env=1+ branch also skips the 32-byte compiler cache key, not just the 64-byte+ boot/system stamp. Therefore a compiler update can retain stale shader+ output even after its key changes. The native GLES cache repair keeps the+ key comparison on the reuse path and derives the driver's key from the+ installed plugin; see [Native GLES semantics](#native-gles-semantics).+ The measurements above establish cross-boot reuse but did not test compiler-version changes.+Effect on the first go-home, five Settings rounds after a backboardd relaunchwith a foreign UUID in its cache (a stand-in for a boot):@@ -1113,6 +1121,116 @@ No `MTLCompilerService` crash and no GPU restart in any of these.`Research/0_binary_patch_comparison.md` ("OpenGL ES in guests (2026-11-02)") hasthe bytes and what is not covered.+### Native GLES semantics++Further testing on iOS 26.6.2 (23G90), cloudOS 26.4 (23E5207q) and macOS+26.6.2 (25G83, Apple M5 Max) found failures after contexts and basic draws+worked. The following results come from development builds on that OS pair.+Six declarations cover these repairs; their semantic discovery, version gates+and rollback rules are in the [patch comparison](../0_binary_patch_comparison.md#native-gles-follow-up-2026-11-02).++**Drawable orientation.** The renderer normally uses a private IOSurface+attachment `yInvert` flag. A 16-case host/guest control showed it reversing+host rows but having no effect through PV. Selecting the renderer's existing+`AGX_GL_VIEWPORT_INVERT_CONFIG=UPPER_LEFT` path corrects viewport/scissor+orientation. SystemHook sets it only while `/usr/lib/vphone-gles-upper-left`+exists and preserves explicit environment values. This locates a behavioral+gap without identifying the exact missing transport field.++**Vertex and instance IDs.** Captured vertex-ID AIR compiles on host Metal+without a descriptor or with public UInt (36), but private format 43 aborts+in `CloneAttributeDescriptor`; the guest's ID buffer contains the expected+uint values, including 0, 1, 2. Only the serialized formats 43/44 become UInt,+after guest shader variant generation, preserving original descriptors and+AIR. Separately, ES1's generated fragments use `OpenGL ES Program`;+`GLESAIR.mm` accepts it alongside `OpenGL ES GLSL` and completes missing buffer+address space, size and alignment independently, preserving producer values.+Partial buffer metadata was not demonstrated to cause the descriptor crash.++**Restart-disabled strips.** Suppressing the unsupported restart command+leaves Metal discarding the maximum index even when GLES restart is disabled.+The repair selects GLEngine's existing primitive expansion for disabled+indexed line/triangle strips: vertices are packed into a nonindexed draw,+retaining vertex/instance IDs. Every affected strip incurs CPU copying, even+when its indices contain no maximum value. Seven baseline cases, seven+builtin controls and a 36-case line/triangle matrix passed in the guest;+UInt8/UInt16 exercise maximum indices, UInt32 uses 65535 as a high-index control.++**Points.** PV inherits a zero-returning+`pipelineFlagsWithVertexVariant:fragmentVariant:` implementation. Four guards+on the resulting point-size usage bit suppress valid `GL_POINTS` draws.+Removing only those guards restores 12 size cases and three triangle controls+(15/21), but six coordinate gradients remain inverted. Host/guest replay+shows that `pointCoordYFlipEnabled` changes host pixels and has no effect+through the measured PV path, independently of drawable orientation.+The compiler therefore lowers only GLES fragment `air.point_coord.y` to+`1-y` for `float2` and `half2`, preserving X. A named metadata marker makes+this idempotent; malformed indices/types are rejected without mutation,+and ordinary varyings and non-GLES modules are unchanged. Retained+[AIR tests](../../VPhoneGuestComponents/Tests/GLESAIRTests.mm) record fixture+origins and the coordinate oracle. Revisit this compensation if PV begins+honoring the native flag, to avoid double inversion.++**Stale compiler output.** A fresh process cache passed 21/21 point cases+while the old default cache remained at 15/21 after the compiler change.+The driver hashes fixed date/time literals into its function-cache identity;+Metal's library cache has a separate identity. Deriving the driver's seed+from the installed plugin is necessary but insufficient: on this base,+`FS_CACHE_REUSE_ON_REBOOT=1` skips both the 32-byte key comparison and the+64-byte boot/system-stamp comparison. The repair retains key validation while+skipping only the boot check. After restoring the old default cache, updating+and rebooting, the first run and a warm repeat both pass 21/21 without a+cache-path override, cache deletion or rendering hook. The installed driver's+seed was checked against the installed plugin's content-derived identity.++### Verifying the GLES repairs++Historical development validation passed 22 standalone guest processes: 20+correctness checks covering original ID shaders, texture effects, shared+contexts, BGRA/NV12 imports and conversion/fences, a three-slot queue, VBO+controls, restart and points; two timing checks measured submission/completion+and restart copying. Timing observations do not establish application performance.+An ordinary app separately passed ES1/2/3 and Metal, with each surface submitting+30 frames. A nine-position native-resolution screenshot comparison had maximum+sampled RGB difference 1.465452/255 (tolerance 8). These are sampled screen checks.++For independent guest validation, exercise nonzero first/indexed vertex IDs,+instance IDs, restart-enabled/disabled strips with maximum indices, and ES1/2/3+point sizes and coordinate gradients through native GLES. Record pixel results,+process exit status/signal and a native-resolution app screenshot. Change one+selection at a time with `fw set-patches`, run `cfw update-environment`, fully+reboot and check applied/pending receipts before rerunning identical inputs.+Re-upload temporary binaries after each reboot. Point on/off/on measured+21 → 3 → 21: the disabled run had zero GL errors and only triangles passed.+Orientation and restart opt-outs reproduced their failures and recovered when+re-enabled. Restore `standard` after these controls. Separately restore an old+default cache before a compiler update, then verify both first-use and warm+results without overriding the cache path.++Run retained host regressions from the repository root with Xcode and an Apple+GPU. AIR checks cover completion, point pixels, scope and idempotence; patcher+checks cover discovery rejection, exact mutations, dependencies and rollback:++```zsh+make -C VPhoneGuestComponents test-gles-air+xcodebuild -workspace VPhone.xcworkspace -scheme FirmwarePatcherTests \+ -configuration Debug -destination 'platform=macOS,arch=arm64' \+ -derivedDataPath /tmp/vphone-native-patcher-tests \+ -only-testing:FirmwarePatcherTests/DyldSharedCacheMetalVertexFormatTests \+ -only-testing:FirmwarePatcherTests/DyldSharedCacheGLESPrimitiveRestartTests \+ -only-testing:FirmwarePatcherTests/DyldSharedCacheGLESPointDrawTests \+ -only-testing:FirmwarePatcherTests/DyldSharedCacheMetalCacheReuseTests \+ -only-testing:FirmwarePatcherTests/CustomFirmwareParavirtGPUCompilerCacheTests \+ -only-testing:FirmwarePatcherTests/MachOSymbolTargetsTests \+ -only-testing:FirmwarePatcherTests/FirmwarePatchSetCatalogTests \+ -only-testing:FirmwarePatcherTests/FirmwareGuestPatchResolutionTests test+```++Host tests do not establish installed-VM rendering. The guest checks do not+establish full GLES conformance, ES1 lighting/fog, every framebuffer combination,+arbitrary app compatibility, physical-camera behavior or performance. Validate+other OS pairs before widening the gates.+## Settings That Do Nothing HereBoth are private properties of `VZMacGraphicsDeviceConfiguration`, tried ondiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOSymbolTargets.swiftsimilarity index 71%rename from VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swiftrename to VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOSymbolTargets.swiftindex f16bd8b2..d71bd7ba 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogSymbolTargets.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Binary/MachOSymbolTargets.swift@@ -1,4 +1,4 @@-// CustomFirmwareWatchDogSymbolTargets.swift — Resolve watchdogd branch targets.+// MachOSymbolTargets.swift — Resolve Mach-O branch targets.import Foundationimport VPhonePatchKit@@ -15,12 +15,10 @@ import VPhonePatchKit/// `bl _sysctlbyname` takes;/// * directly to a defined symbol, for a statically linked build.///-/// This is deliberately not in `MachOParser`: it needs each section's `flags`,-/// `reserved1` and `reserved2` and the `LC_DYSYMTAB` indirect table, none of-/// which that shared parser exposes. It carries this patcher's name because-/// this patcher is its only caller — the first time a second one needs the same-/// lookup, move it to `Binary/` under a neutral name rather than growing a copy.-struct CustomFirmwareWatchDogSymbolTargets {+/// This needs each section's `reserved1` and `reserved2` and the+/// `LC_DYSYMTAB` indirect table, which `MachOParser` does not expose. Shared by+/// the watchdog and paravirtual GPU compiler-cache patchers.+struct MachOSymbolTargets {/// A section of branch-island stubs, one per imported symbol.struct StubSection {let address: UInt64@@ -61,27 +59,35 @@ struct CustomFirmwareWatchDogSymbolTargets {var stubs: [StubSection] = []let commandCount = data.loadLE(UInt32.self, at: 16)+ let commandBytes = Int(data.loadLE(UInt32.self, at: 20))+ guard commandBytes <= data.count - 32 else { return nil }+ let commandsEnd = 32 + commandBytesvar offset = 32for _ in 0 ..< commandCount {- guard offset + 8 <= data.count else { return nil }+ guard offset + 8 <= commandsEnd else { return nil }let command = data.loadLE(UInt32.self, at: offset)let commandSize = Int(data.loadLE(UInt32.self, at: offset + 4))- guard commandSize > 0 else { return nil }+ guard commandSize >= 8, commandSize % 8 == 0, commandSize <= commandsEnd - offset else { return nil }- if command == Self.lcDysymtab, offset + 64 <= data.count {+ if command == Self.lcDysymtab {+ guard commandSize >= 80 else { return nil }indirectOffset = Int(data.loadLE(UInt32.self, at: offset + 56))indirectCount = Int(data.loadLE(UInt32.self, at: offset + 60))- } else if command == Self.lcSegment64, offset + 72 <= data.count {- let sectionCount = data.loadLE(UInt32.self, at: offset + 64)+ } else if command == Self.lcSegment64 {+ guard commandSize >= 72 else { return nil }+ let sectionCount = Int(data.loadLE(UInt32.self, at: offset + 64))+ guard sectionCount <= (commandSize - 72) / 80 else { return nil }var section = offset + 72for _ in 0 ..< sectionCount {- guard section + 80 <= data.count else { break }let flags = data.loadLE(UInt32.self, at: section + 64)let entrySize = UInt64(data.loadLE(UInt32.self, at: section + 72)) // reserved2- if flags & 0xFF == Self.sectionTypeSymbolStubs, entrySize > 0 {+ if flags & 0xFF == Self.sectionTypeSymbolStubs {+ let address = data.loadLE(UInt64.self, at: section + 32)+ let size = data.loadLE(UInt64.self, at: section + 40)+ guard entrySize > 0, size % entrySize == 0, address <= UInt64.max - size else { return nil }stubs.append(StubSection(- address: data.loadLE(UInt64.self, at: section + 32),- size: data.loadLE(UInt64.self, at: section + 40),+ address: address,+ size: size,entrySize: entrySize,firstIndirectIndex: Int(data.loadLE(UInt32.self, at: section + 68)), // reserved1))@@ -91,6 +97,12 @@ struct CustomFirmwareWatchDogSymbolTargets {}offset += commandSize}+ guard offset == commandsEnd,+ symtab.symoff <= data.count, symtab.nsyms <= (data.count - symtab.symoff) / 16,+ symtab.stroff <= data.count, symtab.strsize <= data.count - symtab.stroff,+ indirectOffset <= data.count, indirectCount <= (data.count - indirectOffset) / 4,+ stubs.allSatisfy({ $0.firstIndirectIndex <= indirectCount && $0.size / $0.entrySize <= UInt64(indirectCount - $0.firstIndirectIndex) })+ else { return nil }self.data = datasymbolOffset = symtab.symoff@@ -111,7 +123,8 @@ struct CustomFirmwareWatchDogSymbolTargets {func importName(atStub address: UInt64) -> String? {guard indirectCount > 0 else { return nil }for section in stubSections {- guard address >= section.address, address < section.address &+ section.size else { continue }+ guard address >= section.address, address < section.address + section.size else { continue }+ guard (address - section.address) % section.entrySize == 0 else { return nil }let index = section.firstIndirectIndex + Int((address - section.address) / section.entrySize)guard index >= 0, index < indirectCount else { return nil }let entryOffset = indirectOffset + index * 4@@ -130,6 +143,8 @@ struct CustomFirmwareWatchDogSymbolTargets {let entry = symbolOffset + index * 16guard entry + 16 <= data.count else { return nil }guard data[entry + 4] & Self.symbolIsDebug == 0 else { continue }+ let type = data[entry + 4] & 0x0E // N_TYPE: N_SECT or N_ABS, never an undefined import.+ guard type == 0x0E || type == 0x02 else { continue }guard data.loadLE(UInt64.self, at: entry + 8) == address else { continue }return symbolName(at: index)}@@ -149,6 +164,7 @@ struct CustomFirmwareWatchDogSymbolTargets {while end < limit, data[end] != 0 {end += 1}+ guard end < limit else { return nil }return String(data: data.subdata(in: start ..< end), encoding: .utf8)}}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUCompilerCache.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUCompilerCache.swiftnew file mode 100644index 00000000..16bc0d79--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUCompilerCache.swift@@ -0,0 +1,332 @@+// The paravirtual driver hashes its build date/time into Metal's cacheUUID.+// Replacing our compiler plugin does not change that identity, so persistent+// caches can return metallibs made by an older compiler. Change only the two+// eight-byte inputs of setupCompiler's SHA-256 calculation, using the plugin's+// content digest. Metal then handles invalidation through its existing key.+//+// Discovery follows setupCompiler's relative Objective-C method metadata and+// the imported CC_SHA256_Init/Update/Final calls. Both Update calls must read+// eight bytes of __cstring, exclusively referenced at those call sites, and+// Final's stack output must become the MTLCompiler initializer's cacheUUID.+// No addresses, build stamps or replacement instructions are embedded here.++import CryptoKit+import Foundation+import VPhonePatchKit++public enum CustomFirmwareParavirtGPUCompilerCache {+ public static let stdoutLog: @Sendable (String) -> Void = { print($0) }+ static let selector = "setupCompiler"+ static let compilerSelector = "initWithTargetData:cacheUUID:pluginPath:device:compilerFlags:"++ public enum State: Sendable, Equatable { case patched, alreadyPatched }++ public struct Site: Sendable, Equatable {+ public let fileOffset: Int+ public let before: Data+ public let after: Data+ }++ public struct Report: Sendable, Equatable {+ public let sites: [Site]+ public let state: State+ public let identity: String+ }++ /// Sixteen printable bytes retain 96 digest bits, rather than the 64 bits+ /// hexadecimal would fit. There are no embedded NULs or altered terminators.+ /// At a million distinct plugin builds, birthday collision probability is+ /// approximately 6.3e-18. This is cache separation, not authentication.+ static func identity(for plugin: Data) throws -> String {+ guard !plugin.isEmpty else { throw failure("compiler plugin is empty") }+ return Data(SHA256.hash(data: plugin).prefix(12)).base64EncodedString()+ }++ @discardableResult+ public static func patch(+ fileAt url: URL, compilerPluginAt pluginURL: URL,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ var data = try Data(contentsOfFileToRewrite: url)+ let report = try patch(&data, compilerPlugin: Data(contentsOf: pluginURL), log: log)+ if report.state == .patched { try data.write(to: url) }+ return report+ }++ /// All discovery and verification completes before the caller's data changes.+ @discardableResult+ public static func patch(+ _ data: inout Data, compilerPlugin: Data,+ log: ((String) -> Void)? = stdoutLog,+ ) throws -> Report {+ let original = Data(data)+ let identity = try identity(for: compilerPlugin)+ let seed = Data(identity.utf8)+ let offsets = try resolve(in: original)+ let sites = offsets.enumerated().map { index, offset in+ Site(fileOffset: offset, before: original.subdata(in: offset ..< offset + 8),+ after: seed.subdata(in: index * 8 ..< index * 8 + 8))+ }+ let changed = sites.contains { $0.before != $0.after }+ if changed {+ var patched = original+ for site in sites {+ patched.replaceSubrange(site.fileOffset ..< site.fileOffset + 8, with: site.after)+ }+ guard try resolve(in: patched) == offsets,+ sites.allSatisfy({ patched.subdata(in: $0.fileOffset ..< $0.fileOffset + 8) == $0.after })+ else { throw failure("cache seed readback failed") }+ data = patched+ }+ for site in sites {+ let before = site.before.map { String(format: "%02x", $0) }.joined()+ let after = site.after.map { String(format: "%02x", $0) }.joined()+ log?(" [\(changed ? "+" : "·")] 0x\(String(site.fileOffset, radix: 16)): compiler cache seed \(before) -> \(after)")+ }+ return Report(sites: sites, state: changed ? .patched : .alreadyPatched, identity: identity)+ }++ /// The two hash-input file offsets, in SHA-256 update order.+ public static func resolve(in data: Data) throws -> [Int] {+ let data = Data(data)+ let sections = MachOParser.parseSections(from: data)+ guard let text = sections["__TEXT,__text"], let strings = sections["__TEXT,__cstring"],+ let methods = sections["__TEXT,__objc_methlist"],+ let symbols = MachOSymbolTargets(data: data)+ else { throw failure("missing code, strings, method lists or symbol imports") }+ for section in [text, strings, methods] { try check(section, in: data) }+ let slots = try selectorSlots(selector, in: data, sections: sections)+ let imps = methodImplementations(naming: slots, in: data, section: methods)+ guard imps.count == 1, let start = imps.first,+ start >= text.address, start < text.address + text.size, start % 4 == 0+ else { throw failure("setupCompiler has no unique in-text implementation") }+ let decoder = ARM64Disassembler()+ let all = decoder.disassemble(data.subdata(in: Int(text.fileOffset) ..< Int(text.fileOffset) + Int(text.size)), at: text.address)+ guard let first = all.firstIndex(where: { $0.address == start }),+ let last = all[first...].firstIndex(where: { $0.isReturn }), last - first < 256+ else { throw failure("setupCompiler has no bounded return") }+ let body = Array(all[first ... last])+ guard body.allSatisfy({ $0.isDecoded && $0.size == 4 }),+ ["pacibsp", "paciasp"].contains(body[0].mnemonic),+ !body.dropFirst().contains(where: { ["pacibsp", "paciasp"].contains($0.mnemonic) })+ else { throw failure("setupCompiler crosses an undecoded instruction or another function") }+ let calls = body.enumerated().compactMap { index, instruction -> (Int, String)? in+ guard instruction.mnemonic == "bl", let target = immediate(instruction),+ let name = symbols.name(forBranchTarget: target), name.hasPrefix("_CC_SHA256_")+ else { return nil }+ return (index, name)+ }+ guard calls.map(\.1) == ["_CC_SHA256_Init", "_CC_SHA256_Update", "_CC_SHA256_Update", "_CC_SHA256_Final"]+ else { throw failure("setupCompiler must contain one Init, two Updates and one Final") }+ let initIndex = calls[0].0+ guard initIndex > 0, let context = stackAddress(body[initIndex - 1], destination: .x(0)), context.base == .sp+ else { throw failure("SHA-256 context is not a local stack buffer") }+ // The digest is one straight-line calculation. A branch or an extra+ // call could bypass an update or change the stack buffer between calls.+ let hashBody = body[(initIndex + 1) ..< calls[3].0]+ let hashCalls = Set(calls[1 ... 2].map { body[$0.0].address })+ guard hashBody.allSatisfy({ !$0.isJump && (!$0.isCall || hashCalls.contains($0.address)) && !writes($0, register: .sp) && !writes($0, register: .x(29)) })+ else { throw failure("SHA-256 calculation has unexpected control flow or stack changes") }+ var offsets: [Int] = []+ var references: [UInt64] = []+ for (index, _) in calls[1 ... 2] {+ guard index >= 4,+ let pointer = addressPair(body[index - 4], body[index - 3], destination: .x(1)),+ stackAddress(body[index - 2], destination: .x(0)) == context,+ moves(body[index - 1], register: .w(2), immediate: 8),+ pointer >= strings.address, pointer + 8 < strings.address + strings.size+ else { throw failure("SHA-256 Update must consume a distinct eight-byte string range") }+ let offset = Int(strings.fileOffset) + Int(pointer - strings.address)+ // Each input starts a complete string, and leaves its terminator+ // untouched. Date has eleven characters; time has eight.+ guard offset == Int(strings.fileOffset) || data[offset - 1] == 0,+ data[offset ..< offset + 8].allSatisfy({ $0 >= 0x20 && $0 <= 0x7e }),+ data[offset + 8 ..< min(offset + 16, Int(strings.fileOffset) + Int(strings.size))].contains(0)+ else { throw failure("hash input is not an eight-byte printable string prefix") }+ offsets.append(offset)+ references.append(body[index - 3].address)+ }+ guard abs(offsets[0] - offsets[1]) >= 8 else { throw failure("hash input ranges overlap") }+ let final = calls[3].0+ guard final >= 2,+ let output = stackAddress(body[final - 2], destination: .x(0)), output.base == .x(29),+ stackAddress(body[final - 1], destination: .x(1)) == context+ else { throw failure("SHA-256 Final does not write the expected local output") }+ let initializerSlots = try selectorSlots(compilerSelector, in: data, sections: sections)+ var initializers = 0+ for index in final + 1 ..< body.count where stackAddress(body[index], destination: .x(3)) == output {+ // cacheUUID is x3. All instructions through the initializer must+ // preserve it; no intervening call can invalidate the argument.+ for next in index + 1 ..< min(index + 8, body.count) {+ let instruction = body[next]+ if instruction.isCall {+ if instruction.mnemonic == "bl", let target = immediate(instruction),+ let stub = sections["__TEXT,__objc_stubs"], target >= stub.address,+ target + 8 <= stub.address + stub.size {+ try check(stub, in: data)+ let offset = Int(stub.fileOffset) + Int(target - stub.address)+ let insns = decoder.disassemble(data.subdata(in: offset ..< offset + 8), at: target)+ if insns.count == 2, let slot = loadPair(insns[0], insns[1]), initializerSlots.contains(slot) {+ initializers += 1+ }+ }+ break+ }+ if instruction.isJump || instruction.isReturn || writes(instruction, register: .x(3)) { break }+ }+ }+ guard initializers == 1 else { throw failure("SHA-256 output does not uniquely reach MTLCompiler cacheUUID") }+ // Refuse shared literals: updating a build stamp must affect only the+ // cache key. Scan decoded ADR/ADRP+ADD references across all driver code.+ for (offset, expected) in zip(offsets, references) {+ let address = strings.address + UInt64(offset - Int(strings.fileOffset))+ var users: [UInt64] = []+ for index in all.indices {+ let instruction = all[index]+ if ["adr", "ldr"].contains(instruction.mnemonic), let target = immediate(instruction), (address ..< address + 8).contains(target) {+ users.append(instruction.address)+ }+ // A scheduled instruction between ADRP and its use must not+ // hide a second reference to the seed. Track the page register+ // until a call, branch, return or overwrite ends its lifetime.+ if instruction.mnemonic == "adrp", let ops = instruction.detail?.operands,+ ops.count == 2, ops[0].type == .register, let page = immediate(instruction) {+ for use in all[(index + 1)...] {+ if let target = addressPair(instruction, use), (address ..< address + 8).contains(target) {+ users.append(use.address)+ }+ for operand in use.detail?.operands ?? [] where operand.type == .memory && operand.mem.base == ops[0].reg && operand.mem.index == .invalid {+ let (target, overflow) = Int64(page).addingReportingOverflow(Int64(operand.mem.disp))+ if !overflow, target >= 0, (address ..< address + 8).contains(UInt64(target)) { users.append(use.address) }+ }+ if use.isCall || use.isJump || use.isReturn || writes(use, register: ops[0].reg) { break }+ }+ }+ }+ guard users == [expected] else { throw failure("compiler cache seed is referenced outside its SHA-256 Update") }+ }+ return offsets+ }++ // MARK: - Semantic decoding++ struct StackAddress: Equatable { let base: ARM64Register; let displacement: Int64 }++ static func writes(_ instruction: ARM64Instruction, register: ARM64Register) -> Bool {+ let aliases: Set<ARM64Register>+ if let index = (0 ..< 31).first(where: { register == .x($0) || register == .w($0) }) {+ aliases = [.x(index), .w(index)]+ } else {+ aliases = [register]+ }+ return instruction.detail?.operands.contains(where: {+ ($0.writesRegister && aliases.contains($0.reg)) ||+ ($0.type == .memory && instruction.detail?.writeback == true && aliases.contains($0.mem.base))+ }) == true+ }++ static func stackAddress(_ instruction: ARM64Instruction, destination: ARM64Register) -> StackAddress? {+ guard ["add", "sub"].contains(instruction.mnemonic), let ops = instruction.detail?.operands, ops.count == 3,+ ops[0].type == .register, ops[0].reg == destination,+ ops[1].type == .register, [.sp, .x(29)].contains(ops[1].reg),+ ops[2].type == .immediate, ops[2].shift.amount == 0+ else { return nil }+ return StackAddress(base: ops[1].reg, displacement: instruction.mnemonic == "sub" ? -ops[2].imm : ops[2].imm)+ }++ static func immediate(_ instruction: ARM64Instruction) -> UInt64? {+ instruction.detail?.operands.last.flatMap { $0.type == .immediate && $0.imm >= 0 ? UInt64($0.imm) : nil }+ }++ static func moves(_ instruction: ARM64Instruction, register: ARM64Register, immediate: Int64) -> Bool {+ guard ["mov", "movz"].contains(instruction.mnemonic), let ops = instruction.detail?.operands, ops.count == 2 else { return false }+ return ops[0].type == .register && ops[0].reg == register && ops[1].type == .immediate && ops[1].imm == immediate && ops[1].shift.amount == 0+ }++ static func addressPair(_ page: ARM64Instruction, _ add: ARM64Instruction, destination: ARM64Register? = nil) -> UInt64? {+ guard page.mnemonic == "adrp", add.mnemonic == "add",+ let p = page.detail?.operands, p.count == 2, let a = add.detail?.operands, a.count == 3,+ p[0].type == .register, p[1].type == .immediate, p[1].imm >= 0,+ a[0].type == .register, a[1].type == .register, a[2].type == .immediate, a[2].imm >= 0,+ a[1].reg == p[0].reg, destination == nil || a[0].reg == destination,+ a[2].shift.amount == 0+ else { return nil }+ return UInt64(p[1].imm) + UInt64(a[2].imm)+ }++ static func loadPair(_ page: ARM64Instruction, _ load: ARM64Instruction) -> UInt64? {+ guard page.mnemonic == "adrp", load.mnemonic == "ldr",+ let p = page.detail?.operands, p.count == 2, let l = load.detail?.operands, l.count == 2,+ p[0].type == .register, p[0].reg == .x(1), p[1].type == .immediate, p[1].imm >= 0,+ l[0].type == .register, l[0].reg == .x(1), l[1].type == .memory,+ l[1].mem.base == .x(1), l[1].mem.index == .invalid, l[1].mem.disp >= 0+ else { return nil }+ return UInt64(p[1].imm) + UInt64(l[1].mem.disp)+ }++ // MARK: - Objective-C metadata++ static func selectorSlots(_ selector: String, in data: Data, sections: [String: MachOSectionInfo]) throws -> Set<UInt64> {+ let referenceSections = sections.values.filter { $0.sectionName == "__objc_selrefs" }+ guard let names = sections["__TEXT,__objc_methname"], referenceSections.count == 1,+ let refs = referenceSections.first, refs.size % 8 == 0+ else { throw failure("missing Objective-C selector metadata") }+ try check(names, in: data)+ try check(refs, in: data)+ let needle = Data(selector.utf8) + [0]+ let range = Int(names.fileOffset) ..< Int(names.fileOffset) + Int(names.size)+ var cursor = range.lowerBound+ var addresses: Set<UInt64> = []+ while cursor < range.upperBound, let found = data.range(of: needle, in: cursor ..< range.upperBound) {+ if found.lowerBound == range.lowerBound || data[found.lowerBound - 1] == 0 {+ addresses.insert(names.address + UInt64(found.lowerBound - range.lowerBound))+ }+ cursor = found.upperBound+ }+ guard addresses.count == 1, let address = addresses.first else { throw failure("selector \(selector) is absent or ambiguous") }+ let base = MachOParser.parseSegments(from: data).first(where: { $0.name == "__TEXT" })?.vmAddr ?? 0+ var slots: Set<UInt64> = []+ for offset in stride(from: 0, to: Int(refs.size) - 7, by: 8) {+ let value = data.loadLE(UInt64.self, at: Int(refs.fileOffset) + offset)+ let target = value & ((1 << 36) - 1)+ if value == address || target == address || (base <= UInt64.max - target && target + base == address) {+ slots.insert(refs.address + UInt64(offset))+ }+ }+ guard !slots.isEmpty else { throw failure("selector \(selector) has no reference") }+ return slots+ }++ static func methodImplementations(naming slots: Set<UInt64>, in data: Data, section: MachOSectionInfo) -> Set<UInt64> {+ var result: Set<UInt64> = []+ var cursor = 0+ while cursor + 8 <= Int(section.size) {+ let file = Int(section.fileOffset) + cursor+ let flags = data.loadLE(UInt32.self, at: file)+ let count = Int(data.loadLE(UInt32.self, at: file + 4))+ guard flags & 0x8000_0000 != 0, flags & 0x7fff_fffc == 12,+ count <= (Int(section.size) - cursor - 8) / 12 else { return [] }+ for index in 0 ..< count {+ let entry = cursor + 8 + index * 12+ let (name, nameOverflow) = Int64(section.address + UInt64(entry)).addingReportingOverflow(Int64(data.loadLE(Int32.self, at: Int(section.fileOffset) + entry)))+ if !nameOverflow, name >= 0, slots.contains(UInt64(name)) {+ let (imp, impOverflow) = Int64(section.address + UInt64(entry + 8)).addingReportingOverflow(Int64(data.loadLE(Int32.self, at: Int(section.fileOffset) + entry + 8)))+ if !impOverflow, imp >= 0 { result.insert(UInt64(imp)) }+ }+ }+ cursor = (cursor + 8 + count * 12 + 7) & ~7+ }+ return result+ }++ static func check(_ section: MachOSectionInfo, in data: Data) throws {+ guard section.size > 0, section.size <= UInt64(data.count),+ UInt64(section.fileOffset) <= UInt64(data.count) - section.size,+ section.address <= UInt64(Int64.max) - section.size+ else { throw failure("invalid \(section.segmentName),\(section.sectionName) bounds") }+ }++ static func failure(_ message: String) -> PatcherError {+ .patchSiteNotFound("paravirtual GPU compiler cache: \(message)")+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swiftindex 2067afb3..ad39453f 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/ParavirtGPU/CustomFirmwareParavirtGPUPrimitiveRestart.swift@@ -20,9 +20,12 @@//// 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.+// primitive restart on, at the index type's largest value. This matches GLES3+// only while GL_PRIMITIVE_RESTART_FIXED_INDEX is enabled; GLES3 starts with+// it disabled, and GLES2 has no such enable. Disabled indexed strips using+// the maximum index therefore also need DyldSharedCacheGLESPrimitiveRestartPatcher,+// which selects GLEngine's nonindexed primitive-buffer path. That fallback+// still sets renderer state, so this command suppression remains required.//// 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 nearestdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swiftindex 967d9caf..fc03f44a 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/CustomFirmware/ExecutablePatches/WatchDog/CustomFirmwareWatchDogDiscovery.swift@@ -24,7 +24,7 @@ extension CustomFirmwareWatchDog {log?(" [.] cstring at va:0x\(hex(literal.address)) "+ "(foff:0x\(hex(UInt64(literal.fileOffset))), sect=\(literal.section))")- guard let symbols = CustomFirmwareWatchDogSymbolTargets(data: data) else {+ guard let symbols = MachOSymbolTargets(data: data) else {throw PatcherError.invalidFormat("no LC_SYMTAB/LC_DYSYMTAB — \(sysctlFunction) cannot be resolved",)@@ -105,7 +105,7 @@ extension CustomFirmwareWatchDog {literalVMA: UInt64,text: MachOSectionInfo,segments: [MachOSegmentInfo],- symbols: CustomFirmwareWatchDogSymbolTargets,+ symbols: MachOSymbolTargets,) -> Site? {// Layer 3: the call, and the import it resolves to.guard let callIndex = firstIndex(diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCachePatchTransaction.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCachePatchTransaction.swiftnew file mode 100644index 00000000..9b64e69e--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/DyldSharedCachePatchTransaction.swift@@ -0,0 +1,145 @@+// Small, verified transactions for multi-site shared-cache patches.+// Snapshot code and its CodeDirectory slots before any write; preserve+// pre-write recovery records when even rollback cannot complete.++import Foundation+import VPhonePatchKit++/// A failed write whose original bytes could not all be restored. The caller+/// must retain the recovery records even though the patch did not succeed.+public struct DyldSharedCachePatchRollbackError: LocalizedError {+ public let label: String+ public let operationError: String+ public let rollbackErrors: [String]+ public let recoveryUndo: DyldSharedCacheUndoLog++ public var errorDescription: String? {+ "\(label) failed: \(operationError). Rollback failed: "+ + rollbackErrors.joined(separator: "; ")+ + ". The cache may be partially modified; retain the undo log for recovery."+ }+}++enum DyldSharedCachePatchTransaction {+ static func headerPadding(in header: Data, at address: UInt64, minimumSize: Int, label: String) throws -> Range<UInt64> {+ guard minimumSize > 0, header.count >= 32, header.loadLE(UInt32.self, at: 0) == 0xFEED_FACF,+ Int(header.loadLE(UInt32.self, at: 20)) + 32 == header.count,+ let text = MachOParser.parseSegments(from: header).first(where: { $0.name == "__TEXT" }),+ text.vmAddr == address,+ let first = MachOParser.parseSections(from: header).values+ .filter({ $0.segmentName == "__TEXT" && $0.size > 0 }).map(\.address).min()+ else { throw PatcherError.invalidFormat("\(label) has no bounded __TEXT header padding") }+ // Header padding is never a string, unwind record or another section.+ // The actual DSC mapping must also permit instruction fetches.+ let start = (address + UInt64(header.count) + 3) & ~UInt64(3)+ guard first >= start, first - start >= minimumSize,+ first <= text.vmAddr + text.vmSize+ else { throw PatcherError.patchSiteNotFound("\(label) has insufficient __TEXT header padding") }+ return start ..< first+ }++ // MARK: - Transactional writes++ struct Snapshot {+ let url: URL+ let offset: Int+ let original: Data+ /// Hash slots have no executable VMA and do not belong in the normal+ /// undo log: a later user-requested revert recomputes shared-page hashes.+ let vma: UInt64?++ var label: String { "\(url.lastPathComponent)@0x\(String(offset, radix: 16))" }+ }++ static func snapshots(for spans: [DyldSharedCacheWriteSpan], in chunks: DyldSharedCacheChunkSet) throws -> [Snapshot] {+ var result: [Snapshot] = []+ var slots: Set<String> = []+ for span in spans {+ let (url, range) = try chunks.fileRange(of: span)+ result.append(try snapshot(url: url, offset: range.lowerBound, length: range.count, vma: span.vma))+ guard let directory = try DyldSharedCacheCodeSignature.readCodeDirectory(ofChunk: url) else {+ throw PatcherError.patchVerificationFailed("Shared-cache patch chunk has no supported code directory: \(url.lastPathComponent)")+ }+ let first = range.lowerBound / directory.pageSize+ let last = (range.upperBound - 1) / directory.pageSize+ for page in first ... last {+ guard page < directory.codeSlotCount,+ (page + 1) * directory.pageSize <= directory.codeLimit+ else { throw PatcherError.patchVerificationFailed("Shared-cache patch page is outside its code directory") }+ let offset = directory.slotOffset(forPage: page)+ guard offset >= directory.blobOffset,+ offset + directory.hashSize <= directory.blobOffset + directory.blobLength+ else { throw PatcherError.patchVerificationFailed("Shared-cache patch hash slot is outside its code directory") }+ if slots.insert("\(url.path)@\(offset)").inserted {+ result.append(try snapshot(url: url, offset: offset, length: directory.hashSize, vma: nil))+ }+ }+ }+ return result+ }++ static func snapshot(url: URL, offset: Int, length: Int, vma: UInt64?) throws -> Snapshot {+ let data = try DyldSharedCacheChunkSet.read(url: url, offset: UInt64(offset), length: length)+ guard data.count == length else {+ throw PatcherError.patchVerificationFailed("Short read while backing up a shared-cache patch")+ }+ return Snapshot(url: url, offset: offset, original: data, vma: vma)+ }++ static func restore(_ snapshot: Snapshot) throws {+ let handle = try FileHandle(forUpdating: snapshot.url)+ defer { try? handle.close() }+ try handle.seek(toOffset: UInt64(snapshot.offset))+ try handle.write(contentsOf: snapshot.original)+ }++ /// File-backed rollback, with a narrow restore injection for failure tests.+ /// Every range was captured before entering `operation`, so even a partial+ /// write which throws before being recorded can be restored. Attempt all+ /// restores and independently read every range back before claiming success.+ static func run<T>(+ snapshots: [Snapshot],+ label: String,+ log: ((String) -> Void)? = nil,+ restoring: ((Snapshot) throws -> Void)? = nil,+ operation: () throws -> T,+ ) throws -> T {+ do {+ return try operation()+ } catch {+ let operationError = error+ var failures: [String] = []+ // Restore the branch before its destination, then restore hashes.+ let ordered = snapshots.filter { $0.vma != nil }.reversed()+ + snapshots.filter { $0.vma == nil }.reversed()+ for item in ordered {+ do { try (restoring ?? restore)(item) }+ catch { failures.append("\(item.label): \(error.localizedDescription)") }+ }+ var verified = true+ for item in snapshots {+ do {+ let actual = try DyldSharedCacheChunkSet.read(url: item.url, offset: UInt64(item.offset), length: item.original.count)+ if actual != item.original {+ verified = false+ failures.append("\(item.label): original bytes did not read back")+ }+ } catch {+ verified = false+ failures.append("\(item.label): cannot verify rollback: \(error.localizedDescription)")+ }+ }+ if verified {+ log?(" [=] \(label) failure rolled back; original code and hash bytes verified")+ throw operationError+ }+ let undo = DyldSharedCacheUndoLog(records: snapshots.compactMap { item in+ guard let vma = item.vma else { return nil }+ return .init(patchID: "", chunk: item.url.lastPathComponent, fileOffset: item.offset, vma: vma, original: item.original)+ })+ throw DyldSharedCachePatchRollbackError(+ label: label, operationError: operationError.localizedDescription, rollbackErrors: failures, recoveryUndo: undo,+ )+ }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPointDrawPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPointDrawPatcher.swiftnew file mode 100644index 00000000..c787bb0a--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPointDrawPatcher.swift@@ -0,0 +1,384 @@+// The paravirtual Metal device reports no vertex usage flags even when the+// compiled AIR writes point_size. AppleMetalGLRenderer consequently skips+// GL_POINTS before issuing a Metal draw. GLES 2/3 point shaders must write+// gl_PointSize (otherwise its value is undefined); ES 1 supplies it itself.+// Remove only the four reflection-based suppressions, preserving the point+// mode, pipeline-null, raster and transform-feedback gates around them.+//+// Resolve the renderer's own symbols and recover its context fields from the+// actual setRenderPipelineState: argument/store dataflow. No firmware address+// or context layout is built in. The indexed IMP/selector fields are recovered+// from beginRenderPass's methodForSelector: call and the exact draw selector.+// Whole local-symbol spans matter: the direct+// callback has an early return before all three draw paths. All four sites+// must be original, or all four must already be NOP, before any write occurs.++import Foundation+import VPhonePatchKit++public struct DyldSharedCacheGLESPointDrawPatch: Sendable {+ public let functionVMA: UInt64+ public let siteVMAs: [UInt64]+ public let wasAlreadyPatched: Bool+ public let sitesWritten: Int+ public let reattestation: DyldSharedCacheReattestation?+}++public enum DyldSharedCacheGLESPointDrawPatcher {+ public static let imagePath = DyldSharedCacheGLESPrimitiveRestartPatcher.imagePath+ public static let symbolName = DyldSharedCacheGLESPrimitiveRestartPatcher.symbolName+ static let primitiveSymbol = "__ZL21gldEndPrimitiveBufferP13GLDContextRecjji"+ static let pipelineSymbol = "__ZN13GLDContextRec17setRenderPipelineEv"+ static let beginRenderPassSymbol = "__ZN13GLDContextRec15beginRenderPassEv"+ static let pipelineSelector = "_objc_msgSend$setRenderPipelineState:"+ static let methodForSelector = "_objc_msgSend$methodForSelector:"+ static let indexedDrawSelector = "drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:"+ static let drawSelectors = [+ "_objc_msgSend$drawPrimitives:vertexStart:vertexCount:",+ "_objc_msgSend$drawPrimitives:vertexStart:vertexCount:instanceCount:",+ ]+ static let label = "GLES point draw"++ struct Fields: Equatable {+ let pipeline: Int32+ let usage: Int32+ let encoder: Int32+ }++ struct IndexedDrawFields: Equatable {+ let selector: Int32+ let imp: Int32+ }++ struct Site {+ let address: UInt64+ let modeOffset: Int32+ let skip: UInt64+ let alreadyPatched: Bool+ }++ struct Plan {+ let sites: [Site]+ var alreadyPatched: Bool { sites.allSatisfy(\.alreadyPatched) }+ }++ @discardableResult+ public static func patch(+ chunksDirectory: URL,+ dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheGLESPointDrawPatch {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ do {+ let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)+ let result = try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)+ if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) }+ return result+ } catch {+ if captureUndo, let failure = error as? DyldSharedCachePatchRollbackError {+ onUndo?(failure.recoveryUndo)+ }+ throw error+ }+ }++ @discardableResult+ public static func patch(+ chunks: DyldSharedCacheChunkSet,+ resolver: DyldSharedCacheSymbolResolver,+ dryRun: Bool = false,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheGLESPointDrawPatch {+ try resolver.requireLocalSymbols()+ let symbols = try resolver.symbols(inImage: imagePath)+ let required = [symbolName, primitiveSymbol, pipelineSymbol, pipelineSelector, beginRenderPassSymbol, methodForSelector] + drawSelectors+ let addresses = try resolver.addresses(of: required, inImage: imagePath)+ let decoder = ARM64Disassembler()+ func code(_ name: String) throws -> [ARM64Instruction] {+ let start = addresses[name]!+ let span = try functionSpan(at: start, symbolAddresses: symbols.values.map(\.address))+ guard chunks.mappings.contains(where: {+ $0.initProt & 4 != 0 && $0.address <= span.lowerBound && $0.address + $0.size >= span.upperBound+ }) else { throw PatcherError.invalidFormat("\(label) function is not wholly executable") }+ let instructions = decoder.disassemble(try chunks.bytesAtVMA(start, length: Int(span.count)), at: start)+ guard instructions.count * 4 == span.count,+ instructions.enumerated().allSatisfy({ $0.element.isDecoded && $0.element.size == 4 && $0.element.address == start + UInt64($0.offset * 4) })+ else { throw PatcherError.patchSiteNotFound("\(label) function did not decode completely") }+ return instructions+ }+ let fields = try pipelineFields(in: code(pipelineSymbol), selector: addresses[pipelineSelector]!)+ let indexedDraw = try indexedDrawFields(in: code(beginRenderPassSymbol), fields: fields,+ methodForSelector: addresses[methodForSelector]!) {+ try chunks.bytesAtVMA($0, length: $1)+ }+ let plan = try plan(direct: code(symbolName), primitive: code(primitiveSymbol), fields: fields,+ indexedDraw: indexedDraw, drawTargets: Set(drawSelectors.map { addresses[$0]! }))+ log?(" [.] \(label) pipeline/usage context fields +0x\(String(fields.pipeline, radix: 16))/+0x\(String(fields.usage, radix: 16))")+ log?(" [.] \(label) indexed selector/IMP context fields +0x\(String(indexedDraw.selector, radix: 16))/+0x\(String(indexedDraw.imp, radix: 16))")+ for site in plan.sites {+ log?(" [\(plan.alreadyPatched ? "=" : dryRun ? "~" : "+")] \(label) @ 0x\(String(site.address, radix: 16)): \(site.alreadyPatched ? "NOP (already patched)" : "TBZ usage bit 7 -> NOP"); retained skip gate -> 0x\(String(site.skip, radix: 16))")+ }+ var reattestation: DyldSharedCacheReattestation?+ if !dryRun, !plan.alreadyPatched {+ let spans = plan.sites.map { DyldSharedCacheWriteSpan(vma: $0.address, length: 4) }+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ chunks.clearRecordedWrites()+ reattestation = try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: label, log: log) {+ for site in plan.sites { try chunks.write(at: site.address, ARM64.nop) }+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: log)+ guard result.isFullyAttested else { throw PatcherError.patchVerificationFailed("\(label) re-attestation skipped pages") }+ for site in plan.sites {+ guard try chunks.bytesAtVMA(site.address, length: 4) == ARM64.nop else {+ throw PatcherError.patchVerificationFailed("\(label) NOP did not read back")+ }+ }+ return result+ }+ }+ return .init(functionVMA: addresses[symbolName]!, siteVMAs: plan.sites.map(\.address),+ wasAlreadyPatched: plan.alreadyPatched, sitesWritten: dryRun || plan.alreadyPatched ? 0 : plan.sites.count,+ reattestation: reattestation)+ }++ // MARK: - Symbol bounds and pipeline argument dataflow++ static func functionSpan(at start: UInt64, symbolAddresses: [UInt64]) throws -> Range<UInt64> {+ guard start % 4 == 0, let end = symbolAddresses.filter({ $0 > start }).min(),+ end % 4 == 0, end - start <= 65536+ else { throw PatcherError.patchSiteNotFound("\(label) has no safe next-symbol function bound") }+ return start ..< end+ }++ static func pipelineFields(in code: [ARM64Instruction], selector: UInt64) throws -> Fields {+ var candidates: [Fields] = []+ for i in code.indices where i >= 5 && i + 1 < code.count && branch(code[i], mnemonic: "bl") == selector {+ // x2 is the pipeline supplied to objc_msgSend. The adjacent wrapper+ // word is copied to the context and reloaded as usage flags after+ // the call. Both fields and the encoder derive from this sequence.+ guard let pipeline = memory(code[i - 5], mnemonic: "ldr"), pipeline.register == .x(2), pipeline.offset == 0,+ let savedPipeline = memory(code[i - 4], mnemonic: "str"), savedPipeline.register == .x(2),+ let usage = memory(code[i - 3], mnemonic: "ldr"), usage.base == pipeline.base, usage.offset == 8,+ isX(usage.register),+ let savedUsage = memory(code[i - 2], mnemonic: "str"), savedUsage.register == usage.register,+ savedUsage.base == savedPipeline.base, savedUsage.offset == savedPipeline.offset + 8,+ let encoder = memory(code[i - 1], mnemonic: "ldr"), encoder.register == .x(0), encoder.base == savedPipeline.base,+ let reloadedUsage = memory(code[i + 1], mnemonic: "ldr"), reloadedUsage.base == savedPipeline.base,+ reloadedUsage.offset == savedUsage.offset, isX(reloadedUsage.register),+ savedPipeline.offset >= 0, encoder.offset >= 0,+ contextRegister(in: Array(code.prefix(i))) == savedPipeline.base+ else { continue }+ candidates.append(.init(pipeline: savedPipeline.offset, usage: savedUsage.offset, encoder: encoder.offset))+ }+ guard candidates.count == 1, let fields = candidates.first else {+ throw PatcherError.patchSiteNotFound("\(label) expected one verified pipeline/usage store chain, found \(candidates.count)")+ }+ return fields+ }++ static func indexedDrawFields(+ in code: [ARM64Instruction], fields: Fields, methodForSelector: UInt64,+ readBytes: (UInt64, Int) throws -> Data,+ ) throws -> IndexedDrawFields {+ guard let context = contextRegister(in: code) else {+ throw PatcherError.patchSiteNotFound("\(label) render-pass setup has no saved context")+ }+ let literal = Data((indexedDrawSelector + "\0").utf8)+ var candidates: [IndexedDrawFields] = []+ for i in code.indices where i >= 4 && i + 1 < code.count && branch(code[i], mnemonic: "bl") == methodForSelector {+ // methodForSelector: receives the encoder in x0 and the named+ // selector in x2; save that selector and the returned IMP into+ // the same context. Adjacent slots alone cannot identify a draw.+ guard let encoder = memory(code[i - 4], mnemonic: "ldr"), encoder.register == .x(0),+ encoder.base == context, encoder.offset == fields.encoder,+ let selectorAddress = materializedAddress(code[i - 3], code[i - 2], destination: .x(2)),+ let selector = memory(code[i - 1], mnemonic: "str"), selector.register == .x(2),+ selector.base == context, selector.offset >= 0,+ let imp = memory(code[i + 1], mnemonic: "str"), imp.register == .x(0),+ imp.base == context, imp.offset == selector.offset + 8,+ try readBytes(selectorAddress, literal.count) == literal+ else { continue }+ candidates.append(.init(selector: selector.offset, imp: imp.offset))+ }+ guard let fields = candidates.only else {+ throw PatcherError.patchSiteNotFound("\(label) expected one verified indexed draw selector/IMP store chain, found \(candidates.count)")+ }+ return fields+ }++ // MARK: - Four independently checked draw guards++ static func plan(direct: [ARM64Instruction], primitive: [ARM64Instruction], fields: Fields, indexedDraw: IndexedDrawFields, drawTargets: Set<UInt64>) throws -> Plan {+ let directSites = try sites(in: direct, fields: fields, indexedDraw: indexedDraw, drawTargets: drawTargets, primitive: false)+ let primitiveSites = try sites(in: primitive, fields: fields, indexedDraw: indexedDraw, drawTargets: drawTargets, primitive: true)+ guard directSites.count == 3, primitiveSites.count == 1 else {+ throw PatcherError.patchSiteNotFound("\(label) expected 3 direct and 1 primitive-buffer guards, found \(directSites.count) and \(primitiveSites.count)")+ }+ let sites = (directSites + primitiveSites).sorted { $0.address < $1.address }+ guard Set(sites.map(\.address)).count == 4, Set(sites.map(\.modeOffset)).count == 1 else {+ throw PatcherError.patchVerificationFailed("\(label) guards disagree on point-mode state")+ }+ let patchedCount = sites.filter(\.alreadyPatched).count+ guard patchedCount == 0 || patchedCount == sites.count else {+ throw PatcherError.patchVerificationFailed("\(label) refuses mixed original and patched guards")+ }+ return .init(sites: sites)+ }++ static func sites(in code: [ARM64Instruction], fields: Fields, indexedDraw: IndexedDrawFields, drawTargets: Set<UInt64>, primitive: Bool) throws -> [Site] {+ guard let context = contextRegister(in: code), let end = code.last.map({ $0.address + 4 }) else {+ throw PatcherError.patchSiteNotFound("\(label) draw callback has no saved context")+ }+ var result: [Site] = []+ for i in code.indices where i >= 4 && i + 1 < code.count {+ guard let mode = memory(code[i - 3], mnemonic: "ldrb"), mode.base == context, mode.offset >= 0,+ bitBranch(code[i - 2], mnemonic: "tbz", register: mode.register, bit: 0) == code[i].address + 4,+ let usage = memory(code[i - 1], mnemonic: "ldrb"), usage.base == context, usage.offset == fields.usage,+ isW(mode.register), isW(usage.register)+ else { continue }+ let skip: UInt64?+ if primitive {+ skip = bitBranch(code[i - 4], mnemonic: "tbnz", register: nil, bit: 0)+ // This callback folds the pipeline-null and raster gates into+ // the saved boolean consumed by that retained TBNZ.+ guard code[..<(i - 4)].enumerated().contains(where: { j, instruction in+ guard let load = memory(instruction, mnemonic: "ldr"), load.base == context,+ load.offset == fields.pipeline, isX(load.register), j + 1 < i - 4+ else { return false }+ return compareBranch(code[j + 1], mnemonic: "cbz", register: load.register) != nil+ }) else { continue }+ } else {+ // One indexed path loads its buffer between CBZ and point+ // mode. Search only that small, straight-line prefix.+ skip = (max(0, i - 7) ..< i - 3).compactMap { j -> UInt64? in+ guard let load = memory(code[j], mnemonic: "ldr"), load.base == context,+ load.offset == fields.pipeline, isX(load.register), j + 1 < i - 3,+ code[j + 2 ..< i - 3].allSatisfy({ !$0.isJump && !$0.isCall && !$0.isReturn })+ else { return nil }+ return compareBranch(code[j + 1], mnemonic: "cbz", register: load.register)+ }.only+ }+ guard let skip, skip > code[i].address + 4, skip < end,+ let skipIndex = code.firstIndex(where: { $0.address == skip }),+ containsDraw(Array(code[i + 1 ..< skipIndex]), context: context, fields: fields, indexedDraw: indexedDraw, drawTargets: drawTargets)+ else { continue }+ let patched = code[i].mnemonic == "nop" && Data(code[i].bytes) == ARM64.nop+ guard patched || bitBranch(code[i], mnemonic: "tbz", register: usage.register, bit: 7) == skip else { continue }+ result.append(.init(address: code[i].address, modeOffset: mode.offset, skip: skip, alreadyPatched: patched))+ }+ return result+ }++ static func containsDraw(_ code: [ARM64Instruction], context: ARM64Register, fields: Fields, indexedDraw: IndexedDrawFields, drawTargets: Set<UInt64>) -> Bool {+ // Follow in-function branches: the EBO path jumps over the arrays+ // block to its indexed IMP. Seeing an unrelated call in the skipped+ // address range is not proof that this guard controls a Metal draw.+ let indices = Dictionary(uniqueKeysWithValues: code.enumerated().map { ($0.element.address, $0.offset) })+ var pending = [(index: 0, encoderLoaded: false)]+ var visited = Set<Int>()+ while let state = pending.popLast() {+ let i = state.index+ guard code.indices.contains(i), visited.insert(i * 2 + (state.encoderLoaded ? 1 : 0)).inserted else { continue }+ let instruction = code[i]+ if state.encoderLoaded, let target = branch(instruction, mnemonic: "bl"), drawTargets.contains(target) { return true }+ // The indexed draw's authenticated IMP and selector must be the+ // exact fields populated by its verified methodForSelector: call.+ if state.encoderLoaded, i >= 3, instruction.mnemonic == "blraaz", let operand = instruction.detail?.operands.only,+ operand.type == .register,+ let imp = memory(code[i - 3], mnemonic: "ldr"), imp.register == operand.reg, imp.base == context,+ let selector = memory(code[i - 2], mnemonic: "ldr"), selector.register == .x(1), selector.base == context,+ imp.offset == indexedDraw.imp, selector.offset == indexedDraw.selector,+ move(code[i - 1], destination: .x(5)) != nil {+ return true+ }+ if instruction.isReturn { continue }+ var encoderLoaded = state.encoderLoaded+ if let load = memory(instruction, mnemonic: "ldr"), load.register == .x(0),+ load.base == context, load.offset == fields.encoder {+ encoderLoaded = true+ } else if instruction.isCall || instruction.detail?.operands.contains(where: {+ $0.type == .register && $0.writesRegister && ($0.reg == .x(0) || $0.reg == .w(0))+ }) == true {+ encoderLoaded = false+ }+ if instruction.isJump, !instruction.isCall {+ guard let target = instruction.detail?.operands.last, target.type == .immediate else { continue }+ if let index = indices[UInt64(bitPattern: target.imm)] { pending.append((index, encoderLoaded)) }+ if instruction.mnemonic == "b" { continue }+ }+ pending.append((i + 1, encoderLoaded))+ }+ return false+ }++ // MARK: - Typed operand helpers++ static func materializedAddress(_ page: ARM64Instruction, _ add: ARM64Instruction, destination: ARM64Register) -> UInt64? {+ guard page.address + 4 == add.address, page.mnemonic == "adrp", add.mnemonic == "add",+ let p = page.detail?.operands, p.count == 2,+ p[0].type == .register, isX(p[0].reg), p[1].type == .immediate, p[1].imm > 0,+ let a = add.detail?.operands, a.count == 3,+ a[0].type == .register, a[0].reg == destination,+ a[1].type == .register, a[1].reg == p[0].reg,+ a[2].type == .immediate, a[2].imm >= 0, a[2].imm < 4096, a[2].shift.amount == 0+ else { return nil }+ return UInt64(p[1].imm) + UInt64(a[2].imm)+ }++ struct Memory {+ let register: ARM64Register+ let base: ARM64Register+ let offset: Int32+ }++ static func memory(_ instruction: ARM64Instruction, mnemonic: String) -> Memory? {+ guard instruction.mnemonic == mnemonic, let operands = instruction.detail?.operands, operands.count == 2,+ operands[0].type == .register, operands[1].type == .memory,+ operands[1].mem.index == .invalid, instruction.detail?.writeback == false+ else { return nil }+ return .init(register: operands[0].reg, base: operands[1].mem.base, offset: operands[1].mem.disp)+ }++ static func move(_ instruction: ARM64Instruction, destination: ARM64Register) -> ARM64Register? {+ guard instruction.mnemonic == "mov", let operands = instruction.detail?.operands, operands.count == 2,+ operands[0].type == .register, operands[0].reg == destination, operands[1].type == .register+ else { return nil }+ return operands[1].reg+ }++ static func contextRegister(in code: [ARM64Instruction]) -> ARM64Register? {+ let candidates = (19 ... 28).filter { register in+ code.prefix(24).prefix(while: { !$0.isCall }).contains { move($0, destination: .x(register)) == .x(0) }+ }+ return candidates.only.map { .x($0) }+ }++ static func isX(_ register: ARM64Register) -> Bool { (0 ... 30).contains { register == .x($0) } }+ static func isW(_ register: ARM64Register) -> Bool { (0 ... 30).contains { register == .w($0) } }++ static func branch(_ instruction: ARM64Instruction, mnemonic: String) -> UInt64? {+ guard instruction.mnemonic == mnemonic, let operand = instruction.detail?.operands.only,+ operand.type == .immediate, operand.imm > 0 else { return nil }+ return UInt64(operand.imm)+ }++ static func compareBranch(_ instruction: ARM64Instruction, mnemonic: String, register: ARM64Register) -> UInt64? {+ guard instruction.mnemonic == mnemonic, let operands = instruction.detail?.operands, operands.count == 2,+ operands[0].type == .register, operands[0].reg == register,+ operands[1].type == .immediate, operands[1].imm > 0 else { return nil }+ return UInt64(operands[1].imm)+ }++ static func bitBranch(_ instruction: ARM64Instruction, mnemonic: String, register: ARM64Register?, bit: Int64) -> UInt64? {+ guard instruction.mnemonic == mnemonic, let operands = instruction.detail?.operands, operands.count == 3,+ operands[0].type == .register, register == nil || operands[0].reg == register,+ operands[1].type == .immediate, operands[1].imm == bit,+ operands[2].type == .immediate, operands[2].imm > 0 else { return nil }+ return UInt64(operands[2].imm)+ }+}++private extension Array {+ var only: Element? { count == 1 ? first : nil }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPrimitiveRestartPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPrimitiveRestartPatcher.swiftnew file mode 100644index 00000000..0d80dcc6--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheGLESPrimitiveRestartPatcher.swift@@ -0,0 +1,235 @@+// Keep the paravirtual command-91 suppression, but restore GLES's disabled+// primitive-restart semantics for indexed strips. Returning zero from the+// renderer's fast-draw callback asks GLEngine to pack the original indexed+// vertices and use its nonindexed primitive-buffer path. Enabled restart and+// all other draws keep the original renderer path. GLEngine packs original+// vertex/instance IDs, including for its instanced and range-draw entry points.+//+// No runtime context offsets are built into the patch. Resolve both routines+// from the image's symbols, recover the state fields from the actual restart+// updater, and install a checked entry trampoline in unused executable header+// padding. The ABI's flags 1/3 mean elements/range-elements; arrays use zero.+// This patch requires the existing paravirtual primitive-restart suppression:+// even the primitive-buffer path still applies the renderer's Metal state.++import Foundation+import VPhonePatchKit++public struct DyldSharedCacheGLESPrimitiveRestartPatch: Sendable {+ public let functionVMA: UInt64+ public let siteVMA: UInt64+ public let caveVMA: UInt64+ public let wasAlreadyPatched: Bool+ public let sitesWritten: Int+ public let reattestation: DyldSharedCacheReattestation?+}++public enum DyldSharedCacheGLESPrimitiveRestartPatcher {+ public static let imagePath = "/System/Library/Extensions/AppleMetalGLRenderer.bundle/AppleMetalGLRenderer"+ public static let symbolName = "__ZL20gldRenderVertexArrayP13GLDContextRecjjiijPKviS2_"+ static let stateSymbol = "__ZN13GLDContextRec28updateRenderPrimitiveRestartEv"+ static let label = "GLES primitive restart"+ static let caveSize = 68++ struct StateFields: Equatable {+ let pointerOffset: UInt32+ let enabledOffset: UInt16+ }++ struct Site {+ let address: UInt64+ let existingCave: UInt64?+ }++ struct Plan {+ let cave: UInt64+ let branch: Data+ let program: Data+ let alreadyPatched: Bool+ }++ @discardableResult+ public static func patch(+ chunksDirectory: URL,+ dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheGLESPrimitiveRestartPatch {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ do {+ let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)+ let result = try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)+ if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) }+ return result+ } catch {+ if captureUndo, let failure = error as? DyldSharedCachePatchRollbackError {+ onUndo?(failure.recoveryUndo)+ }+ throw error+ }+ }++ @discardableResult+ public static func patch(+ chunks: DyldSharedCacheChunkSet,+ resolver: DyldSharedCacheSymbolResolver,+ dryRun: Bool = false,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheGLESPrimitiveRestartPatch {+ let function = try resolver.address(of: symbolName, inImage: imagePath)+ let updater = try resolver.address(of: stateSymbol, inImage: imagePath)+ let decoder = ARM64Disassembler()+ let entry = decoder.disassemble(try chunks.bytesAtVMA(function, length: 128), at: function)+ let site = try findEntry(in: entry)+ let state = try stateFields(in: DyldSharedCacheIOMFBSwapEndPatcher.disassembleFunction(+ in: chunks, at: updater, maximumInstructions: 32, disassembler: decoder,+ ))+ let headerAddress = try resolver.headerAddress(ofImage: imagePath)+ let prefix = try chunks.bytesAtVMA(headerAddress, length: 32)+ let commandsSize = Int(prefix.loadLE(UInt32.self, at: 20))+ guard commandsSize <= 1 << 20 else { throw PatcherError.invalidFormat("\(label) image load commands are too large") }+ let header = try chunks.bytesAtVMA(headerAddress, length: 32 + commandsSize)+ let padding = try DyldSharedCachePatchTransaction.headerPadding(+ in: header, at: headerAddress, minimumSize: caveSize, label: label,+ )+ guard chunks.mappings.contains(where: {+ $0.initProt & 4 != 0 && $0.address <= padding.lowerBound && $0.address + $0.size >= padding.upperBound+ }) else { throw PatcherError.invalidFormat("\(label) header padding is not executable") }+ let plan = try plan(site: site, fields: state, padding: padding) { try chunks.bytesAtVMA($0, length: $1) }+ log?(" [.] \(label) callback @ 0x\(String(function, radix: 16)); trampoline @ 0x\(String(plan.cave, radix: 16))")+ log?(" [\(plan.alreadyPatched ? "=" : dryRun ? "~" : "+")] disabled indexed strips use GLEngine primitive buffers\(plan.alreadyPatched ? " (already patched)" : "")")+ var reattestation: DyldSharedCacheReattestation?+ if !dryRun, !plan.alreadyPatched {+ let spans = [+ DyldSharedCacheWriteSpan(vma: plan.cave, length: plan.program.count),+ DyldSharedCacheWriteSpan(vma: site.address, length: plan.branch.count),+ ]+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ chunks.clearRecordedWrites()+ reattestation = try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: label, log: log) {+ try chunks.write(at: plan.cave, plan.program)+ try chunks.write(at: site.address, plan.branch)+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: log)+ guard result.isFullyAttested else { throw PatcherError.patchVerificationFailed("\(label) re-attestation skipped pages") }+ guard try chunks.bytesAtVMA(plan.cave, length: caveSize) == plan.program,+ try chunks.bytesAtVMA(site.address, length: 4) == plan.branch+ else { throw PatcherError.patchVerificationFailed("\(label) bytes did not read back") }+ return result+ }+ }+ return .init(functionVMA: function, siteVMA: site.address, caveVMA: plan.cave,+ wasAlreadyPatched: plan.alreadyPatched, sitesWritten: dryRun || plan.alreadyPatched ? 0 : 2,+ reattestation: reattestation)+ }++ // MARK: - Source-derived ABI and state fields++ static func findEntry(in code: [ARM64Instruction]) throws -> Site {+ guard code.count >= 24, let first = code.first,+ first.mnemonic == "pacibsp" || target(first) != nil,+ code[1].mnemonic == "sub", let stack = code[1].detail?.operands,+ stack.count == 3, stack[0].reg == .sp, stack[1].reg == .sp,+ stack[2].type == .immediate, stack[2].imm > 0,+ code[2 ..< 8].allSatisfy({ $0.mnemonic == "stp" }),+ code[12 ..< 24].contains(where: { move($0, source: .x(2)) }),+ code[12 ..< 24].contains(where: { move($0, source: .x(5)) }),+ code[12 ..< 24].contains(where: { move($0, source: .x(7)) })+ else { throw PatcherError.patchSiteNotFound("\(label) fast-draw entry has an unfamiliar ABI/prologue") }+ return Site(address: first.address, existingCave: target(first))+ }++ static func move(_ instruction: ARM64Instruction, source: ARM64Register) -> Bool {+ guard instruction.mnemonic == "mov", let operands = instruction.detail?.operands,+ operands.count == 2, operands[0].type == .register, operands[1].type == .register+ else { return false }+ return operands[1].reg == source+ }++ static func target(_ instruction: ARM64Instruction) -> UInt64? {+ guard instruction.mnemonic == "b", let operand = instruction.detail?.operands.first,+ operand.type == .immediate, operand.imm > 0 else { return nil }+ return UInt64(operand.imm)+ }++ static func stateFields(in code: [ARM64Instruction]) throws -> StateFields {+ guard code.count >= 7, code[0].mnemonic == "ldr", code[1].mnemonic == "mov",+ code[2].mnemonic == "ldrb", code[3].mnemonic == "cmp", code[4].mnemonic == "cset",+ code[5].mnemonic == "mov", code[6].mnemonic == "strb",+ let load = code[0].detail?.operands, load.count == 2,+ load[0].type == .register, load[1].type == .memory,+ load[1].mem.base == .x(0), load[1].mem.index == .invalid,+ load[1].mem.disp >= 0, load[1].mem.disp % 8 == 0,+ code[0].detail?.writeback == false,+ let pointer = (1 ... 17).first(where: { load[0].reg == .x($0) }),+ let offset = code[1].detail?.operands, offset.count == 2,+ let index = (1 ... 17).first(where: { offset[0].reg == .w($0) }),+ pointer != index, offset[1].type == .immediate,+ let byteOffset = UInt16(exactly: offset[1].imm),+ let byte = code[2].detail?.operands, byte.count == 2,+ byte[0].reg == .w(pointer), byte[1].type == .memory,+ byte[1].mem.base == .x(pointer), byte[1].mem.index == .x(index),+ byte[1].mem.disp == 0, byte[1].shift.amount == 0,+ code[2].detail?.writeback == false,+ let compare = code[3].detail?.operands, compare.count == 2,+ compare[0].reg == .w(pointer), compare[1].type == .immediate, compare[1].imm == 0,+ code[4].detail?.conditionCode == .ne,+ code[4].detail?.operands.first?.reg == .w(pointer),+ let store = code[6].detail?.operands, store.count == 2,+ store[0].reg == .w(pointer), store[1].type == .memory, store[1].mem.base == .x(0)+ else { throw PatcherError.patchSiteNotFound("\(label) updater does not expose a verified current-state byte") }+ return StateFields(pointerOffset: UInt32(load[1].mem.disp), enabledOffset: byteOffset)+ }++ // MARK: - Checked header trampoline++ static func plan(site: Site, fields: StateFields, padding: Range<UInt64>, read: (UInt64, Int) throws -> Data) throws -> Plan {+ guard padding.count >= caveSize else { throw PatcherError.patchSiteNotFound("\(label) padding is too small") }+ let cave: UInt64+ if let existing = site.existingCave {+ guard existing % 4 == 0, padding.contains(existing), existing <= padding.upperBound - UInt64(caveSize)+ else { throw PatcherError.patchVerificationFailed("\(label) entry branch leaves header padding") }+ cave = existing+ } else {+ let bytes = try read(padding.lowerBound, Int(padding.count))+ guard let offset = stride(from: 0, through: bytes.count - caveSize, by: 4).first(where: {+ bytes[$0 ..< $0 + caveSize].allSatisfy { $0 == 0 }+ }) else { throw PatcherError.patchSiteNotFound("\(label) header padding is occupied") }+ cave = padding.lowerBound + UInt64(offset)+ }+ let program = try trampoline(at: cave, returningTo: site.address + 4, fields: fields)+ guard let branch = ARM64Encoder.encodeB(from: Int(site.address), to: Int(cave)) else {+ throw PatcherError.patchVerificationFailed("\(label) trampoline is out of branch range")+ }+ if site.existingCave != nil, try read(cave, caveSize) != program {+ throw PatcherError.patchVerificationFailed("\(label) trampoline differs from this patch's complete output")+ }+ return Plan(cave: cave, branch: branch, program: program, alreadyPatched: site.existingCave != nil)+ }++ static func trampoline(at cave: UInt64, returningTo resume: UInt64, fields: StateFields) throws -> Data {+ guard let base = Int(exactly: cave), let end = Int(exactly: resume),+ let elements = ARM64Encoder.encodeCmpWImmediate(rn: 1, imm12: 1),+ let isElements = ARM64Encoder.encodeBCond(from: base + 8, to: base + 20, condition: .eq),+ let rangeElements = ARM64Encoder.encodeCmpWImmediate(rn: 1, imm12: 3),+ let notElements = ARM64Encoder.encodeBCond(from: base + 16, to: base + 64, condition: .ne),+ let line = ARM64Encoder.encodeCmpWImmediate(rn: 2, imm12: 3),+ let isLine = ARM64Encoder.encodeBCond(from: base + 24, to: base + 36, condition: .eq),+ let triangle = ARM64Encoder.encodeCmpWImmediate(rn: 2, imm12: 5),+ let notStrip = ARM64Encoder.encodeBCond(from: base + 32, to: base + 64, condition: .ne),+ let state = ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 0, offset: fields.pointerOffset),+ let byteOffset = ARM64Encoder.encodeMovzX(rd: 9, imm16: fields.enabledOffset),+ let byteAddress = ARM64Encoder.encodeAddSubXShifted(subtract: false, rd: 8, rn: 8, rm: 9),+ let enabled = ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 8, offset: 0),+ let restartOn = ARM64Encoder.encodeCompareBranch(nonzero: true, register: 8, from: base + 52, to: base + 64, width64: false),+ let original = ARM64Encoder.encodeB(from: base + 64, to: end)+ else { throw PatcherError.patchVerificationFailed("Cannot encode \(label) trampoline") }+ // Only caller-saved x8/x9 and NZCV change. Arguments x0...x7, stack and+ // LR survive the forwarding path. PACIBSP is the displaced first+ // instruction; the early return therefore uses matching RETAB.+ let instructions = [ARM64.pacibsp, elements, isElements, rangeElements, notElements,+ line, isLine, triangle, notStrip, state, byteOffset, byteAddress,+ enabled, restartOn, ARM64.movW0_0, ARM64.retab, original]+ return instructions.reduce(into: Data()) { $0 += $1 }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalCacheReusePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalCacheReusePatcher.swiftnew file mode 100644index 00000000..52fbacf5--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalCacheReusePatcher.swift@@ -0,0 +1,348 @@+// FS_CACHE_REUSE_ON_REBOOT=1 currently bypasses both the boot identity and the+// 32-byte client key in libCoreFSCache. A changed Metal compiler identity must+// still reject an old GLES shader cache. Route only that environment branch+// through the existing key check, setting the existing third-party flag so+// its successful comparison continues to bypass the boot identity alone.+//+// Resolve verify_list_file and is_third_party from this image's own symbols.+// Derive the environment branch, key buffers and flag register from decoded+// operands; prove that the flag is otherwise dead until its ABI restoration.+// The two-instruction trampoline occupies verified unused executable header+// padding. Partial or altered prior patches fail before any cache write.++import Foundation+import VPhonePatchKit++public struct DyldSharedCacheMetalCacheReusePatch: Sendable {+ public let functionVMA: UInt64+ public let siteVMA: UInt64+ public let caveVMA: UInt64+ public let wasAlreadyPatched: Bool+ public let sitesWritten: Int+ public let reattestation: DyldSharedCacheReattestation?+}++public enum DyldSharedCacheMetalCacheReusePatcher {+ public static let imagePath = "/System/Library/Frameworks/OpenGLES.framework/libCoreFSCache.dylib"+ public static let symbolName = "_verify_list_file"+ static let thirdPartySymbol = "_is_third_party"+ static let environment = Data("FS_CACHE_REUSE_ON_REBOOT\0".utf8)+ static let label = "Metal cache reuse key"+ static let caveSize = 8++ struct Site {+ let address: UInt64+ let resume: UInt64+ let flagRegister: UInt32+ let existingCave: UInt64?+ }++ struct Plan {+ let site: Site+ let cave: UInt64+ let branch: Data+ let program: Data+ var alreadyPatched: Bool { site.existingCave != nil }+ }++ @discardableResult+ public static func patch(+ chunksDirectory: URL,+ dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheMetalCacheReusePatch {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ do {+ let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)+ let result = try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)+ if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) }+ return result+ } catch {+ if captureUndo, let failure = error as? DyldSharedCachePatchRollbackError {+ onUndo?(failure.recoveryUndo)+ }+ throw error+ }+ }++ @discardableResult+ public static func patch(+ chunks: DyldSharedCacheChunkSet,+ resolver: DyldSharedCacheSymbolResolver,+ dryRun: Bool = false,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheMetalCacheReusePatch {+ try resolver.requireLocalSymbols()+ let symbols = try resolver.symbols(inImage: imagePath)+ let addresses = try resolver.addresses(of: [symbolName, thirdPartySymbol], inImage: imagePath)+ let function = addresses[symbolName]!+ let span = try DyldSharedCacheGLESPointDrawPatcher.functionSpan(at: function, symbolAddresses: symbols.values.map(\.address))+ let headerAddress = try resolver.headerAddress(ofImage: imagePath)+ let prefix = try chunks.bytesAtVMA(headerAddress, length: 32)+ let commandsSize = Int(prefix.loadLE(UInt32.self, at: 20))+ guard commandsSize <= 1 << 20 else { throw PatcherError.invalidFormat("\(label) load commands are too large") }+ let header = try chunks.bytesAtVMA(headerAddress, length: 32 + commandsSize)+ let padding = try DyldSharedCachePatchTransaction.headerPadding(in: header, at: headerAddress, minimumSize: caveSize, label: label)+ for range in [span, padding] {+ guard chunks.mappings.contains(where: {+ $0.initProt & 4 != 0 && $0.address <= range.lowerBound && $0.address + $0.size >= range.upperBound+ }) else { throw PatcherError.invalidFormat("\(label) function or padding is not wholly executable") }+ }+ let code = ARM64Disassembler().disassemble(try chunks.bytesAtVMA(function, length: Int(span.count)), at: function)+ guard code.count * 4 == span.count else { throw PatcherError.patchSiteNotFound("\(label) function did not decode completely") }+ let stackFailure = try resolver.address(of: "___stack_chk_fail", inImage: "/usr/lib/system/libsystem_c.dylib")+ let site = try findSite(in: code, thirdParty: addresses[thirdPartySymbol]!, stackFailure: stackFailure) { try chunks.bytesAtVMA($0, length: $1) }+ let plan = try plan(site: site, padding: padding) { try chunks.bytesAtVMA($0, length: $1) }+ log?(" [\(plan.alreadyPatched ? "=" : dryRun ? "~" : "+")] \(label) @ 0x\(String(site.address, radix: 16)) -> trampoline 0x\(String(plan.cave, radix: 16)); preserve 32-byte key validation on reboot reuse\(plan.alreadyPatched ? " (already patched)" : "")")+ var reattestation: DyldSharedCacheReattestation?+ if !dryRun, !plan.alreadyPatched {+ let spans = [DyldSharedCacheWriteSpan(vma: plan.cave, length: caveSize), DyldSharedCacheWriteSpan(vma: site.address, length: 4)]+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ chunks.clearRecordedWrites()+ reattestation = try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: label, log: log) {+ try chunks.write(at: plan.cave, plan.program)+ try chunks.write(at: site.address, plan.branch)+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: log)+ guard result.isFullyAttested else { throw PatcherError.patchVerificationFailed("\(label) re-attestation skipped pages") }+ guard try chunks.bytesAtVMA(plan.cave, length: caveSize) == plan.program,+ try chunks.bytesAtVMA(site.address, length: 4) == plan.branch+ else { throw PatcherError.patchVerificationFailed("\(label) did not read back") }+ return result+ }+ }+ return .init(functionVMA: function, siteVMA: site.address, caveVMA: plan.cave,+ wasAlreadyPatched: plan.alreadyPatched, sitesWritten: dryRun || plan.alreadyPatched ? 0 : 2,+ reattestation: reattestation)+ }++ // MARK: - Environment branch and both identity checks++ static func findSite(in code: [ARM64Instruction], thirdParty: UInt64, stackFailure: UInt64, read: (UInt64, Int) throws -> Data) throws -> Site {+ guard let start = code.first?.address, code.count >= 30,+ code.enumerated().allSatisfy({ $0.element.isDecoded && $0.element.size == 4 && $0.element.address == start + UInt64($0.offset * 4) })+ else { throw PatcherError.patchSiteNotFound("\(label) function did not decode completely") }+ guard let last = code.last, let failureTarget = branch(last, "bl"),+ try isStackFailure(failureTarget, resolved: stackFailure, read: read)+ else { throw PatcherError.patchVerificationFailed("\(label) terminal call is not the resolved stack-check failure") }+ var candidates: [Site] = []+ for i in code.indices where i >= 8 && i + 9 < code.count {+ // getenv(string), missing-value CBZ, load first character, call+ // is_third_party, compare with '1', B.NE normal, B reuse. The+ // missing-value path calls the same helper then shares normal's+ // saved result. Leave all of those instructions intact.+ guard let literal = DyldSharedCacheGLESPointDrawPatcher.materializedAddress(code[i - 8], code[i - 7], destination: .x(0)),+ branch(code[i - 6], "bl") != nil,+ compareBranch(code[i - 5], "cbz", .x(0)) == code[i + 1].address,+ let character = memory(code[i - 4], "ldrb"), character.base == .x(0), character.offset == 0,+ (19 ... 28).contains(where: { character.register == .w($0) }),+ branch(code[i - 3], "bl") == thirdParty,+ compareImmediate(code[i - 2], register: character.register, value: 49),+ branch(code[i - 1], "b.ne") == code[i + 2].address,+ let destination = branch(code[i], "b"),+ branch(code[i + 1], "bl") == thirdParty,+ let flag = movedRegister(code[i + 2], source: .x(0)),+ let flagNumber = (19 ... 28).first(where: { flag == .x($0) }),+ let stackKey = add(code[i + 3]), stackKey.source == .sp,+ let clientKey = add(code[i + 4]), clientKey.destination == .x(0), clientKey.offset == 64,+ let storedKey = add(code[i + 5]), storedKey.destination == .x(1),+ storedKey.source == stackKey.destination, storedKey.offset == clientKey.offset,+ immediateMove(code[i + 6], .w(2), 32),+ let comparison = branch(code[i + 7], "bl"),+ let bootAddress = compareBranch(code[i + 8], "cbz", .w(0)),+ immediateMove(code[i + 9], .w(0), 0),+ let boot = code.firstIndex(where: { $0.address == bootAddress }), boot > i + 9, boot + 6 < code.count,+ let success = bitBranch(code[boot], register: .w(flagNumber)),+ let bootBuffer = add(code[boot + 1]), bootBuffer.destination == .x(1),+ bootBuffer.source == .sp, bootBuffer.offset == stackKey.offset,+ movedRegister(code[boot + 2], source: clientKey.source) == .x(0),+ immediateMove(code[boot + 3], .w(2), 64),+ branch(code[boot + 4], "bl") == comparison,+ compareBranch(code[boot + 5], "cbnz", .w(0)) == code[i + 9].address,+ success == code[boot + 6].address,+ try read(literal, environment.count) == environment+ else { continue }+ // Both client buffers must belong to the saved second argument;+ // otherwise a same-sized unrelated comparison is not this key.+ guard let clientRegister = (19 ... 28).first(where: { clientKey.source == .x($0) }),+ let save = code[..<(i - 8)].lastIndex(where: { movedRegister($0, source: .x(1)) == clientKey.source }),+ code[save + 1 ..< i + 4].allSatisfy({ !writes($0, register: clientRegister) }) else { continue }+ try verifyFlagLiveness(in: code, from: i + 3, bitTest: boot, register: flagNumber, failureTarget: failureTarget)+ let existing = destination == success ? nil : destination+ if let existing, start <= existing && existing < code.last!.address + 4 {+ throw PatcherError.patchVerificationFailed("\(label) unexpected in-function reuse branch")+ }+ candidates.append(.init(address: code[i].address, resume: code[i + 3].address,+ flagRegister: UInt32(flagNumber), existingCave: existing))+ }+ guard candidates.count == 1, let site = candidates.first else {+ throw PatcherError.patchSiteNotFound("\(label) expected one verified environment/key/boot chain, found \(candidates.count)")+ }+ return site+ }++ // The trampoline changes a callee-saved register, so every return must+ // restore its incoming value. Calls preserve it by ABI. Reject any other+ // use, redefinition, indirect control flow, or path escaping this function.+ static func verifyFlagLiveness(in code: [ARM64Instruction], from start: Int, bitTest: Int, register: Int, failureTarget: UInt64) throws {+ func mentions(_ instruction: ARM64Instruction) -> Bool {+ instruction.detail?.operands.contains(where: {+ ($0.type == .register && ($0.reg == .x(register) || $0.reg == .w(register))) ||+ ($0.type == .memory && ($0.mem.base == .x(register) || $0.mem.index == .x(register)))+ }) == true+ }+ func stackPair(_ instruction: ARM64Instruction, mnemonic: String) -> [ARM64Operand]? {+ guard instruction.mnemonic == mnemonic, let operands = instruction.detail?.operands,+ operands.count == 3, operands[0].type == .register, operands[1].type == .register,+ operands[2].type == .memory, operands[2].mem.base == .sp,+ operands[2].mem.index == .invalid, instruction.detail?.writeback == false,+ [operands[0].reg, operands[1].reg].contains(.x(register)) else { return nil }+ return operands+ }+ let restores = (start ..< code.count).filter { stackPair(code[$0], mnemonic: "ldp") != nil }+ guard restores.count == 1, let restore = restores.first,+ let pair = stackPair(code[restore], mnemonic: "ldp"),+ code[..<start].filter({ instruction in+ guard let save = stackPair(instruction, mnemonic: "stp") else { return false }+ return save[0].reg == pair[0].reg && save[1].reg == pair[1].reg && save[2].mem == pair[2].mem+ }).count == 1,+ (start ..< code.count).allSatisfy({ $0 == bitTest || $0 == restore || !mentions(code[$0]) })+ else { throw PatcherError.patchVerificationFailed("\(label) flag register is live outside the boot gate or lacks an exact ABI save/restore") }+ let indices = Dictionary(uniqueKeysWithValues: code.enumerated().map { ($0.element.address, $0.offset) })+ var pending = [(start, false)]+ var visited = Set<Int>()+ var returned = false+ while let (index, restored) = pending.popLast() {+ guard code.indices.contains(index) else { throw PatcherError.patchVerificationFailed("\(label) control flow leaves the function") }+ guard visited.insert(index * 2 + (restored ? 1 : 0)).inserted else { continue }+ let instruction = code[index]+ if instruction.isReturn {+ guard restored else { throw PatcherError.patchVerificationFailed("\(label) returns without restoring its flag register") }+ returned = true+ continue+ }+ let didRestore = restored || index == restore+ if index == bitTest, restored { throw PatcherError.patchVerificationFailed("\(label) boot gate reads an already restored flag") }+ if instruction.isJump && !instruction.isCall {+ guard let operand = instruction.detail?.operands.last, operand.type == .immediate,+ let target = indices[UInt64(bitPattern: operand.imm)], target >= start+ else { throw PatcherError.patchVerificationFailed("\(label) unsupported flag control flow") }+ pending.append((target, didRestore))+ if instruction.mnemonic == "b" { continue }+ }+ // A terminal stack-check failure call does not return. It is the+ // only tolerated out-of-span fallthrough, and has no flag uses.+ if index == code.count - 1, branch(instruction, "bl") == failureTarget { continue }+ pending.append((index + 1, didRestore))+ }+ guard returned else { throw PatcherError.patchVerificationFailed("\(label) has no verified restored return") }+ }++ // MARK: - Verified padding and code generation++ static func plan(site: Site, padding: Range<UInt64>, read: (UInt64, Int) throws -> Data) throws -> Plan {+ guard padding.lowerBound % 4 == 0, padding.count >= caveSize else { throw PatcherError.patchSiteNotFound("\(label) header padding is too small or unaligned") }+ let cave: UInt64+ if let existing = site.existingCave {+ guard existing % 4 == 0, padding.contains(existing), existing <= padding.upperBound - UInt64(caveSize)+ else { throw PatcherError.patchVerificationFailed("\(label) branch leaves its header padding") }+ cave = existing+ } else {+ let bytes = try read(padding.lowerBound, Int(padding.count))+ guard bytes.count == padding.count else { throw PatcherError.patchSiteNotFound("\(label) header padding read is truncated") }+ for offset in stride(from: 0, through: bytes.count - caveSize, by: 4) {+ let address = padding.lowerBound + UInt64(offset)+ if try Data(bytes[offset ..< offset + caveSize]) == trampoline(at: address, returningTo: site.resume, flagRegister: site.flagRegister) {+ throw PatcherError.patchVerificationFailed("\(label) orphaned trampoline has no matching site branch")+ }+ }+ guard let offset = stride(from: 0, through: bytes.count - caveSize, by: 4).first(where: {+ bytes[$0 ..< $0 + caveSize].allSatisfy { $0 == 0 }+ }) else { throw PatcherError.patchSiteNotFound("\(label) header padding is occupied") }+ cave = padding.lowerBound + UInt64(offset)+ }+ let program = try trampoline(at: cave, returningTo: site.resume, flagRegister: site.flagRegister)+ guard let from = Int(exactly: site.address), let to = Int(exactly: cave),+ let branch = ARM64Encoder.encodeB(from: from, to: to)+ else { throw PatcherError.patchVerificationFailed("\(label) trampoline is out of branch range") }+ if site.existingCave != nil, try read(cave, caveSize) != program {+ throw PatcherError.patchVerificationFailed("\(label) trampoline differs from this patch's output")+ }+ return .init(site: site, cave: cave, branch: branch, program: program)+ }++ static func trampoline(at cave: UInt64, returningTo resume: UInt64, flagRegister: UInt32) throws -> Data {+ guard (19 ... 28).contains(flagRegister), cave % 4 == 0, resume % 4 == 0,+ let base = Int(exactly: cave), let end = Int(exactly: resume),+ let flag = ARM64Encoder.encodeMovzW(rd: flagRegister, imm16: 1),+ let resumeBranch = ARM64Encoder.encodeB(from: base + 4, to: end)+ else { throw PatcherError.patchVerificationFailed("Cannot encode \(label) trampoline") }+ // MOVZ and B leave NZCV, LR and SP unchanged. The forced flag survives+ // the 32-byte comparison and skips only the subsequent boot check.+ return flag + resumeBranch+ }++ // MARK: - Typed operands++ static func writes(_ instruction: ARM64Instruction, register: Int) -> Bool {+ instruction.detail?.operands.contains(where: {+ ($0.type == .register && $0.writesRegister && ($0.reg == .x(register) || $0.reg == .w(register))) ||+ ($0.type == .memory && instruction.detail?.writeback == true && $0.mem.base == .x(register))+ }) == true+ }++ static func isStackFailure(_ target: UInt64, resolved: UInt64, read: (UInt64, Int) throws -> Data) throws -> Bool {+ if target == resolved { return true }+ // Cache-builder branch islands materialize the true destination in a+ // scratch register and BR to it. Resolve that dataflow, not its VMA.+ let stub = ARM64Disassembler().disassemble(try read(target, 12), at: target)+ guard stub.count == 3, stub.allSatisfy({ $0.isDecoded && $0.size == 4 }),+ stub[2].mnemonic == "br", let operands = stub[2].detail?.operands,+ operands.count == 1, operands[0].type == .register,+ DyldSharedCacheGLESPointDrawPatcher.materializedAddress(stub[0], stub[1], destination: operands[0].reg) == resolved+ else { return false }+ return true+ }++ static func branch(_ instruction: ARM64Instruction, _ mnemonic: String) -> UInt64? {+ DyldSharedCacheMetalVertexFormatPatcher.branchTarget(instruction, mnemonic: mnemonic)+ }++ static func movedRegister(_ instruction: ARM64Instruction, source: ARM64Register) -> ARM64Register? {+ guard instruction.mnemonic == "mov", let operands = instruction.detail?.operands,+ operands.count == 2, operands[0].type == .register, operands[1].type == .register, operands[1].reg == source else { return nil }+ return operands[0].reg+ }++ static func immediateMove(_ instruction: ARM64Instruction, _ register: ARM64Register, _ value: Int64) -> Bool {+ DyldSharedCacheMetalVertexFormatPatcher.isImmediateMove(instruction, destination: register, value: value)+ }++ static func compareImmediate(_ instruction: ARM64Instruction, register: ARM64Register, value: Int64) -> Bool {+ guard instruction.mnemonic == "cmp", let operands = instruction.detail?.operands,+ operands.count == 2, operands[0].type == .register, operands[0].reg == register,+ operands[1].type == .immediate, operands[1].imm == value else { return false }+ return true+ }++ static func add(_ instruction: ARM64Instruction) -> (destination: ARM64Register, source: ARM64Register, offset: Int64)? {+ guard instruction.mnemonic == "add", let operands = instruction.detail?.operands,+ operands.count == 3, operands[0].type == .register, operands[1].type == .register,+ operands[2].type == .immediate, operands[2].shift.amount == 0 else { return nil }+ return (operands[0].reg, operands[1].reg, operands[2].imm)+ }++ static func memory(_ instruction: ARM64Instruction, _ mnemonic: String) -> (register: ARM64Register, base: ARM64Register, offset: Int32)? {+ guard let value = DyldSharedCacheGLESPointDrawPatcher.memory(instruction, mnemonic: mnemonic) else { return nil }+ return (value.register, value.base, value.offset)+ }++ static func compareBranch(_ instruction: ARM64Instruction, _ mnemonic: String, _ register: ARM64Register) -> UInt64? {+ DyldSharedCacheGLESPointDrawPatcher.compareBranch(instruction, mnemonic: mnemonic, register: register)+ }++ static func bitBranch(_ instruction: ARM64Instruction, register: ARM64Register) -> UInt64? {+ DyldSharedCacheGLESPointDrawPatcher.bitBranch(instruction, mnemonic: "tbnz", register: register, bit: 0)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalVertexFormatPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalVertexFormatPatcher.swiftnew file mode 100644index 00000000..88d6e314--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheMetalVertexFormatPatcher.swift@@ -0,0 +1,251 @@+// AppleMetalGLRenderer uses private vertex formats 43 and 44 for the supplied+// vertex/instance IDs in its primitive buffer. The guest compiler consumes+// those formats while adding software vertex fetches to AIR. Sending the same+// formats in the pipeline descriptor to macOS then aborts MTLCompilerService+// in Air::CloneAttributeDescriptor: its supported-format mask excludes both.+//+// Normalize only the serialized attribute's format, after the guest has made+// its shader variants. PipelineLibrarySerializer::serializeVertexDescriptor is+// the wire writer reached by -[_MTLDevice serializeRenderPipelineDescriptor:].+// Neither the original MTLVertexDescriptor nor the generated AIR is changed.+// UInt (36) describes the existing four-byte ID buffer to the host compiler.+//+// The site is the format getter's result saved for wire property 1. Both the+// containing function and the getter stub are resolved from this image's own+// symbols; operand/control-flow checks distinguish the actual value from the+// getter used for the default value. A 32-byte trampoline uses only existing+// ARM64Encoder helpers, with no absolute addresses or runtime hooks. Its space+// must be unused header padding before the first __TEXT section. An unfamiliar+// shape, occupied padding, or altered prior trampoline fails before any write.++import Foundation+import VPhonePatchKit++public struct DyldSharedCacheMetalVertexFormatPatch: Sendable {+ public let functionVMA: UInt64+ public let siteVMA: UInt64+ public let caveVMA: UInt64+ public let wasAlreadyPatched: Bool+ public let sitesWritten: Int+ public let reattestation: DyldSharedCacheReattestation?+}++public enum DyldSharedCacheMetalVertexFormatPatcher {+ public static let imagePath = "/System/Library/Frameworks/Metal.framework/Metal"+ public static let symbolName =+ "__ZN28MTLPipelineLibrarySerializer25PipelineLibrarySerializer25serializeVertexDescriptorEP19MTLVertexDescriptor"+ static let formatSymbol = "_objc_msgSend$format"+ static let caveSize = 32++ struct Site {+ let address: UInt64+ let valueRegister: UInt32+ let existingCave: UInt64?+ }++ struct Plan {+ let site: Site+ let cave: UInt64+ let branch: Data+ let program: Data+ var alreadyPatched: Bool { site.existingCave != nil }+ }++ @discardableResult+ public static func patch(+ chunksDirectory: URL,+ dryRun: Bool = false,+ captureUndo: Bool = false,+ onUndo: ((DyldSharedCacheUndoLog) -> Void)? = nil,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheMetalVertexFormatPatch {+ let chunks = try DyldSharedCacheChunkSet(directory: chunksDirectory, captureUndo: captureUndo)+ do {+ let resolver = try DyldSharedCacheSymbolResolver(chunks: chunks)+ let result = try patch(chunks: chunks, resolver: resolver, dryRun: dryRun, log: log)+ if captureUndo, let undo = chunks.takeUndoLog() { onUndo?(undo) }+ return result+ } catch {+ // A successful rollback needs no persistent undo entry. A failed+ // rollback needs the pre-write snapshot, including a partial write+ // that FileHandle may have thrown before ChunkSet recorded it.+ if captureUndo, let failure = error as? DyldSharedCachePatchRollbackError {+ onUndo?(failure.recoveryUndo)+ }+ throw error+ }+ }++ @discardableResult+ public static func patch(+ chunks: DyldSharedCacheChunkSet,+ resolver: DyldSharedCacheSymbolResolver,+ dryRun: Bool = false,+ log: ((String) -> Void)? = DyldSharedCacheCodeSignature.stderrLog,+ ) throws -> DyldSharedCacheMetalVertexFormatPatch {+ let function = try resolver.address(of: symbolName, inImage: imagePath)+ let format = try resolver.address(of: formatSymbol, inImage: imagePath)+ let headerAddress = try resolver.headerAddress(ofImage: imagePath)+ let prefix = try chunks.bytesAtVMA(headerAddress, length: 32)+ let commandsSize = Int(prefix.loadLE(UInt32.self, at: 20))+ guard commandsSize <= 1 << 20 else {+ throw PatcherError.invalidFormat("Metal Mach-O load commands are too large")+ }+ let header = try chunks.bytesAtVMA(headerAddress, length: 32 + commandsSize)+ let padding = try headerPadding(in: header, at: headerAddress)+ guard chunks.mappings.contains(where: {+ $0.initProt & 4 != 0 && $0.address <= padding.lowerBound+ && $0.address + $0.size >= padding.upperBound+ }) else { throw PatcherError.invalidFormat("Metal header padding is not executable") }+ let instructions = try DyldSharedCacheIOMFBSwapEndPatcher.disassembleFunction(+ in: chunks, at: function, maximumInstructions: 1024, disassembler: ARM64Disassembler(),+ )+ let site = try findFormatSite(in: instructions, formatStub: format)+ let plan = try plan(site: site, padding: padding) {+ try chunks.bytesAtVMA($0, length: $1)+ }++ log?(" [.] Metal vertex descriptor format @ 0x\(hex(site.address)); trampoline @ 0x\(hex(plan.cave))")+ log?(" [\(plan.alreadyPatched ? "=" : dryRun ? "~" : "+")] serialized builtin vertex formats 43/44 -> UInt (36)\(plan.alreadyPatched ? " already patched" : "")")+ var reattestation: DyldSharedCacheReattestation?+ if !dryRun, !plan.alreadyPatched {+ let spans = [+ DyldSharedCacheWriteSpan(vma: plan.cave, length: plan.program.count),+ DyldSharedCacheWriteSpan(vma: site.address, length: plan.branch.count),+ ]+ // Save code AND hash slots before any mutation. Re-attestation can+ // itself partially write before throwing; recomputing hashes on+ // rollback would not guarantee the exact original file bytes.+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ chunks.clearRecordedWrites()+ reattestation = try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: "Metal vertex format patch", log: log) {+ // Install the complete destination before exposing its branch.+ try chunks.write(at: plan.cave, plan.program)+ try chunks.write(at: site.address, plan.branch)+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: log)+ guard result.isFullyAttested else {+ throw PatcherError.patchVerificationFailed("Metal vertex format re-attestation skipped \(result.skipped.count) page(s)")+ }+ guard try chunks.bytesAtVMA(plan.cave, length: caveSize) == plan.program,+ try chunks.bytesAtVMA(site.address, length: 4) == plan.branch+ else { throw PatcherError.patchVerificationFailed("Metal vertex format patch did not read back") }+ return result+ }+ }+ return DyldSharedCacheMetalVertexFormatPatch(+ functionVMA: function, siteVMA: site.address, caveVMA: plan.cave,+ wasAlreadyPatched: plan.alreadyPatched,+ sitesWritten: dryRun || plan.alreadyPatched ? 0 : 2,+ reattestation: reattestation,+ )+ }++ // MARK: - Semantic site discovery++ static func findFormatSite(in code: [ARM64Instruction], formatStub: UInt64) throws -> Site {+ var candidates: [Site] = []+ guard code.count >= 14 else {+ throw PatcherError.patchSiteNotFound("Metal vertex descriptor serializer is truncated")+ }+ for i in 2 ..< code.count - 11 {+ guard branchTarget(code[i - 1], mnemonic: "bl") == formatStub,+ move(code[i - 2], destination: .x(0)) != nil,+ move(code[i + 1], destination: .x(0)) != nil,+ branchTarget(code[i + 2], mnemonic: "bl") == formatStub,+ move(code[i + 3], destination: .x(3)) == .x(0),+ isImmediateMove(code[i + 8], destination: .w(1), value: 1),+ let valueRegister = move(code[i + 9], destination: .x(2)),+ let number = (19 ... 28).first(where: { valueRegister == .x($0) }),+ ["blraa", "blrab", "blr"].contains(code[i + 11].mnemonic)+ else { continue }+ let existingCave = branchTarget(code[i], mnemonic: "b")+ guard existingCave != nil || move(code[i], destination: valueRegister) == .x(0) else { continue }+ candidates.append(Site(address: code[i].address, valueRegister: UInt32(number), existingCave: existingCave))+ }+ guard candidates.count == 1, let site = candidates.first else {+ throw PatcherError.patchSiteNotFound("Metal serialized vertex format: expected one property-1 getter result, found \(candidates.count)")+ }+ return site+ }++ static func move(_ instruction: ARM64Instruction, destination: ARM64Register) -> ARM64Register? {+ guard instruction.mnemonic == "mov", let operands = instruction.detail?.operands,+ operands.count == 2, operands[0].type == .register, operands[0].reg == destination,+ operands[1].type == .register+ else { return nil }+ return operands[1].reg+ }++ static func isImmediateMove(_ instruction: ARM64Instruction, destination: ARM64Register, value: Int64) -> Bool {+ guard instruction.mnemonic == "mov", let operands = instruction.detail?.operands,+ operands.count == 2, operands[0].type == .register, operands[0].reg == destination,+ operands[1].type == .immediate, operands[1].imm == value+ else { return false }+ return true+ }++ static func branchTarget(_ instruction: ARM64Instruction, mnemonic: String) -> UInt64? {+ guard instruction.mnemonic == mnemonic, let operands = instruction.detail?.operands,+ operands.count == 1, operands[0].type == .immediate+ else { return nil }+ return UInt64(bitPattern: operands[0].imm)+ }++ // MARK: - Unused executable space++ static func headerPadding(in header: Data, at address: UInt64) throws -> Range<UInt64> {+ try DyldSharedCachePatchTransaction.headerPadding(in: header, at: address, minimumSize: caveSize, label: "Metal")+ }++ static func plan(+ site: Site,+ padding: Range<UInt64>,+ read: (UInt64, Int) throws -> Data,+ ) throws -> Plan {+ guard padding.count >= caveSize else {+ throw PatcherError.patchSiteNotFound("Metal header padding is too small")+ }+ let cave: UInt64+ if let existing = site.existingCave {+ guard existing % 4 == 0, padding.contains(existing),+ existing <= padding.upperBound - UInt64(caveSize)+ else { throw PatcherError.patchVerificationFailed("Metal format branch leaves its header padding") }+ cave = existing+ } else {+ let bytes = try read(padding.lowerBound, Int(padding.count))+ guard let offset = stride(from: 0, through: bytes.count - caveSize, by: 4).first(where: {+ bytes[$0 ..< $0 + caveSize].allSatisfy { $0 == 0 }+ }) else { throw PatcherError.patchSiteNotFound("Metal header padding is occupied") }+ cave = padding.lowerBound + UInt64(offset)+ }+ let program = try trampoline(at: cave, returningTo: site.address + 4, valueRegister: site.valueRegister)+ guard let branch = ARM64Encoder.encodeB(from: Int(site.address), to: Int(cave)) else {+ throw PatcherError.patchVerificationFailed("Metal format trampoline is out of branch range")+ }+ if site.existingCave != nil, try read(cave, caveSize) != program {+ throw PatcherError.patchVerificationFailed("Metal format trampoline differs from this patch's output")+ }+ return Plan(site: site, cave: cave, branch: branch, program: program)+ }++ // MARK: - Code generation++ static func trampoline(at cave: UInt64, returningTo resume: UInt64, valueRegister: UInt32) throws -> Data {+ guard (19 ... 28).contains(valueRegister), let base = Int(exactly: cave), let end = Int(exactly: resume),+ let subtract43 = ARM64Encoder.encodeSubImm12(rd: 9, rn: 0, imm12: 43),+ let equal43 = ARM64Encoder.encodeCompareBranch(nonzero: false, register: 9, from: base + 4, to: base + 16, width64: true),+ let subtract1 = ARM64Encoder.encodeSubImm12(rd: 9, rn: 9, imm12: 1),+ let unequal44 = ARM64Encoder.encodeCompareBranch(nonzero: true, register: 9, from: base + 12, to: base + 24, width64: true),+ let uintFormat = ARM64Encoder.encodeMovzX(rd: valueRegister, imm16: 36),+ let normalizedReturn = ARM64Encoder.encodeB(from: base + 20, to: end),+ let originalReturn = ARM64Encoder.encodeB(from: base + 28, to: end)+ else { throw PatcherError.patchVerificationFailed("Cannot encode Metal vertex format trampoline") }+ // x9 is caller-saved and dead immediately after the ObjC getter. x0,+ // LR, stack and NZCV survive unchanged. Full-width comparisons leave+ // every value except exactly 43 and 44 untouched, including high bits.+ return subtract43 + equal43 + subtract1 + unequal44 + uintFormat + normalizedReturn+ + ARM64Encoder.encodeMovX(rd: valueRegister, rm: 0) + originalReturn+ }++ private static func hex(_ value: UInt64) -> String { String(value, radix: 16) }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swiftindex 8e9cd3bf..cde53cc0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestPatchResolution.swift@@ -22,6 +22,30 @@ import Foundationimport VPhonePatchKitpublic enum FirmwareGuestPatchResolution {+ /// CoreFSCache's original reuse flag also bypasses the compiler key.+ /// Versioning the driver cannot invalidate stale output unless that key+ /// check is retained, or cross-boot reuse is turned off altogether.+ public static func missingCompilerCacheDependencies(enabled: Set<String>, applied: Set<String>? = nil) -> [String] {+ guard enabled.contains(FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache),+ enabled.contains(FirmwareGuestSystemPatchSet.metalCacheReuse),+ !(applied ?? enabled).contains(FirmwareGuestSystemPatchSet.metalCacheReuseKey)+ else { return [] }+ return [FirmwareGuestSystemPatchSet.metalCacheReuseKey]+ }++ public static let glesPrimitiveRestartDependencies: Set<String> = [+ FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart,+ FirmwareGuestSystemPatchSet.metalVertexIDFormat,+ ]++ /// The primitive-buffer fallback still uses the driver's render-state+ /// setup and private builtin vertex formats. Reject an incomplete choice+ /// before mounting or writing the guest; opting out remains unrestricted.+ public static func missingGLESPrimitiveRestartDependencies(enabled: Set<String>) -> [String] {+ guard enabled.contains(FirmwareGuestSystemPatchSet.glesPrimitiveRestart) else { return [] }+ return glesPrimitiveRestartDependencies.subtracting(enabled).sorted()+ }+/// TV admits the gigalocker repair, opt-in dyld TPRO compatibility, virtual/// Bluetooth, and vphoned with the launchd cache gate its launchd.plist entry needs./// Other payloads, cache patches and shell integration need a TV port anddiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swiftindex 42d7d0a7..e13dc4c1 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareGuestSystemPatchSet.swift@@ -27,6 +27,12 @@ public enum FirmwareGuestSystemPatchSet {public static let ios17Desktop = "system-springboard-exp-ios17_desktop"public static let metalCacheReuse = "system-systemhook-cfw-metal_cache_reuse"public static let metalCacheReuseMarker = "/usr/lib/vphone-metal-cache-reuse"+ public static let glesUpperLeft = "system-systemhook-cfw-gles_upper_left"+ public static let glesUpperLeftMarker = "/usr/lib/vphone-gles-upper-left"+ public static let metalVertexIDFormat = "dyld-cfw-metal_vertex_id_format"+ public static let glesPrimitiveRestart = "dyld-cfw-gles_primitive_restart"+ public static let glesPointDraw = "dyld-cfw-gles_point_draw"+ public static let metalCacheReuseKey = "dyld-cfw-metal_cache_reuse_key"public static let gyroscope = "system-backboardd-cfw-gyroscope"public static let accelerometer = "system-backboardd-cfw-accelerometer"public static let hinge = "system-backboardd-cfw-hinge"@@ -47,6 +53,7 @@ public enum FirmwareGuestSystemPatchSet {public static let paravirtGPUIndexOffset = "system-paravirt_gpu-cfw-heap_index_offset"public static let paravirtGPUPrimitiveRestart = "system-paravirt_gpu-cfw-primitive_restart"+ public static let paravirtGPUCompilerCache = "system-paravirt_gpu-cfw-compiler_cache"public static let paravirtGPUDriverPath ="System/Library/Extensions/AppleParavirtGPUMetalIOGPUFamily.bundle/AppleParavirtGPUMetalIOGPUFamily"@@ -245,6 +252,66 @@ public enum FirmwareGuestSystemPatchSet {// MARK: Shared Cache Policy+ VPhonePatchDeclaration(+ identifier: metalCacheReuseKey,+ title: "Metal cache version validation",+ summary: """+ Keeps the cache-key check when FS_CACHE_REUSE_ON_REBOOT permits reuse across \+ boots. A compiler identity change still invalidates old shader output; \+ cache reuse with the same identity and the opt-out path remain intact.+ """,+ target: .dyldSharedCache,+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),+ VPhonePatchDeclaration(+ identifier: glesPointDraw,+ title: "GLES point draw submission",+ summary: """+ Keeps valid point draws from being discarded because the paravirtual device \+ reports no pipeline usage flags. The vertex shader's point-size output \+ continues to determine rasterization. Changes only the four reflected \+ point-size checks in AppleMetalGLRenderer; other draw guards remain active.+ """,+ target: .dyldSharedCache,+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),+ VPhonePatchDeclaration(+ identifier: glesPrimitiveRestart,+ title: "GLES primitive restart semantics",+ summary: """+ Expands indexed line and triangle strips through GLEngine when primitive \+ restart is disabled, so a valid maximum index is not discarded by Metal. \+ Restart-enabled and other draws retain their normal renderer path. Requires \+ the paravirtual GPU restart-command suppression and GLES vertex ID format \+ correction. The fallback copies vertex data on the CPU.+ """,+ target: .dyldSharedCache,+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),+ VPhonePatchDeclaration(+ identifier: metalVertexIDFormat,+ title: "GLES vertex ID format",+ summary: """+ Serializes Metal's legacy vertex and instance ID attribute formats as UInt \+ for the paravirtual GPU. The original private formats make the host compiler \+ fail while cloning the vertex descriptor. Other attribute formats, the \+ original descriptor and shader code are unchanged.+ """,+ target: .dyldSharedCache,+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),VPhonePatchDeclaration(identifier: "dyld-boot-maxslide",title: "Shared cache max slide",@@ -436,6 +503,21 @@ public enum FirmwareGuestSystemPatchSet {""",target: .guestFile(path: metalCacheReuseMarker),),+ VPhonePatchDeclaration(+ identifier: glesUpperLeft,+ title: "GLES drawable orientation",+ summary: """+ Selects AppleMetalGLRenderer's UPPER_LEFT viewport and scissor path at \+ process startup because the paravirtual GPU does not preserve IOSurface \+ attachment yInvert, which reverses GLES screen output. An explicit \+ environment setting takes precedence. Validated on iOS 26.6 with cloudOS 26.4.+ """,+ target: .guestFile(path: glesUpperLeftMarker),+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),// MARK: Guest Payload@@ -476,6 +558,21 @@ public enum FirmwareGuestSystemPatchSet {target: .guestExecutable(path: "/\(paravirtGPUDriverPath)"),applicability: VPhonePatchApplicability(cloudOS: .release(major: 26, minor: 4)),),+ VPhonePatchDeclaration(+ identifier: paravirtGPUCompilerCache,+ title: "GPU compiler cache identity",+ summary: """+ Derives the paravirtual GPU shader-cache namespace from the installed compiler \+ plugin, so a plugin update compiles fresh shaders while unchanged plugins keep \+ their warm cache. Replaces only the compiler identity seed used by setupCompiler; \+ existing caches are retained.+ """,+ target: .guestExecutable(path: "/\(paravirtGPUDriverPath)"),+ applicability: VPhonePatchApplicability(+ iOSBase: .release(major: 26, minor: 6),+ cloudOS: .release(major: 26, minor: 4),+ ),+ ),VPhonePatchDeclaration(identifier: "system-vphoned-boot-install",title: "vphoned",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 964e7621..127c5751 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -241,6 +241,10 @@ public enum FirmwarePatchSetCatalog {/// plain-arm64 HD cannot load it), debugserver, the environment hooks, and/// the iPhone 19 ARM64E_X1 boot path.public static let tvOSBlockedPatches: Set<String> = [+ FirmwareGuestSystemPatchSet.metalCacheReuseKey,+ FirmwareGuestSystemPatchSet.glesPointDraw,+ FirmwareGuestSystemPatchSet.glesPrimitiveRestart,+ FirmwareGuestSystemPatchSet.metalVertexIDFormat,paravirtTask3Patch,paravirtGLESPatch,FirmwareGuestSystemPatchSet.arm64eX1CacheBootstrap,@@ -287,6 +291,8 @@ public enum FirmwarePatchSetCatalog {FirmwareGuestSystemPatchSet.arm64eX1MountBootstrap,"system-paravirt_gpu-cfw-heap_index_offset","system-paravirt_gpu-cfw-primitive_restart",+ FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache,+ FirmwareGuestSystemPatchSet.glesUpperLeft,"system-systemhook-cfw-metal_cache_reuse","system-systemversion-cfw-build_version","system-virtiosound-cfw-hal_plugin",diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUCompilerCacheTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUCompilerCacheTests.swiftnew file mode 100644index 00000000..fc7a3086--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareParavirtGPUCompilerCacheTests.swift@@ -0,0 +1,288 @@+// The fixture is a synthetic Mach-O with relative Objective-C methods, selector+// references, import stubs and the SHA-256 argument flow. No Apple binary is+// bundled; real-driver acceptance is checked separately against an extracted+// input without writing back to that input.++import CryptoKit+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++private typealias CachePatcher = CustomFirmwareParavirtGPUCompilerCache++private struct CompilerCacheDriver {+ static let base: UInt64 = 0x1_0000_0000+ static let text = 0x400+ static let seeds = [0x1000, 0x100C]+ static let methods = 0x1100+ static let names = 0x1200+ static let objcStub = 0x1400+ static let imports = 0x1500+ static let refs = 0x1800+ static let symbols = 0x1900+ static let symbolStrings = 0x1A00+ static let indirect = 0x1B00+ static let textCommand = 32+ static let textCommandSize = 72 + 6 * 80+ static let dataCommand = textCommand + textCommandSize+ static let symtabCommand = dataCommand + 72 + 80+ static let dysymtabCommand = symtabCommand + 24+ static let firstSection = textCommand + 72+ var data = Data(count: 0x2000)++ init() throws {+ put(0xFEED_FACF, at: 0)+ put(0x0100_000C, at: 4)+ put(2, at: 8) // arm64e+ put(8, at: 12) // MH_BUNDLE+ put(4, at: 16)+ put(UInt32(Self.dysymtabCommand + 80 - 32), at: 20)+ segment(at: Self.textCommand, name: "__TEXT", fileOffset: 0, size: 0x1800, sections: 6)+ section(0, name: "__text", offset: Self.text, size: 0x400)+ section(1, name: "__cstring", offset: Self.seeds[0], size: 0x40)+ section(2, name: "__objc_methlist", offset: Self.methods, size: 24)+ section(3, name: "__objc_methname", offset: Self.names, size: 0x100)+ section(4, name: "__objc_stubs", offset: Self.objcStub, size: 0x20)+ section(5, name: "__auth_stubs", offset: Self.imports, size: 0x30, flags: 8)+ put(16, at: Self.firstSection + 5 * 80 + 72) // reserved2: stub size+ segment(at: Self.dataCommand, name: "__DATA_CONST", fileOffset: Self.refs, size: 16, sections: 1)+ section(0, name: "__objc_selrefs", offset: Self.refs, size: 16, command: Self.dataCommand, segment: "__DATA_CONST")+ put(2, at: Self.symtabCommand)+ put(24, at: Self.symtabCommand + 4)+ put(UInt32(Self.symbols), at: Self.symtabCommand + 8)+ put(3, at: Self.symtabCommand + 12)+ put(UInt32(Self.symbolStrings), at: Self.symtabCommand + 16)+ put(0x100, at: Self.symtabCommand + 20)+ put(0xB, at: Self.dysymtabCommand)+ put(80, at: Self.dysymtabCommand + 4)+ put(UInt32(Self.indirect), at: Self.dysymtabCommand + 56)+ put(3, at: Self.dysymtabCommand + 60)+ var stringOffset = 1+ for (index, name) in ["_CC_SHA256_Init", "_CC_SHA256_Update", "_CC_SHA256_Final"].enumerated() {+ put(UInt32(stringOffset), at: Self.symbols + index * 16)+ data[Self.symbols + index * 16 + 4] = 1 // N_UNDF | N_EXT+ putString(name, at: Self.symbolStrings + stringOffset)+ put(UInt32(index), at: Self.indirect + index * 4)+ stringOffset += name.utf8.count + 1+ }+ putString("Feb 4 2026", at: Self.seeds[0])+ putString("23:05:00", at: Self.seeds[1])+ putString(CachePatcher.selector, at: Self.names)+ let initializerName = Self.names + CachePatcher.selector.utf8.count + 1+ putString(CachePatcher.compilerSelector, at: initializerName)+ put64(Self.base + UInt64(Self.names), at: Self.refs)+ put64(Self.base + UInt64(initializerName), at: Self.refs + 8)+ methodList(at: Self.methods, implementation: Self.text)+ for offset in stride(from: Self.text, to: Self.text + 0x400, by: 4) { write(ARM64.nop, at: offset) }+ let instructions: [Data?] = [+ ARM64.pacibsp,+ ARM64Encoder.encodeSubImm12(rd: 31, rn: 31, imm12: 0xE0),+ ARM64Encoder.encodeAddImm12(rd: 29, rn: 31, imm12: 0xD0),+ ARM64Encoder.encodeAddImm12(rd: 0, rn: 31, imm12: 8),+ branch(4, target: Self.imports),+ page(5, register: 1, target: Self.seeds[0]),+ ARM64Encoder.encodeAddImm12(rd: 1, rn: 1, imm12: UInt32(Self.seeds[0] & 0xFFF)),+ ARM64Encoder.encodeAddImm12(rd: 0, rn: 31, imm12: 8),+ ARM64Encoder.encodeMovzW(rd: 2, imm16: 8),+ branch(9, target: Self.imports + 16),+ page(10, register: 1, target: Self.seeds[1]),+ ARM64Encoder.encodeAddImm12(rd: 1, rn: 1, imm12: UInt32(Self.seeds[1] & 0xFFF)),+ ARM64Encoder.encodeAddImm12(rd: 0, rn: 31, imm12: 8),+ ARM64Encoder.encodeMovzW(rd: 2, imm16: 8),+ branch(14, target: Self.imports + 16),+ ARM64Encoder.encodeSubImm12(rd: 0, rn: 29, imm12: 0x50),+ ARM64Encoder.encodeAddImm12(rd: 1, rn: 31, imm12: 8),+ branch(17, target: Self.imports + 32),+ ARM64.nop,+ ARM64Encoder.encodeSubImm12(rd: 3, rn: 29, imm12: 0x50),+ ARM64Encoder.encodeMovX(rd: 2, rm: 22),+ ARM64Encoder.encodeMovX(rd: 4, rm: 21),+ ARM64Encoder.encodeMovX(rd: 5, rm: 19),+ ARM64Encoder.encodeMovzW(rd: 6, imm16: 0x24),+ branch(24, target: Self.objcStub),+ ARM64.retab,+ ]+ for (index, instruction) in instructions.enumerated() {+ write(try #require(instruction), at: Self.text + index * 4)+ }+ write(try #require(ARM64Encoder.encodeADRP(rd: 1, pc: Self.base + UInt64(Self.objcStub), target: Self.base + UInt64(Self.refs + 8))), at: Self.objcStub)+ write(try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 1, rn: 1, offset: UInt32((Self.refs + 8) & 0xFFF))), at: Self.objcStub + 4)+ }++ func branch(_ index: Int, target: Int) -> Data? {+ ARM64Encoder.encodeBL(from: Self.text + index * 4, to: target)+ }++ func page(_ index: Int, register: UInt32, target: Int) -> Data? {+ ARM64Encoder.encodeADRP(rd: register, pc: Self.base + UInt64(Self.text + index * 4), target: Self.base + UInt64(target))+ }++ mutating func instruction(_ index: Int, _ bytes: Data?) throws {+ write(try #require(bytes), at: Self.text + index * 4)+ }++ mutating func segment(at command: Int, name: String, fileOffset: Int, size: Int, sections: Int) {+ put(0x19, at: command)+ put(UInt32(72 + sections * 80), at: command + 4)+ putString(name, at: command + 8)+ put64(Self.base + UInt64(fileOffset), at: command + 24)+ put64(UInt64(size), at: command + 32)+ put64(UInt64(fileOffset), at: command + 40)+ put64(UInt64(size), at: command + 48)+ put(UInt32(sections), at: command + 64)+ }++ mutating func section(_ index: Int, name: String, offset: Int, size: Int, flags: UInt32 = 0, command: Int = Self.textCommand, segment: String = "__TEXT") {+ let entry = command + 72 + index * 80+ putString(name, at: entry)+ putString(segment, at: entry + 16)+ put64(Self.base + UInt64(offset), at: entry + 32)+ put64(UInt64(size), at: entry + 40)+ put(UInt32(offset), at: entry + 48)+ put(flags, at: entry + 64)+ }++ mutating func methodList(at offset: Int, implementation: Int) {+ put(0x8000_000C, at: offset)+ put(1, at: offset + 4)+ put(UInt32(bitPattern: Int32(Self.refs - (offset + 8))), at: offset + 8)+ put(UInt32(bitPattern: Int32(implementation - (offset + 16))), at: offset + 16)+ }++ mutating func put(_ value: UInt32, at offset: Int) { write(ARM64.encodeU32(value), at: offset) }+ mutating func put64(_ value: UInt64, at offset: Int) {+ put(UInt32(truncatingIfNeeded: value), at: offset)+ put(UInt32(truncatingIfNeeded: value >> 32), at: offset + 4)+ }+ mutating func putString(_ value: String, at offset: Int) { write(Data(value.utf8) + [0], at: offset) }+ mutating func write(_ bytes: Data, at offset: Int) { data.replaceSubrange(offset ..< offset + bytes.count, with: bytes) }+}++@Suite("Paravirtual GPU compiler cache identity")+struct CustomFirmwareParavirtGPUCompilerCacheTests {+ static let plugin = Data("compiler plugin build one".utf8)++ @Test func `Only the sixteen hash-input bytes change and the same plugin is idempotent`() throws {+ var fixture = try CompilerCacheDriver()+ let before = fixture.data+ let report = try CachePatcher.patch(&fixture.data, compilerPlugin: Self.plugin, log: nil)+ let expected = Data(SHA256.hash(data: Self.plugin).prefix(12)).base64EncodedString()+ #expect(report.state == .patched)+ #expect(report.identity == expected)+ #expect(report.identity.utf8.count == 16)+ #expect(report.sites.map(\.fileOffset) == CompilerCacheDriver.seeds)+ #expect(report.sites.reduce(into: Data()) { $0.append($1.after) } == Data(expected.utf8))+ let selected = Set(CompilerCacheDriver.seeds.flatMap { Array($0 ..< $0 + 8) })+ #expect(before.count == fixture.data.count)+ #expect(before.indices.filter { before[$0] != fixture.data[$0] }.count == 16)+ #expect(before.indices.allSatisfy { selected.contains($0) || before[$0] == fixture.data[$0] })+ let once = fixture.data+ let again = try CachePatcher.patch(&fixture.data, compilerPlugin: Self.plugin, log: nil)+ #expect(again.state == .alreadyPatched)+ #expect(again.sites.allSatisfy { $0.before == $0.after })+ #expect(fixture.data == once)+ }++ @Test func `Another plugin changes the identity and returning to the first restores its bytes`() throws {+ var fixture = try CompilerCacheDriver()+ let first = try CachePatcher.patch(&fixture.data, compilerPlugin: Self.plugin, log: nil)+ let firstBytes = fixture.data+ let second = try CachePatcher.patch(&fixture.data, compilerPlugin: Data("compiler plugin build two".utf8), log: nil)+ #expect(second.state == .patched)+ #expect(second.identity != first.identity)+ #expect(fixture.data != firstBytes)+ try CachePatcher.patch(&fixture.data, compilerPlugin: Self.plugin, log: nil)+ #expect(fixture.data == firstBytes)+ }++ @Test func `An empty plugin or malformed driver never changes the input`() throws {+ var valid = try CompilerCacheDriver().data+ let original = valid+ #expect(throws: PatcherError.self) { try CachePatcher.patch(&valid, compilerPlugin: Data(), log: nil) }+ #expect(valid == original)+ for size in [0, 1, 31, 32, 100, 0x1000] {+ var truncated = Data(original.prefix(size))+ let before = truncated+ #expect(throws: PatcherError.self) { try CachePatcher.patch(&truncated, compilerPlugin: Self.plugin, log: nil) }+ #expect(truncated == before)+ }+ }++ @Test(arguments: ["count", "flags", "duplicate", "outsideText", "noSelector", "noReference", "sectionBounds", "shortSelrefs"])+ func `Malformed or ambiguous Objective-C metadata refuses`(_ mutation: String) throws {+ var fixture = try CompilerCacheDriver()+ switch mutation {+ case "count": fixture.put(UInt32.max, at: CompilerCacheDriver.methods + 4)+ case "flags": fixture.put(0xC000_000C, at: CompilerCacheDriver.methods)+ case "duplicate":+ fixture.put64(48, at: CompilerCacheDriver.firstSection + 2 * 80 + 40)+ fixture.methodList(at: CompilerCacheDriver.methods + 24, implementation: CompilerCacheDriver.text + 0x100)+ case "outsideText": fixture.methodList(at: CompilerCacheDriver.methods, implementation: CompilerCacheDriver.seeds[0])+ case "noSelector": fixture.data[CompilerCacheDriver.names] = 0+ case "noReference": fixture.put64(0, at: CompilerCacheDriver.refs)+ case "sectionBounds": fixture.put64(UInt64.max, at: CompilerCacheDriver.firstSection + 2 * 80 + 40)+ case "shortSelrefs": fixture.put64(15, at: CompilerCacheDriver.dataCommand + 72 + 40)+ default: Issue.record("Unknown fixture mutation")+ }+ try refusedWithoutChanges(&fixture)+ }++ @Test(arguments: ["hashLength", "hashContext", "hashCall", "hashOutput", "cacheArgument", "argumentClobber", "middleOfStub", "noReturn", "secondFunction", "sharedLiteral", "sharedScheduledLiteral", "sharedLoad"])+ func `Changed hash semantics and shared literals refuse without mutation`(_ mutation: String) throws {+ var fixture = try CompilerCacheDriver()+ switch mutation {+ case "hashLength": try fixture.instruction(13, ARM64Encoder.encodeMovzW(rd: 2, imm16: 9))+ case "hashContext": try fixture.instruction(12, ARM64Encoder.encodeAddImm12(rd: 0, rn: 31, imm12: 16))+ case "hashCall": try fixture.instruction(14, fixture.branch(14, target: CompilerCacheDriver.imports))+ case "hashOutput": try fixture.instruction(15, ARM64Encoder.encodeSubImm12(rd: 0, rn: 29, imm12: 0x48))+ case "cacheArgument": try fixture.instruction(19, ARM64Encoder.encodeSubImm12(rd: 2, rn: 29, imm12: 0x50))+ case "argumentClobber": try fixture.instruction(23, ARM64Encoder.encodeMovzW(rd: 3, imm16: 0))+ case "middleOfStub": try fixture.instruction(9, fixture.branch(9, target: CompilerCacheDriver.imports + 20))+ case "noReturn": try fixture.instruction(25, ARM64.nop)+ case "secondFunction": try fixture.instruction(18, ARM64.pacibsp)+ case "sharedLiteral", "sharedScheduledLiteral", "sharedLoad":+ try fixture.instruction(32, fixture.page(32, register: 8, target: CompilerCacheDriver.seeds[0]))+ if mutation == "sharedLoad" {+ try fixture.instruction(33, ARM64Encoder.encodeLdrBUnsignedOffset(rt: 9, rn: 8, offset: 0))+ } else {+ try fixture.instruction(mutation == "sharedLiteral" ? 33 : 34, ARM64Encoder.encodeAddImm12(rd: 8, rn: 8, imm12: 0))+ }+ default: Issue.record("Unknown fixture mutation")+ }+ try refusedWithoutChanges(&fixture)+ }++ private func refusedWithoutChanges(_ fixture: inout CompilerCacheDriver) throws {+ let original = fixture.data+ #expect(throws: PatcherError.self) { try CachePatcher.patch(&fixture.data, compilerPlugin: Self.plugin, log: nil) }+ #expect(fixture.data == original)+ }+}++@Suite("Mach-O branch symbol targets")+struct MachOSymbolTargetsTests {+ @Test func `Imports resolve only at stub starts`() throws {+ let fixture = try CompilerCacheDriver()+ let symbols = try #require(MachOSymbolTargets(data: fixture.data))+ #expect(symbols.importName(atStub: CompilerCacheDriver.base + UInt64(CompilerCacheDriver.imports + 16)) == "_CC_SHA256_Update")+ #expect(symbols.importName(atStub: CompilerCacheDriver.base + UInt64(CompilerCacheDriver.imports + 20)) == nil)+ }++ @Test(arguments: ["commandSize", "commandBounds", "sectionCount", "symbolCount", "strings", "indirect", "stubSize", "stubAddress"])+ func `Malformed load commands and tables refuse`(_ mutation: String) throws {+ var fixture = try CompilerCacheDriver()+ switch mutation {+ case "commandSize": fixture.put(1, at: CompilerCacheDriver.textCommand + 4)+ case "commandBounds": fixture.put(UInt32.max, at: 20)+ case "sectionCount": fixture.put(7, at: CompilerCacheDriver.textCommand + 64)+ case "symbolCount": fixture.put(UInt32.max, at: CompilerCacheDriver.symtabCommand + 12)+ case "strings": fixture.put(UInt32.max, at: CompilerCacheDriver.symtabCommand + 20)+ case "indirect": fixture.put(UInt32.max, at: CompilerCacheDriver.dysymtabCommand + 56)+ case "stubSize": fixture.put(0, at: CompilerCacheDriver.firstSection + 5 * 80 + 72)+ case "stubAddress": fixture.put64(UInt64.max - 1, at: CompilerCacheDriver.firstSection + 5 * 80 + 32)+ default: Issue.record("Unknown fixture mutation")+ }+ #expect(MachOSymbolTargets(data: fixture.data) == nil)+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swiftindex bb79a2b7..e30ab51b 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/CustomFirmware/CustomFirmwareWatchDogTests.swift@@ -105,7 +105,7 @@ enum WatchdogdFixture {/// calls" is measured against an independent count.static func sysctlCallSites(in data: Data) throws -> [UInt64] {let text = try text(in: data)- guard let symbols = CustomFirmwareWatchDogSymbolTargets(data: data) else {+ guard let symbols = MachOSymbolTargets(data: data) else {throw PatcherError.invalidFormat("fixture has no symbol table")}let start = Int(text.fileOffset)@@ -229,7 +229,7 @@ struct CustomFirmwareWatchDogAnchorTests {@Test(.enabled(if: WatchdogdFixture.hasWatchdogd))func `resolves the import through the indirect symbol table`() throws {let data = try Data(contentsOf: WatchdogdFixture.watchdogd)- let symbols = try #require(CustomFirmwareWatchDogSymbolTargets(data: data))+ let symbols = try #require(MachOSymbolTargets(data: data))let sites = try CustomFirmwareWatchDog.locateSites(in: data)let call = try #require(sites.first)diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPointDrawTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPointDrawTests.swiftnew file mode 100644index 00000000..5fa6d01d--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPointDrawTests.swift@@ -0,0 +1,238 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("GLES point draw guards")+struct DyldSharedCacheGLESPointDrawTests {+ typealias Patcher = DyldSharedCacheGLESPointDrawPatcher+ let directBase: UInt64 = 0x4000+ let primitiveBase: UInt64 = 0x8000+ let selector: UInt64 = 0x10000+ let draw: UInt64 = 0x11000+ let fields = Patcher.Fields(pipeline: 0x898, usage: 0x8a0, encoder: 0x10)+ let indexedDraw = Patcher.IndexedDrawFields(selector: 0xde8, imp: 0xdf0)++ func decode(_ bytes: Data, at address: UInt64) -> [ARM64Instruction] {+ ARM64Disassembler().disassemble(bytes, at: address)+ }++ func setter(_ fields: Patcher.Fields) throws -> Data {+ let instructions = [+ ARM64Encoder.encodeMovX(rd: 19, rm: 0),+ try #require(ARM64Encoder.encodeBL(from: 0x2004, to: 0x12000)),+ // A later saved return value must not be confused with `this`.+ ARM64Encoder.encodeMovX(rd: 20, rm: 0),+ try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 2, rn: 8, offset: 0)),+ try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 2, rn: 19, offset: UInt32(fields.pipeline))),+ try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 8, offset: 8)),+ try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 8, rn: 19, offset: UInt32(fields.usage))),+ try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: UInt32(fields.encoder))),+ try #require(ARM64Encoder.encodeBL(from: 0x2020, to: Int(selector))),+ try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 19, offset: UInt32(fields.usage))),+ ARM64.ret,+ ]+ return instructions.reduce(into: Data()) { $0 += $1 }+ }++ struct Fixture {+ var direct: Data+ var primitive: Data+ let directSites: [Int]+ let primitiveSite: Int+ }++ func fixture(fields: Patcher.Fields? = nil, mode: UInt32 = 0x178) throws -> Fixture {+ let fields = fields ?? self.fields+ func block(at start: Int, primitive: Bool, interveningLoads: Bool) throws -> (Data, Int) {+ // Preserve the two intervening index-buffer loads on the EBO path.+ let extra = interveningLoads ? 8 : 0+ let guardOffset = 20 + extra + (primitive ? 4 : 0)+ let end = start + guardOffset + 16+ var bytes = try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 19, offset: UInt32(fields.pipeline)))+ bytes += try #require(ARM64Encoder.encodeCompareBranch(nonzero: false, register: 8, from: start + 4, to: end, width64: true))+ if interveningLoads {+ bytes += try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 27, offset: 24))+ bytes += try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 27, rn: 8, offset: 0))+ }+ if primitive {+ bytes += try #require(ARM64Encoder.encodeTestBitBranch(nonzero: true, register: 22, bit: 0, from: start + bytes.count, to: end))+ }+ bytes += try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 19, offset: mode))+ bytes += try #require(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 0, from: start + bytes.count, to: start + guardOffset + 4))+ bytes += try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 19, offset: UInt32(fields.usage)))+ #expect(bytes.count == guardOffset)+ bytes += try #require(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 7, from: start + bytes.count, to: end))+ bytes += try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: UInt32(fields.encoder)))+ bytes += try #require(ARM64Encoder.encodeBL(from: start + bytes.count, to: Int(draw)))+ bytes += ARM64.nop+ bytes += ARM64.ret+ return (bytes, guardOffset)+ }+ // An early RET is deliberate: discovery must use the symbol span and+ // inspect the later draw paths, as the real direct callback requires.+ var direct = ARM64Encoder.encodeMovX(rd: 19, rm: 0) + ARM64.ret+ var directSites: [Int] = []+ for path in 0 ..< 3 {+ let start = direct.count+ let (bytes, site) = try block(at: Int(directBase) + start, primitive: false, interveningLoads: path == 1)+ directSites.append(start + site)+ direct += bytes+ }+ var primitive = ARM64Encoder.encodeMovX(rd: 19, rm: 0)+ let (bytes, site) = try block(at: Int(primitiveBase) + primitive.count, primitive: true, interveningLoads: false)+ let primitiveSite = primitive.count + site+ primitive += bytes+ return .init(direct: direct, primitive: primitive, directSites: directSites, primitiveSite: primitiveSite)+ }++ func plan(_ fixture: Fixture, fields: Patcher.Fields? = nil) throws -> Patcher.Plan {+ try Patcher.plan(direct: decode(fixture.direct, at: directBase), primitive: decode(fixture.primitive, at: primitiveBase),+ fields: fields ?? self.fields, indexedDraw: indexedDraw, drawTargets: [draw])+ }++ @Test func `derives context layout from the actual pipeline call`() throws {+ #expect(try Patcher.pipelineFields(in: decode(setter(fields), at: 0x2000), selector: selector) == fields)+ let relocated = Patcher.Fields(pipeline: 0x280, usage: 0x288, encoder: 0x28)+ #expect(try Patcher.pipelineFields(in: decode(setter(relocated), at: 0x2000), selector: selector) == relocated)+ #expect(try plan(fixture(fields: relocated, mode: 0x90), fields: relocated).sites.count == 4)+ var wrong = try setter(fields)+ wrong.replaceSubrange(12 ..< 16, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 3, rn: 8, offset: 0)))+ #expect(throws: (any Error).self) { try Patcher.pipelineFields(in: decode(wrong, at: 0x2000), selector: selector) }+ wrong = try setter(fields)+ wrong.replaceSubrange(36 ..< 40, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 19, offset: 0x900)))+ #expect(throws: (any Error).self) { try Patcher.pipelineFields(in: decode(wrong, at: 0x2000), selector: selector) }+ #expect(throws: (any Error).self) { try Patcher.pipelineFields(in: decode(setter(fields), at: 0x2000), selector: selector + 4) }+ }++ @Test func `uses the next symbol rather than an early return`() throws {+ let fixture = try fixture()+ let end = directBase + UInt64(fixture.direct.count)+ #expect(try Patcher.functionSpan(at: directBase, symbolAddresses: [directBase, directBase, end, end + 4]) == directBase ..< end)+ #expect(try plan(fixture).sites.count == 4)+ #expect(throws: (any Error).self) { try Patcher.functionSpan(at: directBase, symbolAddresses: [directBase]) }+ #expect(throws: (any Error).self) { try Patcher.functionSpan(at: directBase, symbolAddresses: [directBase + 65540]) }+ #expect(throws: (any Error).self) { try Patcher.functionSpan(at: directBase, symbolAddresses: [directBase + 3]) }+ let truncated = Fixture(direct: Data(fixture.direct.prefix(8)), primitive: fixture.primitive,+ directSites: [], primitiveSite: fixture.primitiveSite)+ #expect(throws: (any Error).self) { try plan(truncated) }+ }++ @Test func `derives indexed IMP slots from the named selector and method lookup`() throws {+ let lookup: UInt64 = 0x12000+ let literalAddress: UInt64 = 0x307b4+ let literal = Data((Patcher.indexedDrawSelector + "\0").utf8)+ func setup(_ slots: Patcher.IndexedDrawFields) throws -> Data {+ let instructions = [+ ARM64Encoder.encodeMovX(rd: 19, rm: 0),+ try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: UInt32(fields.encoder))),+ try #require(ARM64Encoder.encodeADRP(rd: 8, pc: 0x2008, target: literalAddress)),+ try #require(ARM64Encoder.encodeAddImm12(rd: 2, rn: 8, imm12: UInt32(literalAddress & 0xfff))),+ try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 2, rn: 19, offset: UInt32(slots.selector))),+ try #require(ARM64Encoder.encodeBL(from: 0x2014, to: Int(lookup))),+ try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 19, offset: UInt32(slots.imp))),+ ARM64.ret,+ ]+ return instructions.reduce(into: Data()) { $0 += $1 }+ }+ func discover(_ bytes: Data, text: Data? = nil) throws -> Patcher.IndexedDrawFields {+ try Patcher.indexedDrawFields(in: decode(bytes, at: 0x2000), fields: fields, methodForSelector: lookup) { address, count in+ #expect(address == literalAddress)+ #expect(count == literal.count)+ return text ?? literal+ }+ }+ #expect(try discover(setup(indexedDraw)) == indexedDraw)+ let relocated = Patcher.IndexedDrawFields(selector: 0x380, imp: 0x388)+ #expect(try discover(setup(relocated)) == relocated)+ // An equally shaped cached method with another selector is not a draw.+ #expect(throws: (any Error).self) { try discover(setup(indexedDraw), text: Data("setVertexBuffer:offset:atIndex:\0".utf8)) }+ #expect(throws: (any Error).self) { try discover(setup(indexedDraw), text: Data(literal.dropLast())) }+ let mutations: [(Int, Data)] = [+ (4, try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 0, rn: 19, offset: 0x28))),+ (12, try #require(ARM64Encoder.encodeAddImm12(rd: 3, rn: 8, imm12: UInt32(literalAddress & 0xfff)))),+ (20, try #require(ARM64Encoder.encodeBL(from: 0x2014, to: Int(lookup + 4)))),+ (24, try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 1, rn: 19, offset: UInt32(indexedDraw.imp)))),+ (24, try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 19, offset: UInt32(indexedDraw.imp + 8)))),+ ]+ for (offset, replacement) in mutations {+ var wrong = try setup(indexedDraw)+ wrong.replaceSubrange(offset ..< offset + 4, with: replacement)+ #expect(throws: (any Error).self) { try discover(wrong) }+ }+ }++ @Test func `requires all four original guards or all four exact NOPs`() throws {+ let original = try fixture()+ let initial = try plan(original)+ #expect(!initial.alreadyPatched)+ #expect(initial.sites.map(\.address) == original.directSites.map { directBase + UInt64($0) } + [primitiveBase + UInt64(original.primitiveSite)])+ for count in 1 ... 4 {+ var changed = original+ for site in original.directSites.prefix(count) { changed.direct.replaceSubrange(site ..< site + 4, with: ARM64.nop) }+ if count == 4 { changed.primitive.replaceSubrange(changed.primitiveSite ..< changed.primitiveSite + 4, with: ARM64.nop) }+ if count < 4 {+ #expect(throws: (any Error).self) { try plan(changed) }+ } else {+ #expect(try plan(changed).alreadyPatched)+ #expect(try plan(changed).sites.map(\.address) == initial.sites.map(\.address))+ }+ }+ }++ @Test func `refuses stale flags mode pipeline skip and draw shapes`() throws {+ let original = try fixture()+ let site = original.directSites[0]+ let address = Int(directBase) + site+ let skip = try #require(try plan(original).sites.first?.skip)+ let mutations: [(Int, Data)] = [+ (site, try #require(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 6, from: address, to: Int(skip)))),+ (site, try #require(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 7, from: address, to: Int(skip) - 4))),+ (site - 4, try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 19, offset: 0x900))),+ (site - 8, try #require(ARM64Encoder.encodeTestBitBranch(nonzero: false, register: 8, bit: 1, from: address - 8, to: address + 4))),+ (site - 12, try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 19, offset: 0x188))),+ (site - 20, try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 19, offset: 0x900))),+ (site + 8, ARM64.ret),+ ]+ for (offset, replacement) in mutations {+ var changed = original+ changed.direct.replaceSubrange(offset ..< offset + 4, with: replacement)+ #expect(throws: (any Error).self) { try plan(changed) }+ }+ var wrongPrimitive = original+ let gate = original.primitiveSite - 16+ wrongPrimitive.primitive.replaceSubrange(gate ..< gate + 4, with: ARM64.nop)+ #expect(throws: (any Error).self) { try plan(wrongPrimitive) }+ }++ @Test func `recognizes the real authenticated indexed draw call`() throws {+ // Frozen 23G90 input at renderer __TEXT + 0x145cc. This is the+ // existing call sequence, not generated replacement instructions.+ let words: [UInt32] = [+ 0xf9400a60, 0xd0000028, 0x9117e108, 0xf8765902,+ 0x93407ea3, 0xa94093e6, 0x93407e87, 0xf946fa68,+ 0xf946f661, 0xaa1703e5, 0xd63f091f,+ ]+ let bytes = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }+ #expect(Patcher.containsDraw(decode(bytes, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ var wrong = bytes+ wrong.replaceSubrange(32 ..< 36, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 1, rn: 20, offset: 0xde8)))+ #expect(!Patcher.containsDraw(decode(wrong, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ // A different adjacent selector/IMP pair can have exactly the same+ // calling shape; it must not satisfy this guard's draw proof.+ wrong = bytes+ wrong.replaceSubrange(28 ..< 32, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 19, offset: 0xde0)))+ wrong.replaceSubrange(32 ..< 36, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 1, rn: 19, offset: 0xdd8)))+ #expect(!Patcher.containsDraw(decode(wrong, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ wrong = bytes+ wrong.replaceSubrange(0 ..< 4, with: ARM64.nop)+ #expect(!Patcher.containsDraw(decode(wrong, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ // A call after an unconditional return is not a draw on this path.+ wrong = bytes+ wrong.replaceSubrange(4 ..< 8, with: ARM64.ret)+ #expect(!Patcher.containsDraw(decode(wrong, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ wrong = bytes+ wrong.replaceSubrange(16 ..< 20, with: ARM64Encoder.encodeMovX(rd: 0, rm: 19))+ #expect(!Patcher.containsDraw(decode(wrong, at: directBase), context: .x(19), fields: fields, indexedDraw: indexedDraw, drawTargets: []))+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPrimitiveRestartTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPrimitiveRestartTests.swiftnew file mode 100644index 00000000..32c3de2c--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheGLESPrimitiveRestartTests.swift@@ -0,0 +1,129 @@+@testable import FirmwarePatcher+import Darwin+import Foundation+import Testing+import VPhonePatchKit++@_silgen_name("sys_icache_invalidate")+private func invalidateGLESRestartTestCode(_ memory: UnsafeMutableRawPointer, _ count: Int)++@Suite("GLES primitive restart fallback")+struct DyldSharedCacheGLESPrimitiveRestartTests {+ typealias Patcher = DyldSharedCacheGLESPrimitiveRestartPatcher+ let entry: UInt64 = 0x2000++ // Original 23G90 renderer instructions, frozen as input evidence. Patch+ // replacements themselves are produced exclusively by ARM64Encoder.+ func entryFixture() -> Data {+ let words: [UInt32] = [+ 0xd503237f, 0xd10303ff, 0xa9066ffc, 0xa90767fa,+ 0xa9085ff8, 0xa90957f6, 0xa90a4ff4, 0xa90b7bfd,+ 0x9102c3fd, 0xf940c408, 0xb4000748, 0xaa0003f3,+ 0x9140041a, 0x394f6f49, 0x37003529, 0xaa0703f4,+ 0xaa0603f8, 0xaa0503f9, 0xaa0403f5, 0xaa0303f7,+ 0xaa0203f6, 0x3945e269, 0x721c093f, 0x54000060,+ ]+ return words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }+ }++ func stateFixture() -> Data {+ let words: [UInt32] = [+ 0xf9403408, 0x52878a89, 0x38696908, 0x7100011f,+ 0x1a9f07e8, 0x52827b89, 0x38296808, 0xb949a808,+ 0x32110108, 0xb909a808, 0xd65f03c0,+ ]+ return words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }+ }++ func decode(_ data: Data) -> [ARM64Instruction] { ARM64Disassembler().disassemble(data, at: entry) }++ @Test func `recovers actual fields and rejects stale layouts`() throws {+ let fields = try Patcher.stateFields(in: decode(stateFixture()))+ #expect(fields == .init(pointerOffset: 0x68, enabledOffset: 0x3c54))+ let site = try Patcher.findEntry(in: decode(entryFixture()))+ #expect(site.address == entry)+ #expect(site.existingCave == nil)++ var relocated = stateFixture()+ relocated.replaceSubrange(0 ..< 4, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 0, offset: 0x38)))+ relocated.replaceSubrange(4 ..< 8, with: try #require(ARM64Encoder.encodeMovzW(rd: 9, imm16: 0x2568)))+ #expect(try Patcher.stateFields(in: decode(relocated)) == .init(pointerOffset: 0x38, enabledOffset: 0x2568))+ var wrongBase = stateFixture()+ wrongBase.replaceSubrange(0 ..< 4, with: try #require(ARM64Encoder.encodeLdrXUnsignedOffset(rt: 8, rn: 1, offset: 0x68)))+ #expect(throws: (any Error).self) { try Patcher.stateFields(in: decode(wrongBase)) }+ var cachedInstead = stateFixture()+ cachedInstead.replaceSubrange(8 ..< 12, with: try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 8, rn: 0, offset: 0)))+ #expect(throws: (any Error).self) { try Patcher.stateFields(in: decode(cachedInstead)) }+ var wrongEntry = entryFixture()+ wrongEntry.replaceSubrange(0 ..< 4, with: ARM64.ret)+ #expect(throws: (any Error).self) { try Patcher.findEntry(in: decode(wrongEntry)) }+ wrongEntry = entryFixture()+ wrongEntry.replaceSubrange(20 * 4 ..< 21 * 4, with: ARM64.nop)+ #expect(throws: (any Error).self) { try Patcher.findEntry(in: decode(wrongEntry)) }+ }++ @Test func `admits only unused padding or its complete previous trampoline`() throws {+ let fields = try Patcher.stateFields(in: decode(stateFixture()))+ let site = try Patcher.findEntry(in: decode(entryFixture()))+ let padding: Range<UInt64> = 0x1000 ..< 0x1100+ var bytes = Data(repeating: 0, count: padding.count)+ bytes[0] = 1+ func read(_ at: UInt64, _ count: Int) -> Data {+ Data(bytes[Int(at - padding.lowerBound) ..< Int(at - padding.lowerBound) + count])+ }+ let plan = try Patcher.plan(site: site, fields: fields, padding: padding, read: read)+ #expect(plan.cave == 0x1004)+ #expect(plan.program.count == 68)+ #expect(!plan.alreadyPatched)+ bytes.replaceSubrange(4 ..< 4 + plan.program.count, with: plan.program)+ var patchedEntry = entryFixture()+ patchedEntry.replaceSubrange(0 ..< 4, with: plan.branch)+ let previous = try Patcher.findEntry(in: decode(patchedEntry))+ let again = try Patcher.plan(site: previous, fields: fields, padding: padding, read: read)+ #expect(again.alreadyPatched)+ #expect(again.program == plan.program)+ bytes[4] ^= 1+ #expect(throws: (any Error).self) { try Patcher.plan(site: previous, fields: fields, padding: padding, read: read) }+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: .init(address: entry, existingCave: 0x4000), fields: fields, padding: padding, read: read)+ }+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: site, fields: fields, padding: padding) { _, count in Data(repeating: 0xFF, count: count) }+ }+ }++ #if arch(arm64)+ @Test func `executes disabled indexed strip selection and authenticates both returns`() throws {+ // The original continuation returns 1; the new early fallback returns+ // 0. Execute real generated instructions for all primitive/flag/state+ // combinations, including noncanonical nonzero GLboolean values.+ let fields = Patcher.StateFields(pointerOffset: 0x18, enabledOffset: 0x2f)+ var code = try #require(ARM64Encoder.encodeB(from: 0, to: 0x100)) + ARM64.movW0_1 + ARM64.retab+ code += Data(repeating: 0, count: 0x100 - code.count)+ code += try Patcher.trampoline(at: 0x100, returningTo: 4, fields: fields)+ let memory = try #require(mmap(nil, 0x4000, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0))+ try #require(memory != MAP_FAILED)+ defer { munmap(memory, 0x4000) }+ code.copyBytes(to: memory.assumingMemoryBound(to: UInt8.self), count: code.count)+ try #require(mprotect(memory, 0x4000, PROT_READ | PROT_EXEC) == 0)+ invalidateGLESRestartTestCode(memory, code.count)+ typealias Function = @convention(c) (UnsafeMutableRawPointer, UInt32, UInt32) -> UInt32+ let run = unsafeBitCast(memory, to: Function.self)+ let context = UnsafeMutableRawPointer.allocate(byteCount: 64, alignment: 8)+ let state = UnsafeMutableRawPointer.allocate(byteCount: 64, alignment: 8)+ defer { context.deallocate(); state.deallocate() }+ context.initializeMemory(as: UInt8.self, repeating: 0, count: 64)+ state.initializeMemory(as: UInt8.self, repeating: 0, count: 64)+ context.storeBytes(of: state, toByteOffset: Int(fields.pointerOffset), as: UnsafeMutableRawPointer.self)+ for enabled: UInt8 in [0, 1, 2, 255] {+ state.storeBytes(of: enabled, toByteOffset: Int(fields.enabledOffset), as: UInt8.self)+ for flags: UInt32 in [0, 1, 2, 3, 4, .max] {+ for mode: UInt32 in Array(0 ... 6) + [.max] {+ let fallback = enabled == 0 && [1, 3].contains(flags) && [3, 5].contains(mode)+ #expect(run(context, flags, mode) == (fallback ? 0 : 1))+ }+ }+ }+ }+ #endif+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalCacheReuseTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalCacheReuseTests.swiftnew file mode 100644index 00000000..156a7fcb--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalCacheReuseTests.swift@@ -0,0 +1,170 @@+@testable import FirmwarePatcher+import Foundation+import Testing+import VPhonePatchKit++@Suite("Metal cache reboot reuse preserves the client key")+struct DyldSharedCacheMetalCacheReuseTests {+ typealias Patcher = DyldSharedCacheMetalCacheReusePatcher+ let base: UInt64 = 0x1000+ let thirdParty: UInt64 = 0x3000+ let comparison: UInt64 = 0x3100+ let stackFailure: UInt64 = 0x3200+ let literal: UInt64 = 0x5000+ let siteOffset = 0xc8++ // Entire verify_list_file from libCoreFSCache, iOS 26.6.2 (23G90).+ // Relocate calls and the environment literal; retain the actual multiple+ // return/control-flow layout, stack canary and ABI register save/restore.+ func fixture() throws -> Data {+ let words: [UInt32] = [+ 0xd503237f, 0xd10303ff, 0xa9085ff8, 0xa90957f6,+ 0xa90a4ff4, 0xa90b7bfd, 0x9102c3fd, 0xaa0303f4,+ 0xaa0203f3, 0xaa0103f5, 0xaa0003f6, 0x901bc1e8,+ 0xf9424108, 0xf9400108, 0xf81c83a8, 0xb9000fff,+ 0x94097a37, 0x910033e0, 0x52800021, 0x52800082,+ 0xaa1603e3, 0x940979d6, 0xaa0003e8, 0x52800000,+ 0xb9400fe9, 0xf100111f, 0x5286c8a8, 0x72a304e8,+ 0x7a480120, 0x540003e1, 0xf9003bff, 0x6f00e400,+ 0xad0283e0, 0xad0183e0, 0xad0083e0, 0x910043e0,+ 0x52800021, 0x52800d02, 0xaa1603e3, 0x940979c4,+ 0xf101a01f, 0x54000241, 0x90000020, 0x91388c00,+ 0x940979e3, 0xb40000c0, 0x39400017, 0x97fffb29,+ 0x7100c6ff, 0x54000061, 0x1400001c, 0x97fffb25,+ 0xaa0003f6, 0x910043e8, 0x910102a0, 0x91010101,+ 0x52800402, 0x94000f9f, 0x340001c0, 0x52800000,+ 0xf85c83a8, 0x901bc1e9, 0xf9424129, 0xf9400129,+ 0xeb08013f, 0x54000401, 0xa94b7bfd, 0xa94a4ff4,+ 0xa94957f6, 0xa9485ff8, 0x910303ff, 0xd65f0fff,+ 0x370000d6, 0x910043e1, 0xaa1503e0, 0x52800802,+ 0x94000f8c, 0x35fffdc0, 0xb98073e8, 0xd37ae509,+ 0xcb080d28, 0x9101b115, 0xeb15027f, 0x54000142,+ 0x901bc1e0, 0xf9447800, 0x52800201, 0x940979e0,+ 0x34fffc80, 0xaa1503e0, 0xaa1303e1, 0x94000e5e,+ 0x17ffffdf, 0x9101a108, 0xf9000288, 0x52800020,+ 0x17ffffdc, 0x94097946,+ ]+ var bytes = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }+ for offset in [0xbc, 0xcc] { put(try #require(ARM64Encoder.encodeBL(from: Int(base) + offset, to: Int(thirdParty))), in: &bytes, at: offset) }+ for offset in [0xe4, 0x130] { put(try #require(ARM64Encoder.encodeBL(from: Int(base) + offset, to: Int(comparison))), in: &bytes, at: offset) }+ put(try #require(ARM64Encoder.encodeBL(from: Int(base) + 0x184, to: Int(stackFailure))), in: &bytes, at: 0x184)+ put(try #require(ARM64Encoder.encodeADRP(rd: 0, pc: base + 0xa8, target: literal)), in: &bytes, at: 0xa8)+ put(try #require(ARM64Encoder.encodeAddImm12(rd: 0, rn: 0, imm12: 0)), in: &bytes, at: 0xac)+ return bytes+ }++ func put(_ instruction: Data, in bytes: inout Data, at offset: Int) {+ bytes.replaceSubrange(offset ..< offset + instruction.count, with: instruction)+ }++ func site(_ bytes: Data, environment: Data = Patcher.environment) throws -> Patcher.Site {+ try Patcher.findSite(in: ARM64Disassembler().disassemble(bytes, at: base), thirdParty: thirdParty, stackFailure: stackFailure) { address, count in+ if address != literal { return Data(repeating: 0, count: count) }+ #expect(address == literal)+ #expect(count == Patcher.environment.count)+ return environment+ }+ }++ @Test func `whole function reveals the environment branch and both identity checks`() throws {+ let found = try site(fixture())+ #expect(found.address == base + UInt64(siteOffset))+ #expect(found.resume == base + 0xd4)+ #expect(found.flagRegister == 22)+ #expect(found.existingCave == nil)+ // verify_list_file returns before its boot comparison and success+ // block; truncating disassembly at that first return is insufficient.+ #expect(throws: (any Error).self) { try site(Data(try fixture().prefix(0x120))) }+ let code = ARM64Disassembler().disassemble(try fixture(), at: base)+ #expect(throws: (any Error).self) {+ try Patcher.findSite(in: code + code, thirdParty: thirdParty, stackFailure: stackFailure) { _, _ in Patcher.environment }+ }+ #expect(throws: (any Error).self) { try site(fixture(), environment: Data("FS_CACHE_REUSE_ON_REBOOTX".utf8)) }+ }++ @Test func `rejects changed environment key boot and saved-register dataflow`() throws {+ let edits: [(Int, Data)] = [+ (0xc0, try #require(ARM64Encoder.encodeCmpWImmediate(rn: 23, imm12: 48))), // env '0'+ (0xb8, try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 0, rn: 0, offset: 0))),+ (0xcc, try #require(ARM64Encoder.encodeBL(from: Int(base) + 0xcc, to: 0x3300))),+ (0xd8, try #require(ARM64Encoder.encodeAddImm12(rd: 0, rn: 21, imm12: 32))),+ (0xe0, try #require(ARM64Encoder.encodeMovzW(rd: 2, imm16: 64))),+ (0x12c, try #require(ARM64Encoder.encodeMovzW(rd: 2, imm16: 32))),+ (0x130, try #require(ARM64Encoder.encodeBL(from: Int(base) + 0x130, to: 0x3300))),+ (0x120, try #require(ARM64Encoder.encodeTestBitBranch(nonzero: true, register: 23, bit: 0, from: Int(base) + 0x120, to: Int(base) + 0x138))),+ (0x138, ARM64Encoder.encodeMovX(rd: 8, rm: 22)), // live read on success+ (0x140, ARM64Encoder.encodeMovX(rd: 22, rm: 8)), // flag redefinition+ (0x110, ARM64.nop), // missing restore+ (0x0c, ARM64.nop), // missing original save+ (0x40, ARM64Encoder.encodeMovX(rd: 21, rm: 2)), // saved client key clobbered+ (0x104, ARM64.ret), // early return skips restoration+ (0x180, try #require(ARM64Encoder.encodeB(from: Int(base) + 0x180, to: 0x9000))),+ (0x184, try #require(ARM64Encoder.encodeBL(from: Int(base) + 0x184, to: 0x9000))),+ ]+ for (offset, instruction) in edits {+ var bytes = try fixture()+ put(instruction, in: &bytes, at: offset)+ #expect(throws: (any Error).self) { try site(bytes) }+ }+ var callerSavedCharacter = try fixture()+ put(try #require(ARM64Encoder.encodeLdrBUnsignedOffset(rt: 0, rn: 0, offset: 0)), in: &callerSavedCharacter, at: 0xb8)+ put(try #require(ARM64Encoder.encodeCmpWImmediate(rn: 0, imm12: 49)), in: &callerSavedCharacter, at: 0xc0)+ #expect(throws: (any Error).self) { try site(callerSavedCharacter) }+ }++ @Test func `terminal no-return exception resolves the actual stack failure through its island`() throws {+ let island: UInt64 = 0x7000+ let resolved: UInt64 = 0x9124+ // BR x16 is frozen from the cache-builder island inspected alongside+ // verify_list_file. The relocation-dependent words use the encoder.+ let program = try #require(ARM64Encoder.encodeADRP(rd: 16, pc: island, target: resolved))+ + #require(ARM64Encoder.encodeAddImm12(rd: 16, rn: 16, imm12: UInt32(resolved & 0xfff)))+ + ARM64.encodeU32(0xd61f0200)+ let accepted = try Patcher.isStackFailure(island, resolved: resolved) { at, count in+ #expect(at == island)+ #expect(count == 12)+ return program+ }+ #expect(accepted)+ #expect(try !Patcher.isStackFailure(island, resolved: resolved + 4) { _, _ in program })+ #expect(try !Patcher.isStackFailure(island, resolved: resolved) { _, _ in Data(program.prefix(8)) + ARM64.ret })+ }++ @Test func `plans an eight byte cave and verifies exact complete prior output`() throws {+ let original = try fixture()+ let found = try site(original)+ let padding: Range<UInt64> = 0x800 ..< 0x840+ var bytes = Data(repeating: 0, count: padding.count)+ bytes[0] = 1+ func read(_ at: UInt64, _ count: Int) -> Data {+ Data(bytes[Int(at - padding.lowerBound) ..< Int(at - padding.lowerBound) + count])+ }+ let first = try Patcher.plan(site: found, padding: padding, read: read)+ #expect(first.cave == 0x804)+ #expect(first.program.count == 8)+ #expect(!first.alreadyPatched)+ let program = ARM64Disassembler().disassemble(first.program, at: first.cave)+ #expect(Patcher.immediateMove(program[0], .w(22), 1))+ #expect(Patcher.branch(program[1], "b") == found.resume)+ var patched = original+ put(first.branch, in: &patched, at: siteOffset)+ let patchedSite = try site(patched)+ #expect(patchedSite.existingCave == first.cave)+ #expect(throws: (any Error).self) { try Patcher.plan(site: patchedSite, padding: padding, read: read) }+ bytes.replaceSubrange(4 ..< 12, with: first.program)+ #expect(throws: (any Error).self) { try Patcher.plan(site: found, padding: padding, read: read) }+ let again = try Patcher.plan(site: patchedSite, padding: padding, read: read)+ #expect(again.alreadyPatched)+ #expect(again.program == first.program)+ bytes[8] ^= 1+ #expect(throws: (any Error).self) { try Patcher.plan(site: patchedSite, padding: padding, read: read) }+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: found, padding: padding) { _, count in Data(repeating: 0xff, count: count) }+ }+ for destination: UInt64 in [0x802, 0x83c, 0x1000, 0x9000] {+ let foreign = Patcher.Site(address: found.address, resume: found.resume, flagRegister: found.flagRegister, existingCave: destination)+ #expect(throws: (any Error).self) { try Patcher.plan(site: foreign, padding: padding, read: read) }+ }+ #expect(throws: (any Error).self) { try Patcher.trampoline(at: 0x800, returningTo: 0x1000, flagRegister: 18) }+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalVertexFormatTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalVertexFormatTests.swiftnew file mode 100644index 00000000..9cdb49e3--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheMetalVertexFormatTests.swift@@ -0,0 +1,289 @@+@testable import FirmwarePatcher+import CryptoKit+import Darwin+import Foundation+import Testing+import VPhonePatchKit++@_silgen_name("sys_icache_invalidate")+private func invalidateMetalVertexFormatTestCode(_ memory: UnsafeMutableRawPointer, _ count: Int)++@Suite("Metal serialized vertex ID formats")+struct DyldSharedCacheMetalVertexFormatTests {+ typealias Patcher = DyldSharedCacheMetalVertexFormatPatcher+ let base: UInt64 = 0x1000+ let formatStub: UInt64 = 0x3000++ /// Frozen from Metal in iOS 26.6.2 (23G90), serializer property 1. Only+ /// the BL displacements are relocated by the fixture. These words include+ /// the real authenticated C++ serializer dispatch, not a mock getter.+ func fixture() throws -> Data {+ let words: [UInt32] = [+ 0xaa1803e0, 0x9408dea3, 0xaa0003fa, 0xaa1903e0,+ 0x9408dea0, 0xaa0003e3, 0xf94002f0, 0xdac11b70,+ 0xf8420e08, 0xaa1703e0, 0x52800021, 0xaa1a03e2,+ 0xf2ee3070, 0xd73f0910,+ ]+ var result = words.reduce(into: Data()) { $0 += ARM64.encodeU32($1) }+ for offset in [4, 16] {+ result.replaceSubrange(offset ..< offset + 4, with:+ try #require(ARM64Encoder.encodeBL(from: Int(base) + offset, to: Int(formatStub))))+ }+ return result+ }++ func site(_ bytes: Data) throws -> Patcher.Site {+ try Patcher.findFormatSite(in: ARM64Disassembler().disassemble(bytes, at: base), formatStub: formatStub)+ }++ @Test func `finds the actual attribute format and rejects nearby lookalikes`() throws {+ let code = try fixture()+ let found = try site(code)+ #expect(found.address == base + 8)+ #expect(found.valueRegister == 26)+ #expect(found.existingCave == nil)++ var wrongProperty = code+ wrongProperty.replaceSubrange(40 ..< 44, with: try #require(ARM64Encoder.encodeMovzW(rd: 1, imm16: 2)))+ #expect(throws: (any Error).self) { try site(wrongProperty) }+ var wrongGetter = code+ wrongGetter.replaceSubrange(16 ..< 20, with: try #require(ARM64Encoder.encodeBL(from: Int(base) + 16, to: 0x4000)))+ #expect(throws: (any Error).self) { try site(wrongGetter) }+ var wrongValue = code+ wrongValue.replaceSubrange(44 ..< 48, with: ARM64Encoder.encodeMovX(rd: 2, rm: 25))+ #expect(throws: (any Error).self) { try site(wrongValue) }+ let twice = ARM64Disassembler().disassemble(code, at: base)+ + ARM64Disassembler().disassemble(code, at: base)+ #expect(throws: (any Error).self) { try Patcher.findFormatSite(in: twice, formatStub: formatStub) }+ }++ @Test func `plans in unused padding and accepts only its complete prior output`() throws {+ let code = try fixture()+ let found = try site(code)+ let padding: Range<UInt64> = 0x800 ..< 0x880+ var bytes = Data(repeating: 0, count: padding.count)+ bytes[0] = 1 // occupied bytes are never overwritten+ let first = try Patcher.plan(site: found, padding: padding) { at, count in+ Data(bytes[Int(at - padding.lowerBound) ..< Int(at - padding.lowerBound) + count])+ }+ #expect(first.cave == 0x804)+ #expect(first.program.count == 32)+ #expect(!first.alreadyPatched)++ var patched = code+ patched.replaceSubrange(8 ..< 12, with: first.branch)+ let patchedSite = try site(patched)+ #expect(patchedSite.existingCave == first.cave)+ bytes.replaceSubrange(4 ..< 36, with: first.program)+ let again = try Patcher.plan(site: patchedSite, padding: padding) { at, count in+ Data(bytes[Int(at - padding.lowerBound) ..< Int(at - padding.lowerBound) + count])+ }+ #expect(again.alreadyPatched)+ #expect(again.program == first.program)+ bytes[4] ^= 1+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: patchedSite, padding: padding) { at, count in+ Data(bytes[Int(at - padding.lowerBound) ..< Int(at - padding.lowerBound) + count])+ }+ }+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: found, padding: padding) { _, count in Data(repeating: 0xFF, count: count) }+ }+ let alien = Patcher.Site(address: found.address, valueRegister: 26, existingCave: 0x4000)+ #expect(throws: (any Error).self) {+ try Patcher.plan(site: alien, padding: padding) { _, count in Data(repeating: 0, count: count) }+ }+ }++ @Test func `header padding excludes all section bytes`() throws {+ // One LC_SEGMENT_64 containing one __text section.+ var header = Data(repeating: 0, count: 32 + 72 + 80)+ func put<T: FixedWidthInteger>(_ value: T, at offset: Int) {+ var le = value.littleEndian+ withUnsafeBytes(of: &le) { header.replaceSubrange(offset ..< offset + $0.count, with: $0) }+ }+ func name(_ string: String, at offset: Int) {+ header.replaceSubrange(offset ..< offset + string.utf8.count, with: string.utf8)+ }+ put(UInt32(0xFEED_FACF), at: 0)+ put(UInt32(1), at: 16)+ put(UInt32(152), at: 20)+ put(UInt32(0x19), at: 32)+ put(UInt32(152), at: 36)+ name("__TEXT", at: 40)+ put(base, at: 56)+ put(UInt64(0x1000), at: 64)+ put(UInt32(1), at: 96)+ name("__text", at: 104)+ name("__TEXT", at: 120)+ put(base + 0x200, at: 136)+ put(UInt64(0x100), at: 144)+ let padding = try Patcher.headerPadding(in: header, at: base)+ #expect(padding == base + UInt64(header.count) ..< base + 0x200)+ put(base + UInt64(header.count) + 16, at: 136)+ #expect(throws: (any Error).self) { try Patcher.headerPadding(in: header, at: base) }+ }++ enum FailurePoint: String, CaseIterable {+ case partialSecondWrite, partialReattestation, readback+ }++ enum InjectedFailure: Error { case operation, rollback }++ /// Two real cache pages and SHA-256 CodeDirectory slots, without symbols+ /// or a Mach-O image: transaction tests exercise the same ChunkSet writes,+ /// slot discovery and re-attestation used after production site discovery.+ func withTransactionCache(_ body: (DyldSharedCacheChunkSet, [DyldSharedCacheWriteSpan], Data) throws -> Void) throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("metal-format-transaction-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ defer { try? FileManager.default.removeItem(at: directory) }+ let pageSize = 0x4000+ let codeLimit = pageSize * 2+ let blobLength = 48 + 2 * 32+ let signatureLength = 20 + blobLength+ var bytes = Data(repeating: 0, count: codeLimit + signatureLength)+ func put<T: FixedWidthInteger>(_ value: T, at offset: Int, bigEndian: Bool = false) {+ var encoded = bigEndian ? value.bigEndian : value.littleEndian+ withUnsafeBytes(of: &encoded) { bytes.replaceSubrange(offset ..< offset + $0.count, with: $0) }+ }+ bytes.replaceSubrange(0 ..< 14, with: Data("dyld_v1 arm64e".utf8))+ put(UInt32(0x238), at: 0x10)+ put(UInt32(1), at: 0x14)+ put(UInt64(codeLimit), at: 0x28)+ put(UInt64(signatureLength), at: 0x30)+ put(base, at: 0x238)+ put(UInt64(codeLimit), at: 0x240)+ put(UInt64(0), at: 0x248)+ put(UInt32(5), at: 0x250)+ put(UInt32(5), at: 0x254)+ for (index, value) in [UInt32(0xFADE_0CC0), UInt32(signatureLength), 1, 0, 20].enumerated() {+ put(value, at: codeLimit + index * 4, bigEndian: true)+ }+ let cd = codeLimit + 20+ for (offset, value) in [(0, UInt32(0xFADE_0C02)), (4, UInt32(blobLength)), (8, 0x20400), (16, 48), (28, 2), (32, UInt32(codeLimit))] {+ put(value, at: cd + offset, bigEndian: true)+ }+ bytes[cd + 36] = 32+ bytes[cd + 37] = 2+ bytes[cd + 39] = 14+ for page in 0 ..< 2 {+ let hash = Data(SHA256.hash(data: bytes[page * pageSize ..< (page + 1) * pageSize]))+ bytes.replaceSubrange(cd + 48 + page * 32 ..< cd + 48 + (page + 1) * 32, with: hash)+ }+ let url = directory.appendingPathComponent("dyld_shared_cache_arm64e")+ try bytes.write(to: url)+ let chunks = try DyldSharedCacheChunkSet(directory: directory, captureUndo: true)+ let spans = [+ DyldSharedCacheWriteSpan(vma: base + 0x1000, length: 32),+ DyldSharedCacheWriteSpan(vma: base + 0x5000, length: 4),+ ]+ try body(chunks, spans, bytes)+ }++ @Test(arguments: FailurePoint.allCases)+ func `failed writes signing and readback restore the entire file exactly`(failure: FailurePoint) throws {+ try withTransactionCache { chunks, spans, original in+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ #expect(snapshots.count == 4)+ #expect(snapshots.filter { $0.vma == nil }.count == 2)+ #expect(throws: InjectedFailure.self) {+ try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: "Metal vertex format patch") {+ try chunks.write(at: spans[0].vma, Data(repeating: 0x55, count: spans[0].length))+ if failure == .partialSecondWrite {+ // Deliberately bypass ChunkSet's successful-write log:+ // a write(2) failure can leave a partial range behind.+ let (url, range) = try chunks.fileRange(of: spans[1])+ try DyldSharedCachePatchTransaction.restore(.init(url: url, offset: range.lowerBound, original: Data([0xAA, 0xBB]), vma: nil))+ throw InjectedFailure.operation+ }+ try chunks.write(at: spans[1].vma, Data(repeating: 0x66, count: spans[1].length))+ if failure == .partialReattestation {+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: [spans[0]], log: nil)+ #expect(result.updated.count == 1)+ throw InjectedFailure.operation+ }+ let result = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: nil)+ #expect(result.updated.count == 2)+ // Fault after signing, as a failed readback would occur.+ throw InjectedFailure.operation+ }+ }+ #expect(try Data(contentsOf: chunks.mainCacheURL) == original)+ }+ }++ @Test func `rollback failure is explicit retains recovery records and restores other ranges`() throws {+ try withTransactionCache { chunks, spans, original in+ let snapshots = try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks)+ var failure: DyldSharedCachePatchRollbackError?+ do {+ try DyldSharedCachePatchTransaction.run(snapshots: snapshots, label: "Metal vertex format patch", restoring: { item in+ if item.vma == spans[1].vma { throw InjectedFailure.rollback }+ try DyldSharedCachePatchTransaction.restore(item)+ }) {+ for span in spans { try chunks.write(at: span.vma, Data(repeating: 0x55, count: span.length)) }+ _ = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: spans, log: nil)+ throw InjectedFailure.operation+ }+ } catch let error as DyldSharedCachePatchRollbackError {+ failure = error+ }+ let caught = try #require(failure)+ #expect(caught.localizedDescription.contains("Rollback failed"))+ #expect(caught.recoveryUndo.records.count == 2)+ #expect(caught.recoveryUndo.records.map(\.vma) == spans.map(\.vma))+ let bytes = try Data(contentsOf: chunks.mainCacheURL)+ #expect(bytes != original)+ for item in snapshots where item.vma != spans[1].vma {+ #expect(bytes[item.offset ..< item.offset + item.original.count] == item.original)+ }+ // The normal persisted-undo path can still recover the failed run.+ var recovery = caught.recoveryUndo+ recovery.stamp(patchID: "test-metal-format")+ let restored = try recovery.restore(patchIDs: recovery.patchIDs, in: chunks.directory)+ _ = try DyldSharedCacheCodeSignature.reattest(in: chunks, modifiedSpans: restored, log: nil)+ #expect(try Data(contentsOf: chunks.mainCacheURL) == original)+ }+ }++ @Test func `missing hash coverage is rejected before any writes`() throws {+ try withTransactionCache { chunks, spans, _ in+ let handle = try FileHandle(forUpdating: chunks.mainCacheURL)+ try handle.seek(toOffset: 0x28)+ try handle.write(contentsOf: Data(repeating: 0, count: 16))+ try handle.close()+ let before = try Data(contentsOf: chunks.mainCacheURL)+ #expect(throws: (any Error).self) { try DyldSharedCachePatchTransaction.snapshots(for: spans, in: chunks) }+ #expect(try Data(contentsOf: chunks.mainCacheURL) == before)+ }+ }++ #if arch(arm64)+ @Test func `native trampoline changes exactly 43 and 44 and preserves getter result`() throws {+ // Preserve the ABI's x26 around the generated code, recording both the+ // original getter result (x0) and wire value (x26) for each input.+ var code = ARM64Encoder.encodeMovX(rd: 10, rm: 26)+ code += try #require(ARM64Encoder.encodeB(from: 4, to: 24))+ code += try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 0, rn: 1, offset: 0))+ code += try #require(ARM64Encoder.encodeStrXUnsignedOffset(rt: 26, rn: 1, offset: 8))+ code += ARM64Encoder.encodeMovX(rd: 26, rm: 10)+ code += ARM64.ret+ code += try Patcher.trampoline(at: 24, returningTo: 8, valueRegister: 26)+ let memory = try #require(mmap(nil, 0x4000, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0))+ try #require(memory != MAP_FAILED)+ defer { munmap(memory, 0x4000) }+ code.copyBytes(to: memory.assumingMemoryBound(to: UInt8.self), count: code.count)+ try #require(mprotect(memory, 0x4000, PROT_READ | PROT_EXEC) == 0)+ invalidateMetalVertexFormatTestCode(memory, code.count)+ typealias Function = @convention(c) (UInt64, UnsafeMutablePointer<UInt64>) -> Void+ let run = unsafeBitCast(memory, to: Function.self)+ let values = (0 ... 255).map(UInt64.init) + [1 << 32 | 43, 1 << 32 | 44, 1 << 63, .max]+ for value in values {+ var output: [UInt64] = [0, 0]+ output.withUnsafeMutableBufferPointer { run(value, $0.baseAddress!) }+ #expect(output[0] == value)+ #expect(output[1] == (value == 43 || value == 44 ? 36 : value))+ }+ }+ #endif+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swiftindex 97d59ad7..3b9953d0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwareGuestPatchResolutionTests.swift@@ -12,6 +12,58 @@ import VPhonePatchKit@Suite("Guest patch resolution")struct FirmwareGuestPatchResolutionTests {+ @Test func `compiler identity needs cache key validation only when reuse is selected`() throws {+ let identity = FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache+ let reuse = FirmwareGuestSystemPatchSet.metalCacheReuse+ let key = FirmwareGuestSystemPatchSet.metalCacheReuseKey+ let enabled: Set<String> = [identity, reuse, key]+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: enabled).isEmpty)+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: [identity, reuse]) == [key])+ // Selection succeeds before installation, but a failed key patch must+ // still stop the plugin/driver update. A prior applied key is sufficient.+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: enabled, applied: []) == [key])+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: enabled, applied: [identity, reuse]) == [key])+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: enabled, applied: [key]).isEmpty)+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: [identity], applied: []).isEmpty)+ let choices: [Set<String>] = [[], [identity], [reuse], [key], [identity, key], [reuse, key]]+ for choice in choices {+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: choice).isEmpty)+ }+ let standard = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.6.2"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(standard.enabled.isSuperset(of: enabled))+ #expect(FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: standard.enabled).isEmpty)+ }++ @Test func `GLES primitive expansion rejects missing transport prerequisites but permits opt out`() throws {+ let patch = FirmwareGuestSystemPatchSet.glesPrimitiveRestart+ let dependencies = FirmwareGuestPatchResolution.glesPrimitiveRestartDependencies+ #expect(dependencies == [FirmwareGuestSystemPatchSet.paravirtGPUPrimitiveRestart,+ FirmwareGuestSystemPatchSet.metalVertexIDFormat])+ let plan = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.6.2"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(plan.isEnabled(patch))+ #expect(FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: plan.enabled).isEmpty)+ for dependency in dependencies {+ let blocked = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.6.2"), cloudOS: VPhoneVersion("26.4"),+ blocked: [dependency],+ )+ #expect(FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: blocked.enabled) == [dependency])+ #expect(FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: blocked.enabled.subtracting([patch])).isEmpty)+ }+ #expect(FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: [patch]) == dependencies.sorted())+ #expect(FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: []).isEmpty)+ }+@Test func `HomeView environment simulation is explicit and limited to its reviewed base`() throws {let id = FirmwareGuestSystemPatchSet.homeViewEnvironmentServicefor preset in FirmwarePatchSetCatalog.builtInPresets {diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swiftindex 25e29d1b..757ff6e0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/PatchSets/FirmwarePatchSetCatalogTests.swift@@ -462,6 +462,55 @@ struct FirmwarePatchSetCatalogTests {}}+ @Test(arguments: [FirmwareGuestSystemPatchSet.glesUpperLeft, FirmwareGuestSystemPatchSet.metalVertexIDFormat,+ FirmwareGuestSystemPatchSet.glesPrimitiveRestart, FirmwareGuestSystemPatchSet.glesPointDraw,+ FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache, FirmwareGuestSystemPatchSet.metalCacheReuseKey])+ func `Native GLES corrections follow the measured OS pair and can be reverted`(patch: String) throws {+ for base in ["26.4", "26.5", "26.6", "26.6.2", "26.7", "27.0.1", "unknown"] {+ for cloud in ["26.1", "26.4", "26.5", "unknown"] {+ let plan = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion(base), cloudOS: VPhoneVersion(cloud),+ )+ let supported = (base == "26.6" || base == "26.6.2") && cloud == "26.4"+ #expect(plan.isEnabled(patch) == supported, "\(base)/\(cloud)")+ let updated = FirmwareGuestPatchResolution.effectiveEnabled(+ planEnabled: [], selectionEnabled: plan.enabled,+ )+ #expect(updated.contains(patch) == supported, "A guest update must include new patches absent from the boot plan")+ }+ }+ let blocked = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.6.2"), cloudOS: VPhoneVersion("26.4"),+ blocked: [patch],+ )+ #expect(!blocked.isEnabled(patch))+ #expect(FirmwareGuestPatchResolution.guestPatchesOff(selectionEnabled: blocked.enabled).contains(patch))+ #expect(!FirmwareGuestPatchResolution.effectiveEnabled(+ planEnabled: [patch], selectionEnabled: blocked.enabled,+ ).contains(patch))+ let unsupported = try VPhonePatchPlan.resolve(+ preset: FirmwarePatchSetCatalog.standardPreset,+ patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("27.0.1"), cloudOS: VPhoneVersion("26.4"),+ allowed: [patch],+ )+ #expect(!unsupported.isEnabled(patch), "An explicit selection must not widen the version gate")+ // Test the preset exclusions on the applicable pair so the version+ // gate cannot hide an accidentally missing block-list entry.+ for preset in [FirmwarePatchSetCatalog.tvOSPreset, FirmwarePatchSetCatalog.tvOS4KPreset,+ FirmwarePatchSetCatalog.homePodMiniPreset, FirmwarePatchSetCatalog.homeViewPreset] {+ let plan = try VPhonePatchPlan.resolve(+ preset: preset, patchSets: FirmwarePatchSetCatalog.bundled,+ iOSBase: VPhoneVersion("26.6.2"), cloudOS: VPhoneVersion("26.4"),+ )+ #expect(!plan.isEnabled(patch), "\(preset.identifier)")+ }+ }+@Testfunc `Standard names the GLES renderer on every base while tvOS stays off`() throws {let patch = FirmwarePatchSetCatalog.paravirtGLESPatchdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swiftindex 693c27db..69dde834 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareDyldSharedCacheVerbsCommand.swift@@ -74,6 +74,10 @@ enum VPhoneCustomFirmwareDyldSharedCacheVerbs {/// Registered into `vphone-cli cfw` by `VPhoneCustomFirmwareCommand`.static var all: [ParsableCommand.Type] {[+ VPhoneCustomFirmwarePatchMetalVertexIDFormatCommand.self,+ VPhoneCustomFirmwarePatchGLESPrimitiveRestartCommand.self,+ VPhoneCustomFirmwarePatchMetalCacheReuseKeyCommand.self,+ VPhoneCustomFirmwarePatchGLESPointDrawCommand.self,VPhoneCustomFirmwarePatchHomeViewEnvironmentCommand.self,VPhoneCustomFirmwarePatchSettingsSoftwareUpdateCommand.self,VPhoneCustomFirmwarePatchArm64eX1BootstrapCacheCommand.self,@@ -218,6 +222,182 @@ struct VPhoneCustomFirmwarePatchHypervisorVirtualMachineDyldSharedCacheCommand:}}+// MARK: - patch-metal-vertex-id-format++struct VPhoneCustomFirmwarePatchMetalVertexIDFormatCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-metal-vertex-id-format",+ abstract: "Serialize legacy GLES vertex ID formats as UInt for the paravirtual GPU",+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Flag(name: .customLong("dry-run"), help: "Report the patch sites without writing")+ var dryRun = false++ @OptionGroup var undo: DyldSharedCacheUndoOptions++ func run() throws {+ var captured = DyldSharedCacheUndoLog()+ do {+ try DyldSharedCacheMetalVertexFormatPatcher.patch(+ chunksDirectory: chunksDirectory,+ dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ } catch {+ // A rollback failure returns all pre-write originals, including+ // partially written ranges. Preserve them before reporting failure.+ // A verified rollback returns no records and changes no undo log.+ do {+ try undo.persist(captured, dryRun: dryRun)+ } catch let persistenceError {+ throw ValidationError("\(error.localizedDescription) Recovery undo could not be saved: \(persistenceError.localizedDescription)")+ }+ throw error+ }+ try undo.persist(captured, dryRun: dryRun)+ }+}++// MARK: - patch-gles-primitive-restart++struct VPhoneCustomFirmwarePatchGLESPrimitiveRestartCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-gles-primitive-restart",+ abstract: "Preserve disabled GLES primitive restart through native primitive expansion",+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Flag(name: .customLong("dry-run"), help: "Report the patch sites without writing")+ var dryRun = false++ @OptionGroup var undo: DyldSharedCacheUndoOptions++ func run() throws {+ var captured = DyldSharedCacheUndoLog()+ do {+ try DyldSharedCacheGLESPrimitiveRestartPatcher.patch(+ chunksDirectory: chunksDirectory,+ dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ } catch {+ // A rollback failure returns all pre-write originals, including+ // partially written ranges. Preserve them before reporting failure.+ // A verified rollback returns no records and changes no undo log.+ do {+ try undo.persist(captured, dryRun: dryRun)+ } catch let persistenceError {+ throw ValidationError("\(error.localizedDescription) Recovery undo could not be saved: \(persistenceError.localizedDescription)")+ }+ throw error+ }+ try undo.persist(captured, dryRun: dryRun)+ }+}++// MARK: - patch-metal-cache-reuse-key++struct VPhoneCustomFirmwarePatchMetalCacheReuseKeyCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-metal-cache-reuse-key",+ abstract: "Validate compiler cache identities while permitting reuse across boots",+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Flag(name: .customLong("dry-run"), help: "Report the patch sites without writing")+ var dryRun = false++ @OptionGroup var undo: DyldSharedCacheUndoOptions++ func run() throws {+ var captured = DyldSharedCacheUndoLog()+ do {+ try DyldSharedCacheMetalCacheReusePatcher.patch(+ chunksDirectory: chunksDirectory,+ dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ } catch {+ // A rollback failure returns all pre-write originals, including+ // partially written ranges. Preserve them before reporting failure.+ // A verified rollback returns no records and changes no undo log.+ do {+ try undo.persist(captured, dryRun: dryRun)+ } catch let persistenceError {+ throw ValidationError("\(error.localizedDescription) Recovery undo could not be saved: \(persistenceError.localizedDescription)")+ }+ throw error+ }+ try undo.persist(captured, dryRun: dryRun)+ }+}++// MARK: - patch-gles-point-draw++struct VPhoneCustomFirmwarePatchGLESPointDrawCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-gles-point-draw",+ abstract: "Submit valid GLES points despite missing paravirtual pipeline usage flags",+ )++ @Argument(+ help: "The guest's /System/Library/Caches/com.apple.dyld directory",+ transform: URL.init(fileURLWithPath:),+ )+ var chunksDirectory: URL++ @Flag(name: .customLong("dry-run"), help: "Report the patch sites without writing")+ var dryRun = false++ @OptionGroup var undo: DyldSharedCacheUndoOptions++ func run() throws {+ var captured = DyldSharedCacheUndoLog()+ do {+ try DyldSharedCacheGLESPointDrawPatcher.patch(+ chunksDirectory: chunksDirectory,+ dryRun: dryRun,+ captureUndo: undo.captures,+ onUndo: { captured.merge($0) },+ log: VPhoneCustomFirmwareDyldSharedCacheVerbs.stdout,+ )+ } catch {+ // A rollback failure returns all pre-write originals, including+ // partially written ranges. Preserve them before reporting failure.+ // A verified rollback returns no records and changes no undo log.+ do {+ try undo.persist(captured, dryRun: dryRun)+ } catch let persistenceError {+ throw ValidationError("\(error.localizedDescription) Recovery undo could not be saved: \(persistenceError.localizedDescription)")+ }+ throw error+ }+ try undo.persist(captured, dryRun: dryRun)+ }+}+// MARK: - patch-iomfb-swapendstruct VPhoneCustomFirmwarePatchIOMFBSwapEndCommand: ParsableCommand {diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swiftindex 15710bb1..90fbcaac 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareInstaller.swift@@ -262,6 +262,14 @@ struct VPhoneCustomFirmwareInstaller {if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.homePodOTAUserland), device.family != .homePod {throw ValidationError("The HomePod OTA userland patch is supported only for a HomePod guest.")}+ let missingGLESDependencies = FirmwareGuestPatchResolution.missingGLESPrimitiveRestartDependencies(enabled: effectiveEnabled)+ guard missingGLESDependencies.isEmpty else {+ throw ValidationError("The GLES primitive-restart correction requires these selected guest patches: \(missingGLESDependencies.joined(separator: ", ")).")+ }+ let missingCacheDependencies = FirmwareGuestPatchResolution.missingCompilerCacheDependencies(enabled: effectiveEnabled)+ guard missingCacheDependencies.isEmpty else {+ throw ValidationError("GPU compiler cache versioning with cross-boot reuse requires these selected guest patches: \(missingCacheDependencies.joined(separator: ", ")).")+ }let missingGlowDependencies = FirmwareGuestPatchResolution.missingHomePodSoundGlowDependencies(enabled: effectiveEnabled)guard missingGlowDependencies.isEmpty else {throw ValidationError("The HomePod Sound Glow patch requires these selected guest patches: \(missingGlowDependencies.joined(separator: ", ")).")@@ -363,6 +371,9 @@ struct VPhoneCustomFirmwareInstaller {if isOTAUpdate, !cloned {throw ValidationError("The OTA update needs a private APFS disk clone; the original disk was left untouched.")}+ if effectiveEnabled.contains(FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache), !cloned {+ throw ValidationError("GPU compiler cache versioning needs a private APFS disk clone so the compiler and its cache identity update together; the original disk was left untouched.")+ }if device.usesTVOS {// A paired dyld edit must never fall back to mutating the live disk.// Its errors propagate below, so this clone is committed only after@@ -1314,7 +1325,8 @@ struct VPhoneCustomFirmwareInstaller {// Whether the VM's plan (its guest half re-resolved from the current// selection) turned this guest patch on. A VM with no plan gets every// legacy patch, which is what it was restored with. New Settings-row- // preferences and motion sensors still require an explicit plan.+ // preferences, motion sensors and version-gated GLES compatibility still+ // require an explicit plan.func on(_ identifier: String) -> Bool {guard let plan else {return !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(identifier)@@ -1324,6 +1336,8 @@ struct VPhoneCustomFirmwareInstaller {&& identifier != FirmwareGuestSystemPatchSet.hinge&& identifier != FirmwareGuestSystemPatchSet.foldGuard&& identifier != FirmwareGuestSystemPatchSet.ios17Desktop+ && identifier != FirmwareGuestSystemPatchSet.glesUpperLeft+ && identifier != FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache}guard plan.isEnabled(identifier) else {print(" [·] \(identifier): off in preset \(plan.presetIdentifier)")@@ -1757,6 +1771,10 @@ struct VPhoneCustomFirmwareInstaller {dyld.append(("dyld-boot-iomfb_swapend", "patch-iomfb-swapend", [dsc, "--target-size", "0x560"]))}dyld += [+ (FirmwareGuestSystemPatchSet.metalCacheReuseKey, "patch-metal-cache-reuse-key", [dsc]),+ (FirmwareGuestSystemPatchSet.metalVertexIDFormat, "patch-metal-vertex-id-format", [dsc]),+ (FirmwareGuestSystemPatchSet.glesPrimitiveRestart, "patch-gles-primitive-restart", [dsc]),+ (FirmwareGuestSystemPatchSet.glesPointDraw, "patch-gles-point-draw", [dsc]),(FirmwareGuestSystemPatchSet.homeViewEnvironmentService, "patch-homeview-environment", [dsc]),(FirmwareGuestSystemPatchSet.settingsSoftwareUpdate, "patch-settings-software-update", [dsc]),(FirmwarePatchSetCatalog.misTrustAuthPatch, "patch-mis-trust-auth", [dsc]),@@ -1769,6 +1787,16 @@ struct VPhoneCustomFirmwareInstaller {)try requireX1Bootstrap()+ // Selected is not necessarily applied: optional DSC failures are+ // isolated above. Stop before refreshing the compiler if cache reuse+ // would still bypass its new identity. The private clone is discarded.+ let cacheDependencies = FirmwareGuestPatchResolution.missingCompilerCacheDependencies(+ enabled: Set(plan?.enabledPatches ?? []), applied: live,+ )+ guard cacheDependencies.isEmpty else {+ throw ValidationError("Required GPU compiler cache patches failed; the compiler was not updated: \(cacheDependencies.joined(separator: ", ")).")+ }+// The feature plist exists from iOS 26. Turning the patch off restores// the original.let bluetoothID = FirmwareGuestSystemPatchSet.virtualBluetooth@@ -1928,29 +1956,49 @@ struct VPhoneCustomFirmwareInstaller {// 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. Both ride+ // reinstalled is already pristine, which is what "off" means. The+ // compiler identity also changes with the installed plugin so its old+ // shader output is never reused after an update. All selected fixes 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"),+ (FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache, "patch-paravirt-gpu-compiler-cache"),]let gpuDriver = FirmwareGuestSystemPatchSet.paravirtGPUDriverPathlet gpuBundle = "System/Library/Extensions/\(VPhonePCCGPUDriver.name)"let gpuDriverOn = gpuDriverPatches.filter { on($0.id) }isolate(gpuDriverPatches.map(\.id)) {if !gpuDriverOn.isEmpty {+ let compilerCache = gpuDriverOn.first { $0.id == FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache }+ let pluginName = "gpu-compiler-cache-plugin.dylib"+ if compilerCache != nil {+ // Read the confined installed file, not bundle resources:+ // refreshing the plugin can fail independently, and the+ // cache identity must describe what the guest will load.+ try work.directory.removeItem(pluginName)+ try system.copyFile(+ from: "\(gpuBundle)/libAppleParavirtCompilerPluginIOGPUFamily.dylib",+ to: pluginName, in: work.directory,+ )+ }try patchMachO(system: system, work: work, path: gpuDriver,- verbs: gpuDriverOn.map(\.verb),+ verbs: gpuDriverOn.filter { $0.id != compilerCache?.id }.map(\.verb),identifier: "com.apple.driver.AppleParavirtGPUMetalIOGPUFamily",+ beforeSigning: { staged in+ if let compilerCache {+ try patch(compilerCache.verb, [staged.path, "--compiler-plugin", work.file(pluginName).path])+ }+ },)try sealGuestBundle(system: system, bundle: gpuBundle)for patch in gpuDriverOn {live.insert(patch.id)}} else if try revertMachO(system: system, work: work, path: gpuDriver, bundle: gpuBundle) {- print(" [+] \(gpuDriver) restored from backup (heap index and primitive restart patches off)")+ print(" [+] \(gpuDriver) restored from backup (GPU driver 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)")@@ -1959,6 +2007,11 @@ struct VPhoneCustomFirmwareInstaller {}}+ if on(FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache),+ failures.contains(FirmwareGuestSystemPatchSet.paravirtGPUCompilerCache) {+ throw ValidationError("GPU compiler cache identity update failed; the private disk clone was discarded to keep the compiler and driver consistent.")+ }+machO("system-launchd_cache_loader-boot-unsecure_cache_gate", path: "usr/libexec/launchd_cache_loader", verbs: ["patch-launchd-cache-loader"], codeIdentifier: "com.apple.launchd_cache_loader")// The TV declaration has its own 27.2 gate and preset selection; the// implementation and reversible backup are shared with iPhone.@@ -2316,6 +2369,19 @@ struct VPhoneCustomFirmwareInstaller {}}+ // Select the renderer's viewport/scissor path instead of IOSurface+ // attachment yInvert. The declaration gates the measured OS pair.+ let glesOrientationPatch = FirmwareGuestSystemPatchSet.glesUpperLeft+ let glesOrientationMarker = String(FirmwareGuestSystemPatchSet.glesUpperLeftMarker.dropFirst())+ isolate([glesOrientationPatch]) {+ if on(glesOrientationPatch) {+ try system.writeFile(glesOrientationMarker, contents: Data("1\n".utf8), mode: 0o644, owner: Self.guestOwner)+ live.insert(glesOrientationPatch)+ } else {+ try system.removeItem(glesOrientationMarker)+ }+ }+if !failures.isEmpty {print("[!] \(failures.count) guest patch(es) failed and were left in their prior state: \(Set(failures).sorted().joined(separator: ", "))")if strict {@@ -2355,7 +2421,13 @@ struct VPhoneCustomFirmwareInstaller {failures: inout [String],) throws {func enabled(_ id: String) -> Bool {- if id == FirmwareGuestSystemPatchSet.homeViewEnvironmentService { return plan?.isEnabled(id) == true }+ if id == FirmwareGuestSystemPatchSet.homeViewEnvironmentService+ || id == FirmwareGuestSystemPatchSet.metalCacheReuseKey+ || id == FirmwareGuestSystemPatchSet.metalVertexIDFormat+ || id == FirmwareGuestSystemPatchSet.glesPointDraw+ || id == FirmwareGuestSystemPatchSet.glesPrimitiveRestart {+ return plan?.isEnabled(id) == true+ }return plan?.isEnabled(id) ?? !FirmwareGuestSystemPatchSet.settingsRowPatches.contains(id)}func requireBootstrap(_ id: String, error: any Error) throws {@@ -2412,7 +2484,7 @@ struct VPhoneCustomFirmwareInstaller {live.insert(entry.id)} catch {failures.append(entry.id)- print(" [!] \(entry.id): dyld patch failed, left in its prior state: \(error)")+ print(" [!] \(entry.id): dyld patch failed; inspect the error for recovery details: \(error)")try requireBootstrap(entry.id, error: error)}case (false, true):@@ -3911,7 +3983,8 @@ struct VPhoneCustomFirmwareInstaller {/// `verbs` runs in order against the one staged copy — the staging starts/// from the pristine backup, so two calls would not compose. Empty: a/// binary that only needs a library injected — as installd does for- /// libmisfix — has no bytes of its own to change.+ /// libmisfix — has no bytes of its own to change. `beforeSigning` can apply+ /// a patch requiring additional staged inputs to that same copy.private func patchMachO(system: VPhoneConfinedDirectory,work: WorkDirectory,@@ -3920,6 +3993,7 @@ struct VPhoneCustomFirmwareInstaller {identifier: String? = nil,preserveEntitlements: Bool = false,injectedDylibPath: String? = nil,+ beforeSigning: ((URL) throws -> Void)? = nil,) throws {let backup = "\(path).bak"if try !system.exists(backup) {@@ -3946,6 +4020,7 @@ struct VPhoneCustomFirmwareInstaller {if let injectedDylibPath {try patch("inject-dylib", [staged.path, injectedDylibPath])}+ try beforeSigning?(staged)// The ad-hoc shape, not ldid's: TXM 187.100.3 routes a CodeDirectory// without the CS_ADHOC flag into a selector-24 branch that demands a// CMS wrapper no ad-hoc re-sign carries, and iOS 27.0.1's launchd isdiff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swiftindex a1f09731..6e2eafcd 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/Firmware/VPhoneCustomFirmwareMachOVerbsCommand.swift@@ -670,6 +670,38 @@ struct VPhoneCustomFirmwarePatchParavirtGPUPrimitiveRestartCommand: ParsableComm}}+// MARK: - patch-paravirt-gpu-compiler-cache++struct VPhoneCustomFirmwarePatchParavirtGPUCompilerCacheCommand: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "patch-paravirt-gpu-compiler-cache",+ abstract: "Version the paravirtual GPU shader cache with its compiler plugin",+ discussion: """+ The cloudOS 26.4 driver hashes a fixed compiler identity into its shader-cache+ namespace. Replace its two eight-byte identity inputs with a SHA-256-derived+ identity of the compiler plugin that will be loaded in the guest. A plugin+ update then recompiles shaders without deleting existing caches.++ The setupCompiler SHA256_Update call flow locates both inputs. Instructions+ are unchanged. Reapplying the same plugin identity leaves the file unchanged.+ The caller must re-sign the driver after patching.+ """,+ )++ @Argument(help: "Path to the AppleParavirtGPUMetalIOGPUFamily Mach-O, patched in place", transform: URL.init(fileURLWithPath:))+ var binary: URL++ @Option(name: .customLong("compiler-plugin"), help: "Path to the compiler plugin installed alongside the driver", transform: URL.init(fileURLWithPath:))+ var compilerPlugin: URL++ func run() throws {+ try requireUntruncatedMachO(at: binary)+ try CustomFirmwareParavirtGPUCompilerCache.patch(+ fileAt: binary, compilerPluginAt: compilerPlugin, log: machOVerbLog,+ )+ }+}+enum VPhoneCustomFirmwareMachOVerbs {/// Registered into `vphone-cli cfw` by `VPhoneCustomFirmwareCommand`.///@@ -692,6 +724,7 @@ enum VPhoneCustomFirmwareMachOVerbs {VPhoneCustomFirmwarePatchVirtualAudioDeviceStateNullGateCommand.self,VPhoneCustomFirmwarePatchParavirtGPUIndexOffsetCommand.self,VPhoneCustomFirmwarePatchParavirtGPUPrimitiveRestartCommand.self,+ VPhoneCustomFirmwarePatchParavirtGPUCompilerCacheCommand.self,]}}diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plistindex d3297244..acf64304 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homepod-mini.plist@@ -102,6 +102,10 @@<string>dyld-boot-arm64e_x1_bootstrap</string><string>dyld-boot-iomfb_swapend</string><string>dyld-cfw-camera</string>+ <string>dyld-cfw-metal_vertex_id_format</string>+ <string>dyld-cfw-gles_primitive_restart</string>+ <string>dyld-cfw-metal_cache_reuse_key</string>+ <string>dyld-cfw-gles_point_draw</string><string>dyld-cfw-arm64e_x1_cache</string><string>system-cibarcode-cfw-arm64e_x1</string><string>kernel-boot-arm64e_x1</string>@@ -143,6 +147,8 @@<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-paravirt_gpu-cfw-compiler_cache</string>+ <string>system-systemhook-cfw-gles_upper_left</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.plistindex 9a880221..61971982 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/homeview.plist@@ -85,6 +85,10 @@<string>dyld-boot-iomfb_swapend</string><string>dyld-cfw-arm64e_x1_cache</string><string>dyld-cfw-camera</string>+ <string>dyld-cfw-metal_vertex_id_format</string>+ <string>dyld-cfw-gles_primitive_restart</string>+ <string>dyld-cfw-metal_cache_reuse_key</string>+ <string>dyld-cfw-gles_point_draw</string><string>dyld-exp-hv_vmm</string><string>dyld-exp-mis_trust_auth</string><string>dyld-exp-settings_software_update_row</string>@@ -144,12 +148,14 @@<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-paravirt_gpu-cfw-compiler_cache</string><string>system-preferences-cfw-followup_groups</string><string>system-preferences-exp-root_rows</string><string>system-setup-exp-deferred_focus</string><string>system-setupbackground-exp-pineboard_lookup</string><string>system-springboard-cfw-fold_display</string><string>system-springboard-cfw-fold_guard</string>+ <string>system-systemhook-cfw-gles_upper_left</string><string>system-systemhook-cfw-metal_cache_reuse</string><string>system-systemversion-cfw-build_version</string><string>system-tv-exp-legacy_setup</string>diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plistindex 314ba2c3..d2bc47bb 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos-4k.plist@@ -114,6 +114,10 @@<string>dyld-boot-arm64e_x1_bootstrap</string><string>dyld-boot-iomfb_swapend</string><string>dyld-cfw-camera</string>+ <string>dyld-cfw-metal_vertex_id_format</string>+ <string>dyld-cfw-gles_primitive_restart</string>+ <string>dyld-cfw-metal_cache_reuse_key</string>+ <string>dyld-cfw-gles_point_draw</string><string>dyld-cfw-arm64e_x1_cache</string><string>system-cibarcode-cfw-arm64e_x1</string><string>kernel-boot-arm64e_x1</string>@@ -149,6 +153,8 @@<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-paravirt_gpu-cfw-compiler_cache</string>+ <string>system-systemhook-cfw-gles_upper_left</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.plistindex 60ced4b6..1f7a6183 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/tvos.plist@@ -117,6 +117,10 @@<string>dyld-boot-maxslide</string><string>dyld-boot-xpc_lwcr</string><string>dyld-cfw-camera</string>+ <string>dyld-cfw-metal_vertex_id_format</string>+ <string>dyld-cfw-gles_primitive_restart</string>+ <string>dyld-cfw-metal_cache_reuse_key</string>+ <string>dyld-cfw-gles_point_draw</string><string>dyld-cfw-arm64e_x1_cache</string><string>system-cibarcode-cfw-arm64e_x1</string><string>kernel-boot-arm64e_x1</string>@@ -153,6 +157,8 @@<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-paravirt_gpu-cfw-compiler_cache</string>+ <string>system-systemhook-cfw-gles_upper_left</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.hindex 28eca30e..cba7386a 100644--- a/VPhoneGuestComponents/GraphicLoader/GLESAIR.h+++ b/VPhoneGuestComponents/GraphicLoader/GLESAIR.h@@ -4,10 +4,13 @@typedef struct LLVMOpaqueModule *LLVMModuleRef;typedef struct LLVMOpaqueValue *LLVMValueRef;-// True for a module whose air.language_version is "OpenGL ES GLSL".+// True for GLES shaders ("OpenGL ES GLSL") and ES1 generated fixed-function+// programs ("OpenGL ES Program").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.+// GPUCompiler needs added, and GLES fragment point-coordinate Y converted for+// the PV render-pass path. A metadata marker prevents repeated conversion.+// Non-GLES modules are unchanged. Null when no adaptation is needed, or on+// failure with *error set. The input module is never modified.LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error);diff --git a/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm b/VPhoneGuestComponents/GraphicLoader/GLESAIR.mmindex 09ef8b99..30a67020 100644--- a/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm+++ b/VPhoneGuestComponents/GraphicLoader/GLESAIR.mm@@ -16,6 +16,12 @@// 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.+//+// AppleMetalGLRenderer also requests pointCoordYFlipEnabled on every render+// pass. The supported PV path does not honor that private flag, so implement+// its effect at metadata-identified GLES fragment point-coordinate inputs. This+// is independent of AGX_GL_VIEWPORT_INVERT_CONFIG. Native Metal modules are+// untouched; a module marker prevents applying the conversion twice.#include <cstdio>#include <cstdlib>@@ -32,6 +38,9 @@ extern "C" {typedef struct LLVMOpaqueType *LLVMTypeRef;typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef;+ typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef;+ typedef struct LLVMOpaqueBuilder *LLVMBuilderRef;+ typedef struct LLVMOpaqueUse *LLVMUseRef;LLVMContextRef LLVMGetModuleContext(LLVMModuleRef M);unsigned LLVMGetNamedMetadataNumOperands(LLVMModuleRef M, const char *Name);@@ -61,6 +70,31 @@ extern "C" {LLVMTargetDataRef LLVMGetModuleDataLayout(LLVMModuleRef M);unsigned long long LLVMABISizeOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);unsigned LLVMABIAlignmentOfType(LLVMTargetDataRef TD, LLVMTypeRef Ty);+ LLVMValueRef LLVMIsAFunction(LLVMValueRef Val);+ LLVMValueRef LLVMIsAConstantInt(LLVMValueRef Val);+ LLVMTypeRef LLVMTypeOf(LLVMValueRef Val);+ unsigned long long LLVMConstIntGetZExtValue(LLVMValueRef ConstantVal);+ LLVMValueRef LLVMGetParam(LLVMValueRef Fn, unsigned Index);+ LLVMUseRef LLVMGetFirstUse(LLVMValueRef Val);+ LLVMBasicBlockRef LLVMGetFirstBasicBlock(LLVMValueRef Fn);+ LLVMValueRef LLVMGetFirstInstruction(LLVMBasicBlockRef BB);+ LLVMValueRef LLVMGetNextInstruction(LLVMValueRef Inst);+ LLVMValueRef LLVMIsAPHINode(LLVMValueRef Val);+ LLVMBuilderRef LLVMCreateBuilderInContext(LLVMContextRef C);+ void LLVMPositionBuilderBefore(LLVMBuilderRef Builder, LLVMValueRef Instr);+ void LLVMDisposeBuilder(LLVMBuilderRef Builder);+ LLVMTypeRef LLVMInt32TypeInContext(LLVMContextRef C);+ LLVMValueRef LLVMConstInt(LLVMTypeRef IntTy, unsigned long long N, int SignExtend);+ LLVMValueRef LLVMConstReal(LLVMTypeRef RealTy, double N);+ LLVMValueRef LLVMBuildExtractElement(LLVMBuilderRef, LLVMValueRef VecVal, LLVMValueRef Index, const char *Name);+ LLVMValueRef LLVMBuildFSub(LLVMBuilderRef, LLVMValueRef LHS, LLVMValueRef RHS, const char *Name);+ LLVMValueRef LLVMBuildInsertElement(LLVMBuilderRef, LLVMValueRef VecVal, LLVMValueRef EltVal, LLVMValueRef Index, const char *Name);+ void LLVMReplaceAllUsesWith(LLVMValueRef OldVal, LLVMValueRef NewVal);+ void LLVMSetOperand(LLVMValueRef User, unsigned Index, LLVMValueRef Val);+ LLVMValueRef LLVMMDNodeInContext(LLVMContextRef C, LLVMValueRef *Vals, unsigned Count);+ void LLVMAddNamedMetadataOperand(LLVMModuleRef M, const char *Name, LLVMValueRef Val);+ int LLVMVerifyModule(LLVMModuleRef M, int Action, char **OutMessage);+ void LLVMDisposeModule(LLVMModuleRef M);}namespace {@@ -269,14 +303,23 @@ private: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")) {+ if (buffer && type && LLVMGetTypeKind(type) == kindPointer) {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));+ // Some producers already supply only part of the buffer layout.+ // Complete each field independently without duplicating or+ // replacing the producer's existing values.+ if (!hasKey(ops, "air.address_space")) {+ string("air.address_space");+ integer(LLVMGetPointerAddressSpace(type));+ }+ if (!hasKey(ops, "air.arg_type_size")) {+ string("air.arg_type_size");+ integer(LLVMABISizeOfType(layout, pointee));+ }+ if (!hasKey(ops, "air.arg_type_align_size")) {+ string("air.arg_type_align_size");+ integer(LLVMABIAlignmentOfType(layout, pointee));+ }}if (!hasKey(ops, "air.arg_type_name")) {string("air.arg_type_name");@@ -292,6 +335,88 @@ private:}};+constexpr const char *pointCoordinateMarker = "vphone.gles.point_coord_y_flipped";+struct PointCoordinate {+ LLVMValueRef parameter;+ LLVMTypeRef scalar;+ LLVMValueRef insertion;+};++bool pointCoordinates(LLVMModuleRef module, std::vector<PointCoordinate> &result, const char **error) {+ if (LLVMGetNamedMetadataNumOperands(module, pointCoordinateMarker))+ return true;+ unsigned count = LLVMGetNamedMetadataNumOperands(module, "air.fragment");+ std::vector<LLVMValueRef> entries(count);+ if (count)+ LLVMGetNamedMetadataOperands(module, "air.fragment", entries.data());+ std::set<LLVMValueRef> seen;+ for (LLVMValueRef entry : entries) {+ auto fields = operands(entry);+ if (fields.size() < 3 || !fields[0] || !LLVMIsAFunction(fields[0]))+ continue;+ LLVMValueRef function = fields[0];+ LLVMTypeRef signature = LLVMGlobalGetValueType(function);+ std::vector<LLVMTypeRef> parameters(LLVMCountParamTypes(signature));+ if (!parameters.empty())+ LLVMGetParamTypes(signature, parameters.data());+ for (LLVMValueRef node : operands(fields[2])) {+ auto argument = operands(node);+ if (argument.size() < 2 || stringOf(argument[1]) != "air.point_coord")+ continue;+ if (!argument[0] || !LLVMIsAConstantInt(argument[0]) ||+ LLVMGetIntTypeWidth(LLVMTypeOf(argument[0])) > 64) {+ *error = "OpenGL ES point-coordinate input has no supported integer parameter index";+ return false;+ }+ unsigned long long index = LLVMConstIntGetZExtValue(argument[0]);+ if (index >= parameters.size() || LLVMGetTypeKind(parameters[index]) != kindVector ||+ LLVMGetVectorSize(parameters[index]) != 2) {+ *error = "OpenGL ES point-coordinate input must be a two-component vector";+ return false;+ }+ LLVMTypeRef scalar = LLVMGetElementType(parameters[index]);+ if (LLVMGetTypeKind(scalar) != kindHalf && LLVMGetTypeKind(scalar) != kindFloat) {+ *error = "OpenGL ES point-coordinate input must contain half or float values";+ return false;+ }+ LLVMValueRef parameter = LLVMGetParam(function, (unsigned)index);+ if (!LLVMGetFirstUse(parameter) || !seen.insert(parameter).second)+ continue;+ LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(function);+ LLVMValueRef insertion = block ? LLVMGetFirstInstruction(block) : nullptr;+ while (insertion && LLVMIsAPHINode(insertion))+ insertion = LLVMGetNextInstruction(insertion);+ if (!insertion) {+ *error = "OpenGL ES point-coordinate input has no function body";+ return false;+ }+ result.push_back({parameter, scalar, insertion});+ }+ }+ return true;+}++void flipPointCoordinates(LLVMModuleRef module, const std::vector<PointCoordinate> &inputs) {+ LLVMContextRef context = LLVMGetModuleContext(module);+ LLVMBuilderRef builder = LLVMCreateBuilderInContext(context);+ LLVMValueRef oneIndex = LLVMConstInt(LLVMInt32TypeInContext(context), 1, 0);+ for (const PointCoordinate &input : inputs) {+ LLVMPositionBuilderBefore(builder, input.insertion);+ LLVMValueRef y = LLVMBuildExtractElement(builder, input.parameter, oneIndex, "vphone.point.y");+ LLVMValueRef flipped = LLVMBuildFSub(builder, LLVMConstReal(input.scalar, 1.0), y, "vphone.point.flipped_y");+ LLVMValueRef coordinate = LLVMBuildInsertElement(builder, input.parameter, flipped, oneIndex, "vphone.point.coord");+ LLVMReplaceAllUsesWith(input.parameter, coordinate);+ // RAUW includes the two instructions just created. Restore their+ // source operands to the original parameter; otherwise they form a+ // self-reference. All original uses now see the converted vector.+ LLVMSetOperand(y, 0, input.parameter);+ LLVMSetOperand(coordinate, 0, input.parameter);+ }+ LLVMDisposeBuilder(builder);+ LLVMValueRef version = LLVMConstInt(LLVMInt32TypeInContext(context), 1, 0);+ LLVMAddNamedMetadataOperand(module, pointCoordinateMarker, LLVMMDNodeInContext(context, &version, 1));+}+} // namespacebool isGLESModule(LLVMModuleRef module) {@@ -301,10 +426,21 @@ bool isGLESModule(LLVMModuleRef module) {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";+ if (ops.empty())+ return false;+ const std::string language = stringOf(ops[0]);+ // ES1's generated fixed-function programs use the same legacy argument+ // layout as GLSL, but identify themselves as "OpenGL ES Program".+ return language == "OpenGL ES GLSL" || language == "OpenGL ES Program";}LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error) {+ *error = nullptr;+ if (!module || !isGLESModule(module))+ return nullptr;+ std::vector<PointCoordinate> inputs;+ if (!pointCoordinates(module, inputs, error))+ return nullptr;char *printed = LLVMPrintModuleToString(module);if (!printed) {*error = "cannot print the OpenGL ES module";@@ -314,7 +450,7 @@ LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error) {LLVMDisposeMessage(printed);for (const char *stage : {"air.vertex", "air.fragment", "air.kernel"})rewriter.completeStage(stage);- if (!rewriter.changed)+ if (!rewriter.changed && inputs.empty())return nullptr;std::string text = rewriter.text();LLVMMemoryBufferRef buffer = LLVMCreateMemoryBufferWithMemoryRangeCopy(text.data(), text.size(), "OpenGL ES shader");@@ -328,5 +464,26 @@ LLVMModuleRef completedGLESModule(LLVMModuleRef module, const char **error) {*error = reason.c_str();return nullptr;}+ if (!inputs.empty()) {+ // Resolve parameters in the parsed copy, never mutate the caller's+ // module or retain references to its original function values.+ inputs.clear();+ if (!pointCoordinates(completed, inputs, error)) {+ LLVMDisposeModule(completed);+ return nullptr;+ }+ flipPointCoordinates(completed, inputs);+ if (LLVMVerifyModule(completed, 2 /* LLVMReturnStatusAction */, &message)) {+ static thread_local std::string reason;+ reason = std::string("invalid OpenGL ES point-coordinate conversion: ") + (message ? message : "");+ if (message)+ LLVMDisposeMessage(message);+ LLVMDisposeModule(completed);+ *error = reason.c_str();+ return nullptr;+ }+ if (message)+ LLVMDisposeMessage(message);+ }return completed;}diff --git a/VPhoneGuestComponents/GraphicLoader/README.md b/VPhoneGuestComponents/GraphicLoader/README.mdindex bd8c6d83..9301f251 100644--- a/VPhoneGuestComponents/GraphicLoader/README.md+++ b/VPhoneGuestComponents/GraphicLoader/README.md@@ -26,10 +26,20 @@ 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`.+`GLESAIR.mm` completes the argument metadata of AIR modules AppleMetalGLRenderer+builds for OpenGL ES, and `main.mm` supplies missing `air.version` metadata+before GPUCompiler consumes them. The original missing fields caused GLES+shader compilation to crash `MTLCompilerService`. This includes ES1 generated+programs, identified by `OpenGL ES Program`, as well as `OpenGL ES GLSL`.++The compiler also converts GLES fragment `air.point_coord` Y to `1-y` because+the supported PV render-pass path does not honor the private Y-flip flag that+AppleMetalGLRenderer requests. It accepts half2 and float2 inputs, preserves X,+and records a module marker to avoid repeated conversion. This compensation+must be revisited if PV gains native support for the render-pass flag.++`make -C VPhoneGuestComponents test-gles-air` runs captured modules through the+plugin and into host Metal, checking pixels, scope and idempotence. The retained+[AIR tests](../Tests/GLESAIRTests.mm) record fixture origins and the coordinate+oracle. See [OpenGL ES research](../../Research/Guest/gpu_acceleration.md#opengl-es)+for the native guest results and limits of these host checks.diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefileindex 9b6581af..d5cfb37f 100644--- a/VPhoneGuestComponents/Makefile+++ b/VPhoneGuestComponents/Makefile@@ -176,6 +176,27 @@ GPU_DYNAMIC_LOOKUP_SYMS := \-Wl,-U,_LLVMParseIRInContext \-Wl,-U,_LLVMPrintModuleToString \-Wl,-U,_LLVMStructGetTypeAtIndex \+ -Wl,-U,_LLVMIsAFunction \+ -Wl,-U,_LLVMIsAConstantInt \+ -Wl,-U,_LLVMTypeOf \+ -Wl,-U,_LLVMConstIntGetZExtValue \+ -Wl,-U,_LLVMGetParam \+ -Wl,-U,_LLVMGetFirstUse \+ -Wl,-U,_LLVMGetFirstBasicBlock \+ -Wl,-U,_LLVMGetFirstInstruction \+ -Wl,-U,_LLVMGetNextInstruction \+ -Wl,-U,_LLVMIsAPHINode \+ -Wl,-U,_LLVMCreateBuilderInContext \+ -Wl,-U,_LLVMPositionBuilderBefore \+ -Wl,-U,_LLVMDisposeBuilder \+ -Wl,-U,_LLVMConstReal \+ -Wl,-U,_LLVMBuildExtractElement \+ -Wl,-U,_LLVMBuildFSub \+ -Wl,-U,_LLVMBuildInsertElement \+ -Wl,-U,_LLVMReplaceAllUsesWith \+ -Wl,-U,_LLVMSetOperand \+ -Wl,-U,_LLVMVerifyModule \+ -Wl,-U,_LLVMDisposeModule \-Wl,-U,_MTLGPUCompilerCreate \-Wl,-U,_MTLGPUCompilerDestroy \-Wl,-U,_MTLDowngradeAIRModule \diff --git a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.cindex b5eb0f8f..290176aa 100644--- a/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c+++ b/VPhoneGuestComponents/SystemHook/SystemHook-vphone.c@@ -228,6 +228,12 @@ __attribute__((constructor)) static void vpLogProcess(void) {if (access("/usr/lib/vphone-metal-cache-reuse", F_OK) == 0) {setenv("FS_CACHE_REUSE_ON_REBOOT", "1", 0);}+ // The paravirtual GPU does not preserve IOSurface attachment yInvert.+ // Select AppleMetalGLRenderer's native viewport/scissor alternative before+ // an EAGLContext exists, preserving an explicit application setting.+ if (access("/usr/lib/vphone-gles-upper-left", F_OK) == 0) {+ setenv("AGX_GL_VIEWPORT_INVERT_CONFIG", "UPPER_LEFT", 0);+ }char path[PATH_MAX];uint32_t length = sizeof(path);diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-fragment.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-fragment.llnew file mode 100644index 00000000..010b1d19--- /dev/null+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-fragment.ll@@ -0,0 +1,64 @@+; iOS 26.6.2 (23G90), 2026-11-02: extracted from captured pipeline 2's+; fragment metallib with complete argument metadata and no point-coordinate flip.+; ModuleID = '/tmp/vphone-native-fixes/point-coordinate-metallibs/2-fragment.metallib'+source_filename = "Fragment_State_Program"+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.0 = type opaque+%struct._sampler_t.1 = type opaque++; Function Attrs: nounwind+define { <4 x float> } @"#main"(<4 x float> %0, <4 x float> %1, <2 x float> %2, <4 x float> addrspace(2)* %3, %struct._texture_2d_t.0 addrspace(1)* %4, %struct._sampler_t.1 addrspace(2)* %5) #0 {+allocaBlock:+ %6 = alloca <4 x float>, align 16+ store <4 x float> undef, <4 x float>* %6, align 16+ br label %entry++entry: ; preds = %allocaBlock+ %7 = shufflevector <2 x float> %2, <2 x float> %2, <4 x i32> <i32 0, i32 1, i32 0, i32 0>+ %8 = getelementptr <4 x float>, <4 x float> addrspace(2)* %3, i32 0+ %9 = load <4 x float>, <4 x float> addrspace(2)* %8, align 16+ %10 = extractelement <4 x float> %7, i32 0+ %11 = insertelement <2 x float> undef, float %10, i32 0+ %12 = extractelement <4 x float> %7, i32 1+ %13 = insertelement <2 x float> %11, float %12, i32 1+ %14 = extractelement <4 x float> %9, i32 0+ %15 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t.0 addrspace(1)* %4, %struct._sampler_t.1 addrspace(2)* %5, <2 x float> %13, i1 false, <2 x i32> zeroinitializer, i1 false, float %14, float 0.000000e+00, i32 0)+ %texVal = extractvalue { <4 x float>, i8 } %15, 0+ %16 = call reassoc nsz arcp contract afn <4 x float> @air.clamp.v4f32(<4 x float> %texVal, <4 x float> zeroinitializer, <4 x float> <float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00>)+ store <4 x float> %16, <4 x float>* %6, align 16+ %17 = load <4 x float>, <4 x float>* %6, align 16+ %returnValue = insertvalue { <4 x float> } undef, <4 x float> %17, 0+ ret { <4 x float> } %returnValue+}++; Function Attrs: nounwind readonly+declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(%struct._texture_2d_t.0 addrspace(1)*, %struct._sampler_t.1 addrspace(2)*, <2 x float>, i1, <2 x i32>, i1, float, float, i32) #1++; Function Attrs: nounwind readonly+declare <4 x float> @air.clamp.v4f32(<4 x float>, <4 x float>, <4 x float>) #1++attributes #0 = { nounwind }+attributes #1 = { nounwind readonly }++!air.language_version = !{!0}+!air.compile_options = !{!1, !2, !3}+!air.fragment = !{!4}+!air.version = !{!14}++!0 = !{!"OpenGL ES Program", 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 float> } (<4 x float>, <4 x float>, <2 x float>, <4 x float> addrspace(2)*, %struct._texture_2d_t.0 addrspace(1)*, %struct._sampler_t.1 addrspace(2)*)* @"#main", !5, !7}+!5 = !{!6}+!6 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}+!7 = !{!8, !9, !10, !11, !12, !13}+!8 = !{i32 0, !"air.fragment_input", !"user(front_color)", !"air.perspective", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"_gles_arg0"}+!9 = !{i32 1, !"air.fragment_input", !"user(tex_coord0)", !"air.perspective", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"_gles_arg1"}+!10 = !{i32 2, !"air.point_coord", !"air.arg_type_name", !"float2", !"air.arg_name", !"_gles_arg2"}+!11 = !{i32 3, !"air.buffer", !"air.buffer_size", i32 16, !"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_arg3"}+!12 = !{i32 4, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d<float, sample>", !"air.arg_name", !"_gles_arg4"}+!13 = !{i32 5, !"air.sampler", !"air.location_index", i32 0, i32 1, !"air.arg_type_name", !"sampler", !"air.arg_name", !"_gles_arg5"}+!14 = !{i32 2, i32 7, i32 0}diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-vertex.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-vertex.llnew file mode 100644index 00000000..3d52b394--- /dev/null+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es1-vertex.ll@@ -0,0 +1,88 @@+; iOS 26.6.2 (23G90), 2026-11-02: extracted from captured pipeline 2's+; vertex metallib after argument metadata completion.+; ModuleID = '/tmp/vphone-native-fixes/point-coordinate-metallibs/2-vertex.metallib'+source_filename = "Vertex_State_Program"+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 float>, <4 x float>, <4 x float>, float } @"#main"(<4 x float> %0, <4 x float> %1, <4 x float> %2, <4 x float> addrspace(2)* %3) #0 {+allocaBlock:+ %4 = alloca <4 x float>, align 16+ store <4 x float> undef, <4 x float>* %4, align 16+ %5 = alloca <4 x float>, align 16+ store <4 x float> undef, <4 x float>* %5, align 16+ %6 = alloca <4 x float>, align 16+ store <4 x float> undef, <4 x float>* %6, align 16+ %7 = alloca <4 x float>, align 16+ store <4 x float> undef, <4 x float>* %7, align 16+ br label %entry++entry: ; preds = %allocaBlock+ store <4 x float> %0, <4 x float>* %4, align 16+ store <4 x float> %1, <4 x float>* %5, align 16+ %8 = getelementptr <4 x float>, <4 x float> addrspace(2)* %3, i32 0+ %9 = load <4 x float>, <4 x float> addrspace(2)* %8, align 16+ %10 = load <4 x float>, <4 x float>* %6, align 16+ %11 = extractelement <4 x float> %9, i32 0+ %12 = insertelement <4 x float> %10, float %11, i32 0+ store <4 x float> %12, <4 x float>* %6, align 16+ store <4 x float> %2, <4 x float>* %7, align 16+ %13 = load <4 x float>, <4 x float>* %5, align 16+ %14 = call nsz arcp <4 x float> @air.clamp.v4f32(<4 x float> %13, <4 x float> zeroinitializer, <4 x float> <float 1.000000e+00, float 1.000000e+00, float 1.000000e+00, float 1.000000e+00>)+ %returnValue = insertvalue { <4 x float>, <4 x float>, <4 x float>, float } undef, <4 x float> %14, 0+ %15 = load <4 x float>, <4 x float>* %7, align 16+ %returnValue1 = insertvalue { <4 x float>, <4 x float>, <4 x float>, float } %returnValue, <4 x float> %15, 1+ %16 = load <4 x float>, <4 x float>* %4, align 16+ %returnValue2 = insertvalue { <4 x float>, <4 x float>, <4 x float>, float } %returnValue1, <4 x float> %16, 2+ %17 = load <4 x float>, <4 x float>* %6, align 16+ %18 = extractelement <4 x float> %17, i32 0+ %returnValue3 = insertvalue { <4 x float>, <4 x float>, <4 x float>, float } %returnValue2, float %18, 3+ ret { <4 x float>, <4 x float>, <4 x float>, float } %returnValue3+}++; Function Attrs: nounwind readonly+declare <4 x float> @air.clamp.v4f32(<4 x float>, <4 x float>, <4 x float>) #1++define { <4 x float>, <4 x float>, <4 x float>, float } @air.vertexFetchFunction(<4 x float> addrspace(2)* %0, <{ [32 x i8] }> addrspace(2)* %1, <{ [8 x i8] }> addrspace(1)* %2, i32 zeroext %3) {+Body:+ %4 = zext i32 %3 to i64+ %5 = getelementptr <{ [8 x i8] }>, <{ [8 x i8] }> addrspace(1)* %2, i64 %4, i32 0, i64 0+ %6 = bitcast i8 addrspace(1)* %5 to <2 x float> addrspace(1)*+ %7 = load <2 x float>, <2 x float> addrspace(1)* %6, align 4+ %8 = shufflevector <2 x float> %7, <2 x float> <float 1.000000e+00, float 0.000000e+00>, <4 x i32> <i32 0, i32 1, i32 3, i32 2>+ %9 = getelementptr <{ [32 x i8] }>, <{ [32 x i8] }> addrspace(2)* %1, i64 0, i32 0, i64 0+ %10 = bitcast i8 addrspace(2)* %9 to <4 x float> addrspace(2)*+ %11 = load <4 x float>, <4 x float> addrspace(2)* %10, align 4+ %12 = getelementptr <{ [32 x i8] }>, <{ [32 x i8] }> addrspace(2)* %1, i64 0, i32 0, i64 16+ %13 = bitcast i8 addrspace(2)* %12 to <4 x float> addrspace(2)*+ %14 = load <4 x float>, <4 x float> addrspace(2)* %13, align 4+ %15 = call { <4 x float>, <4 x float>, <4 x float>, float } @"#main"(<4 x float> %8, <4 x float> %11, <4 x float> %14, <4 x float> addrspace(2)* %0)+ ret { <4 x float>, <4 x float>, <4 x float>, float } %15+}++attributes #0 = { nounwind }+attributes #1 = { nounwind readonly }++!air.compile_options = !{!0, !1, !2, !3}+!air.language_version = !{!4}+!air.vertex = !{!5}+!air.version = !{!16}++!0 = !{!"air.compile.fast_math_disable"}+!1 = !{!"air.compile.fast_math_enable"}+!2 = !{!"air.compile.denorms_disable"}+!3 = !{!"air.compile.native_double_disable"}+!4 = !{!"OpenGL ES Program", i32 1, i32 0, i32 0}+!5 = !{{ <4 x float>, <4 x float>, <4 x float>, float } (<4 x float> addrspace(2)*, <{ [32 x i8] }> addrspace(2)*, <{ [8 x i8] }> addrspace(1)*, i32)* @air.vertexFetchFunction, !6, !11}+!6 = !{!7, !8, !9, !10}+!7 = !{!"air.vertex_output", !"user(front_color)", !"air.perspective", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"_gles_out0"}+!8 = !{!"air.vertex_output", !"user(tex_coord0)", !"air.perspective", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"_gles_out1"}+!9 = !{!"air.position", !"air.perspective", !"air.center", !"air.arg_type_name", !"float4", !"air.arg_name", !"_gles_out2"}+!10 = !{!"air.point_size", !"air.perspective", !"air.center", !"air.arg_type_name", !"float", !"air.arg_name", !"_gles_out3"}+!11 = !{!12, !13, !14, !15}+!12 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 16, !"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_arg0"}+!13 = !{i32 1, !"air.buffer", !"air.location_index", i32 14, i32 1, !"air.read", !"air.arg_type_name", !"void", !"air.arg_name", !".hidden", !"air.address_space", i32 2, !"air.arg_type_size", i32 32, !"air.arg_type_align_size", i32 1}+!14 = !{i32 2, !"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 8, !"air.arg_type_align_size", i32 1}+!15 = !{i32 3, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"_gles_arg3"}+!16 = !{i32 2, i32 7, i32 0}diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es3-fragment.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es3-fragment.llnew file mode 100644index 00000000..dd9f6bbb--- /dev/null+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-coord-es3-fragment.ll@@ -0,0 +1,55 @@+; iOS 26.6.2 (23G90), 2026-11-02: extracted from captured pipeline 6's+; fragment metallib with complete argument metadata and no point-coordinate flip.+; ModuleID = '/tmp/vphone-native-fixes/point-coordinate-metallibs/6-fragment.metallib'+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 float> } @"#main"(<2 x half> %0, <4 x float> addrspace(2)* %1) #0 {+allocaBlock:+ %2 = alloca <2 x half>, align 4+ %3 = alloca <2 x half>, align 4+ %4 = alloca <4 x half>, align 8+ %5 = alloca <4 x float>, align 16+ %6 = alloca <4 x float>, align 16+ br label %globalBlock++globalBlock: ; preds = %allocaBlock+ br label %block++block: ; preds = %globalBlock+ store <2 x half> %0, <2 x half>* %2, align 4+ %7 = load <2 x half>, <2 x half>* %2, align 4+ store <2 x half> %7, <2 x half>* %3, align 4+ %8 = load <2 x half>, <2 x half>* %3, align 4+ %9 = shufflevector <2 x half> %8, <2 x half> <half 0xH3C00, half 0xH3C00>, <4 x i32> <i32 0, i32 1, i32 2, i32 3>+ store <4 x half> %9, <4 x half>* %4, align 8+ %10 = load <4 x half>, <4 x half>* %4, align 8+ %11 = fpext <4 x half> %10 to <4 x float>+ store <4 x float> %11, <4 x float>* %5, align 16+ %12 = load <4 x float>, <4 x float>* %5, align 16+ store <4 x float> %12, <4 x float>* %6, align 16+ %13 = load <4 x float>, <4 x float>* %6, align 16+ %14 = insertvalue { <4 x float> } undef, <4 x float> %13, 0+ ret { <4 x float> } %14+}++attributes #0 = { nounwind }++!air.language_version = !{!0}+!air.compile_options = !{!1, !2, !3}+!air.fragment = !{!4}+!air.version = !{!10}++!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 float> } (<2 x half>, <4 x float> addrspace(2)*)* @"#main", !5, !7}+!5 = !{!6}+!6 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}+!7 = !{!8, !9}+!8 = !{i32 0, !"air.point_coord", !"air.arg_type_name", !"half2", !"air.arg_name", !"_gles_arg0"}+!9 = !{i32 1, !"air.buffer", !"air.buffer_size", i32 16, !"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_arg1"}+!10 = !{i32 2, i32 7, i32 0}diff --git a/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-vertex.ll b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-vertex.llnew file mode 100644index 00000000..8decb398--- /dev/null+++ b/VPhoneGuestComponents/Tests/GLESAIRFixtures/point-vertex.ll@@ -0,0 +1,75 @@+; iOS 26.6.2 (23G90), 2026-11-02: captured before argument metadata+; completion as 409-2-before.ll; vertex partner for the ES3 point-coordinate test.+; 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 { float, <4 x float> } @"#main"(<2 x float> %0, <4 x float> addrspace(2)* %1) #0 {+allocaBlock:+ %2 = alloca <2 x float>, align 8+ %3 = alloca <2 x float>, align 8+ %4 = alloca <4 x float>, align 16+ %5 = alloca <4 x float>, align 16+ %6 = alloca float, align 4+ %7 = alloca <4 x float>, align 16+ %8 = alloca float, align 4+ br label %globalBlock++globalBlock: ; preds = %allocaBlock+ %9 = getelementptr <4 x float>, <4 x float> addrspace(2)* %1, i32 0+ br label %block++block: ; preds = %globalBlock+ store <2 x float> %0, <2 x float>* %2, align 8+ %10 = load <2 x float>, <2 x float>* %2, align 8+ store <2 x float> %10, <2 x float>* %3, align 8+ %11 = load <2 x float>, <2 x float>* %3, align 8+ %12 = shufflevector <2 x float> %11, <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> %12, <4 x float>* %4, align 16+ %13 = load <4 x float>, <4 x float>* %4, align 16+ store <4 x float> %13, <4 x float>* %5, align 16+ %14 = bitcast <4 x float> addrspace(2)* %9 to float addrspace(2)*+ %15 = load float, float addrspace(2)* %14, align 4+ store float %15, float* %6, align 4+ %16 = load <4 x float>, <4 x float>* %5, align 16+ store <4 x float> %16, <4 x float>* %7, align 16+ %17 = load float, float* %6, align 4+ %18 = load float, float* %8, align 4+ store float %17, float* %8, align 4+ %19 = load <4 x float>, <4 x float>* %7, align 16+ %20 = insertvalue { float, <4 x float> } undef, <4 x float> %19, 1+ %21 = load float, float* %8, align 4+ %22 = insertvalue { float, <4 x float> } %20, float %21, 0+ ret { float, <4 x float> } %22+}++define { float, <4 x float> } @air.vertexFetchFunction(<4 x float> addrspace(2)* %0, <{ [8 x i8] }> addrspace(1)* %1, i32 zeroext %2) {+Body:+ %3 = zext i32 %2 to i64+ %4 = getelementptr <{ [8 x i8] }>, <{ [8 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 = call { float, <4 x float> } @"#main"(<2 x float> %6, <4 x float> addrspace(2)* %0)+ ret { float, <4 x float> } %7+}++attributes #0 = { nounwind }++!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 = !{{ float, <4 x float> } (<4 x float> addrspace(2)*, <{ [8 x i8] }> addrspace(1)*, i32)* @air.vertexFetchFunction, !5, !8}+!5 = !{!6, !7}+!6 = !{!"air.point_size"}+!7 = !{!"air.position"}+!8 = !{!9, !10, !11}+!9 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 16, !"air.location_index", i32 12, i32 1, !"air.read"}+!10 = !{i32 1, !"air.buffer", !"air.location_index", i32 15, i32 1, !"air.read", !"air.arg_type_name", !"void", !"air.arg_name", !".hidden"}+!11 = !{i32 2, !"air.vertex_id", !"air.arg_type_name", !"uint"}diff --git a/VPhoneGuestComponents/Tests/GLESAIRTests.mm b/VPhoneGuestComponents/Tests/GLESAIRTests.mmindex 965f345b..7110d9aa 100644--- a/VPhoneGuestComponents/Tests/GLESAIRTests.mm+++ b/VPhoneGuestComponents/Tests/GLESAIRTests.mm@@ -1,12 +1,11 @@// 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+// The original fixtures are iOS 27.0.1 guest captures; the point fixtures'+// headers identify their iOS 26.6.2 captures and metadata completion state.+// Each module is run through the plugin as MTLCompilerService runs it, and its+// metallib must load into host Metal as the right function stage. The tests+// check linkage and pixels, while native guest probes separately exercise PV+// transport and draw submission. Built as a dylib and loaded by// GLESAIRTestRunner after libLLVM and libGPUCompiler, as the compiler service// loads the plugin.@@ -27,6 +26,7 @@ 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 LLVMDisposeMessage(char *Message);void *MTLCompilerCreate(void *targetInfo, uint64_t version);bool MTLCompilerBuildRequestWithOptions(void *compiler, const void *inputData, size_t inputSize, unsigned flags, LLVMModuleRef module,@@ -38,26 +38,110 @@ static int failures = 0;static void check(bool condition, const char *what) {printf("%s %s\n", condition ? "ok " : "FAIL", what);+ fflush(stdout);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;+static LLVMModuleRef parseText(const char *text, size_t size, const char *name) {LLVMModuleRef module = nullptr;char *error = nullptr;- if (LLVMParseIRInContext(LLVMContextCreate(), LLVMCreateMemoryBufferWithMemoryRangeCopy((const char *)text.bytes, text.length, name), &module, &error))+ if (LLVMParseIRInContext(LLVMContextCreate(), LLVMCreateMemoryBufferWithMemoryRangeCopy(text, size, name), &module, &error)) {+ if (error)+ LLVMDisposeMessage(error);return nullptr;+ }return module;}+static LLVMModuleRef parse(const char *directory, const char *name) {+ NSString *path = [NSString stringWithFormat:@"%s/%s", directory, name];+ NSData *text = [NSData dataWithContentsOfFile:path];+ return text ? parseText((const char *)text.bytes, text.length, name) : nullptr;+}++static std::string moduleText(LLVMModuleRef module) {+ char *printed = LLVMPrintModuleToString(module);+ std::string text = printed ? printed : "";+ if (printed)+ LLVMDisposeMessage(printed);+ return text;+}+static bool contains(const std::string &text, const char *needle) {return text.find(needle) != std::string::npos;}+static size_t occurrences(const std::string &text, const std::string &needle) {+ size_t count = 0, offset = 0;+ while ((offset = text.find(needle, offset)) != std::string::npos) {+ count++;+ offset += needle.size();+ }+ return count;+}++// A float4 uniform lives in address space 2; the fixture data layout gives it+// size/alignment 16. Exercise every subset of preexisting layout fields, not+// just the all-missing layout of the originally captured module. Derive an+// ES1 language control from the same IR to exercise its legacy metadata too.+static void testPartialBufferCompletion(const char *fixtures) {+ LLVMModuleRef original = parse(fixtures, "textured-fragment.ll");+ check(original != nullptr, "the partial-buffer source fixture parses");+ if (!original)+ return;+ const std::string source = moduleText(original);+ const std::string bufferNode = "!{i32 2, !\"air.buffer\", !\"air.buffer_size\", i32 112, !\"air.location_index\", i32 12, i32 1, !\"air.read\"}";+ const size_t location = source.find(bufferNode);+ const size_t languageOffset = source.find("OpenGL ES GLSL");+ check(location != std::string::npos && languageOffset != std::string::npos,+ "the fixture has the expected GLSL language and legacy uniform-buffer node");+ if (location == std::string::npos || languageOffset == std::string::npos)+ return;+ const char *keys[] = {"air.address_space", "air.arg_type_size", "air.arg_type_align_size"};+ const unsigned derived[] = {2, 16, 16};+ for (const char *language : {"OpenGL ES GLSL", "OpenGL ES Program"}) for (unsigned mask = 0; mask < 8; mask++) {+ std::string input = source;+ std::string additions;+ for (unsigned field = 0; field < 3; field++) {+ if (mask & (1u << field))+ additions += ", !\"" + std::string(keys[field]) + "\", i32 " + std::to_string(derived[field]);+ }+ input.insert(location + bufferNode.size() - 1, additions);+ input.replace(languageOffset, strlen("OpenGL ES GLSL"), language);+ LLVMModuleRef module = parseText(input.data(), input.size(), "partial buffer");+ const char *error = nullptr;+ LLVMModuleRef completed = module ? completedGLESModule(module, &error) : nullptr;+ std::string label = std::string(language) + " partial buffer mask " + std::to_string(mask);+ check(completed && !error, (label + " completes").c_str());+ if (!completed)+ continue;+ const std::string output = moduleText(completed);+ bool fieldsCorrect = true;+ for (unsigned field = 0; field < 3; field++) {+ const std::string key = "!\"" + std::string(keys[field]) + "\"";+ fieldsCorrect &= occurrences(output, key) == 1;+ fieldsCorrect &= contains(output, (key + ", i32 " + std::to_string(derived[field])).c_str());+ }+ check(fieldsCorrect, (label + " has each correct layout field exactly once").c_str());+ error = nullptr;+ check(completedGLESModule(completed, &error) == nullptr && !error && moduleText(completed) == output,+ (label + " is unchanged on a second completion").c_str());+ }++ // Existing producer values are authoritative even when the LLVM pointee's+ // ABI size is smaller than the producer's full logical buffer type.+ std::string preserved = source;+ preserved.insert(location + bufferNode.size() - 1,+ ", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 112, !\"air.arg_type_align_size\", i32 16");+ LLVMModuleRef module = parseText(preserved.data(), preserved.size(), "existing buffer layout");+ const char *error = nullptr;+ LLVMModuleRef completed = module ? completedGLESModule(module, &error) : nullptr;+ const std::string output = completed ? moduleText(completed) : "";+ check(completed && !error && occurrences(output, "!\"air.arg_type_size\"") == 1 &&+ contains(output, "!\"air.arg_type_size\", i32 112"), "an existing buffer type size is preserved");+}+// 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");@@ -132,10 +216,191 @@ static void testMetallibs(const char *fixtures) {}}+static id<MTLFunction> fixtureFunction(const char *fixtures, const char *file, MTLFunctionType type,+ void *compiler, id<MTLDevice> device) {+ LLVMModuleRef module = parse(fixtures, file);+ std::string label(file);+ bool recognized = module && isGLESModule(module);+ check(recognized, (label + " is recognized as GLES").c_str());+ if (!recognized)+ return nil;+ const void *code = nullptr, *reflection = nullptr, *debug = nullptr;+ size_t codeSize = 0, reflectionSize = 0, debugSize = 0;+ const char *error = nullptr;+ bool failed = MTLCompilerBuildRequestWithOptions(compiler, nullptr, 0, 0, module,+ &code, &codeSize, &reflection, &reflectionSize, &debug, &debugSize, &error);+ check(!failed && code && codeSize, (label + " builds a metallib" + (error ? std::string(": ") + error : "")).c_str());+ if (failed || !code || !codeSize)+ return nil;+ NSError *libraryError = nil;+ id<MTLLibrary> library = [device newLibraryWithData:dispatch_data_create(code, codeSize, nil, nil) error:&libraryError];+ id<MTLFunction> value = library.functionNames.count == 1 ? [library newFunctionWithName:library.functionNames.firstObject] : nil;+ check(value && value.functionType == type, (label + " loads as its expected function stage").c_str());+ return value;+}++static void testPointCoordinateAdaptation(const char *fixtures) {+ for (const char *file : {"point-coord-es1-fragment.ll", "point-coord-es3-fragment.ll"}) {+ LLVMModuleRef original = parse(fixtures, file);+ check(original != nullptr, "the captured point-coordinate module parses");+ if (!original)+ continue;+ std::string source = moduleText(original), label(file);+ const char *error = nullptr;+ LLVMModuleRef completed = completedGLESModule(original, &error);+ check(completed && !error, (label + " adapts even though metadata was already complete").c_str());+ check(moduleText(original) == source, (label + " leaves the caller's original module unchanged").c_str());+ if (!completed)+ continue;+ const std::string output = moduleText(completed);+ check(contains(output, "!vphone.gles.point_coord_y_flipped =") &&+ contains(output, "vphone.point.flipped_y = fsub"), (label + " records the typed coordinate conversion").c_str());+ error = nullptr;+ check(completedGLESModule(completed, &error) == nullptr && !error && moduleText(completed) == output,+ (label + " is unchanged on a second module adaptation").c_str());++ std::string nonGLES = source;+ const char *language = contains(source, "OpenGL ES Program") ? "OpenGL ES Program" : "OpenGL ES GLSL";+ nonGLES.replace(nonGLES.find(language), strlen(language), "Metal");+ LLVMModuleRef metal = parseText(nonGLES.data(), nonGLES.size(), "native Metal point coordinate");+ check(metal != nullptr, "the native Metal point-coordinate control parses");+ if (!metal)+ continue;+ const std::string metalBefore = moduleText(metal);+ error = nullptr;+ check(!completedGLESModule(metal, &error) && !error && moduleText(metal) == metalBefore,+ (label + " does not adapt an otherwise identical native Metal module").c_str());++ std::string varying = source;+ const std::string semantic = "!\"air.point_coord\"";+ varying.replace(varying.find(semantic), semantic.size(), "!\"air.fragment_input\", !\"user(point_coord)\", !\"air.perspective\", !\"air.center\"");+ LLVMModuleRef ordinary = parseText(varying.data(), varying.size(), "ordinary varying with point-like name");+ check(ordinary != nullptr, "the ordinary varying control parses");+ if (!ordinary)+ continue;+ const std::string ordinaryBefore = moduleText(ordinary);+ error = nullptr;+ check(!completedGLESModule(ordinary, &error) && !error && moduleText(ordinary) == ordinaryBefore,+ (label + " leaves an ordinary user varying unchanged").c_str());+ }++ // Malformed metadata must produce a recoverable compiler error, without+ // indexing beyond the signature, asserting in APInt, or touching input IR.+ LLVMModuleRef sourceModule = parse(fixtures, "point-coord-es3-fragment.ll");+ if (!sourceModule)+ return;+ const std::string source = moduleText(sourceModule);+ const std::string pointInput = "!{i32 0, !\"air.point_coord\"";+ const size_t inputOffset = source.find(pointInput);+ check(inputOffset != std::string::npos, "the malformed-input fixture has its expected point semantic");+ if (inputOffset == std::string::npos)+ return;+ for (const char *index : {"i32 2", "i32 1", "i128 18446744073709551616", "null"}) {+ std::string malformed = source;+ malformed.replace(inputOffset, pointInput.size(), std::string("!{") + index + ", !\"air.point_coord\"");+ LLVMModuleRef module = parseText(malformed.data(), malformed.size(), "invalid point-coordinate index");+ check(module != nullptr, "the malformed point-coordinate metadata parses as IR");+ if (!module)+ continue;+ std::string before = moduleText(module);+ const char *error = nullptr;+ check(!completedGLESModule(module, &error) && error && moduleText(module) == before,+ "unsupported point-coordinate metadata fails safely without changing the input module");+ }+}++// Replay the actual ES1 float2 texture-coordinate replacement and ES3 half2+// gl_PointCoord programs. The PV path drops Apple's private render-pass Y+// flip; leave that host flag at its default false and require the shader to+// produce the same result as Apple's requested flip. Enabling the host flag+// as well would apply the conversion twice and invalidate this oracle.+// Expected Y follows the upper-left point-coordinate origin:+// t = 1/2 - (yf + 1/2 - yw) / size (OpenGL ES 2.0 section 3.3,+// OpenGL ES 3.0.6 section 3.4.1, and OES_point_sprite). X remains unchanged.+static void testPointCoordinatePixels(const char *fixtures) {+ struct { uint64_t target; } info = {0x700000002};+ void *compiler = MTLCompilerCreate(&info, 8);+ id<MTLDevice> device = MTLCreateSystemDefaultDevice();+ check(compiler && device, "the point-coordinate test has a compiler and device");+ if (!compiler || !device)+ return;+ for (bool es1 : {true, false}) {+ const char *vertexFile = es1 ? "point-coord-es1-vertex.ll" : "point-vertex.ll";+ const char *fragmentFile = es1 ? "point-coord-es1-fragment.ll" : "point-coord-es3-fragment.ll";+ std::string label = es1 ? "ES1 float2 point sprite" : "ES3 half2 point coordinate";+ id<MTLFunction> vertex = fixtureFunction(fixtures, vertexFile, MTLFunctionTypeVertex, compiler, device);+ id<MTLFunction> fragment = fixtureFunction(fixtures, fragmentFile, MTLFunctionTypeFragment, compiler, device);+ if (!vertex || !fragment)+ continue;+ MTLRenderPipelineDescriptor *descriptor = [MTLRenderPipelineDescriptor new];+ descriptor.vertexFunction = vertex;+ descriptor.fragmentFunction = fragment;+ descriptor.colorAttachments[0].pixelFormat = MTLPixelFormatRGBA8Unorm;+ NSError *error = nil;+ id<MTLRenderPipelineState> pipeline = [device newRenderPipelineStateWithDescriptor:descriptor error:&error];+ check(pipeline != nil, (label + " links into a host pipeline").c_str());+ if (!pipeline)+ continue;+ MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:8 height:8 mipmapped:NO];+ textureDescriptor.storageMode = MTLStorageModeShared;+ textureDescriptor.usage = MTLTextureUsageRenderTarget;+ id<MTLTexture> output = [device newTextureWithDescriptor:textureDescriptor];+ MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor];+ pass.colorAttachments[0].texture = output;+ pass.colorAttachments[0].loadAction = MTLLoadActionClear;+ pass.colorAttachments[0].storeAction = MTLStoreActionStore;+ pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1);+ id<MTLCommandBuffer> command = [[device newCommandQueue] commandBuffer];+ id<MTLRenderCommandEncoder> encoder = [command renderCommandEncoderWithDescriptor:pass];+ [encoder setRenderPipelineState:pipeline];+ const float position[] = {0.125f, 0.125f}, uniform[] = {3, 0, 0, 0}, zero[] = {0, 0, 0, 0};+ const float currents[] = {1, 1, 1, 1, 0, 0, 0, 1};+ [encoder setVertexBytes:position length:sizeof(position) atIndex:15];+ [encoder setVertexBytes:uniform length:sizeof(uniform) atIndex:12];+ [encoder setVertexBytes:currents length:sizeof(currents) atIndex:14];+ [encoder setFragmentBytes:zero length:sizeof(zero) atIndex:12];+ if (es1) {+ MTLTextureDescriptor *sourceDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:4 height:4 mipmapped:NO];+ sourceDescriptor.storageMode = MTLStorageModeShared;+ sourceDescriptor.usage = MTLTextureUsageShaderRead;+ id<MTLTexture> source = [device newTextureWithDescriptor:sourceDescriptor];+ uint8_t texels[64] = {};+ const uint8_t values[] = {43, 43, 128, 213};+ for (int y = 0; y < 4; y++) for (int x = 0; x < 4; x++) {+ int i = (y * 4 + x) * 4;+ texels[i] = values[x]; texels[i + 1] = values[y]; texels[i + 2] = texels[i + 3] = 255;+ }+ [source replaceRegion:MTLRegionMake2D(0, 0, 4, 4) mipmapLevel:0 withBytes:texels bytesPerRow:16];+ MTLSamplerDescriptor *sampler = [MTLSamplerDescriptor new];+ sampler.minFilter = MTLSamplerMinMagFilterNearest;+ sampler.magFilter = MTLSamplerMinMagFilterNearest;+ [encoder setFragmentTexture:source atIndex:0];+ [encoder setFragmentSamplerState:[device newSamplerStateWithDescriptor:sampler] atIndex:0];+ }+ [encoder drawPrimitives:MTLPrimitiveTypePoint vertexStart:0 vertexCount:1];+ [encoder endEncoding]; [command commit]; [command waitUntilCompleted];+ check(command.status == MTLCommandBufferStatusCompleted, (label + " completes its GPU command buffer").c_str());+ uint8_t pixels[256] = {};+ [output getBytes:pixels bytesPerRow:32 fromRegion:MTLRegionMake2D(0, 0, 8, 8) mipmapLevel:0];+ bool matches = output != nil;+ const int gradient[] = {43, 128, 213};+ for (int y = 0; y < 8; y++) for (int x = 0; x < 8; x++) {+ bool covered = x >= 3 && x <= 5 && y >= 2 && y <= 4;+ int expected[] = {covered ? gradient[x - 3] : 0, covered ? gradient[4 - y] : 0, covered ? 255 : 0, 255};+ for (int c = 0; c < 4; c++)+ matches &= abs((int)pixels[(y * 8 + x) * 4 + c] - expected[c]) <= 2;+ }+ check(matches, (label + " renders the full expected XY gradient and footprint").c_str());+ }+}+extern "C" int GLESAIRRunTests(const char *fixtures) {@autoreleasepool {testCompletion(fixtures);+ testPartialBufferCompletion(fixtures);testMetallibs(fixtures);+ testPointCoordinateAdaptation(fixtures);+ testPointCoordinatePixels(fixtures);}printf("%s\n", failures ? "GLES AIR tests FAILED" : "GLES AIR tests passed");return failures ? 1 : 0;