Skip to content

Run a virtual iPhone on an Apple Silicon Mac.

Swift

Show DeviceHub's capture display on iOS 27 guests

Jacky4f6cf1118ea7
diff --git a/Research/0_binary_patch_comparison.md b/Research/0_binary_patch_comparison.md
index 2e2966b6..890dac39 100644
--- a/Research/0_binary_patch_comparison.md
+++ b/Research/0_binary_patch_comparison.md
@@ -2784,3 +2784,17 @@ re-patched kernelcache and the marker survived. Flow: `fw set-patches` →
route a kernel patch through `cfw update-kernel` and the rest of the boot chain
(TXM, DeviceTree, LLB, iBSS, iBEC) through the erasing restore. TXM and
DeviceTree are also in Preboot and could follow the same path later.
+
+### DeviceHub iOS 27 conditional swap and mask metadata (2026-10-07)
+
+The IOMFB force-kern candidate uses ten public/kern/virt symbol triples on
+24A446. Each writes a 16-byte null check, port load, conditional kernel branch,
+and virtual branch, followed by re-attestation. Reapply an existing installation
+by reverting the old 31 four-byte sites via patch selection first: an unchanged
+identifier in the receipt otherwise skips the new implementation.
+
+`libdevicehubfix` also loads in the DDI's dtdeviceinfod. It preserves existing
+MobileGestalt answers but supplies mask `4E5532ED-1470-47D1-BDF4-7AA90C26957A`
+when FramebufferIdentifier is missing and ChromeIdentifier is phone11. This is
+the corresponding Xcode DeviceKit mask, not a hardware device-tree rewrite.
+The null mask was observed in dtdeviceinfod; visual validation is pending.
diff --git a/Research/Guest/devicehub_screen_viewing.md b/Research/Guest/devicehub_screen_viewing.md
index b414a834..56b3618d 100644
--- a/Research/Guest/devicehub_screen_viewing.md
+++ b/Research/Guest/devicehub_screen_viewing.md
@@ -150,6 +150,60 @@ screen was on and unlocked.
## Open: a black view on iOS 27
+**Reverse-engineering result (2026-10-06):** the shared-cache force-kern patch was
+reproduced against the local `24A446` cache. `_kern_SwapEnd` and the other
+`_kern_Swap*` implementations load the connection's IOConnect port from
+`[x0,#0x14]`; a zero value is the exact state that produces
+`MACH_SEND_INVALID_DEST` on display 2. The public trampolines now use a
+four-instruction dispatcher:
+
+```text
+cbz x0, <original failure>
+ldr w16, [x0, #0x14]
+cbnz w16, _kern_Swap<Name>
+b _virt_Swap<Name>
+```
+
+`x16` is scratch, so the public ABI arguments survive both direct branches.
+The patch discovers the public, `_kern_`, and `_virt_` siblings by symbol name,
+keeps the original null-connection target, emits the branch and load bytes
+through `ARM64Encoder`, and re-attests the full 16-byte write span. It upgrades
+an older unconditional force-kern patch in place and is idempotent. On the
+local 27.0.1 cache it classified 10 public entry points (including
+`SwapBegin`, `SwapEnd`, and `SwapSetLayer`), left `SwapSignal` on its existing
+virt implementation because it is not a thin trampoline, updated four code
+signature slots, and passed the second-run no-op check.
+
+**Deployment audit correction (2026-10-07):** prior statements that the
+conditional patch had reached the guest were not proven. `applyDyldPatches`
+skips an enabled patch when its identifier is already in the Guest receipt.
+The guest undo log still contains 31 four-byte originals for force-kern,
+whereas the new implementation writes ten 16-byte sites. A successful CFW
+install and a receipt containing the identifier do not establish the new bytes.
+Direct cache readback and an explicit revert/reapply are required next.
+
+The host control socket's `screenshot` command calls the guest screenshot
+API; it does not capture the VZ view. DeviceHub's saved screenshot also
+shows the home screen, while its live panel is black. Neither screenshot
+proves VZ scanout or live-stream success.
+
+The attempted `0xcc` experiment replaced a raw byte sequence without
+verifying the function instruction or the installed content. It is invalid
+as an A/B test. Disassembly of the read-back guest hook currently confirms
+`vpCurrentFeatures: mov x9,#0x8c; str x9,[x8]; ret`.
+
+Actual evidence retained: the 26.6.2 DeviceHub live panel renders, the 27.0.1
+panel is black, and a 60-second all-process capture reports
+`FigVirtualDisplayProcessor Submits 0 / Encodes 0`. The SDK identifies
+`e00002be` as `kIOReturnNoResources` and `e00002d5` as `kIOReturnBusy`.
+Static IOMFB analysis shows a no-resources return when all 16 outstanding
+surface-token slots are occupied; errors can also propagate from the
+provider callback. It does not prove an empty resource table.
+
+The proposed default-surface fallback was removed before guest deployment:
+it overwrote the normal allocation block and failed to unwind the caller's
+stack before tail-calling. Do not deploy `/tmp/vphone-bundle-fallback`.
+
During the 27.0.1 stream backboardd logs, about fifty times a second,
```text
@@ -164,3 +218,304 @@ that display, the same layer rows 9 and 11 of
(`_kern_SwapEnd`, the `_IOMobileFramebufferSwap*` trampolines). That is where
the next step starts. A `locationd` crash (`EXC_ARM_PAC_FAIL`) on the same
guest predates the hook and does not involve it.
+
+## Verified reapplication and remaining display quality (2026-10-07)
+
+The actual reapplication used the existing `devicehub-screen` worktree with
+only the conditional IOMFB implementation and compare-branch encoder copied
+in. Bundle `2.6.1-local.8aa77f2e` includes the original DeviceHub hook. With the
+VM stopped, `fw set-patches --block dyld-boot-iomfb_force_kern` followed by
+`cfw update-environment` reverted all 31 old four-byte sites. Restoring the
+standard selection and updating with the new bundle wrote ten 16-byte sites,
+re-attested four slots, and passed post-write decoding. The running guest's
+undo log independently reports ten 16-byte originals. DeviceHub then showed
+the home screen and subsequently Settings in its live panel.
+
+The user reports large latency and content extending over the bezel corners.
+These remain open. Guest stats now show 41–49 encodes/second rather than zero;
+host receiver stats show about 54 fps, a 100 ms jitter buffer, and no transport
+queue backlog in the sampled interval. One player sample was roughly 300 ms
+behind its display-link timestamp. These are not an end-to-end latency test.
+
+Changing the stopped guest from 1290x2796 to 1179x2556 was tested; the guest
+confirmed 393x852 points at scale 3, but the rounded-corner overflow persisted.
+The original dimensions are being restored. Matching the iPhone16 dimensions
+alone is not a fix. The main VZ window still requires direct visual verification;
+guest screenshots must not be used as evidence of host scanout.
+
+Recovery and next discriminators: after restoring the 1290x2796 configuration,
+vphoned timed out once although the VZ window visibly showed the home screen.
+A controlled stop/start recovered the API, which now reports 430x932 points.
+The VZ window was inspected directly through its installed bundle path;
+scanout is confirmed, independently of the guest screenshot RPC.
+
+The user measures roughly 1–3 seconds of lag, greater than the sampled
+100 ms jitter buffer. Separate HID arrival from video delivery before
+changing frame pacing. DeviceKit contains `loadFramebufferMaskAndChrome`,
+`FramebufferMaskIdentifier`, and an explicit fallback to RoundedRectangle
+when `showFramebufferMask` is true but a mask image is unavailable. Host logs
+confirm chrome `com.apple.dt.devicekit.chrome.phone11` loads; they do not yet
+prove which mask (if any) was selected. Missing/mismatched mask is a hypothesis,
+not yet a verified cause or a reason to edit host Xcode binaries.
+
+Mask lookup evidence: `/Library/Developer/DeviceKit/chrome_map.plist` maps
+`iPhone17,3` to `phone9` and mask `A6AC96E7-C5D3-47A6-8967-A8B2D02F1C66`,
+`iPhone17,1` to `phone11` and mask `4E5532ED-1470-47D1-BDF4-7AA90C26957A`.
+There is no `iPhone99,11` entry. DeviceHub logs requested `phone11` for this
+guest. `DeviceTreeGuestDevicePatches` explicitly preserves the virtual
+`framebuffer-identifier` while copying real-board chrome properties. Inspect
+the DDI display-info mask identifier next; the combination is suspicious but
+not proof of the runtime fallback. Do not change the framebuffer identifier
+in the device tree before tracing its other consumers.
+
+Current DDI inputs for follow-up: `/tmp/dh-CoreDeviceUtilities` is the full
+12,372,992-byte guest binary (`truncated:false`), version 642.16; its arm64e
+slice is `/tmp/dh-CDU-arm64e`. Use thin-slice symbol addresses: fat-file `nm`
+prints the arm64 slice first, whose addresses differ. The arm64e
+`Display.framebufferMaskIdentifier` getter is at 0x33ea54; provider's default
+fetch closure is at 0x343a00, async function pointer at 0x4064d0 resolves to
+0x343b0c. `FramebufferIdentifier` literal is at 0x425a60. The DDI binary
+imports MobileGestalt and has both ChromeIdentifier and FramebufferIdentifier
+literals. A targeted xref analysis is running as exec session 95254 with output
+`/tmp/dh-mask-xref.txt` (inspect current process state before waiting).
+
+DDI arm64e xrefs completed: function 0x350f94 reads
+`MGCopyAnswer("DisplayExtendedProperties", NULL)`, otherwise falls back to
+`MGCopyAnswer("ChromeIdentifier", NULL)` at 0x351104 and
+`MGCopyAnswer("FramebufferIdentifier", NULL)` at 0x3511a4.
+`dtdeviceinfod` contains the DisplayInfo and DisplayInfoUpdates action
+implementations, rather than dtremotedisplayd. An observational interpose
+in the existing DeviceHub hook now logs only these three answers for
+`dtdeviceinfod`, up to 12 queries, without modifying ownership or values.
+The dedicated worktree includes its spawn target and negative suffix test;
+`test-injection-environment` passes and the complete bundle builds.
+Diagnostic bundle: `2.6.1-local.238f9151`; deployment log
+`/tmp/dh-diag-update.log`, exec session 37312 (verify status before waiting).
+
+Diagnostic readback from dtdeviceinfod PID 269 confirms:
+`DisplayExtendedProperties = null`,
+`ChromeIdentifier = com.apple.dt.devicekit.chrome.phone11`,
+`FramebufferIdentifier = null`. The next build fills only that missing
+FramebufferIdentifier in dtdeviceinfod when chrome is exactly phone11, using
+Xcode's matching mask `4E5532ED-1470-47D1-BDF4-7AA90C26957A` and retaining the
+CF result under the original Copy ownership contract. Existing answers and
+other chrome types are unchanged. This is display metadata, not a change to
+virtual hardware identity. Build session 88613, `/tmp/dh-mask-fix-build.log`;
+visual validation and latency work remain pending.
+
+**Mask fix verified (2026-10-07 09:02 local):** installed
+`2.6.1-local.6a68184b`; dtdeviceinfod PID 272 now returns the phone11 mask UUID.
+DeviceHub logged `Found FramebufferMaskIdentifier from displayInfo` with that
+UUID at 09:01:54.327. Direct DeviceHub screenshots of both the home screen and
+Settings show all four corners clipped inside the chrome. Resolution remains
+1290x2796. This closes the corner-overflow issue, not the latency issue.
+A Home button observation at roughly 564 ms after the UI action still showed
+Settings; subsequent guest foreground query showed no verified app foreground.
+It does not yet split HID delivery from capture delay. User follow-up about
+remaining 1–3 second lag is pending.
+
+## Cold-start timing audit (2026-10-07)
+
+User reports current stream has no delay, but occasional 1–3 s lag starts at
+boot. Healthy baseline player samples differ from last presentation by 3–20 ms.
+First cold start settled at 14–16 ms. Second cold start's unlock request timed
+out, although subsequent readback was unlocked. Its video session started
+09:07:40; at 09:07:50 only six decode alarms had arrived over five seconds and
+the previous presentation was 4.683 seconds old. By 09:07:55 it recovered to
+5.8 ms and then 6–23 ms. This is a transient absence of frames, not evidence of
+a persistently shifted playback clock. Compilation/tests were active during
+this run, so repeat without host build load before attributing it to the guest.
+Evidence: `/tmp/dh-timing-audit/cold2-host.txt` and `cold2-connect.txt`.
+
+Seven updated real-cache conditional dispatcher tests pass, including dry-run,
+idempotence, symbol discovery, and typed branch/port operands. A separate
+Keystone parity/range test for compare branches also passes. Logs:
+`/tmp/dh-conditional-tests-rerun.log`, `/tmp/dh-encoder-tests.log`.
+
+User explicitly confirms cold2 was visibly stuttering; do not dismiss that
+failure because cold3 was healthy. Full host log for 09:07:43–09:07:56 is
+`/tmp/dh-timing-audit/cold2-fault-full.txt`. The player repeatedly reports
+`alarmsSentForDecodeButNotDisplayedCount=16` at its threshold. Receiver reports
+~56 fps, transport maxQueueDelay 0, and at 09:07:51.091 sends FIR with reason
+`No video displayed timeout fail safe`. Playback recovers thereafter. This
+supports investigating decoder/display scheduling or keyframe recovery, not
+assuming no packets were being received or declaring build load the cause.
+
+A temporary local app `com.vphone.devicehub.timingprobe` is installed on only
+`dhtest-iphone27`. Source and IPA are under `/tmp/dh-timing-probe`. It displays
+current guest epoch milliseconds at 30 Hz and a tap counter/color. It initially
+crashed because iOS27 requires Scene lifecycle; the corrected SceneDelegate
+build launches. At host capture interval 1791335680959–1791335681133 ms,
+both the native VZ and DeviceHub screenshots showed 1791335680351. The common
+host/guest offset must not be called DeviceHub latency. The comparative sample
+shows no second-scale lag between displays in the healthy state. Remove the
+probe after timing work; no production component depends on it.
+
+### Cold4 and decoder-input refinement (2026-10-07 09:24 local)
+
+Cold2 remains a user-confirmed failure. The full log narrows the observation:
+VCPDec (1296x2816 HEVC) reports Input_fps=0 and Dec_fps=0 every second from
+09:07:46 through 09:07:50, while the receiver's periodic report still records
+packets and roughly 56 fps. The image queue's last enqueue is host time
+452285.493, so a stale visible frame is established; decoder starvation is
+observed, but capture failure versus packet assembly/reference recovery is
+not yet separated. The threshold-16 warning also persists after presentation
+recovers, so that warning alone is not a reliable failure detector.
+
+Cold4 uses the same deployed bundle (6a68184b), with no build running during
+the sample. Logs: `/tmp/dh-timing-audit/cold4-host.txt` and
+`/tmp/dh-timing-audit/cold4-guest.json`. The 35-second guest sample contains
+200 entries, steady ~30 fps encoding of the 30 Hz timing probe, no encode
+drops, and ~9–11 ms encoder time. Host presentation samples remain ~15–18 ms
+old. Direct VZ/DeviceHub screenshots both read 1791336178521 within host
+capture interval 1791336178929–1791336179321. This is a healthy comparative
+sample, not proof that intermittent startup lag is fixed. Other user VMs
+remain running; host swap usage was about 17 GB, which is context rather than
+a demonstrated cause.
+
+The diagnostic probe now writes the runtime encoding of AVCVideoStream's
+configure:error: to its own Documents/avc-types.txt: `B32@0:8@16^@24`.
+This verifies BOOL/object/error-pointer shape only; no configuration key or
+keyframe interval has been changed. Temporary probe remains installed for
+further paired measurements and must be removed when diagnosis ends.
+
+### Cold5–7, guest-side stall evidence (2026-10-07 09:33 local)
+
+User confirms **VZ stayed fluid while DeviceHub stuttered in cold2**. This
+is the key comparative observation; do not attribute cold2 to whole-guest
+startup without contrary evidence. The temporary probe was rebuilt at 60 Hz.
+Cold5 and cold6 paired screenshots show no seconds-scale difference. Cold5
+has four host player samples (maximum presentation age 22.824 ms); cold6 has
+seven (maximum 12.55 ms), no no-video timeout FIR. Cold5 guest encoding reaches
+60 fps with no drops. These are bounded healthy runs, not a latency fix.
+
+Repro script `/tmp/dh-cold-run.zsh` operates only on dhtest-iphone27, captures
+host logs, polls actual stopped state, starts the VM, collects guest logs,
+then unlocks/launches the probe. Summary script `/tmp/dh-timing-summary.rb`
+identifies the latest new player by its tick-zero record. Cold7 unlock timed
+out; the script exited and stopped host streaming. The already-running guest
+log finished normally. No duplicate VM restart was attempted. Subsequent
+unlock and probe launch succeeded (PID 374). Host history recovered the
+missing interval into `/tmp/dh-timing-audit/cold7-full-host.txt`.
+
+Cold7 is not yet the same confirmed failure as cold2: an early screenshot
+showed VZ still at the boot logo (8 fps), DeviceHub connecting, and the probe
+had not launched. Nevertheless paired logs expose a concrete guest-side
+anomaly. Guest AVConference encoder/FigVirtualDisplayProcessor reports stop
+between 01:31:28Z and 01:31:45Z, while VTP health messages continue. At
+01:31:45Z, 22 VTP_Send calls fail with errno 55 (ENOBUFS, verified against
+Xcode SDK sys/errno.h), and the encoder reports 124.65 ms encode time. Host
+HEVC decoder input drops to 0–4 fps for much of that interval, with player
+presentation ages up to ~6.6 seconds. This is evidence of a guest capture /
+encoder / send-path interruption; ENOBUFS may be a consequence of the burst
+on recovery, not the initiating cause. Detailed timeline:
+`/tmp/dh-timing-audit/cold7-encoder-timeline.txt`.
+
+Next investigate the guest encoder/capture thread during a reproduced stall,
+including scheduling and queue waits, before altering periodic keyframes.
+The keyframe configuration path was statically traced in pristine 24A446:
+AVCVideoStreamConfig.dictionary emits vcMediaStreamKeyFrameInterval;
+VCVideoStreamConfig.applyVideoStreamClientDictionary reads it;
+VCVideoTransmitterDefault.initWithConfig passes it into its transmitter
+configuration. A different VT stream-transmitter path maps it to
+MaxKeyFrameIntervalDuration, but that alone does not establish semantics of
+the active HEVC path. No production keyframe/LTRP configuration was changed.
+Evidence disassemblies are `/tmp/dh-avc-*.txt`; no IDA MCP was available, so
+local ipsw cache disassembly was used. Do not paste raw disassembly in chat.
+
+### Thread profiling established (2026-10-07 09:44 local)
+
+Used the existing safe guest profiling procedure in
+`Research/Guest/display_refresh_rate.md`. Never run a host VM-process sample
+at the same time as guest spindump. A temporary launchd job under /var/tmp
+runs /usr/sbin/spindump; after each finished capture it is unloaded and
+verified not loaded. No production hooks or configuration changed.
+
+Healthy baseline: 8 seconds, `/tmp/dh-healthy-spindump.txt` (5,643,448 bytes,
+readback not truncated). avconferenced encoder thread is normally mostly
+waiting for work (167/240 samples), with 51/240 samples in frame checksum
+pixel transfer through VideoToolbox / IOSurfaceAccelerator. This is normal
+baseline evidence, not proof that this path causes the intermittent stall.
+Symbolicated excerpt: `/tmp/dh-healthy-avc-symbolicated.txt`.
+
+Cold8: 35-second whole-guest capture, `/tmp/dh-cold8-spindump.txt`
+(16,807,571 bytes, readback not truncated), six host player health samples,
+maximum presentation age 6.344 ms, no no-video timeout FIR. Probe initially
+launched verified PID 378, but the later screenshot showed Home, so this is
+not a verified full-duration continuous-probe test. No new TimingProbe crash
+report appeared (only the initial 09:12 lifecycle crashes exist).
+
+Cold9 validated a much cheaper targeted capture:
+`spindump avconferenced 40 20 -onlyTarget -wait -noBinary -file <report>`.
+It exits 0, and the text report is 140,796 bytes, containing 955 samples of
+avconferenced. Guest encoding stayed around 58–60 fps; seven host samples
+have maximum presentation age 5.656 ms, no timeout FIR. Report:
+`/tmp/dh-cold9-avc-symbolicated.txt`. Use this targeted recipe next time so
+report transfer and unrelated process sampling do not dominate diagnosis.
+The temporary com.vphone.devicehub.spindump job is unloaded.
+
+Symbolication uses pristine 24A446's per-image symbols with runtime cache
+base 0x180000000 (zero slide here), via `/tmp/dh-symbolicate.rb`; symbol dumps
+are `/tmp/dh-{avc,VideoToolbox,CoreMedia,VideoProcessing,IOSurfaceAccelerator}-symbols.txt`.
+Do not reuse zero slide for another guest without checking its report header.
+Host currently has 64 GiB RAM, 18 logical CPUs; memory_pressure reported 70%
+free, so its ~15 GiB historical swap allocation is not proof of current
+memory pressure. Cold7 CoreDevice tunnel history shows old connection
+teardown before the new video stream, no established transport root cause.
+
+Settings real-content check: direct guest input.swipe from (215,800) to
+(215,300) moved the list, and direct VZ/DeviceHub screenshots showed the same
+result with correct masks. This is functional display evidence, not a precise
+latency measurement. CUA scroll/drag in DeviceHub itself did not visibly move
+the list, so DeviceHub-input verification remains separate and inconclusive;
+do not claim that end-to-end interaction passed from the direct guest swipe.
+Cold2 remains the user-confirmed VZ-fluid / DeviceHub-stuttering failure;
+no current evidence supports closing the intermittent-lag issue.
+
+### Cold10–12 and bounded load comparison (2026-10-07 09:53 local)
+
+Cold10: nine post-start host samples, maximum presentation age 13.658 ms;
+guest encoding 59–60 fps; direct VZ and DeviceHub timestamp captures differed
+by 34 ms in a 423 ms capture window. Targeted spindump readback was 143,528
+bytes, not truncated. No matching fault captured.
+
+Cold11 deliberately reran the same real-cache patch tests that were active
+during cold2 (not an arbitrary CPU stressor). All seven tests passed again:
+`/tmp/dh-timing-audit/cold11-load-tests.log`. The VM's vphoned did not answer
+within 90 seconds and a subsequent ping still said guest not connected. Thus
+no guest profiler was loaded in this round. The guest UI itself was alive:
+native HID swipe dismissed Lock Screen and both VZ/DeviceHub displayed Home.
+Host video samples reached a maximum presentation age of 239.904 ms, not the
+cold2 multi-second fault. The guest console logged APFS transaction waits of
+~1–1.7 seconds. This cannot establish a cause for cold2. After both test and
+startup command were terminal and control stayed offline, cold12 restarted
+the same VM without test load; vphoned connected in four seconds.
+
+Cold12: nine new-stream samples, maximum presentation age 10.025 ms, guest
+encoding ~58–61 fps; 35-second backboardd capture has 73 entries, not
+truncated, and no swap_end / get_wireless_surface_options / invalid-dest
+match. Targeted profiling ended and its temporary job was unloaded. Latest
+report JSON: `/tmp/dh-cold12-spindump.json`.
+
+The summary parser was corrected to discard all health lines preceding the
+last tick-zero initialization, not merely match the player pointer. The
+allocator reused the cold11 player address in cold12; a 4-second presentation
+age from the old closing stream otherwise falsely contaminated the new run.
+Recomputed cold4–10 figures are unchanged. Do not use pointer identity alone
+across a stream restart. Health-age samples still do not measure full input
+latency or prove the intermittent problem fixed.
+
+Code comments now describe the current conditional dispatcher, its actual
+real-cache tests, and the third DeviceHubFix injection target (dtdeviceinfod).
+Removed stale claims that Python is executed or current output must match the
+old unconditional patch digest. These are comment-only edits. Awaiting the
+user's current visual observation before repeating the same cold-start matrix.
+
+Startup-readiness hypothesis checked against current DDI arm64e:
+MediaStreamSupportedFeatures.current at 0x392f38 calls CurrentDevice.init at
+0x329850 and returns no features if device identity cannot be constructed.
+The initializer's required optional inputs are versionNumber, buildUpdate,
+and deviceType (0x329c88, 0x32a284, 0x32aacc). This does not establish a
+SpringBoard/compositor-ready gate, so do not add an arbitrary startup delay
+or claim the support-info interpose skipped such a gate. Disassemblies:
+`/tmp/dh-cdu-current-features.txt`, `/tmp/dh-cdu-currentdevice-init.txt`.
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
index fddca9d8..aee28e24 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcher/DyldSharedCache/Patchers/DyldSharedCacheIOMFBForceKernPatcher.swift
@@ -1,5 +1,5 @@
-// DyldSharedCacheIOMFBForceKernPatcher.swift — Force IOMobileFramebuffer's present onto the
-// kernel (userclient method-5) path instead of the virt (in-process callback) one.
+// DyldSharedCacheIOMFBForceKernPatcher.swift — Route IOMobileFramebuffer presents
+// to the kernel only for connections that actually have a kernel userclient.
//
// Why
// ---
@@ -20,18 +20,19 @@
// What is rewritten
// -----------------
// The public `_IOMobileFramebufferSwap*` entry points are thin dispatch
-// trampolines that tail-call a per-connection function pointer:
+// trampolines that tail-call a per-connection function pointer. On iOS 27 the
+// capture display has no kernel userclient port, while the paravirtual primary
+// display does. The patch therefore replaces each trampoline with:
//
// cbz x0, <fail>
-// ldr xN, [x0, #<slot>] ; the connection's swap fp (kern or virt impl)
-// cbz xN, <fail>
-// braaz xN ; tail-call, all argument registers intact
+// ldr w16, [x0, #0x14] ; IOConnect port (zero for display 2)
+// cbnz w16, _kern_Swap<Name>
+// b _virt_Swap<Name>
//
-// The FIRST instruction of each such trampoline becomes an unconditional
-// `b _kern_Swap<Name>`. Because the trampoline tail-calls with the argument
-// registers untouched, that is behaviourally identical to the connection having
-// selected the kern fp — every present call now routes through the kern/method-5
-// implementation regardless of how iOS 27 classified the display.
+// x16 is an intra-procedure-call scratch register, so the public ABI arguments
+// remain untouched on either direct branch. The port offset is anchored by the
+// `_kern_Swap*` implementations, which all pass `[x0,#0x14]` to the external
+// method call.
//
// Companion kernel patch: `KernelCustomFirmwarePatcher.patchIomfbSwapEndVariableSize` /
// `…HandlerSize`, which make the 26.4 userclient accept iOS 27's native 0x6e0
@@ -39,33 +40,23 @@
// kern without the kernel size-accept makes method 5 return
// `kIOReturnBadArgument`.
//
-// Nothing is hardcoded. The public entry points and their `_kern_` counterparts
-// are resolved by NAME through `DyldSharedCacheSymbolResolver` (export trie plus the cache's
-// own `.symbols` table — no `ipsw` subprocess), the trampoline shape is verified
-// by Capstone decode of typed operands rather than operand text, the replacement
-// branch comes from `ARM64Encoder.encodeB`, and every DSC page the writes
-// dirtied is re-attested through the span log `DyldSharedCacheChunkSet` keeps.
+// Entry-point addresses and both siblings are resolved by name through
+// `DyldSharedCacheSymbolResolver` (export trie and cache symbols). Capstone
+// verifies the trampoline's typed operands; ARM64Encoder produces the four
+// replacement instructions. The connection layout's port offset is 0x14 on
+// the verified cache. Modified pages are re-attested through the chunk span log.
//
-// Port of `scripts/patchers/cfw_patch_iomfb_force_kern.py`, which stays the
-// independent reference — `DyldSharedCacheIOMFBForceKernTests` runs the Python on one clone
-// of the real cache and this on another, and compares the two byte for byte.
-//
-// One place diverges from the reference on purpose. The Python writes every site
-// first and only then checks that the three required entry points were covered,
-// so a cache missing one is left half-patched AND un-attested — the worst of the
-// three possible states, because an un-attested DSC page is a
-// `KERN_PROTECTION_FAILURE` on first demand-page-in rather than a visible
-// failure. Here the whole candidate set is classified before anything is
-// written, so that check happens while the cache is still untouched. On the
-// success path the bytes are identical.
+// Classify the complete candidate set before writing, and require Begin, End,
+// and SetLayer coverage. Unlike the historical unconditional patch, only
+// operations with both kern and virt siblings participate. Real-cache tests
+// verify conditional routing, preserved null handling, dry-run and idempotence.
import Foundation
import VPhonePatchKit
-/// Retargets IOMobileFramebuffer's public swap trampolines at their `_kern_`
-/// implementations, inside a chunked dyld shared cache.
+/// Routes public swap trampolines to kern or virt according to the connection.
public enum DyldSharedCacheIOMFBForceKernPatcher {
- /// The image that carries both halves of every pair.
+ /// The image that carries the public entry points and their siblings.
public static let imagePath =
"/System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer"
@@ -75,6 +66,7 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
/// Prefix of the kernel-path siblings. `End` → `_kern_SwapEnd`.
public static let kernPrefix = "_kern_Swap"
+ public static let virtPrefix = "_virt_Swap"
/// The present transaction the render server drives. Discovery finds
/// whatever the cache has, but these three must come out covered or the
@@ -94,8 +86,7 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
// MARK: - Model
- /// A public entry point paired with the `_kern_` implementation it should
- /// branch to.
+ /// A public entry point with its kernel and in-process implementations.
public struct EntryPoint: Sendable, Hashable {
/// The swap operation, spelled as the reference spells it in a record
/// ID: `SwapEnd`, not `End`.
@@ -104,14 +95,18 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
public let publicAddress: UInt64
public let kernName: String
public let kernAddress: UInt64
+ public let virtName: String
+ public let virtAddress: UInt64
}
/// What was decided about one entry point.
public enum Disposition: String, Sendable {
- /// A thin trampoline whose first instruction this run rewrote.
+ /// A thin trampoline rewritten to the conditional four-instruction form.
case forced
/// Already `b _kern_Swap<Name>` — a previous run did it.
case alreadyForced
+ /// Already conditional on the per-connection kernel port.
+ case alreadyConditional
/// Not a thin dispatch trampoline; left on whatever path it had.
case notATrampoline
}
@@ -122,6 +117,7 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
public let disposition: Disposition
/// The first instruction as it was found, e.g. `cbz x0, #0x22ac0c1c0`.
public let originalDisassembly: String
+ public let failureAddress: UInt64
}
/// What one run did.
@@ -141,6 +137,10 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
sites.filter { $0.disposition == .alreadyForced }
}
+ public var alreadyConditional: [Site] {
+ sites.filter { $0.disposition == .alreadyConditional }
+ }
+
public var notTrampolines: [Site] {
sites.filter { $0.disposition == .notATrampoline }
}
@@ -222,14 +222,17 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
for site in sites {
switch site.disposition {
case .alreadyForced:
- log?(" [=] \(site.entry.publicName) already -> b \(site.entry.kernName) (idempotent)")
+ log?(" [=] \(site.entry.publicName) already -> conditional kern/virt dispatch (idempotent)")
+ case .alreadyConditional:
+ log?(" [=] \(site.entry.publicName) already -> conditional kern/virt dispatch (idempotent)")
case .notATrampoline:
log?(" [=] \(site.entry.publicName) not a thin trampoline; leaving on virt path")
case .forced:
log?(
" [+] \(site.entry.publicName) @ 0x\(hex(site.entry.publicAddress)): "
+ "'\(site.originalDisassembly)' -> 'b \(site.entry.kernName)' "
- + "(0x\(hex(site.entry.kernAddress)))",
+ + "(0x\(hex(site.entry.kernAddress))) when port != 0, "
+ + "virt otherwise (0x\(hex(site.entry.virtAddress)))",
)
}
}
@@ -245,11 +248,12 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
try records.append(force(site, chunks: chunks))
}
+
var reattestation: DyldSharedCacheReattestation?
if records.isEmpty {
log?(
- " [=] all \(sites.count { $0.disposition == .alreadyForced }) entrypoint(s) "
- + "already forced; nothing to patch/re-attest",
+ " [=] all \(sites.count { $0.disposition == .alreadyForced || $0.disposition == .alreadyConditional }) entrypoint(s) "
+ + "already conditional; nothing to patch/re-attest",
)
} else {
log?(" [.] re-attesting the pages \(records.count) write(s) dirtied...")
@@ -265,10 +269,12 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
}
let forcedCount = toWrite.count
- let alreadyCount = sites.count { $0.disposition == .alreadyForced }
+ let alreadyCount = sites.count {
+ $0.disposition == .alreadyForced || $0.disposition == .alreadyConditional
+ }
log?(
" [+] IOMFB force-kern complete: \(forcedCount) newly forced, "
- + "\(alreadyCount) already -> _kern_*",
+ + "\(alreadyCount) already conditional",
)
return Outcome(sites: sites, records: records, reattestation: reattestation)
}
@@ -291,7 +297,8 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
for (publicName, publicAddress) in publicEntries {
let suffix = "Swap" + publicName.dropFirst(publicPrefix.count)
let kernName = kernPrefix + publicName.dropFirst(publicPrefix.count)
- guard let kern = all[kernName] else { continue }
+ let virtName = virtPrefix + publicName.dropFirst(publicPrefix.count)
+ guard let kern = all[kernName], let virt = all[virtName] else { continue }
entries.append(
EntryPoint(
suffix: suffix,
@@ -299,6 +306,8 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
publicAddress: publicAddress,
kernName: kernName,
kernAddress: kern.address,
+ virtName: virtName,
+ virtAddress: virt.address,
),
)
}
@@ -321,16 +330,53 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
let first = instructions.first
let text = first.map { "\($0.mnemonic) \($0.operandString)" } ?? "<undecodable>"
- // Idempotent: a prior run already rewrote this entry point.
+ // Idempotent: accept both the historical unconditional form and the
+ // new conditional form while upgrading an already patched cache.
if let first, first.mnemonic == "b",
let target = immediate(first, at: 0), UInt64(bitPattern: target) == entry.kernAddress
{
- return Site(entry: entry, disposition: .alreadyForced, originalDisassembly: text)
+ return Site(
+ entry: entry, disposition: .forced, originalDisassembly: text,
+ failureAddress: entry.publicAddress + 16,
+ )
+ }
+
+ if isConditionalDispatch(instructions, entry: entry) {
+ return Site(
+ entry: entry, disposition: .alreadyConditional, originalDisassembly: text,
+ failureAddress: immediate(instructions[0], at: 1).map(UInt64.init(bitPattern:))
+ ?? entry.publicAddress + 16,
+ )
}
let disposition: Disposition =
isDispatchTrampoline(instructions) ? .forced : .notATrampoline
- return Site(entry: entry, disposition: disposition, originalDisassembly: text)
+ return Site(
+ entry: entry, disposition: disposition, originalDisassembly: text,
+ failureAddress: immediate(instructions[0], at: 1).map(UInt64.init(bitPattern:))
+ ?? entry.publicAddress + 16,
+ )
+ }
+
+ private static func isConditionalDispatch(
+ _ instructions: [ARM64Instruction], entry: EntryPoint
+ ) -> Bool {
+ guard instructions.count >= 4,
+ instructions[0].mnemonic == "cbz",
+ register(instructions[0], at: 0) == .x(0),
+ instructions[1].mnemonic == "ldr",
+ register(instructions[1], at: 0) == .w(16),
+ let memory = memory(instructions[1]), memory.base == .x(0),
+ memory.index == .invalid, memory.disp == 0x14,
+ instructions[2].mnemonic == "cbnz",
+ register(instructions[2], at: 0) == .w(16),
+ let kernTarget = firstImmediate(instructions[2]),
+ UInt64(bitPattern: kernTarget) == entry.kernAddress,
+ instructions[3].mnemonic == "b",
+ let virtTarget = firstImmediate(instructions[3]),
+ UInt64(bitPattern: virtTarget) == entry.virtAddress
+ else { return false }
+ return true
}
/// True iff the four instructions are
@@ -378,20 +424,33 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
private static func force(_ site: Site, chunks: DyldSharedCacheChunkSet) throws -> PatchRecord {
let entry = site.entry
- guard let branch = ARM64Encoder.encodeB(
- from: Int(entry.publicAddress),
- to: Int(entry.kernAddress),
- ), branch.count == 4 else {
+ guard let portLoad = ARM64Encoder.encodeLdrWUnsignedOffset(rt: 16, rn: 0, offset: 0x14),
+ let nullBranch = ARM64Encoder.encodeCompareBranch(
+ nonzero: false, register: 0,
+ from: Int(entry.publicAddress), to: Int(site.failureAddress), width64: true,
+ ),
+ let kernBranch = ARM64Encoder.encodeCompareBranch(
+ nonzero: true, register: 16,
+ from: Int(entry.publicAddress + 8), to: Int(entry.kernAddress),
+ ),
+ let virtBranch = ARM64Encoder.encodeB(
+ from: Int(entry.publicAddress + 12), to: Int(entry.virtAddress),
+ ), portLoad.count == 4, kernBranch.count == 4, virtBranch.count == 4 else {
throw PatcherError.patchVerificationFailed(
- "cannot encode b 0x\(hex(entry.publicAddress)) -> 0x\(hex(entry.kernAddress)) "
+ "cannot encode conditional IOMFB dispatch for \(entry.publicName) "
+ "for \(entry.publicName)",
)
}
- let span = DyldSharedCacheWriteSpan(vma: entry.publicAddress, length: 4)
+ var patched = Data()
+ patched.append(nullBranch)
+ patched.append(portLoad)
+ patched.append(kernBranch)
+ patched.append(virtBranch)
+ let span = DyldSharedCacheWriteSpan(vma: entry.publicAddress, length: 16)
let (chunkURL, range) = try chunks.fileRange(of: span)
- let original = try chunks.bytesAtVMA(entry.publicAddress, length: 4)
- try chunks.write(at: entry.publicAddress, branch)
+ let original = try chunks.bytesAtVMA(entry.publicAddress, length: 16)
+ try chunks.write(at: entry.publicAddress, patched)
return PatchRecord(
patchID: "\(recordGroup).\(entry.suffix)",
@@ -399,11 +458,10 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
fileOffset: range.lowerBound,
virtualAddress: entry.publicAddress,
originalBytes: original,
- patchedBytes: branch,
+ patchedBytes: patched,
beforeDisasm: site.originalDisassembly,
- afterDisasm: "b #0x\(hex(entry.kernAddress).lowercased())",
- description: "\(entry.publicName) trampoline -> b \(entry.kernName) "
- + "(0x\(hex(entry.kernAddress)))",
+ afterDisasm: "cbz x0, fail; ldr w16, [x0,#0x14]; cbnz w16, #0x\(hex(entry.kernAddress).lowercased()); b #0x\(hex(entry.virtAddress).lowercased())",
+ description: "\(entry.publicName) conditional kern/virt dispatch",
)
}
@@ -414,16 +472,17 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
chunks: DyldSharedCacheChunkSet,
disassembler: ARM64Disassembler,
) throws {
- for site in sites {
+ for site in sites where site.disposition == .forced {
let address = site.entry.publicAddress
- let data = try chunks.bytesAtVMA(address, length: 4)
- guard let instruction = disassembler.disassembleOne(data, at: address),
- instruction.mnemonic == "b",
- let target = immediate(instruction, at: 0),
- UInt64(bitPattern: target) == site.entry.kernAddress
+ let data = try chunks.bytesAtVMA(address, length: 16)
+ let instructions = try disassembler.disassemble(data, at: address, count: 4)
+ guard isConditionalDispatch(instructions, entry: site.entry)
else {
+ let bytes = data.map { String(format: "%02x", $0) }.joined()
throw PatcherError.patchVerificationFailed(
- "post-write verify failed at 0x\(hex(address)) for \(site.entry.publicName)",
+ "post-write verify failed at 0x\(hex(address)) for \(site.entry.publicName): "
+ + " bytes=\(bytes)"
+ + " insns=" + instructions.map(\.description).joined(separator: "; "),
)
}
}
@@ -445,6 +504,10 @@ public enum DyldSharedCacheIOMFBForceKernPatcher {
return operands[index].imm
}
+ private static func firstImmediate(_ instruction: ARM64Instruction) -> Int64? {
+ instruction.detail?.operands.first(where: { $0.type == .immediate })?.imm
+ }
+
private static func memory(_ instruction: ARM64Instruction) -> ARM64MemoryOperand? {
guard let operands = instruction.detail?.operands,
let operand = operands.first(where: { $0.type == .memory })
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
index a183004d..9aca67cd 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/Core/ARM64EncoderTests.swift
@@ -690,3 +690,22 @@ struct ARM64EncoderRangeTests {
#expect(ARM64Encoder.decodeBranchTarget(insn: ARM64.retU32, pc: 0) == nil)
}
}
+
+struct ARM64CompareBranchTests {
+ @Test func `Compare branch matches Keystone and rejects unreachable targets`() throws {
+ // Keystone 0.9.2 C API in /tmp/ks2.c, assembled at 0x2000.
+ let backward = try #require(ARM64Encoder.encodeCompareBranch(
+ nonzero: true, register: 16, from: 0x2000, to: 0x1000
+ ))
+ #expect(word(backward) == 0x35FF_8010)
+ // Keystone C API in /tmp/ks.c, cbz x0 to PC+16.
+ let null = try #require(ARM64Encoder.encodeCompareBranch(
+ nonzero: false, register: 0, from: 0x1000, to: 0x1010, width64: true
+ ))
+ #expect(word(null) == 0xB400_0080)
+ #expect(ARM64Encoder.encodeCompareBranch(nonzero: true, register: 16,
+ from: 0, to: 1 << 20) == nil)
+ #expect(ARM64Encoder.encodeCompareBranch(nonzero: true, register: 32,
+ from: 0, to: 4) == nil)
+ }
+}
diff --git a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
index ac55bb5c..d15be96c 100644
--- a/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
+++ b/VPhoneExecutable/VPhoneCommand/FirmwarePatcherTests/DyldSharedCache/DyldSharedCacheIOMFBForceKernTests.swift
@@ -1,15 +1,11 @@
-// DyldSharedCacheIOMFBForceKernTests.swift — Parity for the IOMFB force-kern DSC patcher.
+// DyldSharedCacheIOMFBForceKernTests.swift — Conditional IOMFB routing checks.
//
-// There is no independent oracle for a patched dyld shared cache: `codesign -v`
-// does not apply to a cache chunk, and nothing but the guest kernel reads the
-// slot hashes. The only reference was
-// `scripts/patchers/cfw_patch_iomfb_force_kern.py`, and that Python has been
-// removed — so what it did on the real cache is frozen in `FrozenReference`
-// below: the 35 entry points it discovered, the address it resolved for each,
-// which four it refused to touch, and the SHA-256 of the one chunk it changed.
-// The Swift runs on a clone and is graded against those. A port that writes a
-// different number of sites, or the same number in different places, or
-// re-attests a different set of pages, lands on a different digest.
+// FrozenReference preserves the historical unconditional patch's symbol
+// addresses and changed chunk. ConditionalReference selects the operations
+// that also have virt siblings. Current tests verify discovery, decoded branch
+// targets and null handling, changed chunks, dry-run, and idempotence. The old
+// unconditional patch's recorded digest is historical data, not the expected
+// output of the conditional implementation. No Python is executed.
//
// The tests need the real cache. Point `VPHONE_DSC_PRISTINE` at a directory of
// `dyld_shared_cache_arm64e*` chunks, or leave the default
@@ -468,11 +464,24 @@ private enum Digest {
let mine = try chunkDigests(of: directory)
let changed = mine.filter { pristineDigests[$0.key] != $0.value }.keys.sorted()
#expect(changed == FrozenReference.changedChunks.keys.sorted())
- for name in changed {
- let frozen = FrozenReference.changedChunks[name] ?? "(not a chunk the Python moved)"
- #expect(mine[name] == frozen, "\(name): Swift \(mine[name] ?? "—"), reference \(frozen)")
- }
+
+ }
+}
+
+// The conditional dispatcher requires a real virtual sibling. These ten were
+// independently resolved on the 24A446 cache; the remaining old force sites
+// must not be rewritten by this narrower patch.
+private enum ConditionalReference {
+ static let suffixes: Set<String> = [
+ "Begin", "Cancel", "DebugInfo", "End", "SetEventSignal",
+ "SetEventSignalOnGlass", "SetEventWait", "SetLayer", "Wait", "WaitWithTimeout",
+ ]
+ static let forcedPairs = FrozenReference.forcedPairs.filter {
+ suffixes.contains(String($0.publicName.dropFirst("_IOMobileFramebufferSwap".count)))
}
+ static let newlyForced = 10
+ static let leftOnVirtPath: Set<String> = ["_IOMobileFramebufferSwapSignal"]
+ static let discoveredNames = Set(forcedPairs.map(\.publicName)).union(leftOnVirtPath)
}
// MARK: - Parity against the frozen reference
@@ -481,7 +490,7 @@ private enum Digest {
struct DyldSharedCacheIOMFBForceKernParityTests {
/// The one test that decides whether this port is done.
@Test
- func `Swift force-kern reproduces the reference cache byte for byte`() throws {
+ func `Conditional dispatch changes only the expected cache chunk`() throws {
_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
let swiftClone = try ForceKernFixture.cloneCache(named: "swift")
@@ -493,16 +502,16 @@ struct DyldSharedCacheIOMFBForceKernParityTests {
)
#expect(
- outcome.writtenSiteCount == FrozenReference.newlyForced,
- "swift wrote \(outcome.writtenSiteCount) sites, reference \(FrozenReference.newlyForced)",
+ outcome.writtenSiteCount == ConditionalReference.newlyForced,
+ "swift wrote \(outcome.writtenSiteCount) sites, reference \(ConditionalReference.newlyForced)",
)
// The same entry points, not merely the same count.
#expect(
Set(outcome.forced.map(\.entry.publicName))
- == Set(FrozenReference.forcedPairs.map(\.publicName)),
+ == Set(ConditionalReference.forcedPairs.map(\.publicName)),
)
#expect(Set(outcome.notTrampolines.map(\.entry.publicName))
- == Set(FrozenReference.leftOnVirtPath))
+ == Set(ConditionalReference.leftOnVirtPath))
try Digest.expectMatchesReference(swiftClone)
}
@@ -519,14 +528,14 @@ struct DyldSharedCacheIOMFBForceKernParityTests {
defer { ForceKernFixture.discard(clone) }
let first = try DyldSharedCacheIOMFBForceKernPatcher.patch(chunksDirectory: clone, log: nil)
- #expect(first.writtenSiteCount == FrozenReference.newlyForced)
+ #expect(first.writtenSiteCount == ConditionalReference.newlyForced)
let hashesBefore = try Digest.chunkDigests(of: clone)
let second = try DyldSharedCacheIOMFBForceKernPatcher.patch(chunksDirectory: clone, log: nil)
#expect(second.writtenSiteCount == 0, "a second pass rewrote \(second.writtenSiteCount) site(s)")
#expect(second.reattestation == nil, "a second pass re-attested pages it did not dirty")
- #expect(second.alreadyForced.count == FrozenReference.newlyForced)
+ #expect(second.alreadyConditional.count == ConditionalReference.newlyForced)
let hashesAfter = try Digest.chunkDigests(of: clone)
#expect(hashesAfter == hashesBefore, "a no-op run changed bytes")
@@ -547,7 +556,7 @@ struct DyldSharedCacheIOMFBForceKernParityTests {
dryRun: true,
log: nil,
)
- #expect(dry.writtenSiteCount == FrozenReference.newlyForced)
+ #expect(dry.writtenSiteCount == ConditionalReference.newlyForced)
#expect(dry.records.isEmpty)
#expect(dry.reattestation == nil)
let hashesAfter = try Digest.chunkDigests(of: clone)
@@ -576,14 +585,14 @@ struct DyldSharedCacheIOMFBForceKernDiscoveryTests {
#expect(entries.count >= DyldSharedCacheIOMFBForceKernPatcher.requiredSuffixes.count)
let discovered = Set(entries.map(\.publicName))
- let expected = FrozenReference.discoveredNames
+ let expected = ConditionalReference.discoveredNames
let disagreement = discovered.symmetricDifference(expected).sorted()
#expect(discovered == expected, "discovery differs from the reference: \(disagreement)")
// The 31 the reference resolved an address for — it printed no address
// for the four it left on the virt path.
let byName = Dictionary(uniqueKeysWithValues: entries.map { ($0.publicName, $0) })
- for pair in FrozenReference.forcedPairs {
+ for pair in ConditionalReference.forcedPairs {
let entry = try #require(byName[pair.publicName], "\(pair.publicName) was not discovered")
let mine = String(entry.publicAddress, radix: 16, uppercase: true)
let theirs = String(pair.publicAddress, radix: 16, uppercase: true)
@@ -642,7 +651,7 @@ struct DyldSharedCacheIOMFBForceKernDiscoveryTests {
#expect(
dry.notTrampolines.map(\.entry.publicName).sorted()
- == FrozenReference.leftOnVirtPath.sorted(),
+ == ConditionalReference.leftOnVirtPath.sorted(),
)
#expect(dry.forced.count + dry.notTrampolines.count + dry.alreadyForced.count == dry.sites.count)
@@ -666,7 +675,7 @@ struct DyldSharedCacheIOMFBForceKernDiscoveryTests {
/// kern sibling — checked from the record the patcher emits, which is what
/// the record-comparison harness consumes.
@Test
- func `Every record is a four-byte branch to the paired kern implementation`() throws {
+ func `Every record preserves null handling and branches by kernel port`() throws {
_ = try #require(ForceKernFixture.pristine, ForceKernFixture.missing)
let clone = try ForceKernFixture.cloneCache(named: "records")
@@ -675,32 +684,30 @@ struct DyldSharedCacheIOMFBForceKernDiscoveryTests {
#expect(outcome.records.count == outcome.writtenSiteCount)
let kernAddresses = Dictionary(
- uniqueKeysWithValues: FrozenReference.forcedPairs.map { ($0.publicAddress, $0.kernAddress) },
+ uniqueKeysWithValues: ConditionalReference.forcedPairs.map { ($0.publicAddress, $0.kernAddress) },
)
let chunks = try DyldSharedCacheChunkSet(directory: clone)
let disassembler = ARM64Disassembler()
for record in outcome.records {
#expect(record.patchID.hasPrefix("\(DyldSharedCacheIOMFBForceKernPatcher.recordGroup)."))
- #expect(record.patchedBytes.count == 4)
- #expect(record.originalBytes.count == 4)
+ #expect(record.patchedBytes.count == 16)
+ #expect(record.originalBytes.count == 16)
#expect(record.originalBytes != record.patchedBytes)
let address = try #require(record.virtualAddress)
- let instruction = try #require(
- try disassembler.disassembleOne(
- chunks.bytesAtVMA(address, length: 4),
- at: address,
- ),
- )
- #expect(instruction.mnemonic == "b")
- // …and it lands on the kern sibling the reference named for this
- // entry point, rather than merely on some branch.
- let target = try #require(kernAddresses[address], "0x\(String(address, radix: 16)) is not a reference site")
- let expected = "0x\(String(target, radix: 16))"
- let site = "0x\(String(address, radix: 16))"
- #expect(
- instruction.operandString == expected,
- "\(site) branches to \(instruction.operandString), reference paired it with \(expected)",
- )
+ let decoded = disassembler.disassemble(record.patchedBytes, at: address, count: 4)
+ #expect(decoded.count == 4)
+ let entry = try #require(outcome.forced.first { $0.entry.publicAddress == address }?.entry)
+ #expect(decoded.map(\.mnemonic) == ["cbz", "ldr", "cbnz", "b"])
+ #expect(decoded[0].detail?.operands[0].reg == .x(0))
+ #expect(decoded[0].detail?.operands[1].imm == Int64(address + 16))
+ #expect(decoded[1].detail?.operands[0].reg == .w(16))
+ #expect(decoded[1].detail?.operands[1].mem.base == .x(0))
+ #expect(decoded[1].detail?.operands[1].mem.disp == 0x14)
+ #expect(decoded[2].detail?.operands[0].reg == .w(16))
+ #expect(decoded[2].detail?.operands[1].imm == Int64(entry.kernAddress))
+ #expect(decoded[3].detail?.operands[0].imm == Int64(entry.virtAddress))
+ #expect(try chunks.bytesAtVMA(address, length: 16) == record.patchedBytes)
+
}
}
}
diff --git a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
index 6ca426b6..f1970b69 100644
--- a/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
+++ b/VPhoneExecutable/VPhoneCommand/VPhonePatchKit/ARM64/ARM64Encoder.swift
@@ -62,6 +62,30 @@ public enum ARM64Encoder {
return ARM64.encodeU32(insn)
}
+ /// Encode `CBZ`/`CBNZ` for a general-purpose register.
+ ///
+ /// The 32-bit form is used by the IOMFB display dispatcher so the loaded
+ /// mach port does not overwrite the upper half of the scratch register.
+ /// The immediate is a signed 19-bit instruction offset (±1 MiB).
+ public static func encodeCompareBranch(
+ nonzero: Bool,
+ register: UInt32,
+ from pc: Int,
+ to target: Int,
+ width64: Bool = false,
+ ) -> Data? {
+ guard register < 32 else { return nil }
+ let delta = target - pc
+ guard delta & 0x3 == 0 else { return nil }
+ let imm19 = delta >> 2
+ guard imm19 >= -(1 << 18), imm19 < (1 << 18) else { return nil }
+ var insn: UInt32 = (width64 ? 0xB400_0000 : 0x3400_0000)
+ if nonzero { insn |= 1 << 24 }
+ insn |= (UInt32(bitPattern: Int32(imm19)) & 0x7FFFF) << 5
+ insn |= register
+ return ARM64.encodeU32(insn)
+ }
+
/// Encode BL (branch with link) instruction.
///
/// Format: `[31:26] = 0b100101`, `[25:0] = signed offset / 4`
diff --git a/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
index 0fd14185..46ac9f86 100644
--- a/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
+++ b/VPhoneGuestComponents/DeviceHubFix/libdevicehubfix.c
@@ -1,7 +1,8 @@
// libdevicehubfix.c — let Xcode's DeviceHub show a vphone guest's screen.
//
// DeviceHub (Xcode 27) views a device through the developer disk image's
-// dtremotedisplayd. Two things stop it on a vphone guest, one per process.
+// dtremotedisplayd. Guest compatibility also requires DDI mounting and display
+// metadata from dtdeviceinfod.
//
// ## cryptexd: the DDI does not mount on iOS 27
//
@@ -52,14 +53,21 @@
// host still intersects the answer with its own features, so asking for more
// than the Mac can take changes nothing.
//
+// ## dtdeviceinfod: missing framebuffer mask
+//
+// The virtual board reports phone11 chrome with no FramebufferIdentifier.
+// Supply the matching Xcode mask only for that missing answer in dtdeviceinfod,
+// preserving existing answers and MobileGestalt's Copy ownership contract.
+//
// ## Reach
//
-// The interposes reach both callers because cryptexd, dtremotedisplayd and
+// The interposes reach their callers because cryptexd, dtremotedisplayd,
+// dtdeviceinfod and
// CoreDeviceUtilities are standalone images, not shared-cache ones: dyld binds
// their imports through the interposing table. CoreDeviceUtilities is on the
// DDI and not in the SDK, so its two symbols are weak flat-namespace imports;
// in cryptexd they resolve to nothing and dyld skips those entries. The spawn
-// hooks insert this into those two processes only — `vpIsDeviceHubFixTarget`
+// hooks insert this into those three processes only — `vpIsDeviceHubFixTarget`
// in Shared/InjectionEnvironment.h.
#include <errno.h>
@@ -67,8 +75,12 @@
#include <stdarg.h>
#include <stdatomic.h>
#include <stdio.h>
+#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
+#include <CoreFoundation/CoreFoundation.h>
+
+extern CFTypeRef MGCopyAnswer(CFStringRef key, CFDictionaryRef options);
// The features a Mac host reports for itself (raw 0x8c): primary display
// mirrored output 0x4, system audio output 0x8, display information 0x80.
@@ -139,12 +151,46 @@ __attribute__((constructor)) static void vpLogLoad(void) {
vpOriginalIsCustomerRestricted ? "interposed" : "absent");
}
-int vphone_devicehubfix_version(void) { return 1; }
+// Fill the missing mask and preserve Copy ownership. Bounded diagnostics log
+// only the three identifiers consumed by the DDI DisplayInfoProvider.
+static CFTypeRef vpDisplayAnswer(CFStringRef key, CFDictionaryRef options) {
+ CFTypeRef result = MGCopyAnswer(key, options);
+ // The virtual board advertises phone11 chrome but no framebuffer mask.
+ // DDI metadata only: use the matching mask shipped in Xcode's
+ // /Library/Developer/DeviceKit/chrome_map.plist. Keep real answers intact.
+ if (!result && key && !strcmp(getprogname(), "dtdeviceinfod") &&
+ CFEqual(key, CFSTR("FramebufferIdentifier"))) {
+ CFTypeRef chrome = MGCopyAnswer(CFSTR("ChromeIdentifier"), NULL);
+ if (chrome && CFEqual(chrome, CFSTR("com.apple.dt.devicekit.chrome.phone11")))
+ result = CFRetain(CFSTR("4E5532ED-1470-47D1-BDF4-7AA90C26957A"));
+ if (chrome) CFRelease(chrome);
+ }
+ if (key && (!strcmp(getprogname(), "dtdeviceinfod")) &&
+ (CFEqual(key, CFSTR("FramebufferIdentifier")) ||
+ CFEqual(key, CFSTR("ChromeIdentifier")) ||
+ CFEqual(key, CFSTR("DisplayExtendedProperties")))) {
+ static atomic_uint count;
+ if (atomic_fetch_add(&count, 1) < 12) {
+ char name[128] = {0}, value[4096] = {0};
+ CFStringGetCString(key, name, sizeof(name), kCFStringEncodingUTF8);
+ CFStringRef description = result ? CFCopyDescription(result) : NULL;
+ if (description) {
+ CFStringGetCString(description, value, sizeof(value), kCFStringEncodingUTF8);
+ CFRelease(description);
+ }
+ vpLog("display %s = %s", name, result ? value : "<null>");
+ }
+ }
+ return result;
+}
+
+int vphone_devicehubfix_version(void) { return 2; }
__attribute__((used, section("__DATA,__interpose"))) static const struct {
const void *replacement;
const void *replacee;
} vpInterpose[] = {
+ {(const void *)vpDisplayAnswer, (const void *)MGCopyAnswer},
{(const void *)vpFcntl, (const void *)fcntl},
{(const void *)vpCurrentFeatures, (const void *)vpOriginalCurrentFeatures},
{(const void *)vpIsCustomerRestricted, (const void *)vpOriginalIsCustomerRestricted},
diff --git a/VPhoneGuestComponents/Makefile b/VPhoneGuestComponents/Makefile
index 025db09f..5c348465 100644
--- a/VPhoneGuestComponents/Makefile
+++ b/VPhoneGuestComponents/Makefile
@@ -221,6 +221,7 @@ $(DEVICEHUBFIX): $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_INCLUDES) DeviceHubFix |
$(CLANG) $(GUEST_C_FLAGS) -dynamiclib \
-install_name /usr/lib/libdevicehubfix.dylib \
-o $@ $(DEVICEHUBFIX_SOURCES) $(DEVICEHUBFIX_DYNAMIC_LOOKUP_SYMS) \
+ -framework CoreFoundation -lMobileGestalt \
-Wl,-not_for_dyld_shared_cache
@codesign --force --sign - $@
diff --git a/VPhoneGuestComponents/Shared/InjectionEnvironment.h b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
index dad69c6b..38c76910 100644
--- a/VPhoneGuestComponents/Shared/InjectionEnvironment.h
+++ b/VPhoneGuestComponents/Shared/InjectionEnvironment.h
@@ -90,7 +90,8 @@ static const char *vpBatteryHealthFixFor(const char *path) {
// suffixes are matched like the other targets.
static int vpIsDeviceHubFixTarget(const char *path) {
return path && (vpPathHasSuffix(path, "/usr/libexec/cryptexd") ||
- vpPathHasSuffix(path, "/usr/libexec/dtremotedisplayd"));
+ vpPathHasSuffix(path, "/usr/libexec/dtremotedisplayd") ||
+ vpPathHasSuffix(path, "/usr/libexec/dtdeviceinfod"));
}
static const char *vpDeviceHubFixFor(const char *path) {
diff --git a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
index eca6b49b..8393b9e8 100644
--- a/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
+++ b/VPhoneGuestComponents/Tests/InjectionEnvironmentTests.c
@@ -66,6 +66,8 @@ static void namesTheDeviceHubFixTarget(void) {
assert(vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/dtremotedisplayd"));
assert(vpIsDeviceHubFixTarget("/usr/libexec/dtremotedisplayd"));
assert(vpIsDeviceHubFixTarget("/usr/libexec/cryptexd"));
+ assert(vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/dtdeviceinfod"));
+ assert(!vpIsDeviceHubFixTarget("/usr/libexec/dtdeviceinfodx"));
assert(!vpIsDeviceHubFixTarget("/usr/libexec/cryptexdx"));
assert(!vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/dtremotedisplaydx"));
assert(!vpIsDeviceHubFixTarget("/System/Developer/usr/libexec/remoted"));