Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Let a guest run at 120 Hz, and show its frame rate

Jacky141e114966c4
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index ec3ead6f..55d13cb0 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -481,6 +481,7 @@
| JB-27 | B | `patch_iomfb_swapend_handler_size` | method-5 handler internal size gate (`cmp w2,#0x588 ; b.ne <err>`) | Companion to JB-26: beyond the dispatch-table check the handler re-checks the struct size (`cmp w2,#0x588 ; b.ne <kIOReturnBadArgument>`; verified unique at decompressed file-off 0x16ae22c; success path forwards the raw struct ptr to a `vtable+0x590` paravirt swap method). Retarget the `cmp` immediate to `0x6e0` so forced-kern iOS 27's native SwapEnd reaches real swap processing (27's IOMFBSwapRec prefix matches 26.x → handler reads valid fields). Semantic anchor (`cmp w2,#imm` word + following `b.ne` decode). Enabled together with JB-26 + DSC force-kern for iOS 27. | Y |
| 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 |
### EXP-Only Kernel Methods (Reference List)
diff --git a/Research/Guest/display_refresh_rate.md b/Research/Guest/display_refresh_rate.md
new file mode 100644
index 00000000..c810ff47
--- /dev/null
+++ b/Research/Guest/display_refresh_rate.md
@@ -0,0 +1,239 @@
+# Guest Display Refresh Rate
+
+A vphone guest renders at 60 Hz whatever the host display does. This note
+records where the 60 comes from, why no Virtualization setting changes it, and
+the opt-in kernel patch `kernel-exp-display_refresh_120hz` that makes the guest
+display advertise 120 Hz. Measured on 2026-10-04 on macOS 27.0.1 (26A434),
+Apple M5 Pro, built-in 120 Hz display, cloudOS 26.4 (23E5207q) kernel with an
+iPadOS 26.6.2 (23G90) userland.
+
+## Where 60 Hz Comes From
+
+### Host: a constant in the VM service
+
+`com.apple.Virtualization.VirtualMachine` (the XPC service that owns the guest)
+creates the display with one mode:
+
+```
+[[PGDisplayMode alloc] initWithSizeInPixels:… refreshRateInHz:60.0]
+```
+
+The double `0x404E000000000000` is materialized inline at three sites, the two
+that build a `PGDisplayMode` among them, and the binary holds no `120.0`.
+`VZMacGraphicsDisplayConfiguration` has no refresh property, public or private:
+its private surface is `_displayMode` (an integer enum, meaning not decoded),
+`_connectionType`, `_displayIdentifier` and `_enableHDR`, and the mode is built
+the same way whatever they hold. The service lives on the sealed system volume,
+so this side is not patchable short of injecting into an Apple process.
+
+### Host: nothing paces the guest
+
+`ParavirtualizedGraphics` has no vsync clock for a `PGDisplay`. A guest present
+reaches `-[_PGDisplayNub _presentMappedSurface:…]`, which hands the frame to
+`-[_PGDisplay presentFrame:…completionBlock:]` and fires the client's
+`newFrameEventHandler`. The VM service's handler calls
+`encodeCurrentFrameToCommandBuffer:texture:region:`, `commit` and
+`waitUntilScheduled`; it imports no display link. The completion block then
+sets event bit 2 in the display's shared state page and raises the display
+interrupt. In the guest, `AppleParavirtGPU`'s interrupt handler walks the
+per-display bitmask and kicks each display's "VBL timer", an
+`IOTimerEventSource` that is only ever armed to fire at once. So the guest's
+VBL is the host's present completion, not a clock.
+
+The only timer ivar among the framework's display classes is
+`PGEFIDisplay._presentTimer`, on the pre-boot framebuffer.
+
+### The shared state page is the one channel
+
+`-[_PGDisplayNub testUpdateModeList:]` writes each mode into the shared state
+page at `+0x210 + 16 × index`, with the count at `+0x208`:
+
+| Offset | Size | Field |
+| --- | --- | --- |
+| 0 | u16 | width in pixels |
+| 2 | u16 | height in pixels |
+| 4 | u32 | refresh rate, 16.16 fixed-point Hz (`floor(rate × 65536 + 0.5)`) |
+| 8 | u8 | flags (bit 0 EDR, bit 1 10 bpc) |
+
+### Guest: the timing element
+
+`AppleParavirtDisplay::createDisplayAttributes`
+(`com.apple.driver.AppleParavirtGPUIOGPUFamily`) builds the display's
+`DisplayAttributes`, among them `TimingElements`. For each mode entry it calls
+a helper with the index, width, height and the 16.16 rate, and the helper
+makes an IOAV timing element from them:
+
+```
+ldurh w1, [x8, #-8] ; width
+ldurh w2, [x8, #-6] ; height
+ldur w3, [x8, #-4] ; refresh, 16.16 Hz
+mov x0, x21 ; index
+bl <make timing element>
+```
+
+`x8` points at the entry's flags byte, hence the negative displacements.
+`TimingElements` is the only place the rate appears in the attributes the
+driver publishes; the results below show the userland takes its pace from it.
+
+## The Patch
+
+`KernelCustomFirmwarePatcher.patchParavirtDisplayRefreshRate`
+(`Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchDisplayRefresh.swift`)
+replaces the load of `w3` with `movz w3, #120, lsl #16`, that is 120.0 Hz in
+16.16. One instruction, one record: `kernel-exp-display_refresh_120hz`.
+
+Reveal procedure, no offsets:
+
+1. Find the cstring `createDisplayAttributes`, the function name the driver
+ passes to its logger.
+2. Take its ADRP+ADD references in `__TEXT_EXEC` (23 on 23E5207q) and require
+ that they all resolve to one function start.
+3. Between that start and the last reference, find three consecutive
+ instructions `ldurh w1, [b, #-8]`, `ldurh w2, [b, #-6]`, `ldur w3, [b, #-4]`
+ off one base, followed within three instructions by a `bl` with no other
+ control flow in between. Require exactly one.
+4. Emit `ARM64Encoder.encodeMovzW(rd: 3, imm16: 120, shift: 16)` over the
+ `ldur`.
+
+On the 23E5207q research kernelcache the record lands at file offset
+`0xEB1A98`.
+
+It is declared in `com.vphone.patchset.kernel.cfw` with no version gate and
+blocked in `standard`, so it is a per-VM checkmark or a preset of its own. It is
+a preference, not a fix: see the cost in the results.
+
+## Results
+
+Test guest: `hz120-ipadpro`, an iPad Pro 13-inch (iPad17,x, 2064×2752) created
+with the patch on, 8 vCPUs. Load was driven with vphoned's `input.swipe`; the
+host side was read from the GPU accounting in the IORegistry
+(`AGXDeviceUserClient` → `AppUsage`), where the VM service's client submits
+once per frame it scans out.
+
+| Workload | Frames scanned out | Gap between frames | Guest share of host GPU |
+| --- | --- | --- | --- |
+| Settings list, continuous scroll | 117.8 per second (112–120 in any one second) | median 8.3 ms, 98% under 12 ms | 30% |
+| Home Screen, continuous page swipes | 103.6 per second (102–119) | median 8.4 ms, 90% under 12 ms | 24% |
+| Home Screen, static page | — | — | 2% |
+
+The three questions the patch had to answer:
+
+- **The host shows every frame.** Nothing between the guest's present and the
+ window drops to 60: the scan-out count follows the guest up to 120.
+- **The userland follows the timing element.** backboardd and SpringBoard on
+ iPadOS 26.6.2 rendered at the advertised rate with no userland change.
+- **It costs what twice the frames cost.** While scrolling, the VM service used
+ 92–139% of one core and the host GPU tasks 33–40%. For comparison, an
+ unpatched iPad mini guest (1488×2266, 60 Hz) scrolling the same list scanned
+ out 55 frames per second and took 12–17% of the host GPU; the iPad Pro panel
+ has 1.7 times the pixels.
+
+A guest whose product type is a 60 Hz device follows the patch too:
+`hz120-ipadmini` (iPad16,1, 1488×2266) scanned out 118 frames per second
+scrolling Settings, 97% of them on time, and about 102 swiping Home Screen
+pages. The userland does not cap the rate by model.
+
+Not measured: an iPhone guest, an iOS 27 userland, and a host display that is
+not 120 Hz, where the window cannot show the extra frames whatever the guest
+renders.
+
+
+## Animations at 120 Hz
+
+Each row is about twelve seconds of one gesture repeated on `hz120-ipadpro`. A
+frame is on time when it follows the previous one by less than 12.5 ms; motion is
+a run of frames less than 50 ms apart, because an idle screen still scans out
+about ten times a second and those ticks are not animation. A gap of 50–90 ms
+inside a gesture is counted as a hitch.
+
+| Animation | Frames per second while moving | On time | Hitches | Guest share of host GPU |
+| --- | --- | --- | --- | --- |
+| Maps, panning | 119 | 98.2% | 0 | 41% |
+| Photos, scrolling | 117 | 97.5% | 1 | 19% |
+| Settings, scrolling | 117 | 94.6% | 0 | 33% |
+| Notification Center, down and up | 116 | 92.4% | 0 | 40% |
+| Control Center, down and up | 117 | 92.1% | 16 | 25% |
+| App open and close | 107 | 92.3% | 7 | 22% |
+| Spotlight, open and dismiss | 105 | 91.0% | 15 | 26% |
+| Home Screen page swipes | 103–115 | 89–96% | 6 | 16–31% |
+| Today View, in and out | 97 | 87.9% | 23 | 22% |
+| Safari, scrolling apple.com/ipad-pro | 70 | 46.3% | 1 | 15% |
+
+The app switcher and rotation could not be driven through vphoned and are not
+in the table. The GPU is never the limit: the worst case for pacing, Safari, is
+the cheapest on the GPU.
+
+### Where the time goes
+
+Two profilers, never both at once (see below): the host's `sample` on the VM
+service, the compositor's GPU task and `vphone-vm`; and the guest's own
+`/usr/sbin/spindump`, run as a temporary launchd job and symbolicated against
+the guest's dyld shared cache with `ipsw dyld a2s`.
+
+- **Safari.** No thread is busy: MobileSafari's main thread and the WebContent
+ main thread each use about 40% of a core. backboardd's display thread spends
+ 24% of its time blocked in
+ `CA::OGL::MetalContext::create_surface_with_properties` →
+ `AppleParavirtGPUMetalIOGPUFamily` → `-[_MTLCommandBuffer waitUntilCompleted]`,
+ a synchronous round trip to the host GPU for every offscreen surface the
+ render needs, and another 20% in `CA::WindowServer::IOMFBDisplay::swap_wait_timeout`
+ waiting for the previous swap to finish. That is the paravirtual Metal driver's
+ behaviour, not the page's cost.
+- **Today View and Spotlight.** The compositor's display thread is idle about
+ 70% of the time and SpringBoard's main thread 84–93%. The late frames there
+ are not a CPU or GPU limit inside the guest; what delays them was not found.
+- **Host.** The eight vCPU threads sit in `hv_trap` and the rest of the VM
+ service is small: handling a present costs about 0.8 ms per frame, almost all
+ of it `-[_MTLCommandBuffer waitUntilScheduled]` under
+ `-[_PGDisplayNub _presentMappedSurface:…]`, and mapping and unmapping guest
+ IOSurfaces takes 1–5% of wall time. The compositor's host GPU task uses about
+ 5% of a core and `vphone-vm` close to none.
+- **Idle.** A static Home Screen still scans out about ten frames a second and
+ costs about 15% of a host core. The guest capture taken then also shows
+ `aonsensed` being respawned by launchd (`throttled after exit`).
+
+### Window visibility and App Nap
+
+`vphone-vm` takes no activity assertion, so macOS naps it once its window has
+been covered for a while: every thread drops to priority 4. That does not reach
+the guest. The threads that run it and scan it out belong to the VM service,
+which stayed at its default priorities (31, a few 37/46) in every state below.
+Settings scrolling at 120 Hz, ten seconds per run, measured from the VM service's
+GPU submits:
+
+| Guest | Window | Frames per second while moving | On time | Hitches | Swipe RPC |
+| --- | --- | --- | --- | --- | --- |
+| `narrowtest-ipad` | visible | 113.1–113.5 | 94.3–96.1% | 3–5 | 398–419 ms |
+| `narrowtest-ipad` | hidden 20 s | 112.0–115.6 | 94.8–97.1% | 4 | 405–416 ms |
+| `gpuaccel-ipad` | covered, napped (priority 4 during the run) | 109.9–113.6 | 93.3–95.9% | 3–6 | 402–438 ms |
+| `gpuaccel-ipad` | after waking (37/46) | 109.5–111.2 | 91.5% | 5 | 421–458 ms |
+
+The differences are within run-to-run noise. A napped `vphone-vm` costs nothing
+while nobody looks at the window, and vphoned RPCs, which pass through it, were no
+slower either. A guest animating on its own while napped (the Weather app, no
+input) kept scanning out until the guest's own Auto-Lock turned the screen off
+120 s after the last input. So an activity assertion would buy nothing for
+rendering.
+
+### Profiling a guest without panicking it
+
+`sample` suspends the target's threads for every sample, the vCPU threads
+included. A guest stackshot has to stop every CPU first, and when a vCPU does not
+answer in time the guest panics with
+`DebuggerXCallEnter> Debugger synch pending on cpu 0`, panicked task `spindump`.
+Running both profilers over the same window did exactly that on the third
+capture. Take the host sample and the guest spindump in separate runs.
+
+The guest side, with vphoned only:
+
+1. `files.write` a launchd plist whose `ProgramArguments` are
+ `/usr/sbin/spindump -notarget <seconds> 10 -file /var/tmp/<name>.txt`, with
+ `RunAtLoad`.
+2. `services.load {paths: [plist]}`, drive the animation, and wait for
+ `services.status` to report no pid.
+3. `files.read` the report (`limit` large enough; it is several megabytes),
+ then `services.unload` with `force` and remove both files.
+
+The report gives exact CPU time per thread and unsymbolicated frames as
+`library + offset [address]`. Subtract the `System Primary` shared cache slide
+in the report header from an address and pass it to `ipsw dyld a2s`.
diff --git a/Research/README.md b/Research/README.md
index 2908bdd8..3691b70c 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), [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), [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/Drivers/KernelCustomFirmwarePatchDisplayRefresh.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchDisplayRefresh.swift
new file mode 100644
index 00000000..c0785c67
--- /dev/null
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/CustomFirmwarePatches/Drivers/KernelCustomFirmwarePatchDisplayRefresh.swift
@@ -0,0 +1,119 @@
+// KernelCustomFirmwarePatchDisplayRefresh.swift — CFW kernel patch: make the
+// paravirtual display advertise a 120 Hz timing instead of the host's 60 Hz.
+//
+// Background: the host's VM service builds its one display mode with a constant
+// `refreshRateInHz: 60.0`, and Virtualization has no setting for it.
+// ParavirtualizedGraphics writes each mode into the display's shared state page
+// as a 16-byte entry — u16 width, u16 height, u32 refresh in 16.16 Hz, flags —
+// and that page is the only way the rate reaches the guest. Nothing on the host
+// paces the guest: a present is consumed when it arrives, and its completion is
+// what the guest's display driver sees as VBL.
+//
+// In the guest, `AppleParavirtDisplay::createDisplayAttributes`
+// (AppleParavirtGPUIOGPUFamily) walks those entries and turns each into an IOAV
+// timing element:
+//
+// ldurh w1, [xN, #-8] ; width
+// ldurh w2, [xN, #-6] ; height
+// ldur w3, [xN, #-4] ; refresh, 16.16 Hz
+// mov x0, xIndex
+// bl <make timing element>
+//
+// `TimingElements` is where IOMobileFramebuffer and the render server learn the
+// display's rate, so the load of `w3` becomes `movz w3, #120, lsl #16`.
+//
+// Anchor (no offsets): the `createDisplayAttributes` function-name cstring the
+// driver passes to its logger, whose references all sit in that one function;
+// inside it, the only place three consecutive loads off one base fill w1, w2 and
+// w3 from displacements -8, -6 and -4 ahead of a call.
+
+import Foundation
+import VPhonePatchKit
+
+extension KernelCustomFirmwarePatcher {
+ /// The rate the guest display advertises once patched.
+ private static let displayRefreshHz: UInt16 = 120
+
+ @discardableResult
+ func patchParavirtDisplayRefreshRate() -> Bool {
+ log("\n[CFW]AppleParavirtDisplay timing element refresh: host 60 Hz -> \(Self.displayRefreshHz) Hz")
+
+ guard let (ks, ke) = kernTextRange else {
+ log(" [-] no kernel text range")
+ return false
+ }
+ guard let nameOff = buffer.findString("createDisplayAttributes") else {
+ log(" [-] createDisplayAttributes cstring not found")
+ return false
+ }
+ let refs = findStringRefs(nameOff, in: (ks, ke))
+ let starts = Set(refs.compactMap { findFunctionStart($0.adrpOff) })
+ guard starts.count == 1, let funcStart = starts.first,
+ let lastRef = refs.map(\.adrpOff).max()
+ else {
+ log(" [-] createDisplayAttributes not resolved to one function (found \(starts.count))")
+ return false
+ }
+
+ var hits: [Int] = []
+ var off = funcStart
+ while off + 12 <= lastRef {
+ defer { off += 4 }
+ guard let width = loadFromBase(at: off, mnemonic: "ldurh", into: .w(1), disp: -8),
+ let height = loadFromBase(at: off + 4, mnemonic: "ldurh", into: .w(2), disp: -6),
+ let refresh = loadFromBase(at: off + 8, mnemonic: "ldur", into: .w(3), disp: -4),
+ width == height, height == refresh,
+ callFollows(off + 12)
+ else { continue }
+ hits.append(off + 8)
+ }
+
+ guard hits.count == 1, let loadOff = hits.first else {
+ log(" [-] timing element refresh load not found uniquely (found \(hits.count))")
+ return false
+ }
+ guard let movz = ARM64Encoder.encodeMovzW(rd: 3, imm16: Self.displayRefreshHz, shift: 16) else {
+ log(" [-] could not encode the refresh constant")
+ return false
+ }
+
+ emit(
+ loadOff,
+ movz,
+ patchID: "kernel-exp-display_refresh_120hz",
+ virtualAddress: fileOffsetToVA(loadOff),
+ description: "timing element refresh ldur w3,[mode,#-4] -> movz w3,#\(Self.displayRefreshHz),lsl #16 [16.16 Hz]",
+ )
+ return true
+ }
+
+ /// The base register when the instruction at `off` is `mnemonic reg, [base, #disp]`.
+ private func loadFromBase(
+ at off: Int,
+ mnemonic: String,
+ into reg: ARM64Register,
+ disp: Int32,
+ ) -> ARM64Register? {
+ guard let insn = disasAt(off), insn.mnemonic == mnemonic,
+ let ops = insn.detail?.operands, ops.count == 2,
+ ops[0].type == .register, ops[0].reg == reg,
+ ops[1].type == .memory, ops[1].mem.index == .invalid, ops[1].mem.disp == disp
+ else { return nil }
+ return ops[1].mem.base
+ }
+
+ /// True when a `bl` comes within the next three instructions, before any
+ /// other control flow.
+ private func callFollows(_ off: Int) -> Bool {
+ for delta in stride(from: 0, to: 12, by: 4) {
+ guard let insn = disasAt(off + delta) else { return false }
+ if insn.mnemonic == "bl" {
+ return true
+ }
+ if insn.isJump || insn.isReturn {
+ return false
+ }
+ }
+ return false
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
index 795f6f2b..dae343bc 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Kernel/KernelCustomFirmwarePatcher.swift
@@ -31,6 +31,10 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
/// byte-identical when false.
public var applyFrida = false
+ /// Opt-in 120 Hz display timing. Set from the plan: `standard` blocks it, so
+ /// a guest keeps the host's 60 Hz mode unless the VM asked otherwise.
+ public var applyDisplayRefresh = false
+
public func findAll() throws -> [PatchRecord] {
parseMachO()
buildADRPIndex()
@@ -85,6 +89,12 @@ public final class KernelCustomFirmwarePatcher: KernelCustomFirmwarePatcherBase,
patchVmMapDeleteImmutableCode()
}
+ // Opt-in: the paravirtual display advertises 120 Hz instead of the
+ // host's fixed 60 Hz mode.
+ if applyDisplayRefresh {
+ patchParavirtDisplayRefreshRate()
+ }
+
// Group C
patchCredLabelUpdateExecve()
patchHookCredLabelUpdateExecve()
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
index baae9aaa..ab3bae7d 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwareKernelCustomFirmwarePatchSet.swift
@@ -263,6 +263,19 @@ public enum FirmwareKernelCustomFirmwarePatchSet {
applicability: ios27,
bootEssential: true,
),
+
+ // MARK: Display
+
+ VPhonePatchDeclaration(
+ identifier: FirmwarePatchSetCatalog.displayRefreshPatch,
+ title: "120 Hz display timing",
+ summary: """
+ Makes the paravirtual display advertise 120 Hz instead of the host's fixed \
+ 60 Hz mode. Off by default: the guest renders twice as often, and only a \
+ 120 Hz host display shows it.
+ """,
+ target: .firmware(.kernelcache),
+ ),
],
requires: ["vphone.kernel.base"],
provides: ["vphone.kernel.cfw"],
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
index 26890a41..64ebbfc9 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/PatchSets/FirmwarePatchSetCatalog.swift
@@ -54,11 +54,21 @@ public enum FirmwarePatchSetCatalog {
///
/// `dyld-exp-mis_trust_auth` is off because a userspace hook now does its
/// job: see ``misTrustAuthPatch``.
+ ///
+ /// `kernel-exp-display_refresh_120hz` is off because it is a preference with a
+ /// cost: see ``displayRefreshPatch``.
public static let manualOnlyPatches: Set<String> =
Set(FirmwareKernelFridaPatchSet.manifest.patches.map(\.identifier))
.union(hypervisorConcealmentPatches)
.union(experimentalIdentityPatches)
- .union([misTrustAuthPatch])
+ .union([misTrustAuthPatch, displayRefreshPatch])
+
+ /// The 120 Hz timing for the paravirtual display.
+ ///
+ /// Off in `standard`: the host's mode is 60 Hz, a guest rendering twice as
+ /// often costs twice the host CPU and GPU, and only a 120 Hz host display
+ /// shows the difference. See `Research/Guest/display_refresh_rate.md`.
+ public static let displayRefreshPatch = "kernel-exp-display_refresh_120hz"
/// The shared-cache short-circuit of `libmis`'s `checkTrustAndAuthorization`.
///
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
index ec0ed6ec..9970c07f 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/Pipeline/FirmwarePipelineComponents.swift
@@ -90,6 +90,9 @@ extension FirmwarePipeline {
isEnabled($0.identifier, fallback: false)
}
+ // The 120 Hz display timing, off unless the VM asked for it.
+ let applyDisplayRefresh = isEnabled(FirmwarePatchSetCatalog.displayRefreshPatch, 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
// channel-create traps in the 18.x Network.framework and crash-loops
@@ -232,6 +235,7 @@ extension FirmwarePipeline {
applyExcGuard: applyExcGuard,
applyIOS27: applyIOS27,
applyFrida: applyFrida,
+ applyDisplayRefresh: applyDisplayRefresh,
includeBase: includeKernelBase,
includeCustomFirmware: includeKernelCustomFirmware,
includeHypervisor: includeHypervisor,
@@ -374,6 +378,7 @@ extension FirmwarePipeline {
applyExcGuard: Bool,
applyIOS27: Bool,
applyFrida: Bool,
+ applyDisplayRefresh: Bool,
includeBase: Bool,
includeCustomFirmware: Bool,
includeHypervisor: Bool,
@@ -392,6 +397,7 @@ extension FirmwarePipeline {
let p = KernelCustomFirmwarePatcher(data: data, verbose: verbose)
p.applyIOS27 = applyIOS27
p.applyFrida = applyFrida
+ p.applyDisplayRefresh = applyDisplayRefresh
p.gate = gate
return p
}
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
index 08ce844f..0f3fd3d8 100644
--- a/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
+++ b/VPhoneExecutable/VPhoneVirtualization/Resources/Localizable.xcstrings
@@ -17747,6 +17747,74 @@
}
}
},
+ "Show Frame Rate" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Show Frame Rate"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "フレームレートを表示"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "프레임 속도 표시"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Hiển thị tốc độ khung hình"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "显示帧率"
+ }
+ }
+ }
+ },
+ "%ld fps" : {
+ "localizations" : {
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%ld fps"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%ld fps"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%ld fps"
+ }
+ },
+ "vi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%ld fps"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%ld fps"
+ }
+ }
+ }
+ },
"Trackpad Scroll & Pinch to Touch" : {
"localizations" : {
"en" : {
diff --git a/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist b/VPhoneExecutable/VPhoneVirtualization/Resources/patches_presets/standard.plist
index b4015116..c372fa43 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 four groups. The Frida
+ bundle ships and turns on all of their patches bar five groups. The Frida
Stalker pair widens what any process in the guest may do and nothing needs it in
order to boot. The hv_vmm_present concealment — the kernel OID rename, the
shared-cache mangle and the watchdogd patch — leaves a freshly restored 26.4
@@ -19,6 +19,8 @@
userspace in installd, misagent and SpringBoard, so editing the shared cache for
it buys nothing there, costs an iOS 27 guest its boot (issue #532), and on 24A435 cannot
even be applied. See FirmwarePatchSetCatalog.misTrustAuthPatch.
+ The fifth is the 120 Hz display timing, a preference that doubles how often the
+ guest renders. See FirmwarePatchSetCatalog.displayRefreshPatch.
Each patch's own version gate still decides whether it lands on this pairing of
iPhone base and cloudOS.
@@ -115,6 +117,7 @@
<string>devicetree-exp-arm_io_soc_generation</string>
<string>preboot-exp-devicetree_identity</string>
<string>dyld-exp-mis_trust_auth</string>
+ <string>kernel-exp-display_refresh_120hz</string>
</array>
</dict>
</dict>
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
index 935b1e46..36da28e2 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuController.swift
@@ -23,6 +23,7 @@ class VPhoneMenuController {
var hardwareKeyboardItem: NSMenuItem?
var onHardwareKeyboardChange: ((Bool) async throws -> Void)?
+ var onFrameRateDisplayChange: ((Bool) -> Void)?
var onFilesPressed: (() -> Void)?
var onKeychainPressed: (() -> Void)?
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
index 4c08355c..420b4dac 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/Menu/VPhoneMenuDevice.swift
@@ -84,6 +84,12 @@ extension VPhoneMenuController {
trackpadItem.state = VPhoneTrackpadGestures.isEnabled ? .on : .off
trackpadGesturesItem = trackpadItem
menu.addItem(trackpadItem)
+ // Off unless asked for: the window subtitle then carries the frames the
+ // guest presented in the last second.
+ let frameRateItem = makeItem("Show Frame Rate", action: #selector(toggleFrameRateDisplay))
+ frameRateItem.state = VPhoneFrameRateDisplay.isEnabled ? .on : .off
+ frameRateItem.isEnabled = VPhoneFrameRateMeter.isSupported
+ menu.addItem(frameRateItem)
let tidItem = makeItem("Touch ID Home Forwarding", action: #selector(toggleTouchIDForwarding))
if hasTouchID {
let tidEnabled = !UserDefaults.standard.bool(forKey: "touchIDForwardingDisabled")
@@ -256,6 +262,14 @@ extension VPhoneMenuController {
captureView?.trackpadGesturesEnabled = enabled
}
+ /// Shows the guest's frame rate in the window subtitle. Persisted.
+ @objc func toggleFrameRateDisplay(_ sender: NSMenuItem) {
+ let enabled = !VPhoneFrameRateDisplay.isEnabled
+ VPhoneFrameRateDisplay.isEnabled = enabled
+ sender.state = enabled ? .on : .off
+ onFrameRateDisplayChange?(enabled)
+ }
+
// MARK: - Restart
func updateRestartAvailability(available: Bool) {
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
index a277463b..e3174db0 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/UserInterface/VPhoneVirtualMachineWindowController.swift
@@ -13,6 +13,10 @@ class VPhoneVirtualMachineWindowController: NSObject {
private var subtitleLabel: NSTextField?
private var timers: [Timer] = []
private var keyStateObservers: [NSObjectProtocol] = []
+ private var frameRateTimer: Timer?
+ private var frameRateSampledAt: CFTimeInterval = 0
+ /// The guest's frame rate over the last second; nil while the display is off.
+ private var frameRate: Int?
var captureView: VPhoneVirtualMachineView? {
virtualMachineView
@@ -124,12 +128,15 @@ class VPhoneVirtualMachineWindowController: NSObject {
timers.append(Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
Task { @MainActor in self?.pollOrientation() }
})
+ setFrameRateDisplay(VPhoneFrameRateDisplay.isEnabled)
}
/// Disconnect the old display and input devices before rebuilding the VM.
func closeForRestart() {
timers.forEach { $0.invalidate() }
timers.removeAll()
+ frameRateTimer?.invalidate()
+ frameRateTimer = nil
keyStateObservers.forEach { NotificationCenter.default.removeObserver($0) }
keyStateObservers.removeAll()
NotificationCenter.default.removeObserver(self)
@@ -313,6 +320,9 @@ class VPhoneVirtualMachineWindowController: NSObject {
parts.append(address)
}
}
+ if let frameRate {
+ parts.append(VPhoneLocalization.format("%ld fps", frameRate))
+ }
let subtitle = parts.joined(separator: " - ")
if window.subtitle != subtitle {
window.subtitle = subtitle
@@ -321,6 +331,36 @@ class VPhoneVirtualMachineWindowController: NSObject {
}
}
+ // MARK: - Frame Rate
+
+ /// Shows the guest's frame rate in the subtitle, sampled once a second.
+ func setFrameRateDisplay(_ enabled: Bool) {
+ frameRateTimer?.invalidate()
+ frameRateTimer = nil
+ frameRate = nil
+ if enabled, VPhoneFrameRateMeter.isAvailable {
+ _ = VPhoneFrameRateMeter.takeFrameCount()
+ frameRateSampledAt = CACurrentMediaTime()
+ frameRate = 0
+ frameRateTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
+ Task { @MainActor in self?.sampleFrameRate() }
+ }
+ }
+ if let control {
+ updateSubtitle(control: control)
+ }
+ }
+
+ private func sampleFrameRate() {
+ guard frameRate != nil, let control else { return }
+ let now = CACurrentMediaTime()
+ let elapsed = now - frameRateSampledAt
+ guard elapsed > 0 else { return }
+ frameRate = Int((Double(VPhoneFrameRateMeter.takeFrameCount()) / elapsed).rounded())
+ frameRateSampledAt = now
+ updateSubtitle(control: control)
+ }
+
// MARK: - Home Button
private static let homeImage = NSImage(
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
index 01d67915..5647b2bb 100644
--- a/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VPhoneVirtualMachineAppDelegate.swift
@@ -164,6 +164,9 @@ class VPhoneVirtualMachineAppDelegate: NSObject, NSApplicationDelegate {
guard let self else { return }
try await restartWithHardwareKeyboard(enabled)
}
+ mc.onFrameRateDisplayChange = { [weak wc] enabled in
+ wc?.setFrameRateDisplay(enabled)
+ }
mc.captureView = wc.captureView
mc.touchIDMonitor = wc.touchIDMonitor
mc.onFilesPressed = { [weak fileWC, weak control] in
diff --git a/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneFrameRateMeter.swift b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneFrameRateMeter.swift
new file mode 100644
index 00000000..b0e045d7
--- /dev/null
+++ b/VPhoneExecutable/VPhoneVirtualization/UI/VirtualMachine/VPhoneFrameRateMeter.swift
@@ -0,0 +1,71 @@
+import AppKit
+import ObjectiveC.runtime
+import os
+
+// MARK: - Frame Rate Meter
+
+/// Counts the frames the guest presents to the host window.
+///
+/// Virtualization hands every guest frame to its framebuffer view through
+/// `-[_VZFramebufferView presenter:didUpdateFrame:]`. The meter wraps that
+/// method once, counts the call and passes it on unchanged, so the count is the
+/// number of frames that reached the window, not a host refresh rate.
+enum VPhoneFrameRateMeter {
+ /// The frame update is a C++ `shared_ptr` the wrapper never looks at. Two
+ /// pointer-sized arguments carry it whether the ABI passes it by reference
+ /// or in a register pair.
+ private typealias FrameUpdateIMP = @convention(c) (
+ AnyObject, Selector, AnyObject, UnsafeRawPointer?, UnsafeRawPointer?,
+ ) -> Void
+ private typealias FrameUpdateBlock = @convention(block) (
+ AnyObject, AnyObject, UnsafeRawPointer?, UnsafeRawPointer?,
+ ) -> Void
+
+ private static let frames = OSAllocatedUnfairLock(initialState: 0)
+
+ private static var frameUpdateMethod: Method? {
+ NSClassFromString("_VZFramebufferView").flatMap {
+ class_getInstanceMethod($0, NSSelectorFromString("presenter:didUpdateFrame:"))
+ }
+ }
+
+ /// False when this macOS has no such method. Looking does not install anything.
+ static var isSupported: Bool {
+ frameUpdateMethod != nil
+ }
+
+ /// Installs the counter on first use, so a window that never shows the rate
+ /// leaves the framework untouched.
+ static let isAvailable: Bool = {
+ guard let method = frameUpdateMethod else {
+ print("[display] Frame rate unavailable: no framebuffer frame callback on this macOS")
+ return false
+ }
+ let selector = method_getName(method)
+ let original = unsafeBitCast(method_getImplementation(method), to: FrameUpdateIMP.self)
+ let block: FrameUpdateBlock = { view, presenter, update, control in
+ frames.withLock { $0 += 1 }
+ original(view, selector, presenter, update, control)
+ }
+ method_setImplementation(method, imp_implementationWithBlock(block))
+ return true
+ }()
+
+ /// The frames presented since the last call.
+ static func takeFrameCount() -> Int {
+ frames.withLock { count in
+ defer { count = 0 }
+ return count
+ }
+ }
+}
+
+/// Whether the window shows the guest's frame rate. Off unless asked for.
+enum VPhoneFrameRateDisplay {
+ private static let enabledKey = "frameRateDisplayEnabled"
+
+ static var isEnabled: Bool {
+ get { UserDefaults.standard.bool(forKey: enabledKey) }
+ set { UserDefaults.standard.set(newValue, forKey: enabledKey) }
+ }
+}