Run a virtual iPhone on an Apple Silicon Mac.
Swift
Let daemons open the paravirtual GPU, by class name
Jacky37ed2e65b988
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.mdindex 55d13cb0..92328d19 100644--- a/Research/0_binary_patch_comparison.md+++ b/Research/0_binary_patch_comparison.md@@ -482,6 +482,7 @@| JB-28 | A | `patch_disk_images2_client_abi` | `com.apple.driver.AppleDiskImages2` kext: `DIDeviceCreatorUserClient::CreateDevice` + `DIDeviceIOUserClient::Connect` ABI-version gates, and the `AllocPortsArray`/`RegisterNotificationPort` notif-port sizing | **iOS-27 DDI (`/System/Developer`) auto-mount — attach layer.** `pymobiledevice3 mounter auto-mount` on the 26.4-kernel / 27-userland hybrid fails at attach: the kernel DiskImages2 driver is ABI v9, the 27 userland's DiskImages2 controller/daemon is ABI v11 (`DIDeviceCreatorUserClient::CreateDevice: Incompatible client: expected ABI version 9 actual 11`). Three layers: **GATE1** NOPs the CreateDevice controller-ABI `cmp #9 ; b.ne` reject; **GATE2b** NOPs the Connect daemon-ABI `cmp #9 ; b.ne` reject (both anchored on the C++ signature cstring → unique `cmp #9`/`b.ne`; version-robust; no-op-in-effect on version-matched userlands where ABI 9==9). **GATE2** (array + 2 bound checks) fixes a RegisterNotificationPort off-by-one (userland registers at index==maxPorts, one past the array) by widening the AllocPortsArray allocation (`lsl x1,xN,#3` → `mov x1,#0x4000`) AND both bound-check field loads (`ldrh [.,#0xd8]`/`ldr [.,#0xe8]` → `mov wD,#0x800`); applied **all-or-nothing** (widening the bound checks without the backing array would let RegisterNotificationPort write past it → corruption) and skipped/logged on builds whose notif-port codegen differs (the off-by-one is 26.4-hybrid-specific). Pairs with the sandbox ops[124] allow (JB-09) and the diskimagesiod userland patch (CFW binary-patch #13). Anchors structural (Capstone decode of the pinned function's instructions); replacement bytes from the Keystone-backed `ARM64Encoder`. **GATE2a anchor note:** the AllocPortsArray size-shift is matched on `lsl` mnemonic + destination `x1` (the unique size-writing lsl in the function) — NOT a 3-operand `lsl xd,xn,#imm` shape, because Capstone on this toolchain decodes the lsl-immediate (a UBFM alias) as **2 operands**; requiring 3 operands makes GATE2 silently skip (the all-or-nothing returns a harmless no-op). Verified on the `c0ecdb4b` 26.4 deployment kernel via `patch-component --component kernel-jb --records-out`: all five di2 records emit (`di2_createdevice_abi`, `di2_connect_abi`, `di2_allocports_size`, `di2_notif_boundcheck_d8`, `di2_notif_boundcheck_e8`) — always verify the di2 records EMIT, not merely that the JB suite reports "no failures". No-op-in-effect for version-matched userlands. | Y || JB-29 | C | `patch_fpfs_scoped_vnode_open` | Sandbox MACF `mpo_vnode_check_open` (`ops[267]`) → per-process trampoline code cave | **iOS-27 random-respring fix (fpfs balloon).** JB-09 blanket-neuters `mpo_vnode_check_open` (`ops[267]` → allow) so processes can read `/var/jb`. But FileProvider's fpfs parent-walk (`fpfs_pkg_fd_lookup` → `openbyid` climbing via `getattrlistat(ATTR_CMN_PAROBJID)`) uses the stock check's EACCES at the domain-container boundary as its terminus; neutered, the walk climbs unbounded → `ResolverService` (FileProviderResolver) balloons to ~12 GB → `vm-compressor-space-shortage` jetsam → backboardd killed → **respring** (seen on 27b4/24A5390f). Fix keeps the global bypass and enforces the real check for the FileProvider daemons only: on 27, `ops[267]` is left un-neutered (removed from JB-09's blanket list — conditional `if !applyIOS27` in `patchSandboxHooksExtended`), then retargeted to a 20-insn code-cave trampoline that inlines `current_proc` (`mrs tpidr_el1` → `ldr [+0x3F0]` uthread → `ldr [+0x18]` proc), loads `p_comm` (`+0x56C`), compares the first 8 bytes to `"Resolver"`/`"fileprov"`, and on match `b`s to the real `vnode_check_open` (restores the terminus) else returns allow (`mov x0,#0 ; ret` → `/var/jb` reads + Sileo/TrollStore icons unaffected). Register-only (x8–x10), no frame/call (~18 insns/open). Struct offsets recovered via the VZ gdb stub on vphone600; cave bytes from the Keystone-backed `ARM64Encoder`, verified by Capstone round-trip; the `ops[267]` retarget preserves the auth-rebase high bits (same encoder family as JB-09). **VALIDATED on-device (2026-07-23, `17,3_27.0_24A5390f` + cloudOS 26.4, JB, `setup_machine` deploy): resprings stop; Sileo/TrollStoreLite icons render.** Backward-compat: a 26.5 base is unaffected (`ops[267]` still blanket-neutered there) — verified byte-identical kernelcache pre-vs-post (`cmp` clean, `sha256` unchanged). See `KernelJBPatchFpfsScopedOpen.swift`. | Y || JB-30 | B | `patchParavirtDisplayRefreshRate` | `AppleParavirtDisplay::createDisplayAttributes` (AppleParavirtGPUIOGPUFamily), the per-mode timing element call | **120 Hz display timing (opt-in, `kernel-exp-display_refresh_120hz`, off in `standard`).** The host VM service builds its one `PGDisplayMode` with a constant 60.0 Hz and writes it into the display shared state page as a 16-byte entry (u16 width, u16 height, u32 refresh in 16.16 Hz, flags); the guest turns each entry into an IOAV timing element with `ldurh w1,[xN,#-8]; ldurh w2,[xN,#-6]; ldur w3,[xN,#-4]; bl`. The `ldur w3` becomes `movz w3,#120,lsl #16`. Anchor: the `createDisplayAttributes` logger cstring (all refs in one function) + the only w1/w2/w3 load triple off one base at -8/-6/-4 ahead of a call. Gated by `KernelCustomFirmwarePatcher.applyDisplayRefresh`, set from the plan. See `Research/Guest/display_refresh_rate.md`. | opt-in |+| JB-31 | C | `patchParavirtUserClientsNarrow` (records `kernel-exp-paravirt_user_clients.redirect` / `.cave`) | Same IOUserClient Sandbox gate; the deny block's `ldr Xt,[sp,#imm]` eight bytes before the fail-log `adrp` | **Paravirtual device access on a 26.x / 18.x base (opt-in, off in `standard`).** Narrow replacement for the broad gate-off: at the deny point the class-name C string is already in x0, so a code-cave trampoline reads its first eight bytes and branches to the gate's NotPermitted allow target only for `ApplePar` / `AppleVid` / `AppleVir` / `IOSurfac` (AppleParavirt\*, AppleVideoToolboxParavirt\*, AppleVirtIO\*, IOSurfaceAcceleratorParavirtClient); every other denial runs the displaced `ldr` and falls through to the real deny. Fixes `MTLCreateSystemDefaultDevice()` nil in daemons/CLI and the VideoToolbox/ANE/IOSurface denials (upstream issue #22) without opening the rest. Cave words verified by clang/as + capstone round-trip; the two `b` words via `ARM64Encoder`. Gated by `KernelCustomFirmwarePatcher.applyParavirtUserClients`, set from the plan when `applyIOS27` is false. See `Research/Guest/gpu_acceleration.md`. | opt-in |### EXP-Only Kernel Methods (Reference List)diff --git a/Research/Guest/gpu_acceleration.md b/Research/Guest/gpu_acceleration.mdnew file mode 100644index 00000000..d43ac5c0--- /dev/null+++ b/Research/Guest/gpu_acceleration.md@@ -0,0 +1,182 @@+# GPU Acceleration in the Guest++Upstream issue Lakr233/vphone-cli#22 asks two things: why a Metal check run+inside the guest printed `device: (null)`, and why a guest whose apps do get+Metal is still laggy for a while after every boot. This note answers both from+measurements taken on 2026-10-04: macOS 27.0.1 (26A434), Apple M5 Pro,+cloudOS 26.4 (23E5207q) kernel, iPadOS 26.6.2 (23G90) userland, iPad Pro guests+`hz120-ipadpro` and `gpuaccel-ipad`. The measuring method is in+`display_refresh_rate.md`.++## The GPU Is in Use++The guest's Metal device is `Apple Paravirtual device GPU`. Each guest process+that uses Metal has a host `com.apple.gpusw.ParavirtualizedGraphicsGPUTask`+process that replays its commands on the host GPU through the host's own AGX+driver.++The issue's check, extended with a compute pass (a 2048×2048 RGBA16F texture, 64+`sin`/`cos` iterations per pixel) and run as a command-line tool:++| | Guest | Host (M5 Pro) |+| --- | --- | --- |+| GPU time for the pass, warm | 2.3–3.8 ms | 2.0–3.3 ms |+| Empty command buffer, commit and `waitUntilCompleted` | 0.12–0.27 ms | 0.02 ms |+| Compile from source and build the pipeline, warm | 80–220 ms | 265 ms uncached |+| The same, first time in a boot | 4.3–8.3 s | — |++GPU work runs at about native speed. A synchronous round trip costs six to+thirteen times the host's, and the first compile in a boot is slow.++The device reports `MTLGPUFamilyCommon3` and argument buffers tier 1, and no+Apple family or Metal 3. An app that requires those sees a lesser GPU than the+host has.++## `device: (null)` Outside an App++Reproduced on 26.6.2 with the tool run as root from a launchd job:++```+kernel: System Policy: MetalTest(648) deny(1) iokit-open-user-client AppleParavirtDeviceUserClient+kernel: IOUC AppleParavirtDeviceUserClient failed sandbox in process pid 648, MetalTest+MetalTest: Failed to create an IOGPUDevice... IOServiceOpen returned kIOReturn(0xE00002E2)+```++A 26.x sandbox knows nothing of the research board's paravirtual devices. An+app's container profile lets the app open the GPU's user client; the platform+policy every other process falls under does not. So Metal works in apps and in+the system UI, and a daemon or a command-line tool gets no device. The same gate+refused, on the same guest:++| User client | Refused to |+| --- | --- |+| `AppleParavirtDeviceUserClient` (Metal) | the command-line tool |+| `AppleVideoToolboxParavirtualizationUserClient` (video decoder) | `com.apple.WebKit` |+| `AppleVirtIONeuralEngineDeviceUserClient` (Neural Engine) | `spotlightknowledged`, `callservicesd` |+| `IOSurfaceAcceleratorParavirtClient` (scaler) | `vphoned` |++On a 27 base this gate is already off: `kernel-boot-iouc_sandbox_gate` is+boot-essential there, because 27 refuses backboardd its framebuffer. The opt-in+patch `kernel-exp-paravirt_user_clients` makes the same edit on a 26.x or 18.x+base. With it, on `gpuaccel-ipad`, the tool prints+`device: Apple Paravirtual device GPU` and the console holds no+`failed sandbox` line at all.++### Narrow by class name++The patch does not flip the whole gate. The deny block ends by logging+`IOUC %s failed sandbox in process %s`, and its first `%s` is the class name —+already in `x0` as a C string eight bytes before the fail-log `adrp`. The patch+overwrites that `ldr Xt, [sp, #imm]` with a branch to a code cave that reads the+first eight bytes of the class name, and branches to the gate's NotPermitted+allow target only when they equal one of four prefixes — `ApplePar`, `AppleVid`,+`AppleVir`, `IOSurfac` (AppleParavirt\*, AppleVideoToolboxParavirt\*,+AppleVirtIO\*, IOSurfaceAcceleratorParavirtClient). Any other class runs the+displaced `ldr` and falls through to the real deny, so every other sandbox denial+stays. The cave's fixed words are verified by clang/as assembly and a capstone+round-trip; the two position-dependent branches come from `ARM64Encoder`. The+anchor is the fail-string xref, the NotPermitted allow target and the deny-entry+`cbnz`, the same three the broad gate uses; the record is still+`kernel-exp-paravirt_user_clients` (sites `.redirect` and `.cave`).++Verified on a fresh iPad Pro guest (`narrowtest-ipad`, 26.6.2, both opt-in+patches on): it boots, and a plain command-line tool prints++```+RootDomainUserClient IOServiceOpen -> 0xe00002e2 (denied)+Metal device -> ALLOWED+```++— the paravirtual GPU opens from a daemon context while a non-allowlisted client+is still refused. It stays off in `standard`: Metal in daemons/CLI is a niche+need (apps already have it), so turning it on is a per-VM or preset choice; it is+a candidate to default on once it has had wider testing.++What it does not change: HLS video in Safari already played at the stream's+60 frames per second without it, with `mediaplaybackd` at 9% of a core and+`videocodecd` at 4%, so WebKit being refused the decoder is not a visible cost+there.++## Lag After Every Boot++Home Screen page swipes on `hz120-ipadpro`, by time since the VM started:++| Since start | On time | Hitches | Host shader compile | Busiest guest processes |+| --- | --- | --- | --- | --- |+| 7 s | 84% | 14 | 59% of a core | dasd 53%, SpringBoard 35%, backboardd 28%, MTLCompilerService 22% |+| 54 s | 89% | 1 | 1% | SpringBoard 25%, backboardd 17% |+| 85 s | 98% | 3 | 0% | backboardd 28%, SpringBoard 28% |++That is the lag the issue describes: after-boot work in the guest plus shaders+being compiled again, gone in about a minute and a half.++The shaders are compiled again because the host's shader cache is never hit.+Opening four apps that had all been opened in earlier boots cost 1.40 CPU-seconds+of host `MTLCompilerService` the first time after a restart and 0.19 the second+time in the same boot.++### Why the cache misses++Virtualization gives ParavirtualizedGraphics a cache directory per VM,+`$DARWIN_USER_CACHE_DIR/com.apple.paravirtualizedgraphics-<number>`, and each+host GPU task keeps its Metal function cache in a `task-<key>` directory under+it. `-[PGRemoteTask calculateCachePathAndExtension:taskRoot:]` picks the key:++- when the device's feature byte `0x36` is set, it reads 60 bytes of the guest's+ task root page and takes the 20 at offset `0x28`; if they are not all zero,+ the key is those 20 bytes in hex, 40 characters;+- otherwise the key is ten random bytes, 20 characters.++Across every VM and every boot on this Mac — 1823 task directories — the name is+20 characters, the random form. Not one is keyed. So the keyed branch is never+taken here, for any guest, which matches the feature byte being off:+`-[_PGDevice features]` returns the struct inline at device `+0x4e4`, and byte+`0x36` of it (device `+0x51a`) is what gates the read. The guest side has nothing+to offer it either: the AppleParavirt kext's task-root setup makes no use of a+cdhash or any 20-byte identity (its code-signing strings are XNU's, not the+kext's).++So this cannot be fixed by a guest firmware patch, which is the only thing+`fw`/`cfw` produce:++- The cache that misses is the **host's**, kept by `PGRemoteTask` in the VM+ service's address space.+- Whether it is keyed is decided **host-side** by that feature byte, which is off+ on this ParavirtualizedGraphics version and is not something the guest is seen+ to switch.+- Even with the feature on, the key is read from the guest's task-root page, and+ giving the guest driver code to populate it would be new kext code — but it+ would still only matter if the host read it, which it does not.++Reaching the host cache would mean changing the host ParavirtualizedGraphics+framework. That is Apple's code on the sealed system volume, and the shipped+bundle runs only system libraries, so it is out of scope. The post-boot+recompile is therefore a limitation of the host paravirtual GPU, not a guest+patch we can write. (A per-app `MTLBinaryArchive` inside a guest app would+persist that app's own pipelines, but that is an app change, not a VM one.)++## Settings That Do Nothing Here++Both are private properties of `VZMacGraphicsDeviceConfiguration`, tried on+`gpuaccel-ipad` across restarts and not kept in the code.++- `_enableProcessIsolation = false`. The guest still had ten host GPU task+ processes and the same pacing: Settings 98% on time either way, Safari 70%+ against 68%, Today View 87% against 88%.+- `_deviceFeatureLevel`. The default, 0, already gives what the highest level,+ 5 (the framework logs it as "2027"), gives: Common3 and argument buffers tier 1. Level 1+ ("2022") takes both away.++## Reproducing the Check++The tool is the issue's snippet built for the guest:++```zsh+xcrun -sdk iphoneos clang -arch arm64e -miphoneos-version-min=17.0 -fobjc-arc -O2 \+ -framework Foundation -framework Metal -framework QuartzCore -o MetalTest MetalTest.m+codesign -s - -f MetalTest+```++Copy it with `files.write` (`encoding: base64`), `files.chmod` it to 755, and run+it from a launchd plist with `RunAtLoad` and `StandardOutPath` loaded through+`services.load`. `/var/tmp` is emptied at every boot.diff --git a/Research/README.md b/Research/README.mdindex 3691b70c..f5cde6cd 100644--- a/Research/README.md+++ b/Research/README.md@@ -20,7 +20,7 @@ This directory keeps the evidence behind firmware patches, restore and the self-| Other patches and captures | [Launchd jetsam](Patches/cfw_patch_launchd_jetsam.md), [user-mode hypervisor references](Patches/hv_vmm_present_usermode_xrefs.md), [reference capture](Patches/patch_reference_capture.md) || Restore | [DFU probe](Restore/virtual_dfu_probe.md), [in-process restore](Restore/native_restore_architecture.md) || Host and archives | [Binary split](Host/host_binary_split.md), [runtime dependency tiers](Host/runtime_dependency_tiers.md), [archive extraction contracts](Host/archive_extraction_contracts.md), [libarchive validation](Host/libarchive_xcframework_validation.md), [guest MAC, fixed address, port forwarding and names](Host/network_fixed_address.md) |-| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md) |+| Guest interaction and VM identity | [DevMode XPC](Guest/devmode_xpc_protocol.md), [keyboard events](Guest/keyboard_event_pipeline.md), [machine identifier](Guest/machine_identifier_storage_analysis.md), [Auto-Lock on the Lock Screen](Guest/lock_screen_idle_timer.md), [display refresh rate](Guest/display_refresh_rate.md), [GPU acceleration](Guest/gpu_acceleration.md), [RootHide bootstrap base](Guest/roothide_bootstrap_base.md), [the Mac's .local name](Guest/mac_name_resolution.md) || Historical project records | [Migration ledger](History/intg_update_status.md), [manifest refactoring summary](History/manifest_and_refactoring_summary.md) |`KernelSymbols/` holds symbol datasets and indexes; `Reference/` holds source references when present. They are evidence inputs, not steps for running the distributed app. The files in `History/` are preserved snapshots and may describe scripts or variants that have since been removed.diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchIoucSandbox.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchIoucSandbox.swiftindex ac7265c6..d0899ed6 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchIoucSandbox.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchIoucSandbox.swift@@ -96,19 +96,19 @@ extension KernelCustomFirmwarePatcher {}/// CBNZ Wt, <label> (32-bit): high byte 0x35.- private func isCbnzW(_ insn: UInt32) -> Bool {+ func isCbnzW(_ insn: UInt32) -> Bool {((insn >> 24) & 0xFF) == 0x35}/// Decode CBZ/CBNZ target (imm19, sign-extended, scaled by 4).- private func cbTarget(_ insn: UInt32, at pc: Int) -> Int? {+ func cbTarget(_ insn: UInt32, at pc: Int) -> Int? {let imm19 = (insn >> 5) & 0x7FFFFreturn pc + Int(Int32(bitPattern: imm19 << 13) >> 13) * 4}/// If `insn` is B.EQ <label>, return its target; else nil./// B.cond: [31:24]=0x54, [4]=0, cond=[3:0]; EQ cond = 0.- private func bCondEqTarget(_ insn: UInt32, at pc: Int) -> Int? {+ func bCondEqTarget(_ insn: UInt32, at pc: Int) -> Int? {guard (insn & 0xFF00_0010) == 0x5400_0000, (insn & 0xF) == 0x0 else { return nil }let imm19 = (insn >> 5) & 0x7FFFFreturn pc + Int(Int32(bitPattern: imm19 << 13) >> 13) * 4diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchParavirtUserClients.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchParavirtUserClients.swiftnew file mode 100644index 00000000..01c01d57--- /dev/null+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Sandbox/KernelCustomFirmwarePatchParavirtUserClients.swift@@ -0,0 +1,199 @@+// KernelCustomFirmwarePatchParavirtUserClients.swift — CFW kernel patch:+// narrow IOUserClient sandbox allowlist for the paravirtual device clients.+//+// The broad `patchIoucFailedSandbox` redirects the IOUserClient sandbox gate's+// deny block straight to its allow target, which opens *every* user client to a+// process outside an app sandbox. On a 26.x / 18.x base that is more than the+// problem needs: a daemon or a command-line tool is refused only the research+// board's paravirtual devices, because a 26.x sandbox has no allow rule for+// their classes. The symptoms (Lakr233/vphone-cli#22):+// AppleParavirtDeviceUserClient -> Metal in a CLI/daemon+// AppleVideoToolboxParavirtualizationUserClient -> WebKit hardware decode+// AppleVirtIONeuralEngineDeviceUserClient -> Core ML / ANE+// IOSurfaceAcceleratorParavirtClient -> the paravirt scaler+//+// This patch allows only those, by class name, and leaves every other denial in+// place.+//+// Anchor (structural, no offsets). The deny block of the same gate ends by+// logging `IOUC %s failed sandbox in process %s`, whose first `%s` is the+// user-client class name. Right before the fail-log `adrp`, the class-name C+// string is already in x0:+//+// <site> ldr x8, [sp, #imm] ; displaced into the cave verbatim+// stp x0, x8, [sp] ; x0 = class-name cstring, x8 = proc+// <adrp> adrp x0, <"IOUC %s failed sandbox …">+// add x0, x0, #…+// bl <log>+// b <join: return deny>+//+// So `site = adrp - 8`. The patch overwrites `site` with `b <cave>`; the cave+// reads the first eight bytes of the class name, allows (branches to the gate's+// NotPermitted allow target) when they match one of the four prefixes above, and+// otherwise runs the displaced `ldr` and falls back into the real deny path. The+// deny-entry and allow-target are found exactly as `patchIoucFailedSandbox` finds+// them.+//+// Cave instruction words are inline, each verified by clang/as assembly and a+// capstone round-trip (mirroring the fpfs and syscallmask caves); the two+// position-dependent `b` words are built by `ARM64Encoder`.++import Foundation+import VPhonePatchKit++extension KernelCustomFirmwarePatcher {+ /// First eight bytes of each allowed class name, as the four movz/movk+ /// half-words a 64-bit immediate needs (hw[k] = name[2k+1] << 8 | name[2k]).+ private static let allowedClassPrefixes: [[UInt16]] = [+ [0x7041, 0x6C70, 0x5065, 0x7261], // "ApplePar" — AppleParavirt*+ [0x7041, 0x6C70, 0x5665, 0x6469], // "AppleVid" — AppleVideoToolboxParavirt*+ [0x7041, 0x6C70, 0x5665, 0x7269], // "AppleVir" — AppleVirtIO*+ [0x4F49, 0x7553, 0x6672, 0x6361], // "IOSurfac" — IOSurfaceAcceleratorParavirtClient+ ]++ @discardableResult+ func patchParavirtUserClientsNarrow(+ patchID: String = FirmwarePatchSetCatalog.paravirtUserClientsPatch,+ ) -> Bool {+ log("\n[CFW]paravirt user clients: narrow IOUC sandbox allowlist")++ guard let failStrOff = buffer.findString("IOUC %s failed sandbox in process %s") else {+ log(" [-] IOUC failed-sandbox format string not found")+ return false+ }+ let refs = findStringRefs(failStrOff)+ guard !refs.isEmpty else {+ log(" [-] no xrefs for IOUC failed-sandbox format string")+ return false+ }++ for (adrpOff, _) in refs {+ guard let funcStart = findFunctionStart(adrpOff) else { continue }+ let funcEnd = findFuncEnd(funcStart, maxSize: 0x2000)++ var off = funcStart+ while off < adrpOff {+ defer { off += 4 }+ let insn = buffer.readU32(at: off)+ guard isCbnzW(insn), let denyEntry = cbTarget(insn, at: off) else { continue }+ guard denyEntry <= adrpOff, adrpOff < denyEntry + 0x60,+ denyEntry > funcStart, denyEntry < funcEnd else { continue }++ var allowTarget = -1+ for back in stride(from: off - 4, through: off - 0x14, by: -4) where back > funcStart {+ if let t = bCondEqTarget(buffer.readU32(at: back), at: back), t > funcStart, t < funcEnd {+ allowTarget = t+ break+ }+ }+ guard allowTarget >= 0 else { continue }++ // The class-name cstring is live in x0 at `adrp - 8`, which is a+ // position-independent `ldr Xt, [sp, #imm]` (Xt is the proc name).+ let site = adrpOff - 8+ let denyContinue = adrpOff - 4+ guard site > denyEntry else { continue }+ let displaced = buffer.readU32(at: site)+ guard (displaced & 0xFFC0_0000) == 0xF940_0000, (displaced >> 5) & 0x1F == 31 else {+ log(" [-] site is not ldr Xt,[sp,#imm]: 0x\(String(format: "%08X", displaced))")+ continue+ }++ let wordCount = 2 + Self.allowedClassPrefixes.count * 6 + 2 + 1+ guard let caveOff = findCodeCave(size: wordCount * 4) else {+ log(" [-] no code cave")+ return false+ }+ guard let caveBytes = buildAllowlistCave(+ caveOff: caveOff,+ displacedWord: displaced,+ denyContinue: denyContinue,+ allowTarget: allowTarget,+ ) else { return false }+ guard let redirect = ARM64Encoder.encodeB(from: site, to: caveOff) else {+ log(" [-] could not encode redirect branch")+ return false+ }++ log(" [+] narrow allowlist fn=0x\(String(format: "%X", funcStart)), site=0x\(String(format: "%X", site)), cave=0x\(String(format: "%X", caveOff)), deny=0x\(String(format: "%X", denyEntry)), allow=0x\(String(format: "%X", allowTarget))")+ emit(+ site,+ redirect,+ patchID: "\(patchID).redirect",+ virtualAddress: fileOffsetToVA(site),+ description: "ldr Xt,[sp,#imm] -> b cave [paravirt user-client allowlist]",+ )+ emit(+ caveOff,+ caveBytes,+ patchID: "\(patchID).cave",+ virtualAddress: fileOffsetToVA(caveOff),+ description: "allow AppleParavirt/AppleVideoToolboxParavirt/AppleVirtIO/IOSurfaceAcceleratorParavirt, else deny",+ )+ return true+ }+ }++ log(" [-] narrow IOUC sandbox allowlist site not found")+ return false+ }++ /// Build the allowlist trampoline. Every fixed word is verified by clang/as+ /// assembly and a capstone round-trip; the two `b` words come from the+ /// keystone-backed `ARM64Encoder`.+ private func buildAllowlistCave(+ caveOff: Int,+ displacedWord: UInt32,+ denyContinue: Int,+ allowTarget: Int,+ ) -> Data? {+ /// movz x10,#hw0 ; movk x10,#hw{1,2,3},lsl #16·i (x10 = 8-byte prefix)+ func buildConst(_ hw: [UInt16]) -> [UInt32] {+ var out: [UInt32] = [0xD280_0000 | (UInt32(hw[0]) << 5) | 10]+ for i in 1 ..< 4 {+ out.append(0xF280_0000 | (UInt32(i) << 21) | (UInt32(hw[i]) << 5) | 10)+ }+ return out+ }++ var w: [UInt32] = [+ 0, // cbz x0, Ldeny (filled below)+ 0xF940_0009, // ldr x9, [x0] ; x9 = class name[0:8]+ ]+ var beqSites: [Int] = []+ for hw in Self.allowedClassPrefixes {+ w += buildConst(hw) // 4 words -> x10+ w.append(0xEB0A_013F) // cmp x9, x10+ beqSites.append(w.count)+ w.append(0) // b.eq Lallow (filled below)+ }+ let denyIdx = w.count+ w.append(displacedWord) // Ldeny: original ldr Xt,[sp,#imm]+ let denyBranchIdx = w.count+ w.append(0) // b <denyContinue> (filled below)+ let allowIdx = w.count+ w.append(0) // Lallow: b <allowTarget> (filled below)++ // cbz x0, Ldeny (rt = 0): imm19 = denyIdx (forward, in words)+ w[0] = 0xB400_0000 | ((UInt32(denyIdx) & 0x7FFFF) << 5)+ // b.eq Lallow for each class: imm19 = allowIdx - site+ for site in beqSites {+ let imm19 = UInt32(bitPattern: Int32(allowIdx - site)) & 0x7FFFF+ w[site] = 0x5400_0000 | (imm19 << 5) // cond EQ = 0+ }+ guard let denyB = ARM64Encoder.encodeB(from: caveOff + denyBranchIdx * 4, to: denyContinue),+ let allowB = ARM64Encoder.encodeB(from: caveOff + allowIdx * 4, to: allowTarget)+ else {+ log(" [-] could not encode cave branches")+ return nil+ }+ w[denyBranchIdx] = denyB.withUnsafeBytes { $0.load(as: UInt32.self) }.littleEndian+ w[allowIdx] = allowB.withUnsafeBytes { $0.load(as: UInt32.self) }.littleEndian++ var data = Data(capacity: w.count * 4)+ for word in w {+ withUnsafeBytes(of: word.littleEndian) { data.append(contentsOf: $0) }+ }+ return data+ }+}diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swiftindex dae343bc..3209f2da 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift@@ -35,6 +35,12 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,/// a guest keeps the host's 60 Hz mode unless the VM asked otherwise.public var applyDisplayRefresh = false+ /// Opt-in on a base older than 27: a narrow allowlist at the same sandbox gate,+ /// so a process outside an app sandbox can open the paravirtual GPU, video+ /// decoder, Neural Engine and IOSurface scaler user clients and nothing else.+ /// Set from the plan; `standard` blocks it.+ public var applyParavirtUserClients = false+public func findAll() throws -> [PatchRecord] {parseMachO()buildADRPIndex()@@ -61,6 +67,8 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,if applyIOS27 {patchIoucFailedSandbox()patchDiskImages2ClientAbi()+ } else if applyParavirtUserClients {+ patchParavirtUserClientsNarrow()}// Group Bdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swiftindex ab3bae7d..2dfc4ac0 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift@@ -264,6 +264,19 @@ public enum FirmwareKernelCustomFirmwarePatchSet {bootEssential: true,),+ VPhonePatchDeclaration(+ identifier: FirmwarePatchSetCatalog.paravirtUserClientsPatch,+ title: "Paravirtual device access",+ summary: """+ Lets a process outside an app sandbox open the paravirtual GPU, video decoder, \+ Neural Engine and IOSurface scaler, so daemons and command-line tools get Metal \+ and WebKit decodes video in hardware. Allows only those four device classes by \+ name; every other sandbox denial stays. Off by default.+ """,+ target: .firmware(.kernelcache),+ applicability: VPhonePatchApplicability(iOSBase: .oneOf([.major(26), .major(18)])),+ ),+// MARK: DisplayVPhonePatchDeclaration(diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swiftindex 64ebbfc9..02479465 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift@@ -57,11 +57,14 @@ public enum FirmwarePatchSetCatalog {////// `kernel-exp-display_refresh_120hz` is off because it is a preference with a/// cost: see ``displayRefreshPatch``.+ ///+ /// `kernel-exp-paravirt_user_clients` is off because it lifts a sandbox denial+ /// that nothing in the guest needs to boot: see ``paravirtUserClientsPatch``.public static let manualOnlyPatches: Set<String> =Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier)).union(hypervisorConcealmentPatches).union(experimentalIdentityPatches)- .union([misTrustAuthPatch, displayRefreshPatch])+ .union([misTrustAuthPatch, displayRefreshPatch, paravirtUserClientsPatch])/// The 120 Hz timing for the paravirtual display.///@@ -70,6 +73,19 @@ public enum FirmwarePatchSetCatalog {/// shows the difference. See `Research/Guest/display_refresh_rate.md`.public static let displayRefreshPatch = "kernel-exp-display_refresh_120hz"+ /// A narrow IOUserClient sandbox allowlist for the paravirtual devices, on a+ /// base older than 27.+ ///+ /// A 26.x sandbox knows nothing of the research board's paravirtual devices,+ /// so only an app's container profile lets a process open them. A daemon or a+ /// command-line tool gets no Metal device, WebKit no hardware video decoder,+ /// and Core ML no Neural Engine. The edit allows only the four paravirt device+ /// classes, by name, and leaves every other denial in place. Off in `standard`:+ /// apps already get these devices, so it is a per-VM choice.+ /// On 27 the broad `kernel-boot-iouc_sandbox_gate` is boot-essential instead. See+ /// `Research/Guest/gpu_acceleration.md`.+ public static let paravirtUserClientsPatch = "kernel-exp-paravirt_user_clients"+/// The shared-cache short-circuit of `libmis`'s `checkTrustAndAuthorization`.////// Off in `standard` because `libmisfix.dylib` reaches the same outcome fromdiff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swiftindex 9970c07f..976983eb 100644--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift@@ -92,6 +92,7 @@ extension FirmwarePipeline {// The 120 Hz display timing, off unless the VM asked for it.let applyDisplayRefresh = isEnabled(FirmwarePatchSetCatalog.displayRefreshPatch, fallback: false)+ let applyParavirtUserClients = isEnabled(FirmwarePatchSetCatalog.paravirtUserClientsPatch, fallback: false)// iOS 18 bases: disable the skywalk flowswitch netagents via boot-arg so// Network.framework uses the BSD path (the 26.1-kernel skywalk@@ -236,6 +237,7 @@ extension FirmwarePipeline {applyIOS27: applyIOS27,applyFrida: applyFrida,applyDisplayRefresh: applyDisplayRefresh,+ applyParavirtUserClients: applyParavirtUserClients,includeBase: includeKernelBase,includeCustomFirmware: includeKernelCustomFirmware,includeHypervisor: includeHypervisor,@@ -379,6 +381,7 @@ extension FirmwarePipeline {applyIOS27: Bool,applyFrida: Bool,applyDisplayRefresh: Bool,+ applyParavirtUserClients: Bool,includeBase: Bool,includeCustomFirmware: Bool,includeHypervisor: Bool,@@ -398,6 +401,7 @@ extension FirmwarePipeline {p.applyIOS27 = applyIOS27p.applyFrida = applyFridap.applyDisplayRefresh = applyDisplayRefresh+ p.applyParavirtUserClients = applyParavirtUserClientsp.gate = gatereturn p}diff --git a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swiftindex 727c2718..73102b15 100644--- a/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift+++ b/VPhoneExecutable/VPhoneCommand/VPhoneCommand/VPhoneCommand.swift@@ -165,6 +165,9 @@ struct PatchComponentCommand: ParsableCommand {// full set.patcher.applyIOS27 = targetOS.map { $0.hasPrefix("27.") } ?? truepatcher.applyFrida = frida+ // The narrow paravirt user-client allowlist is the 26.x/18.x counterpart+ // of the iOS-27 sandbox gate; exercise it when the 27 gate is off.+ patcher.applyParavirtUserClients = !patcher.applyIOS27count = try patcher.apply()patchedData = patcher.buffer.datarecords = patcher.patchesdiff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plistindex c372fa43..ba172f45 100644--- a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist@@ -4,7 +4,7 @@The preset every VM gets unless another is named.It is the CFW baseline plus the virtual camera. It draws on every patch set the- bundle ships and turns on all of their patches bar five groups. The Frida+ bundle ships and turns on all of their patches bar six groups. The FridaStalker pair widens what any process in the guest may do and nothing needs it inorder to boot. The hv_vmm_present concealment — the kernel OID rename, theshared-cache mangle and the watchdogd patch — leaves a freshly restored 26.4@@ -21,6 +21,10 @@even be applied. See FirmwarePatchSetCatalog.misTrustAuthPatch.The fifth is the 120 Hz display timing, a preference that doubles how often theguest renders. See FirmwarePatchSetCatalog.displayRefreshPatch.+ The sixth lets processes outside an app sandbox reach the paravirtual GPU, video+ decoder, Neural Engine and IOSurface scaler through a narrow sandbox allowlist of+ those classes. See+ FirmwarePatchSetCatalog.paravirtUserClientsPatch.Each patch's own version gate still decides whether it lands on this pairing ofiPhone base and cloudOS.@@ -118,6 +122,7 @@<string>preboot-exp-devicetree_identity</string><string>dyld-exp-mis_trust_auth</string><string>kernel-exp-display_refresh_120hz</string>+ <string>kernel-exp-paravirt_user_clients</string></array></dict></dict>